diff --git a/lib/adaptors/ble.js b/lib/adaptors/ble.js index b67d97e..a3fb84f 100644 --- a/lib/adaptors/ble.js +++ b/lib/adaptors/ble.js @@ -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); } }); diff --git a/lib/packet.js b/lib/packet.js index 0ccdee3..7c720fa 100644 --- a/lib/packet.js +++ b/lib/packet.js @@ -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) {