From c6395e109b7d4a7fe1426f8a87ae1fab2df7d4a2 Mon Sep 17 00:00:00 2001 From: Nathan Kunicki Date: Thu, 28 Jun 2018 17:18:16 +0100 Subject: [PATCH] First pass at buffering incoming data until a complete message has arrived --- lpf2hub.ts | 69 ++++++++++++++++++++++++++++++++++++++---------------- 1 file changed, 49 insertions(+), 20 deletions(-) diff --git a/lpf2hub.ts b/lpf2hub.ts index ba29675..e0e1e00 100644 --- a/lpf2hub.ts +++ b/lpf2hub.ts @@ -25,6 +25,9 @@ export class LPF2Hub extends Hub { private _lastTiltX: number = 0; private _lastTiltY: number = 0; + private _incomingData: Buffer = Buffer.alloc(0); + private _outgoingData: Buffer = Buffer.alloc(0); + constructor (peripheral: Peripheral, autoSubscribe: boolean = true) { super(peripheral, autoSubscribe); @@ -184,29 +187,49 @@ export class LPF2Hub extends Hub { } - private _parseMessage (data: Buffer) { + private _parseMessage (data?: Buffer) { - switch (data[2]) { - case 0x01: - { - this._parseDeviceInfo(data); - break; + if (data) { + this._incomingData = Buffer.concat([this._incomingData, data]); + } + + if (this._incomingData.length <= 0) { + return; + } + + const len = this._incomingData[0]; + if (len >= this._incomingData.length) { + + const message = this._incomingData.slice(0, len); + this._incomingData = this._incomingData.slice(len); + + switch (message[2]) { + case 0x01: + { + this._parseDeviceInfo(message); + break; + } + case 0x04: + { + this._parsePortMessage(message); + break; + } + case 0x45: + { + this._parseSensorMessage(message); + break; + } + case 0x82: + { + this._parsePortAction(message); + break; + } } - case 0x04: - { - this._parsePortMessage(data); - break; - } - case 0x45: - { - this._parseSensorMessage(data); - break; - } - case 0x82: - { - this._parsePortAction(data); - break; + + if (this._incomingData.length > 0) { + this._parseMessage(); } + } } @@ -341,6 +364,12 @@ export class LPF2Hub extends Hub { this.emit("rotate", port.id, rotation); break; } + case Consts.Devices.BOOST_MOVE_HUB_MOTOR: + { + const rotation = data.readInt32LE(2); + this.emit("rotate", port.id, rotation); + break; + } case Consts.Devices.BOOST_TILT: { const tiltX = data[4] > 160 ? data[4] - 255 : data[4];