Skip to content
This repository has been archived by the owner on Dec 20, 2019. It is now read-only.

Bug/BLE packet parsing #91

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion lib/adaptors/ble.js
Original file line number Diff line number Diff line change
Expand Up @@ -165,7 +165,7 @@ Adaptor.prototype.devModeOn = function(callback) {
function(e, c) {
if (e) { return callback(e); }
c.on("read", function(data) {
if (data && data.length > 5) {
if (data) {
self.readHandler(data);
}
});
Expand Down
74 changes: 59 additions & 15 deletions lib/packet.js
Original file line number Diff line number Diff line change
Expand Up @@ -68,33 +68,77 @@ Packet.prototype.create = function(opts) {
return packet;
};

Packet.prototype._checkIfValid = function(buffer) {

if (this._checkMinSize(buffer)) {
// Packet is at least 6 bytes long

if (this._checkSOPs(buffer)) {
// Packet has valid header

if (this._checkExpectedSize(buffer) > -1) {
// If the buffer is at least of length
// specified in the DLEN value the buffer
// is valid (deal with extra bytes later)
return true;
}
}
}

return false;
};

Packet.prototype._checkIfInvalid = function(buffer) {

if (buffer.length >= 2) {

if (!this._checkSOPs(buffer)) {
// Discard packet of minimal size,
// but without a valid header
return true;
}
}

return false;

};

Packet.prototype.parse = function(buffer) {

if (this._checkIfValid(buffer)) {
// HACK: prevent having two valid packets
// in buffer and only react on the most recent one
// If received buffer is valid, compute
// it and drop all previous
this.partialBuffer = new Buffer(0);
return this._parse(buffer);
}

if (this.partialBuffer.length > 0) {
// Concatenate with previous fragment
buffer = Buffer.concat(
[this.partialBuffer, buffer],
buffer.length + this.partialBuffer.length
this.partialBuffer.length + buffer.length
);
}

if (this._checkIfInvalid(buffer)) {
// Drop if concatenation or received
// fragment is clearly invalid
this.partialBuffer = new Buffer(0);
} else {
this.partialBuffer = new Buffer(buffer);
return null;
}

if (this._checkSOPs(buffer)) {
// Check the packet is at least 6 bytes long
if (this._checkMinSize(buffer)) {
// Check the buffer length matches the
// DLEN value specified in the buffer
if (this._checkExpectedSize(buffer) > -1) {
// If the packet looks good parse it
return this._parse(buffer);
}
}

this.partialBuffer = new Buffer(buffer);
if (this._checkIfValid(buffer)) {
// Parse if valid, take care of
// extra bytes within
return this._parse(buffer);
}

// Transfer too small packets to next step
this.partialBuffer = new Buffer(buffer);
return null;

};

Packet.prototype._parse = function(buffer) {
Expand Down