Improve web ble mailbox

This commit is contained in:
Léo Bonnargent 2020-05-25 23:19:04 +02:00
parent bce589a751
commit 93d6a9e45a
2 changed files with 25 additions and 24 deletions

View File

@ -132,31 +132,29 @@ export class PoweredUP extends EventEmitter {
let buf: Buffer = Buffer.alloc(0); let buf: Buffer = Buffer.alloc(0);
device.subscribeToCharacteristic(Consts.BLECharacteristic.LPF2_ALL, (data: Buffer) => { device.subscribeToCharacteristic(Consts.BLECharacteristic.LPF2_ALL, (data: Buffer) => {
buf = Buffer.concat([buf, data]); buf = Buffer.concat([buf, data]);
const len = buf[0]; while (buf[0] <= buf.length) {
if (len >= buf.length) { const len = buf[0];
const message = buf.slice(0, len); const message = buf.slice(0, len);
buf = buf.slice(len); buf = buf.slice(len);
if (message[2] === 0x01 && message[3] === 0x0b) { if (message[2] === 0x01 && message[3] === 0x0b) {
process.nextTick(() => { switch (message[5]) {
switch (message[5]) { case Consts.BLEManufacturerData.REMOTE_CONTROL_ID:
case Consts.BLEManufacturerData.REMOTE_CONTROL_ID: resolve(Consts.HubType.REMOTE_CONTROL);
resolve(Consts.HubType.REMOTE_CONTROL); break;
break; case Consts.BLEManufacturerData.MOVE_HUB_ID:
case Consts.BLEManufacturerData.MOVE_HUB_ID: resolve(Consts.HubType.MOVE_HUB);
resolve(Consts.HubType.MOVE_HUB); break;
break; case Consts.BLEManufacturerData.HUB_ID:
case Consts.BLEManufacturerData.HUB_ID: resolve(Consts.HubType.HUB);
resolve(Consts.HubType.HUB); break;
break; case Consts.BLEManufacturerData.DUPLO_TRAIN_BASE_ID:
case Consts.BLEManufacturerData.DUPLO_TRAIN_BASE_ID: resolve(Consts.HubType.DUPLO_TRAIN_BASE);
resolve(Consts.HubType.DUPLO_TRAIN_BASE); break;
break; case Consts.BLEManufacturerData.TECHNIC_MEDIUM_HUB:
case Consts.BLEManufacturerData.TECHNIC_MEDIUM_HUB: resolve(Consts.HubType.TECHNIC_MEDIUM_HUB);
resolve(Consts.HubType.TECHNIC_MEDIUM_HUB); break;
break; }
} debug("Hub type determined");
debug("Hub type determined");
});
} else { } else {
debug("Stashed in mailbox (LPF2_ALL)", message); debug("Stashed in mailbox (LPF2_ALL)", message);
device.addToCharacteristicMailbox(Consts.BLECharacteristic.LPF2_ALL, message); device.addToCharacteristicMailbox(Consts.BLECharacteristic.LPF2_ALL, message);

View File

@ -99,11 +99,14 @@ export class WebBLEDevice extends EventEmitter implements IBLEAbstraction {
return callback(buf); return callback(buf);
}; };
this._characteristics[uuid].addEventListener("characteristicvaluechanged", this._listeners[uuid]); this._characteristics[uuid].addEventListener("characteristicvaluechanged", this._listeners[uuid]);
for (const data of this._mailbox) {
const mailbox = Array.from(this._mailbox);
this._mailbox = [];
for (const data of mailbox) {
debug("Replayed from mailbox (LPF2_ALL)", data); debug("Replayed from mailbox (LPF2_ALL)", data);
callback(data); callback(data);
} }
this._mailbox = [];
this._characteristics[uuid].startNotifications(); this._characteristics[uuid].startNotifications();
} }