homebridge-dyson-solarcycle-morph 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/CHANGELOG.md +52 -0
  2. package/LICENSE +22 -0
  3. package/README.md +259 -0
  4. package/config.schema.json +118 -0
  5. package/dist/accessory.d.ts +41 -0
  6. package/dist/accessory.js +129 -0
  7. package/dist/accessory.js.map +1 -0
  8. package/dist/cli/pair.d.ts +2 -0
  9. package/dist/cli/pair.js +144 -0
  10. package/dist/cli/pair.js.map +1 -0
  11. package/dist/config.d.ts +51 -0
  12. package/dist/config.js +32 -0
  13. package/dist/config.js.map +1 -0
  14. package/dist/dyson/cloud.d.ts +67 -0
  15. package/dist/dyson/cloud.js +147 -0
  16. package/dist/dyson/cloud.js.map +1 -0
  17. package/dist/dyson/credentials.d.ts +32 -0
  18. package/dist/dyson/credentials.js +73 -0
  19. package/dist/dyson/credentials.js.map +1 -0
  20. package/dist/dyson/crypto.d.ts +38 -0
  21. package/dist/dyson/crypto.js +98 -0
  22. package/dist/dyson/crypto.js.map +1 -0
  23. package/dist/dyson/debounce.d.ts +33 -0
  24. package/dist/dyson/debounce.js +59 -0
  25. package/dist/dyson/debounce.js.map +1 -0
  26. package/dist/dyson/lamp.d.ts +193 -0
  27. package/dist/dyson/lamp.js +692 -0
  28. package/dist/dyson/lamp.js.map +1 -0
  29. package/dist/dyson/protocol.d.ts +91 -0
  30. package/dist/dyson/protocol.js +156 -0
  31. package/dist/dyson/protocol.js.map +1 -0
  32. package/dist/dyson/queue.d.ts +24 -0
  33. package/dist/dyson/queue.js +51 -0
  34. package/dist/dyson/queue.js.map +1 -0
  35. package/dist/dyson/reconcile.d.ts +38 -0
  36. package/dist/dyson/reconcile.js +30 -0
  37. package/dist/dyson/reconcile.js.map +1 -0
  38. package/dist/dyson/settle.d.ts +30 -0
  39. package/dist/dyson/settle.js +56 -0
  40. package/dist/dyson/settle.js.map +1 -0
  41. package/dist/errors.d.ts +8 -0
  42. package/dist/errors.js +20 -0
  43. package/dist/errors.js.map +1 -0
  44. package/dist/index.d.ts +4 -0
  45. package/dist/index.js +7 -0
  46. package/dist/index.js.map +1 -0
  47. package/dist/platform.d.ts +27 -0
  48. package/dist/platform.js +106 -0
  49. package/dist/platform.js.map +1 -0
  50. package/dist/settings.d.ts +4 -0
  51. package/dist/settings.js +5 -0
  52. package/dist/settings.js.map +1 -0
  53. package/docs/PROTOCOL.md +153 -0
  54. package/homebridge-ui/public/index.html +396 -0
  55. package/homebridge-ui/server.js +297 -0
  56. package/package.json +68 -0
  57. package/tools/ble-probe.js +132 -0
