-
Notifications
You must be signed in to change notification settings - Fork 58
/
lpf2hub.ts
633 lines (547 loc) · 24.7 KB
/
lpf2hub.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
import { Peripheral } from "@abandonware/noble";
import { Hub } from "./hub";
import { Port } from "./port";
import * as Consts from "./consts";
import { toBin, toHex } from "./utils";
import Debug = require("debug");
const debug = Debug("lpf2hub");
const modeInfoDebug = Debug("lpf2hubmodeinfo");
/**
* @class LPF2Hub
* @extends Hub
*/
export class LPF2Hub extends Hub {
private static decodeVersion(v: number) {
const t = v.toString(16).padStart(8, "0");
return [t[0], t[1], t.substring(2, 4), t.substring(4)].join(".");
}
private static decodeMACAddress(v: Uint8Array) {
return Array.from(v).map((n) => toHex(n, 2)).join(":");
}
protected _ledPort: number = 0x32;
protected _voltagePort: number | undefined;
protected _voltageMaxV: number = 9.6;
protected _voltageMaxRaw: number = 3893;
protected _currentPort: number | undefined;
protected _currentMaxMA: number = 2444;
protected _currentMaxRaw: number = 4095;
private _lastTiltX: number = 0;
private _lastTiltY: number = 0;
private _lastTiltZ: number = 0;
private _messageBuffer: Buffer = Buffer.alloc(0);
public connect () {
return new Promise(async (resolve, reject) => {
await super.connect();
await this._bleDevice.discoverCharacteristicsForService(Consts.BLEService.LPF2_HUB);
this._bleDevice.subscribeToCharacteristic(Consts.BLECharacteristic.LPF2_ALL, this._parseMessage.bind(this));
if (this._voltagePort !== undefined) {
this._writeMessage(Consts.BLECharacteristic.LPF2_ALL, Buffer.from([0x41, this._voltagePort, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01])); // Activate voltage reports
}
if (this._currentPort !== undefined) {
this._writeMessage(Consts.BLECharacteristic.LPF2_ALL, Buffer.from([0x41, this._currentPort, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01])); // Activate current reports
}
if (this.type === Consts.HubType.DUPLO_TRAIN_HUB) {
this._writeMessage(Consts.BLECharacteristic.LPF2_ALL, Buffer.from([0x41, 0x01, 0x01, 0x01, 0x00, 0x00, 0x00, 0x01]));
}
await this.sleep(100);
this._writeMessage(Consts.BLECharacteristic.LPF2_ALL, Buffer.from([0x01, 0x02, 0x02])); // Activate button reports
this._writeMessage(Consts.BLECharacteristic.LPF2_ALL, Buffer.from([0x01, 0x03, 0x05])); // Request firmware version
this._writeMessage(Consts.BLECharacteristic.LPF2_ALL, Buffer.from([0x01, 0x04, 0x05])); // Request hardware version
this._writeMessage(Consts.BLECharacteristic.LPF2_ALL, Buffer.from([0x01, 0x05, 0x02])); // Activate RSSI updates
this._writeMessage(Consts.BLECharacteristic.LPF2_ALL, Buffer.from([0x01, 0x06, 0x02])); // Activate battery level reports
this._writeMessage(Consts.BLECharacteristic.LPF2_ALL, Buffer.from([0x01, 0x0d, 0x05])); // Request primary MAC address
this.emit("connect");
resolve();
});
}
/**
* Shutdown the Hub.
* @method LPF2Hub#shutdown
* @returns {Promise} Resolved upon successful disconnect.
*/
public shutdown () {
return new Promise((resolve, reject) => {
this._writeMessage(Consts.BLECharacteristic.LPF2_ALL, Buffer.from([0x02, 0x01]), () => {
return resolve();
});
});
}
/**
* Set the name of the Hub.
* @method LPF2Hub#setName
* @param {string} name New name of the hub (14 characters or less, ASCII only).
* @returns {Promise} Resolved upon successful issuance of command.
*/
public setName (name: string) {
if (name.length > 14) {
throw new Error("Name must be 14 characters or less");
}
return new Promise((resolve, reject) => {
let data = Buffer.from([0x01, 0x01, 0x01]);
data = Buffer.concat([data, Buffer.from(name, "ascii")]);
// Send this twice, as sometimes the first time doesn't take
this._writeMessage(Consts.BLECharacteristic.LPF2_ALL, data);
this._writeMessage(Consts.BLECharacteristic.LPF2_ALL, data);
this._name = name;
return resolve();
});
}
/**
* Set the color of the LED on the Hub via a color value.
* @method LPF2Hub#setLEDColor
* @param {Color} color
* @returns {Promise} Resolved upon successful issuance of command.
*/
public setLEDColor (color: number | boolean) {
return new Promise((resolve, reject) => {
let data = Buffer.from([0x41, this._ledPort, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00]);
this._writeMessage(Consts.BLECharacteristic.LPF2_ALL, data);
if (typeof color === "boolean") {
color = 0;
}
data = Buffer.from([0x81, this._ledPort, 0x11, 0x51, 0x00, color]);
this._writeMessage(Consts.BLECharacteristic.LPF2_ALL, data);
return resolve();
});
}
/**
* Set the color of the LED on the Hub via RGB values.
* @method LPF2Hub#setLEDRGB
* @param {number} red
* @param {number} green
* @param {number} blue
* @returns {Promise} Resolved upon successful issuance of command.
*/
public setLEDRGB (red: number, green: number, blue: number) {
return new Promise((resolve, reject) => {
let data = Buffer.from([0x41, this._ledPort, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00]);
this._writeMessage(Consts.BLECharacteristic.LPF2_ALL, data);
data = Buffer.from([0x81, this._ledPort, 0x11, 0x51, 0x01, red, green, blue]);
this._writeMessage(Consts.BLECharacteristic.LPF2_ALL, data);
return resolve();
});
}
public sendRaw (message: Buffer) {
return new Promise((resolve, reject) => {
this._writeMessage(Consts.BLECharacteristic.LPF2_ALL, message, () => {
return resolve();
});
});
}
protected _activatePortDevice (port: number, type: number, mode: number, format: number, callback?: () => void) {
this._writeMessage(Consts.BLECharacteristic.LPF2_ALL, Buffer.from([0x41, port, mode, 0x01, 0x00, 0x00, 0x00, 0x01]), callback);
}
protected _deactivatePortDevice (port: number, type: number, mode: number, format: number, callback?: () => void) {
this._writeMessage(Consts.BLECharacteristic.LPF2_ALL, Buffer.from([0x41, port, mode, 0x01, 0x00, 0x00, 0x00, 0x00]), callback);
}
protected _writeMessage (uuid: string, message: Buffer, callback?: () => void) {
message = Buffer.concat([Buffer.alloc(2), message]);
message[0] = message.length;
debug("Sent Message (LPF2_ALL)", message);
this._bleDevice.writeToCharacteristic(uuid, message, callback);
}
protected _combinePorts (port: string, type: number) {
if (!this._ports[port]) {
return;
}
const portObj = this._portLookup(port);
if (portObj) {
Object.keys(this._ports).forEach((id) => {
if (this._ports[id].type === type && this._ports[id].value !== portObj.value && !this._virtualPorts[`${portObj.value < this._ports[id].value ? portObj.id : this._ports[id].id}${portObj.value > this._ports[id].value ? portObj.id : this._ports[id].id}`]) {
debug("Combining ports", portObj.value < this._ports[id].value ? portObj.id : id, portObj.value > this._ports[id].value ? portObj.id : id);
this._writeMessage(Consts.BLECharacteristic.LPF2_ALL, Buffer.from([0x61, 0x01, portObj.value < this._ports[id].value ? portObj.value : this._ports[id].value, portObj.value > this._ports[id].value ? portObj.value : this._ports[id].value]));
}
});
}
}
protected _checkFirmware (version: string) {
return;
}
private _parseMessage (data?: Buffer) {
if (data) {
this._messageBuffer = Buffer.concat([this._messageBuffer, data]);
}
if (this._messageBuffer.length <= 0) {
return;
}
const len = this._messageBuffer[0];
if (len >= this._messageBuffer.length) {
const message = this._messageBuffer.slice(0, len);
this._messageBuffer = this._messageBuffer.slice(len);
debug("Received Message (LPF2_ALL)", message);
switch (message[2]) {
case 0x01: {
this._parseDeviceInfo(message);
break;
}
case 0x04: {
this._parsePortMessage(message);
break;
}
case 0x43: {
this._parsePortInformationResponse(message);
break;
}
case 0x44: {
this._parseModeInformationResponse(message);
break;
}
case 0x45: {
this._parseSensorMessage(message);
break;
}
case 0x82: {
this._parsePortAction(message);
break;
}
}
if (this._messageBuffer.length > 0) {
this._parseMessage();
}
}
}
private _parseDeviceInfo (data: Buffer) {
// Button press reports
if (data[3] === 0x02) {
if (data[5] === 1) {
/**
* Emits when a button is pressed.
* @event LPF2Hub#button
* @param {string} button
* @param {ButtonState} state
*/
this.emit("button", "GREEN", Consts.ButtonState.PRESSED);
return;
} else if (data[5] === 0) {
this.emit("button", "GREEN", Consts.ButtonState.RELEASED);
return;
}
// Firmware version
} else if (data[3] === 0x03) {
this._firmwareVersion = LPF2Hub.decodeVersion(data.readInt32LE(5));
this._checkFirmware(this._firmwareVersion);
// Hardware version
} else if (data[3] === 0x04) {
this._hardwareVersion = LPF2Hub.decodeVersion(data.readInt32LE(5));
// RSSI update
} else if (data[3] === 0x05) {
const rssi = data.readInt8(5);
if (rssi !== 0) {
this._rssi = rssi;
this.emit("rssiChange", this._rssi);
}
// primary MAC Address
} else if (data[3] === 0x0d) {
this._primaryMACAddress = LPF2Hub.decodeMACAddress(data.slice(5));
// Battery level reports
} else if (data[3] === 0x06) {
this._batteryLevel = data[5];
}
}
private _parsePortMessage (data: Buffer) {
let port = this._getPortForPortNumber(data[3]);
const type = data[4] ? data.readUInt16LE(5) : 0;
if (data[4] === 0x01 && modeInfoDebug.enabled) {
const typeName = Consts.DeviceTypeNames[data[5]] || "unknown";
modeInfoDebug(`Port ${toHex(data[3])}, type ${toHex(type, 4)} (${typeName})`);
const hwVersion = LPF2Hub.decodeVersion(data.readInt32LE(7));
const swVersion = LPF2Hub.decodeVersion(data.readInt32LE(11));
modeInfoDebug(`Port ${toHex(data[3])}, hardware version ${hwVersion}, software version ${swVersion}`);
this._sendPortInformationRequest(data[3]);
}
if (!port) {
if (data[4] === 0x02) {
const portA = this._getPortForPortNumber(data[7]);
const portB = this._getPortForPortNumber(data[8]);
if (portA && portB) {
this._virtualPorts[`${portA.id}${portB.id}`] = new Port(`${portA.id}${portB.id}`, data[3]);
port = this._getPortForPortNumber(data[3]);
if (port) {
port.connected = true;
this._registerDeviceAttachment(port, type);
} else {
return;
}
} else {
return;
}
} else {
return;
}
} else {
port.connected = (data[4] === 0x01 || data[4] === 0x02) ? true : false;
this._registerDeviceAttachment(port, type);
}
}
private _sendPortInformationRequest (port: number) {
this._writeMessage(Consts.BLECharacteristic.LPF2_ALL, Buffer.from([0x21, port, 0x01]));
this._writeMessage(Consts.BLECharacteristic.LPF2_ALL, Buffer.from([0x21, port, 0x02])); // Mode combinations
}
private _parsePortInformationResponse (data: Buffer) {
const port = data[3];
if (data[4] === 2) {
const modeCombinationMasks: number[] = [];
for (let i = 5; i < data.length; i += 2) {
modeCombinationMasks.push(data.readUInt16LE(i));
}
modeInfoDebug(`Port ${toHex(port)}, mode combinations [${modeCombinationMasks.map((c) => toBin(c, 0)).join(", ")}]`);
return;
}
const count = data[6];
const input = toBin(data.readUInt16LE(7), count);
const output = toBin(data.readUInt16LE(9), count);
modeInfoDebug(`Port ${toHex(port)}, total modes ${count}, input modes ${input}, output modes ${output}`);
for (let i = 0; i < count; i++) {
this._sendModeInformationRequest(port, i, 0x00); // Mode Name
this._sendModeInformationRequest(port, i, 0x01); // RAW Range
this._sendModeInformationRequest(port, i, 0x02); // PCT Range
this._sendModeInformationRequest(port, i, 0x03); // SI Range
this._sendModeInformationRequest(port, i, 0x04); // SI Symbol
this._sendModeInformationRequest(port, i, 0x80); // Value Format
}
}
private _sendModeInformationRequest (port: number, mode: number, type: number) {
this._writeMessage(Consts.BLECharacteristic.LPF2_ALL, Buffer.from([0x22, port, mode, type]));
}
private _parseModeInformationResponse (data: Buffer) {
const port = toHex(data[3]);
const mode = data[4];
const type = data[5];
switch (type) {
case 0x00: // Mode Name
modeInfoDebug(`Port ${port}, mode ${mode}, name ${data.slice(6, data.length).toString()}`);
break;
case 0x01: // RAW Range
modeInfoDebug(`Port ${port}, mode ${mode}, RAW min ${data.readFloatLE(6)}, max ${data.readFloatLE(10)}`);
break;
case 0x02: // PCT Range
modeInfoDebug(`Port ${port}, mode ${mode}, PCT min ${data.readFloatLE(6)}, max ${data.readFloatLE(10)}`);
break;
case 0x03: // SI Range
modeInfoDebug(`Port ${port}, mode ${mode}, SI min ${data.readFloatLE(6)}, max ${data.readFloatLE(10)}`);
break;
case 0x04: // SI Symbol
modeInfoDebug(`Port ${port}, mode ${mode}, SI symbol ${data.slice(6, data.length).toString()}`);
break;
case 0x80: // Value Format
const numValues = data[6];
const dataType = ["8bit", "16bit", "32bit", "float"][data[7]];
const totalFigures = data[8];
const decimals = data[9];
modeInfoDebug(`Port ${port}, mode ${mode}, Value ${numValues} x ${dataType}, Decimal format ${totalFigures}.${decimals}`);
}
}
private _parsePortAction (data: Buffer) {
const port = this._getPortForPortNumber(data[3]);
if (!port) {
return;
}
if (data[4] === 0x0a) {
port.busy = false;
if (port.finished) {
port.finished();
port.finished = null;
}
}
}
private _parseSensorMessage (data: Buffer) {
if (data[3] === this._voltagePort) {
const voltageRaw = data.readUInt16LE(4);
this._voltage = voltageRaw * this._voltageMaxV / this._voltageMaxRaw;
return;
} else if (data[3] === this._currentPort) {
const currentRaw = data.readUInt16LE(4);
this._current = this._currentMaxMA * currentRaw / this._currentMaxRaw;
return;
}
if ((data[3] === 0x3d && this.type === Consts.HubType.CONTROL_PLUS_HUB)) { // Control+ CPU Temperature
/**
* Emits when a change is detected on a temperature sensor. Measured in degrees centigrade.
* @event LPF2Hub#temp
* @param {string} port For Control+ Hubs, port will be "CPU" as the sensor reports CPU temperature.
* @param {number} temp
*/
this.emit("temp", "CPU", ((data.readInt16LE(4) / 900) * 90).toFixed(2));
return;
}
const port = this._getPortForPortNumber(data[3]);
if (!port) {
return;
}
if (port && port.connected) {
switch (port.type) {
case Consts.DeviceType.WEDO2_DISTANCE: {
let distance = data[4];
if (data[5] === 1) {
distance = data[4] + 255;
}
/**
* Emits when a distance sensor is activated.
* @event LPF2Hub#distance
* @param {string} port
* @param {number} distance Distance, in millimeters.
*/
this.emit("distance", port.id, distance * 10);
break;
}
case Consts.DeviceType.BOOST_DISTANCE: {
/**
* Emits when a color sensor is activated.
* @event LPF2Hub#color
* @param {string} port
* @param {Color} color
*/
if (data[4] <= 10) {
this.emit("color", port.id, data[4]);
}
let distance = data[5];
const partial = data[7];
if (partial > 0) {
distance += 1.0 / partial;
}
distance = Math.floor(distance * 25.4) - 20;
this.emit("distance", port.id, distance);
/**
* A combined color and distance event, emits when the sensor is activated.
* @event LPF2Hub#colorAndDistance
* @param {string} port
* @param {Color} color
* @param {number} distance Distance, in millimeters.
*/
if (data[4] <= 10) {
this.emit("colorAndDistance", port.id, data[4], distance);
}
break;
}
case Consts.DeviceType.WEDO2_TILT: {
const tiltX = data.readInt8(4);
const tiltY = data.readInt8(5);
this._lastTiltX = tiltX;
this._lastTiltY = tiltY;
/**
* Emits when a tilt sensor is activated.
* @event LPF2Hub#tilt
* @param {string} port If the event is fired from the Move Hub or Control+ Hub's in-built tilt sensor, the special port "TILT" is used.
* @param {number} x
* @param {number} y
* @param {number} z (Only available when using a Control+ Hub)
*/
this.emit("tilt", port.id, this._lastTiltX, this._lastTiltY, this._lastTiltZ);
break;
}
case Consts.DeviceType.BOOST_TACHO_MOTOR: {
const rotation = data.readInt32LE(4);
/**
* Emits when a rotation sensor is activated.
* @event LPF2Hub#rotate
* @param {string} port
* @param {number} rotation
*/
this.emit("rotate", port.id, rotation);
break;
}
case Consts.DeviceType.BOOST_MOVE_HUB_MOTOR: {
const rotation = data.readInt32LE(4);
this.emit("rotate", port.id, rotation);
break;
}
case Consts.DeviceType.CONTROL_PLUS_LARGE_MOTOR: {
const rotation = data.readInt32LE(4);
this.emit("rotate", port.id, rotation);
break;
}
case Consts.DeviceType.CONTROL_PLUS_XLARGE_MOTOR: {
const rotation = data.readInt32LE(4);
this.emit("rotate", port.id, rotation);
break;
}
case Consts.DeviceType.CONTROL_PLUS_TILT: {
const tiltZ = data.readInt16LE(4);
const tiltY = data.readInt16LE(6);
const tiltX = data.readInt16LE(8);
this._lastTiltX = tiltX;
this._lastTiltY = tiltY;
this._lastTiltZ = tiltZ;
this.emit("tilt", "TILT", this._lastTiltX, this._lastTiltY, this._lastTiltZ);
break;
}
case Consts.DeviceType.CONTROL_PLUS_GYRO: {
const gyroX = Math.round(data.readInt16LE(4) * 7 / 400);
const gyroY = Math.round(data.readInt16LE(6) * 7 / 400);
const gyroZ = Math.round(data.readInt16LE(8) * 7 / 400);
/**
* Emits when gyroscope detects movement. Measured in DPS - degrees per second.
* @event LPF2Hub#gyro
* @param {string} port
* @param {number} x
* @param {number} y
* @param {number} z
*/
this.emit("gyro", "GYRO", gyroX, gyroY, gyroZ);
break;
}
case Consts.DeviceType.CONTROL_PLUS_ACCELEROMETER: {
const accelX = Math.round(data.readInt16LE(4) / 4.096);
const accelY = Math.round(data.readInt16LE(6) / 4.096);
const accelZ = Math.round(data.readInt16LE(8) / 4.096);
/**
* Emits when accelerometer detects movement. Measured in mG.
* @event LPF2Hub#accel
* @param {string} port
* @param {number} x
* @param {number} y
* @param {number} z
*/
this.emit("accel", "ACCEL", accelX, accelY, accelZ);
break;
}
case Consts.DeviceType.BOOST_TILT: {
const tiltX = data.readInt8(4);
const tiltY = data.readInt8(5);
this._lastTiltX = tiltX;
this._lastTiltY = tiltY;
this.emit("tilt", port.id, this._lastTiltX, this._lastTiltY, this._lastTiltZ);
break;
}
case Consts.DeviceType.POWERED_UP_REMOTE_BUTTON: {
switch (data[4]) {
case 0x01: {
this.emit("button", port.id, Consts.ButtonState.UP);
break;
}
case 0xff: {
this.emit("button", port.id, Consts.ButtonState.DOWN);
break;
}
case 0x7f: {
this.emit("button", port.id, Consts.ButtonState.STOP);
break;
}
case 0x00: {
this.emit("button", port.id, Consts.ButtonState.RELEASED);
break;
}
}
break;
}
case Consts.DeviceType.DUPLO_TRAIN_BASE_COLOR: {
if (data[4] <= 10) {
this.emit("color", port.id, data[4]);
}
break;
}
case Consts.DeviceType.DUPLO_TRAIN_BASE_SPEEDOMETER: {
/**
* Emits on a speed change.
* @event LPF2Hub#speed
* @param {string} port
* @param {number} speed
*/
const speed = data.readInt16LE(4);
this.emit("speed", port.id, speed);
break;
}
}
}
}
}