@@ -0,0 +1,692 @@
1
+ /**
2
+ * BLE transport and session management for a single Morph lamp.
3
+ *
4
+ * Owns the BlueZ connection, runs the LTK handshake after every reconnect, and
5
+ * exposes the lamp as a small state machine with cached state. All GATT traffic
6
+ * is serialised through one queue: BlueZ will happily return `InProgress` or
7
+ * drop replies if two D-Bus calls overlap on the same characteristic.
8
+ */
9
+ import { describeError } from '../errors.js';
10
+ import { EventEmitter } from 'node:events';
11
+ import { randomBytes } from 'node:crypto';
12
+ import { Variant } from 'dbus-next';
13
+ import { createBluetooth } from 'node-ble';
14
+ import { buildReauthPayloadA, buildReauthPayloadC, deriveAesKey, parseReauthPayloadB } from './crypto.js';
15
+ import { Debouncer } from './debounce.js';
16
+ import { OperationQueue } from './queue.js';
17
+ import { planReconciliation } from './reconcile.js';
18
+ import { SettleWindow } from './settle.js';
19
+ import { CHAR_AUTH, CHAR_BRIGHTNESS_LM, CHAR_COLOR_TEMP, CHAR_MOTION, CHAR_POWER, CHAR_WRITE_ATTR, DAYLIGHT_MODE_DISABLE, MAX_KELVIN, MessageAssembler, MIN_KELVIN, MsgType, fragmentMessage, lumensToPercent, percentToLumens, } from './protocol.js';
20
+ /** Characteristics we look for. Anything else the lamp exposes is ignored. */
21
+ const WANTED_CHARACTERISTICS = new Set([
22
+ CHAR_AUTH,
23
+ CHAR_POWER,
24
+ CHAR_BRIGHTNESS_LM,
25
+ CHAR_COLOR_TEMP,
26
+ CHAR_WRITE_ATTR,
27
+ CHAR_MOTION,
28
+ ]);
29
+ /** Without these there is no point continuing. */
30
+ const REQUIRED_CHARACTERISTICS = [CHAR_AUTH, CHAR_POWER];
31
+ /**
32
+ * Delays between reconnect attempts; the last value repeats.
33
+ *
34
+ * The long tail is deliberate. The lamp can reach a state where it advertises
35
+ * normally but refuses every connection, and only losing power clears it.
36
+ * Retrying every minute indefinitely will not fix that and gives it no quiet,
37
+ * so attempts thin out instead of hammering.
38
+ */
39
+ const RECONNECT_BACKOFF_MS = [2_000, 5_000, 15_000, 30_000, 60_000, 120_000, 300_000];
40
+ /** Consecutive failures after which the log suggests what actually helps. */
41
+ const STUCK_AFTER_ATTEMPTS = 8;
42
+ /** How long to scan for a lamp BlueZ has never seen. */
43
+ const DISCOVERY_TIMEOUT_MS = 30_000;
44
+ /** Pause after starting a scan before the first connect attempt. */
45
+ const DISCOVERY_SETTLE_MS = 3_000;
46
+ /**
47
+ * Connect attempts per reconnect cycle, and the gap between them.
48
+ *
49
+ * Measured over repeated runs: a single attempt succeeds roughly two times in
50
+ * three even under the best conditions, and no arrangement of scanning and
51
+ * waiting does better. Individual attempts are cheap, so several in quick
52
+ * succession are worth far more than a cleverer single one — four of them put
53
+ * a cycle above 98%.
54
+ */
55
+ const CONNECT_ATTEMPTS = 4;
56
+ const CONNECT_RETRY_MS = 1_500;
57
+ /** The lamp can take a while to answer the first handshake message. */
58
+ const HANDSHAKE_TIMEOUT_MS = 30_000;
59
+ /**
60
+ * Re-assert manual mode if the last write was longer ago than this. Doing it
61
+ * before every command wastes a write; never doing it means the lamp ignores us
62
+ * after someone used the physical daylight button.
63
+ */
64
+ const MANUAL_MODE_TTL_MS = 60_000;
65
+ /** The lamp needs a moment to apply a mode change before the next write. */
66
+ const MODE_SETTLE_MS = 200;
67
+ /** Signal strength worth warning about, so a weak link is visible in the log. */
68
+ const WEAK_RSSI_DBM = -80;
69
+ /**
70
+ * How long to wait for a slider to settle before writing. HomeKit emits several
71
+ * values a second while dragging; only the one it stops on matters.
72
+ */
73
+ const WRITE_DEBOUNCE_MS = 400;
74
+ /**
75
+ * How long after the last command to check the lamp agrees. Verification cannot
76
+ * sit in the command's own path: the write costs a millisecond, reading it back
77
+ * costs hundreds.
78
+ */
79
+ const RECONCILE_DELAY_MS = 900;
80
+ /**
81
+ * How long to disregard the lamp's own reports about a value just commanded.
82
+ * It ramps rather than jumping, and those steps are the command happening, not
83
+ * news worth publishing.
84
+ */
85
+ const SETTLE_MS = 3_000;
86
+ const noopLog = {
87
+ debug: () => { },
88
+ info: () => { },
89
+ warn: () => { },
90
+ error: () => { },
91
+ };
92
+ export class DysonMorphLamp extends EventEmitter {
93
+ mac;
94
+ aesKey;
95
+ accountId;
96
+ adapterName;
97
+ log;
98
+ bluetooth;
99
+ adapter;
100
+ device;
101
+ chars = {};
102
+ /** Per-characteristic write mode, derived from the flags the lamp advertises. */
103
+ writeTypes = {};
104
+ assembler = new MessageAssembler();
105
+ waiters = new Map();
106
+ /** Serialises all GATT access. */
107
+ operations = new OperationQueue();
108
+ writes = new Debouncer(WRITE_DEBOUNCE_MS, (task, key) => this.enqueue(task, key));
109
+ reconciles = new Debouncer(RECONCILE_DELAY_MS, (task, key) => this.enqueue(task, key));
110
+ settling = new SettleWindow(SETTLE_MS);
111
+ /** Whether the running scan is one we started and must clean up. */
112
+ discoveryIsOurs = false;
113
+ /** So the "try power-cycling" hint is given once, not on every attempt. */
114
+ hintedStuck = false;
115
+ running = false;
116
+ connected = false;
117
+ reconnectAttempt = 0;
118
+ reconnectTimer;
119
+ manualModeSetAt = 0;
120
+ state = { on: false, brightness: 100, kelvin: 2700 };
121
+ /** What the user last asked for. Reconciliation aims at this, not at guesses. */
122
+ desired = {};
123
+ constructor(options) {
124
+ super();
125
+ this.mac = options.mac.toUpperCase();
126
+ this.aesKey = deriveAesKey(Buffer.from(options.ltk.replace(/[^0-9a-fA-F]/g, ''), 'hex'));
127
+ this.accountId = options.accountId;
128
+ this.adapterName = options.adapter;
129
+ this.log = options.log ?? noopLog;
130
+ }
131
+ /** Last known state. Updated by notifications and polling. */
132
+ getState() {
133
+ return this.state;
134
+ }
135
+ isConnected() {
136
+ return this.connected;
137
+ }
138
+ /** Begin connecting, and keep reconnecting until {@link stop} is called. */
139
+ async start() {
140
+ if (this.running) {
141
+ return;
142
+ }
143
+ this.running = true;
144
+ this.bluetooth = createBluetooth();
145
+ // dbus-next emits socket failures on the bus itself rather than rejecting
146
+ // the call in flight, and an unhandled 'error' event would take Homebridge
147
+ // down with it. Treat it as a lost link and let the backoff handle it.
148
+ const bus = this.bluetooth.bluetooth.dbus;
149
+ bus?.on('error', (error) => {
150
+ this.log.error(`D-Bus error talking to BlueZ: ${describeError(error)}`);
151
+ this.handleDisconnect();
152
+ });
153
+ this.adapter = this.adapterName
154
+ ? await this.bluetooth.bluetooth.getAdapter(this.adapterName)
155
+ : await this.bluetooth.bluetooth.defaultAdapter();
156
+ void this.connectLoop();
157
+ }
158
+ /** Disconnect and release the D-Bus connection. */
159
+ async stop() {
160
+ this.running = false;
161
+ clearTimeout(this.reconnectTimer);
162
+ await this.teardown();
163
+ try {
164
+ this.bluetooth?.destroy();
165
+ }
166
+ catch (error) {
167
+ this.log.debug(`Releasing the D-Bus connection failed: ${describeError(error)}`);
168
+ }
169
+ this.bluetooth = undefined;
170
+ this.adapter = undefined;
171
+ }
172
+ async setPower(on) {
173
+ // Turning the lamp on or off is the one command that must feel immediate,
174
+ // so anything still queued behind a slider drag is dropped rather than
175
+ // made to run first: those values are about to be overtaken anyway, and
176
+ // waiting for them is what made switching off take seconds.
177
+ this.requireConnection();
178
+ this.desired = { ...this.desired, on };
179
+ this.settling.hold('on');
180
+ this.patchState({ on });
181
+ const requestedAt = Date.now();
182
+ const queued = this.operations.depth;
183
+ // Power overrides everything: drop the slider values still waiting, which
184
+ // nobody will see once the lamp is switching.
185
+ this.writes.cancelAll();
186
+ this.reconciles.cancelAll();
187
+ this.operations.cancelQueued();
188
+ await this.enqueue(async () => {
189
+ const waited = Date.now() - requestedAt;
190
+ await this.write(CHAR_POWER, Buffer.from([on ? 0x01 : 0x00]));
191
+ this.log.debug(`Power ${on ? 'on' : 'off'} took ${Date.now() - requestedAt}ms (${waited}ms waiting behind ${queued} queued)`);
192
+ });
193
+ this.scheduleReconcile();
194
+ }
195
+ /** @param percent HomeKit brightness, 0-100 %. */
196
+ async setBrightness(percent) {
197
+ const lumens = percentToLumens(percent);
198
+ this.log.debug(`Brightness ${percent}% requested (${this.operations.depth} queued)`);
199
+ this.requireConnection();
200
+ this.desired = { ...this.desired, brightness: lumensToPercent(lumens) };
201
+ this.settling.hold('brightness');
202
+ this.patchState({ brightness: lumensToPercent(lumens) });
203
+ // Not reconciled: the lamp adjusts brightness to track daylight, so a value
204
+ // that differs from what was asked for is the lamp working, not a command
205
+ // that went missing.
206
+ await this.writes.schedule(CHAR_BRIGHTNESS_LM, () => this.writeUint16(CHAR_BRIGHTNESS_LM, lumens));
207
+ }
208
+ async setColorTemperature(kelvin) {
209
+ const clamped = Math.min(MAX_KELVIN, Math.max(MIN_KELVIN, Math.round(kelvin)));
210
+ this.requireConnection();
211
+ this.desired = { ...this.desired, kelvin: clamped };
212
+ this.settling.hold('kelvin');
213
+ this.patchState({ kelvin: clamped });
214
+ // Not reconciled: a colour temperature that lands slightly off is invisible,
215
+ // and checking it would cost a read on a link that is not always there.
216
+ await this.writes.schedule(CHAR_COLOR_TEMP, () => this.writeUint16(CHAR_COLOR_TEMP, clamped));
217
+ }
218
+ async writeUint16(uuid, value) {
219
+ await this.ensureManualMode();
220
+ const buffer = Buffer.alloc(2);
221
+ buffer.writeUInt16LE(value);
222
+ await this.write(uuid, buffer);
223
+ }
224
+ /**
225
+ * Check the lamp ended up where it was asked to, once commands stop arriving.
226
+ *
227
+ * Control writes are unacknowledged — the characteristics offer no `write`
228
+ * flag at all — so one can be dropped with nothing to say so. The lamp
229
+ * notifies on change, but a lost write changes nothing and therefore notifies
230
+ * nothing, which is exactly the case that leaves HomeKit showing a state the
231
+ * lamp is not in. Checking once at the end costs one read of each value
232
+ * instead of one per command, and none of it in the path the user waits on.
233
+ */
234
+ scheduleReconcile() {
235
+ void this.reconciles
236
+ .schedule('reconcile', () => this.reconcile())
237
+ .catch((error) => this.log.debug(`Reconcile failed: ${describeError(error)}`));
238
+ }
239
+ /**
240
+ * Refuse a command there is no way to deliver.
241
+ *
242
+ * Holding it until the link returns sounds helpful and is not: the lamp is
243
+ * already reported as unreachable, so the user knows it did not happen, and
244
+ * replaying a handful of presses minutes later switches the lamp around on
245
+ * its own. Failing plainly leaves them in control.
246
+ */
247
+ requireConnection() {
248
+ if (!this.connected) {
249
+ throw new Error(`${this.mac} is not connected`);
250
+ }
251
+ }
252
+ async reconcile() {
253
+ if (!this.connected) {
254
+ return;
255
+ }
256
+ const actual = await this.readState();
257
+ const { corrections, missed } = planReconciliation(this.desired, actual);
258
+ if (corrections.length === 0) {
259
+ this.publishFromLamp(actual);
260
+ return;
261
+ }
262
+ for (const correction of corrections) {
263
+ switch (correction.field) {
264
+ case 'on':
265
+ await this.write(CHAR_POWER, Buffer.from([correction.value ? 0x01 : 0x00]));
266
+ break;
267
+ }
268
+ }
269
+ this.log.info(`${this.mac} did not apply ${missed.join(', ')} — resent`);
270
+ // Publish what the lamp reports rather than what was asked for, so HomeKit
271
+ // stops claiming something untrue if the resend does not land either.
272
+ this.publishFromLamp(await this.readState());
273
+ }
274
+ // ---------------------------------------------------------------- internals
275
+ async connectLoop() {
276
+ while (this.running && !this.connected) {
277
+ try {
278
+ await this.connectOnce();
279
+ this.reconnectAttempt = 0;
280
+ this.hintedStuck = false;
281
+ return;
282
+ }
283
+ catch (error) {
284
+ if (!this.running) {
285
+ return;
286
+ }
287
+ const delay = RECONNECT_BACKOFF_MS[Math.min(this.reconnectAttempt, RECONNECT_BACKOFF_MS.length - 1)];
288
+ this.reconnectAttempt++;
289
+ this.log.warn(`Connection to ${this.mac} failed (attempt ${this.reconnectAttempt}): ${describeError(error)}. Retrying in ${delay / 1000}s.`);
290
+ if (this.reconnectAttempt >= STUCK_AFTER_ATTEMPTS && !this.hintedStuck) {
291
+ this.hintedStuck = true;
292
+ this.log.warn(`${this.mac} keeps refusing connections while still advertising. The lamp's Bluetooth ` +
293
+ 'stack gets stuck like this occasionally; disconnecting it from power for ten seconds ' +
294
+ 'clears it. Retries continue in the meantime, more slowly.');
295
+ }
296
+ await this.teardown();
297
+ await sleep(delay);
298
+ }
299
+ }
300
+ }
301
+ async connectOnce() {
302
+ const adapter = this.adapter;
303
+ if (!adapter) {
304
+ throw new Error('Bluetooth adapter is not available');
305
+ }
306
+ this.device = await this.connectDevice(adapter);
307
+ this.device.on('disconnect', () => this.handleDisconnect());
308
+ await this.discoverCharacteristics(await this.device.gatt());
309
+ const auth = this.characteristic(CHAR_AUTH);
310
+ auth.on('valuechanged', (buffer) => this.handleAuthFragment(buffer));
311
+ await auth.startNotifications();
312
+ await this.authenticate();
313
+ const motion = this.chars[CHAR_MOTION];
314
+ if (motion) {
315
+ motion.on('valuechanged', (buffer) => this.emit('motion', buffer.some((b) => b !== 0)));
316
+ await motion.startNotifications().catch((error) => {
317
+ this.log.debug(`Motion notifications unavailable: ${describeError(error)}`);
318
+ });
319
+ }
320
+ await this.stopOurDiscovery();
321
+ this.connected = true;
322
+ this.manualModeSetAt = 0;
323
+ this.settling.clear();
324
+ await this.refreshState();
325
+ // The lamp is the authority on where it is. Anything asked for before the
326
+ // link dropped is history, and aiming at it would have reconciliation
327
+ // "correct" the lamp to a state nobody is asking for any more.
328
+ this.desired = { ...this.state };
329
+ await this.subscribeToState();
330
+ this.log.info(`Connected to Dyson Morph at ${this.mac} — ${describeState(this.state)}`);
331
+ await this.reportSignalStrength();
332
+ this.emit('connected');
333
+ }
334
+ /**
335
+ * Connect, with a scan running, retrying briskly.
336
+ *
337
+ * Two things came out of measuring this. A scan has to be running and must
338
+ * stay running through the connect — stopping it first roughly halves the
339
+ * success rate. And no arrangement is reliable: the best managed two
340
+ * successes in three, so the answer is repetition rather than a cleverer
341
+ * sequence.
342
+ */
343
+ async connectDevice(adapter) {
344
+ if (!(await adapter.isDiscovering())) {
345
+ await adapter.startDiscovery();
346
+ this.discoveryIsOurs = true;
347
+ this.log.debug(`Scanning for ${this.mac}`);
348
+ await sleep(DISCOVERY_SETTLE_MS);
349
+ }
350
+ const device = await adapter.waitDevice(this.mac, DISCOVERY_TIMEOUT_MS);
351
+ await this.markTrusted(device);
352
+ let lastError;
353
+ for (let attempt = 1; attempt <= CONNECT_ATTEMPTS; attempt++) {
354
+ try {
355
+ await device.connect();
356
+ if (attempt > 1) {
357
+ this.log.debug(`Connected to ${this.mac} on attempt ${attempt}`);
358
+ }
359
+ return device;
360
+ }
361
+ catch (error) {
362
+ lastError = error;
363
+ if (attempt < CONNECT_ATTEMPTS) {
364
+ await sleep(CONNECT_RETRY_MS);
365
+ }
366
+ }
367
+ }
368
+ throw lastError;
369
+ }
370
+ /**
371
+ * Stop the scan we started, now that it has served its purpose.
372
+ *
373
+ * Leaving it running makes the radio time-slice between scan windows and
374
+ * connection events for as long as the session lasts.
375
+ */
376
+ async stopOurDiscovery() {
377
+ if (!this.discoveryIsOurs || !this.adapter) {
378
+ return;
379
+ }
380
+ this.discoveryIsOurs = false;
381
+ await this.adapter.stopDiscovery().catch((error) => {
382
+ this.log.debug(`Could not stop discovery: ${describeError(error)}`);
383
+ });
384
+ }
385
+ /**
386
+ * Ask BlueZ to hold on to this device.
387
+ *
388
+ * An untrusted, unbonded device is dropped from the cache once it is neither
389
+ * connected nor being discovered, and the address then stops resolving at all
390
+ * — `bluetoothctl` reports it as "not available". Trusting it keeps the
391
+ * record, so a reconnect does not have to rediscover the lamp first.
392
+ */
393
+ async markTrusted(device) {
394
+ const helper = device.helper;
395
+ if (!helper) {
396
+ return;
397
+ }
398
+ try {
399
+ if (await helper.prop('Trusted')) {
400
+ return;
401
+ }
402
+ await helper.set('Trusted', new Variant('b', true));
403
+ this.log.debug(`Marked ${this.mac} trusted so BlueZ keeps its record`);
404
+ }
405
+ catch (error) {
406
+ this.log.debug(`Could not mark ${this.mac} trusted: ${describeError(error)}`);
407
+ }
408
+ }
409
+ /**
410
+ * Locate the characteristics we need, wherever the firmware puts them.
411
+ *
412
+ * The published protocol notes place everything under one service, but the
413
+ * Solarcycle Morph spreads them across three (`2dd10010` for auth and RSSI,
414
+ * `2dd10020` for attribute writes, `2dd1fff0` for the control values). Rather
415
+ * than hard-coding a layout that varies by model, we sweep every service and
416
+ * match on characteristic UUID, which is unique regardless of its parent.
417
+ */
418
+ async discoverCharacteristics(gatt) {
419
+ this.chars = {};
420
+ this.writeTypes = {};
421
+ for (const serviceUuid of await gatt.services()) {
422
+ const service = await gatt.getPrimaryService(serviceUuid);
423
+ for (const charUuid of await service.characteristics()) {
424
+ if (!WANTED_CHARACTERISTICS.has(charUuid)) {
425
+ continue;
426
+ }
427
+ const characteristic = await service.getCharacteristic(charUuid);
428
+ this.chars[charUuid] = characteristic;
429
+ // The Morph declares its control characteristics write-without-response
430
+ // only; asking BlueZ for an acknowledged write would be rejected. Other
431
+ // models do offer `write`, so take whichever the firmware advertises.
432
+ const flags = await characteristic.getFlags().catch(() => []);
433
+ this.writeTypes[charUuid] = flags.includes('write') ? 'request' : 'command';
434
+ this.log.debug(`Found ${charUuid} in service ${serviceUuid} [${flags.join(', ')}]`);
435
+ }
436
+ }
437
+ const missing = REQUIRED_CHARACTERISTICS.filter((uuid) => !this.chars[uuid]);
438
+ if (missing.length > 0) {
439
+ throw new Error(`${this.mac} is missing required characteristics: ${missing.join(', ')} — is this a Dyson Morph?`);
440
+ }
441
+ }
442
+ /** Write using whichever acknowledgement mode the characteristic supports. */
443
+ async write(uuid, value) {
444
+ await this.characteristic(uuid).writeValue(value, { type: this.writeTypes[uuid] ?? 'command' });
445
+ }
446
+ /**
447
+ * LTK re-authentication: prove we hold the key without contacting the cloud.
448
+ *
449
+ * We send an encrypted nonce, the lamp returns it alongside a challenge of
450
+ * its own, and we send that challenge back encrypted. Until the lamp answers
451
+ * with `CONNECTION_ESTABLISHED` it silently discards every control write.
452
+ */
453
+ async authenticate() {
454
+ // Some firmware needs the product-info exchange before it will talk auth.
455
+ await this.sendMessage(MsgType.REQUEST_PRODUCT_INFO);
456
+ await this.waitForMessage(MsgType.PRODUCT_INFO, 5_000).catch(() => {
457
+ this.log.debug('No product info returned; continuing with the handshake');
458
+ });
459
+ const nonce = randomBytes(16);
460
+ await this.sendMessage(MsgType.REAUTH_PAYLOAD_A, buildReauthPayloadA(this.accountId, this.aesKey, nonce));
461
+ const payloadB = await this.waitForMessage(MsgType.REAUTH_PAYLOAD_B, HANDSHAKE_TIMEOUT_MS);
462
+ const challenge = parseReauthPayloadB(this.aesKey, payloadB.payload);
463
+ await this.sendMessage(MsgType.REAUTH_PAYLOAD_C, buildReauthPayloadC(this.aesKey, challenge));
464
+ await this.waitForMessage(MsgType.CONNECTION_ESTABLISHED, HANDSHAKE_TIMEOUT_MS);
465
+ this.log.debug(`Handshake with ${this.mac} complete`);
466
+ }
467
+ handleAuthFragment(fragment) {
468
+ const message = this.assembler.push(fragment);
469
+ if (!message) {
470
+ return;
471
+ }
472
+ const waiter = this.waiters.get(message.type);
473
+ if (waiter) {
474
+ this.waiters.delete(message.type);
475
+ waiter(message);
476
+ }
477
+ else {
478
+ this.log.debug(`Unsolicited message 0x${message.type.toString(16)} (${message.payload.length} bytes)`);
479
+ }
480
+ }
481
+ async sendMessage(type, payload) {
482
+ for (const fragment of fragmentMessage(type, payload)) {
483
+ await this.write(CHAR_AUTH, fragment);
484
+ }
485
+ }
486
+ waitForMessage(type, timeoutMs) {
487
+ return new Promise((resolve, reject) => {
488
+ const timer = setTimeout(() => {
489
+ this.waiters.delete(type);
490
+ reject(new Error(`Timed out waiting for message 0x${type.toString(16)} from ${this.mac}`));
491
+ }, timeoutMs);
492
+ this.waiters.set(type, (message) => {
493
+ clearTimeout(timer);
494
+ resolve(message);
495
+ });
496
+ });
497
+ }
498
+ /**
499
+ * Take the lamp out of daylight mode so it accepts explicit values.
500
+ *
501
+ * Refreshed on a TTL rather than tracked as state: the lamp offers no way to
502
+ * read the current mode back, and the physical button can change it.
503
+ */
504
+ async ensureManualMode() {
505
+ if (Date.now() - this.manualModeSetAt < MANUAL_MODE_TTL_MS) {
506
+ return;
507
+ }
508
+ if (!this.chars[CHAR_WRITE_ATTR]) {
509
+ return;
510
+ }
511
+ await this.write(CHAR_WRITE_ATTR, DAYLIGHT_MODE_DISABLE);
512
+ await sleep(MODE_SETTLE_MS);
513
+ this.manualModeSetAt = Date.now();
514
+ }
515
+ async refreshState() {
516
+ this.patchState(await this.readState());
517
+ }
518
+ /** Read what the lamp currently reports. Values it will not give up are absent. */
519
+ async readState() {
520
+ const patch = {};
521
+ const failures = [];
522
+ const read = async (uuid, label) => {
523
+ try {
524
+ return await this.chars[uuid]?.readValue();
525
+ }
526
+ catch (error) {
527
+ failures.push(`${label}: ${describeError(error)}`);
528
+ return undefined;
529
+ }
530
+ };
531
+ const power = await read(CHAR_POWER, 'power');
532
+ if (power?.length) {
533
+ patch.on = power[0] !== 0;
534
+ }
535
+ const brightness = await read(CHAR_BRIGHTNESS_LM, 'brightness');
536
+ if (brightness && brightness.length >= 2) {
537
+ const lumens = brightness.readUInt16LE(0);
538
+ // An off lamp reports no output rather than the level it will return to,
539
+ // and HomeKit uses brightness to decide how bright to come back on. Keep
540
+ // the last real level instead of overwriting it with zero.
541
+ if (lumens > 0 || patch.on !== false) {
542
+ patch.brightness = lumensToPercent(lumens);
543
+ }
544
+ }
545
+ const kelvin = await read(CHAR_COLOR_TEMP, 'colour temperature');
546
+ if (kelvin && kelvin.length >= 2) {
547
+ patch.kelvin = kelvin.readUInt16LE(0);
548
+ }
549
+ // Reads failing after a successful handshake means the session was dropped
550
+ // or never really authorised — worth surfacing rather than silently
551
+ // serving stale state to HomeKit.
552
+ if (failures.length > 0) {
553
+ this.log.warn(`Could not read lamp state (${failures.join('; ')})`);
554
+ }
555
+ return patch;
556
+ }
557
+ /**
558
+ * Put the link quality in the log. A weak signal and a bug in the plugin
559
+ * produce the same symptom — repeated disconnects — and only the number
560
+ * distinguishes them.
561
+ */
562
+ async reportSignalStrength() {
563
+ const raw = await this.device?.getRSSI().catch(() => undefined);
564
+ const rssi = typeof raw === 'string' ? Number.parseInt(raw, 10) : raw;
565
+ if (typeof rssi !== 'number' || Number.isNaN(rssi)) {
566
+ return;
567
+ }
568
+ if (rssi <= WEAK_RSSI_DBM) {
569
+ this.log.warn(`Signal from ${this.mac} is weak (${rssi} dBm). Move the lamp or the Homebridge host closer ` +
570
+ 'to each other if the connection keeps dropping.');
571
+ }
572
+ else {
573
+ this.log.debug(`Signal from ${this.mac}: ${rssi} dBm`);
574
+ }
575
+ }
576
+ /**
577
+ * Follow the lamp's own state changes instead of polling for them.
578
+ *
579
+ * There is no need to poll to hold the link open — a BLE connection is
580
+ * maintained by the link layer, not by ATT traffic — and polling actively
581
+ * hurt: a periodic read would eventually come back `ATT error 0x0e` and take
582
+ * the connection down with it. Notifications also pick up changes made at the
583
+ * lamp itself, which polling only caught on its next tick.
584
+ */
585
+ async subscribeToState() {
586
+ const sources = [
587
+ [CHAR_POWER, (value) => (value.length ? { on: value[0] !== 0 } : undefined)],
588
+ [
589
+ CHAR_BRIGHTNESS_LM,
590
+ (value) => {
591
+ if (value.length < 2) {
592
+ return undefined;
593
+ }
594
+ const lumens = value.readUInt16LE(0);
595
+ // Zero means "not lit", not "dimmed to nothing"; keep the level the
596
+ // lamp will return to so HomeKit can restore it.
597
+ return lumens > 0 ? { brightness: lumensToPercent(lumens) } : undefined;
598
+ },
599
+ ],
600
+ [CHAR_COLOR_TEMP, (value) => (value.length >= 2 ? { kelvin: value.readUInt16LE(0) } : undefined)],
601
+ ];
602
+ for (const [uuid, decode] of sources) {
603
+ const characteristic = this.chars[uuid];
604
+ if (!characteristic) {
605
+ continue;
606
+ }
607
+ characteristic.on('valuechanged', (value) => {
608
+ const patch = decode(value);
609
+ if (patch) {
610
+ this.publishFromLamp(patch);
611
+ }
612
+ });
613
+ await characteristic.startNotifications().catch((error) => {
614
+ this.log.debug(`No notifications for ${uuid}: ${describeError(error)}`);
615
+ });
616
+ }
617
+ }
618
+ handleDisconnect() {
619
+ if (!this.connected) {
620
+ return;
621
+ }
622
+ this.connected = false;
623
+ this.log.warn(`Lost connection to ${this.mac} — reconnecting`);
624
+ this.emit('disconnected');
625
+ if (this.running) {
626
+ void this.teardown().then(() => this.connectLoop());
627
+ }
628
+ }
629
+ async teardown() {
630
+ this.connected = false;
631
+ await this.stopOurDiscovery();
632
+ this.writes.cancelAll();
633
+ this.reconciles.cancelAll();
634
+ this.assembler.reset();
635
+ this.waiters.clear();
636
+ this.writeTypes = {};
637
+ for (const characteristic of Object.values(this.chars)) {
638
+ characteristic?.removeAllListeners('valuechanged');
639
+ }
640
+ this.chars = {};
641
+ if (this.device) {
642
+ this.device.removeAllListeners('disconnect');
643
+ await this.device.disconnect().catch(() => { });
644
+ this.device = undefined;
645
+ }
646
+ }
647
+ characteristic(uuid) {
648
+ const characteristic = this.chars[uuid];
649
+ if (!characteristic) {
650
+ throw new Error(`Not connected: characteristic ${uuid} is unavailable`);
651
+ }
652
+ return characteristic;
653
+ }
654
+ /**
655
+ * Run `task` after every previously queued GATT operation has settled.
656
+ *
657
+ * @param key Marks the operation replaceable: queueing another under the same
658
+ * key drops this one. Used for value writes, where an older value is worthless
659
+ * once a newer one is waiting, and omitted for power so it always runs.
660
+ */
661
+ enqueue(task, key) {
662
+ return this.operations.run(task, key);
663
+ }
664
+ /**
665
+ * Publish what the lamp reports, minus the echo of our own commands.
666
+ *
667
+ * A value the user just set must stay where they put it; the steps the lamp
668
+ * takes on its way there are not news, they are the command happening.
669
+ */
670
+ publishFromLamp(patch) {
671
+ this.patchState(this.settling.filter(patch));
672
+ }
673
+ patchState(patch) {
674
+ if (Object.keys(patch).length === 0) {
675
+ return;
676
+ }
677
+ const next = { ...this.state, ...patch };
678
+ const changed = Object.keys(patch).some((k) => this.state[k] !== next[k]);
679
+ this.state = next;
680
+ if (changed) {
681
+ this.log.debug(`State now ${describeState(next)}`);
682
+ this.emit('state', next);
683
+ }
684
+ }
685
+ }
686
+ function describeState(state) {
687
+ return `${state.on ? 'on' : 'off'}, ${state.brightness}%, ${state.kelvin}K`;
688
+ }
689
+ function sleep(ms) {
690
+ return new Promise((resolve) => setTimeout(resolve, ms));
691
+ }
692
+ //# sourceMappingURL=lamp.js.map