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,396 @@
1
+ <!--
2
+ Settings page shown inside the Homebridge UI.
3
+
4
+ Runs in an iframe the host provides; `homebridge.*` is injected by it.
5
+ Styling stays minimal — the host supplies Bootstrap and the active theme.
6
+
7
+ Note: the host's iframe blocks window.confirm/alert, so destructive actions
8
+ confirm inline instead.
9
+ -->
10
+ <style>
11
+ /* Matches the sibling Dyson plugin's settings page, so the two feel alike. */
12
+ .morph-hidden { display: none; }
13
+ .morph-msg { margin-top: .75rem; margin-bottom: 0; font-size: .85rem; }
14
+ .morph-status { display: flex; gap: .5rem; align-items: baseline; flex-wrap: wrap; }
15
+ .morph-ok { color: var(--bs-success, #2e9e5b); font-weight: 600; }
16
+ .morph-hint { font-size: .8rem; opacity: .7; }
17
+ .morph-link { background: none; border: 0; padding: 0; font-size: .85rem;
18
+ text-decoration: underline; cursor: pointer; color: inherit; opacity: .75; }
19
+ </style>
20
+
21
+ <div id="morph">
22
+ <div class="card mb-3">
23
+ <div class="card-body">
24
+ <h5 class="card-title">1. MyDyson account</h5>
25
+ <p class="card-text text-muted small mb-3">
26
+ A lamp ignores every command until it is paired, and its key is issued by Dyson against
27
+ the account the lamp belongs to. <strong>The lamp must already be registered in the
28
+ MyDyson app.</strong> Pairing happens once; after it the plugin works entirely offline.
29
+ </p>
30
+
31
+ <div class="form-group">
32
+ <label for="morph-email">Email</label>
33
+ <input type="email" class="form-control" id="morph-email" autocomplete="username">
34
+ </div>
35
+ <div class="form-group">
36
+ <label for="morph-password">Password</label>
37
+ <input type="password" class="form-control" id="morph-password" autocomplete="current-password">
38
+ </div>
39
+ <div class="form-group">
40
+ <label for="morph-country">Country</label>
41
+ <input type="text" class="form-control" id="morph-country" maxlength="2"
42
+ style="max-width:6rem" placeholder="GB" autocapitalize="characters">
43
+ <small class="form-text text-muted">Two-letter code for the country your Dyson account belongs to.</small>
44
+ </div>
45
+
46
+ <div id="morph-auth">
47
+ <div id="morph-lamps-work" class="alert alert-info morph-hidden">
48
+ Your lights already have their keys and will work without this. Authorising again is only
49
+ needed to add a light or re-pair one.
50
+ </div>
51
+ <button type="button" class="btn btn-primary" id="morph-request">Request code by email</button>
52
+ <div id="morph-code" class="mt-3 morph-hidden">
53
+ <div class="form-group">
54
+ <label for="morph-otp">Code from the Dyson email</label>
55
+ <input type="text" class="form-control" id="morph-otp" inputmode="numeric"
56
+ autocomplete="one-time-code" style="max-width:12rem">
57
+ </div>
58
+ <button type="button" class="btn btn-primary" id="morph-verify">Authorise</button>
59
+ </div>
60
+ </div>
61
+
62
+ <div id="morph-done" class="morph-status morph-hidden">
63
+ <span class="morph-ok">&check; Authorised</span>
64
+ <span id="morph-done-when" class="morph-hint"></span>
65
+ <button type="button" class="morph-link morph-hidden" id="morph-forget-password">Forget password</button>
66
+ <button type="button" class="morph-link" id="morph-again">Authorise again</button>
67
+ </div>
68
+
69
+ <div id="morph-message" class="alert morph-msg morph-hidden"></div>
70
+ </div>
71
+ </div>
72
+
73
+ <div class="card mb-3">
74
+ <div class="card-body">
75
+ <h5 class="card-title">2. Your lights</h5>
76
+ <p class="card-text text-muted small">
77
+ Lists the lights on your Dyson account, then scans for their Bluetooth addresses.
78
+ Takes about 15 seconds. Your account is what identifies a light — over Bluetooth a
79
+ light and a robot vacuum look identical.
80
+ </p>
81
+ <button type="button" class="btn btn-secondary" id="morph-find" disabled>Find my lights</button>
82
+ <div id="morph-found" class="mt-3"></div>
83
+ <hr>
84
+ <h6>Configured</h6>
85
+ <div id="morph-status">…</div>
86
+ </div>
87
+ </div>
88
+ </div>
89
+
90
+ <script>
91
+ (() => {
92
+ 'use strict';
93
+
94
+ const $ = (id) => document.getElementById(id);
95
+ const esc = (text) => String(text).replace(/[&<>"']/g, (c) =>
96
+ ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
97
+
98
+ // Render the schema-generated form (lights and advanced options) below this
99
+ // block; the account fields above are owned here and left out of the layout.
100
+ homebridge.showSchemaForm();
101
+
102
+ const show = (text, kind) => {
103
+ $('morph-message').textContent = text;
104
+ $('morph-message').className = `alert morph-msg alert-${kind}`;
105
+ };
106
+ const clearMessage = () => { $('morph-message').className = 'alert morph-msg morph-hidden'; };
107
+
108
+ /** The plugin's config block, created on first run. */
109
+ async function readConfig() {
110
+ const configs = await homebridge.getPluginConfig();
111
+ if (!configs.length) {
112
+ configs.push({ platform: 'DysonSolarcycleMorph', name: 'Dyson Solarcycle Morph' });
113
+ }
114
+ // Homebridge logs under this name; without it every line is prefixed with
115
+ // the package name instead.
116
+ configs[0].name ??= 'Dyson Solarcycle Morph';
117
+ configs[0].dysonAccount ??= {};
118
+ configs[0].lights ??= [];
119
+ return configs;
120
+ }
121
+
122
+ /**
123
+ * Copy the inputs into the config the UI holds.
124
+ * This does not write config.json — the user still presses Save.
125
+ */
126
+ async function storeAccount() {
127
+ const configs = await readConfig();
128
+ Object.assign(configs[0].dysonAccount, {
129
+ email: $('morph-email').value.trim(),
130
+ password: $('morph-password').value,
131
+ country: $('morph-country').value.trim().toUpperCase(),
132
+ });
133
+ await homebridge.updatePluginConfig(configs);
134
+ return configs[0].dysonAccount;
135
+ }
136
+
137
+ const account = () => ({
138
+ email: $('morph-email').value.trim(),
139
+ password: $('morph-password').value,
140
+ country: $('morph-country').value.trim().toUpperCase(),
141
+ });
142
+
143
+ function showAuthStep() {
144
+ $('morph-done').classList.add('morph-hidden');
145
+ $('morph-auth').classList.remove('morph-hidden');
146
+ $('morph-find').disabled = true;
147
+ }
148
+
149
+ /**
150
+ * Say so when the lights are already usable.
151
+ *
152
+ * A lamp key does not expire, so a paired light keeps working even with no
153
+ * account session stored — which is the normal state after pairing with an
154
+ * older version. Without this the page looks like nothing is set up.
155
+ */
156
+ async function refreshLampsWorkNotice() {
157
+ const serials = (await readConfig())[0].lights.map((l) => (l?.serial ?? '').trim()).filter(Boolean);
158
+ let anyPaired = false;
159
+ if (serials.length) {
160
+ try {
161
+ const { paired } = await homebridge.request('/pair-status', { serials });
162
+ anyPaired = serials.some((s) => paired[s]);
163
+ } catch {
164
+ anyPaired = false;
165
+ }
166
+ }
167
+ const authorising = !$('morph-auth').classList.contains('morph-hidden');
168
+ $('morph-lamps-work').classList.toggle('morph-hidden', !(anyPaired && authorising));
169
+ }
170
+
171
+ /**
172
+ * Collapse the code request once the session works.
173
+ *
174
+ * It stays reachable behind "Authorise again" because a token can be revoked
175
+ * between visits, and re-opens on its own when the check finds it rejected.
176
+ */
177
+ function showAuthorised(created, devices) {
178
+ $('morph-auth').classList.add('morph-hidden');
179
+ $('morph-code').classList.add('morph-hidden');
180
+ $('morph-done').classList.remove('morph-hidden');
181
+ $('morph-find').disabled = false;
182
+ const parts = [];
183
+ if (created) parts.push(`since ${new Date(created).toLocaleDateString()}`);
184
+ if (typeof devices === 'number') parts.push(`${devices} device${devices === 1 ? '' : 's'} in the account`);
185
+ $('morph-done-when').textContent = parts.join(' · ');
186
+ refreshPasswordButton();
187
+ }
188
+
189
+ /** The password is only worth offering to forget when there is one. */
190
+ function refreshPasswordButton() {
191
+ $('morph-forget-password').classList.toggle('morph-hidden', !$('morph-password').value);
192
+ }
193
+
194
+ /** Ask the server whether the stored session still works. */
195
+ async function refreshAuth() {
196
+ if (!$('morph-email').value.trim()) {
197
+ showAuthStep();
198
+ return;
199
+ }
200
+ try {
201
+ const status = await homebridge.request('/auth-status', { account: account() });
202
+ if (status.authorised) {
203
+ showAuthorised(status.created, status.devices);
204
+ clearMessage();
205
+ } else {
206
+ showAuthStep();
207
+ // Only explain when a stored authorisation stopped working; having none
208
+ // yet is the normal first-run state.
209
+ if (status.reason === 'rejected') show(status.message, 'warning');
210
+ }
211
+ } catch {
212
+ showAuthStep();
213
+ }
214
+ refreshPasswordButton();
215
+ await refreshLampsWorkNotice();
216
+ }
217
+
218
+ /** List each configured light and whether it holds a key. */
219
+ async function refreshStatus() {
220
+ const serials = (await readConfig())[0].lights.map((l) => (l?.serial ?? '').trim()).filter(Boolean);
221
+ if (serials.length === 0) {
222
+ $('morph-status').innerHTML = '<span class="text-muted">No lights configured yet.</span>';
223
+ return;
224
+ }
225
+ let paired;
226
+ try {
227
+ ({ paired } = await homebridge.request('/pair-status', { serials }));
228
+ } catch (err) {
229
+ $('morph-status').innerHTML = `<span class="text-danger">${esc(err.message ?? err)}</span>`;
230
+ return;
231
+ }
232
+ $('morph-status').innerHTML = serials.map((serial) => {
233
+ const entry = paired[serial];
234
+ if (!entry) {
235
+ return `<div class="mb-2"><code>${esc(serial)}</code>
236
+ <span class="badge badge-warning ml-2">no key</span></div>`;
237
+ }
238
+ return `<div class="mb-2"><code>${esc(serial)}</code>
239
+ <span class="badge badge-success ml-2">paired</span>
240
+ <span class="text-muted small ml-2">${esc(new Date(entry.created).toLocaleString())}</span>
241
+ <button type="button" class="btn btn-link btn-sm text-danger morph-unpair"
242
+ data-serial="${esc(serial)}">Unpair</button></div>`;
243
+ }).join('');
244
+
245
+ for (const button of document.querySelectorAll('.morph-unpair')) {
246
+ button.addEventListener('click', () => armThenRun(button, 'Unpair', async () => {
247
+ const { message } = await homebridge.request('/forget', { serial: button.dataset.serial });
248
+ show(message, 'success');
249
+ await refreshStatus();
250
+ }));
251
+ }
252
+ }
253
+
254
+ /**
255
+ * Confirm a destructive action in place.
256
+ *
257
+ * The host iframe swallows window.confirm, so the first click turns the
258
+ * button into the confirmation rather than opening a dialog that never shows.
259
+ */
260
+ function armThenRun(button, label, task) {
261
+ if (button.dataset.armed !== 'yes') {
262
+ button.dataset.armed = 'yes';
263
+ button.textContent = 'Are you sure?';
264
+ button.classList.add('font-weight-bold');
265
+ setTimeout(() => {
266
+ if (button.isConnected && button.dataset.armed === 'yes') {
267
+ button.dataset.armed = '';
268
+ button.textContent = label;
269
+ button.classList.remove('font-weight-bold');
270
+ }
271
+ }, 5000);
272
+ return;
273
+ }
274
+ void busy(button, task);
275
+ }
276
+
277
+ /** Run `task` with the spinner up and the button disabled. */
278
+ async function busy(button, task) {
279
+ button.disabled = true;
280
+ homebridge.showSpinner();
281
+ try {
282
+ await task();
283
+ } catch (err) {
284
+ show(err.message ?? String(err), 'danger');
285
+ } finally {
286
+ homebridge.hideSpinner();
287
+ button.disabled = false;
288
+ }
289
+ }
290
+
291
+ $('morph-request').addEventListener('click', () => busy($('morph-request'), async () => {
292
+ const stored = await storeAccount();
293
+ if (!stored.email || !stored.password) {
294
+ show('Enter your MyDyson email address and password first.', 'warning');
295
+ return;
296
+ }
297
+ const { message } = await homebridge.request('/start-auth', { account: stored });
298
+ show(message, 'success');
299
+ $('morph-code').classList.remove('morph-hidden');
300
+ $('morph-otp').focus();
301
+ }));
302
+
303
+ $('morph-verify').addEventListener('click', () => busy($('morph-verify'), async () => {
304
+ const stored = await storeAccount();
305
+ const { message } = await homebridge.request('/finish-auth', { account: stored, otpCode: $('morph-otp').value });
306
+ $('morph-otp').value = '';
307
+ show(message, 'success');
308
+ await refreshAuth();
309
+ }));
310
+
311
+ $('morph-find').addEventListener('click', () => busy($('morph-find'), async () => {
312
+ clearMessage();
313
+ const { lights, skipped } = await homebridge.request('/lights', { account: account() });
314
+
315
+ if (lights.length === 0) {
316
+ $('morph-found').innerHTML =
317
+ '<span class="text-muted">No lights on this Dyson account. Register the lamp in the MyDyson app first.</span>';
318
+ } else {
319
+ $('morph-found').innerHTML = lights.map((light) => {
320
+ const reachable = Boolean(light.mac);
321
+ return `<div class="mb-2">
322
+ <code>${esc(light.serial)}</code>
323
+ <span class="ml-2">${esc(light.name)}</span>
324
+ ${light.model ? `<span class="text-muted small ml-2">${esc(light.model)}</span>` : ''}
325
+ ${reachable
326
+ ? `<span class="text-muted small ml-2">${esc(light.mac)}</span>
327
+ <button type="button" class="btn btn-sm btn-outline-primary ml-2 morph-add"
328
+ data-mac="${esc(light.mac)}" data-serial="${esc(light.serial)}"
329
+ data-name="${esc(light.name)}">Add and pair</button>`
330
+ : '<span class="badge badge-warning ml-2">not in Bluetooth range</span>'}
331
+ </div>`;
332
+ }).join('');
333
+
334
+ for (const button of document.querySelectorAll('.morph-add')) {
335
+ button.addEventListener('click', () => void busy(button, () => addAndPair(button.dataset)));
336
+ }
337
+ }
338
+
339
+ // Saying what was left out is what stops someone adding their vacuum.
340
+ if (skipped.length) {
341
+ $('morph-found').innerHTML +=
342
+ `<p class="text-muted small mt-3 mb-0">Not a Bluetooth light, so not offered: ` +
343
+ skipped.map((d) => `${esc(d.name)} (${esc(d.category ?? 'unknown')})`).join(', ') + '</p>';
344
+ }
345
+ }));
346
+
347
+ async function addAndPair({ mac, serial, name }) {
348
+ const configs = await readConfig();
349
+ const lights = configs[0].lights;
350
+ // Re-adding a light should correct its address, not duplicate it.
351
+ const existing = lights.find((l) => (l.serial ?? '').trim().toUpperCase() === serial.toUpperCase());
352
+ if (existing) {
353
+ existing.mac = mac;
354
+ } else {
355
+ lights.push({ name: name || `Dyson ${serial}`, mac, serial });
356
+ }
357
+ await homebridge.updatePluginConfig(configs);
358
+
359
+ const { message } = await homebridge.request('/pair', { account: account(), serial });
360
+ show(message, 'success');
361
+ await refreshStatus();
362
+ }
363
+
364
+ $('morph-again').addEventListener('click', () => {
365
+ clearMessage();
366
+ showAuthStep();
367
+ });
368
+
369
+ // The password is only needed to exchange a code for a token. Once that is
370
+ // done it can leave config.json, where it would otherwise sit in plain text.
371
+ $('morph-forget-password').addEventListener('click', () => void (async () => {
372
+ const configs = await readConfig();
373
+ delete configs[0].dysonAccount.password;
374
+ await homebridge.updatePluginConfig(configs);
375
+ $('morph-password').value = '';
376
+ refreshPasswordButton();
377
+ show('Password cleared. Press Save to write that to config.json. Enter it again only if you need to authorise afresh.', 'success');
378
+ })());
379
+
380
+ for (const id of ['morph-email', 'morph-password', 'morph-country']) {
381
+ $(id).addEventListener('input', refreshPasswordButton);
382
+ $(id).addEventListener('change', () => void storeAccount().then(refreshAuth));
383
+ }
384
+
385
+ (async () => {
386
+ const [config] = await readConfig();
387
+ const stored = config.dysonAccount;
388
+ $('morph-email').value = stored.email ?? '';
389
+ $('morph-password').value = stored.password ?? '';
390
+ // Prefill the country from the browser; it is usually right and easy to miss.
391
+ $('morph-country').value = stored.country ?? new Intl.Locale(navigator.language).region ?? 'GB';
392
+ await refreshAuth();
393
+ await refreshStatus();
394
+ })();
395
+ })();
396
+ </script>
@@ -0,0 +1,297 @@
1
+ /**
2
+ * Backend for the plugin's settings page in the Homebridge UI.
3
+ *
4
+ * Does the one thing that cannot be done offline: exchange a MyDyson login for
5
+ * a lamp's long-term key. The key is written to the plugin's node-persist
6
+ * store — the same store the running plugin reads — so it never passes through
7
+ * config.json.
8
+ */
9
+ import { HomebridgePluginUiServer, RequestError } from '@homebridge/plugin-ui-utils';
10
+ import { createBluetooth } from 'node-ble';
11
+
12
+ import { DysonCloud, isBluetoothLight } from '../dist/dyson/cloud.js';
13
+ import { describeError } from '../dist/errors.js';
14
+ import { CredentialStore } from '../dist/dyson/credentials.js';
15
+ import { PLUGIN_NAME } from '../dist/settings.js';
16
+
17
+ /**
18
+ * Dyson serials look like `ABC-EU-XXXXXXXX`, and a device advertises its serial
19
+ * as its BLE name. That is all the advertisement gives us: a vacuum and a light
20
+ * expose the same service UUID and carry no manufacturer data, so which is
21
+ * which comes from the account, never from the scan.
22
+ */
23
+ const SERIAL_PATTERN = /^[A-Z0-9]{3}-[A-Z]{2}-[A-Z0-9]{6,}$/;
24
+
25
+ /** How long to leave BLE discovery running before reporting what turned up. */
26
+ const SCAN_MS = 12_000;
27
+
28
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
29
+
30
+ class MorphUiServer extends HomebridgePluginUiServer {
31
+ constructor() {
32
+ super();
33
+
34
+ // Dyson's login is two calls with an emailed code in between. The challenge
35
+ // id ties them together, and it only has to survive between two requests
36
+ // from the same open settings page, so memory is the right place for it —
37
+ // writing it to disk would outlive its usefulness.
38
+ this.challenges = new Map();
39
+
40
+ this.onRequest('/auth-status', (r) => this.authStatus(r));
41
+ this.onRequest('/start-auth', (r) => this.startAuth(r));
42
+ this.onRequest('/finish-auth', (r) => this.finishAuth(r));
43
+ this.onRequest('/lights', (r) => this.lights(r));
44
+ this.onRequest('/pair', (r) => this.pair(r));
45
+ this.onRequest('/pair-status', (r) => this.pairStatus(r));
46
+ this.onRequest('/forget', (r) => this.forget(r));
47
+ this.onRequest('/sign-out', (r) => this.signOut(r));
48
+
49
+ this.ready();
50
+ }
51
+
52
+ store() {
53
+ return new CredentialStore(this.homebridgeStoragePath, PLUGIN_NAME);
54
+ }
55
+
56
+ /**
57
+ * Map serial numbers to BLE addresses by scanning.
58
+ *
59
+ * The account supplies the serials; this only fills in how to reach them.
60
+ */
61
+ async scanForAddresses() {
62
+ let session;
63
+ try {
64
+ session = createBluetooth();
65
+ const adapter = await session.bluetooth.defaultAdapter();
66
+
67
+ if (!(await adapter.isPowered())) {
68
+ throw new RequestError('The Bluetooth adapter is powered off. Run: bluetoothctl power on');
69
+ }
70
+ const alreadyScanning = await adapter.isDiscovering();
71
+ if (!alreadyScanning) {
72
+ await adapter.startDiscovery();
73
+ }
74
+ await sleep(SCAN_MS);
75
+
76
+ const addresses = new Map();
77
+ for (const mac of await adapter.devices()) {
78
+ try {
79
+ const name = await (await adapter.getDevice(mac)).getName();
80
+ if (SERIAL_PATTERN.test(name)) {
81
+ addresses.set(name.toUpperCase(), mac);
82
+ }
83
+ } catch {
84
+ // Devices come and go mid-scan; a disappearing one is not an error.
85
+ }
86
+ }
87
+
88
+ // Leave discovery as we found it: the plugin may be mid-reconnect.
89
+ if (!alreadyScanning) {
90
+ await adapter.stopDiscovery().catch(() => {});
91
+ }
92
+ return addresses;
93
+ } catch (err) {
94
+ if (err instanceof RequestError) {
95
+ throw err;
96
+ }
97
+ throw new RequestError(`Bluetooth scan failed: ${describeError(err)}`);
98
+ } finally {
99
+ try {
100
+ session?.destroy();
101
+ } catch {
102
+ // Nothing useful to do if the D-Bus connection was already gone.
103
+ }
104
+ }
105
+ }
106
+
107
+ /**
108
+ * Report whether this account still holds a usable session.
109
+ *
110
+ * A stored token is not the same as a working one, so this exercises it
111
+ * against the API rather than merely noting that it exists.
112
+ */
113
+ async authStatus(request) {
114
+ const { email } = this.getAccount(request);
115
+ const stored = await this.store().getAccount(email);
116
+ if (!stored) {
117
+ return { authorised: false, reason: 'no-token' };
118
+ }
119
+ try {
120
+ const { country } = this.getAccount(request);
121
+ const devices = await new DysonCloud({ country, culture: cultureFor(country) }).getDevices(stored.token);
122
+ return { authorised: true, created: stored.created, devices: devices.length };
123
+ } catch (err) {
124
+ return {
125
+ authorised: false,
126
+ reason: 'rejected',
127
+ created: stored.created,
128
+ message: `Dyson no longer accepts the stored authorisation (${describeError(err)}). Request a new code.`,
129
+ };
130
+ }
131
+ }
132
+
133
+ /**
134
+ * List the account's lights, with a BLE address where one was found.
135
+ *
136
+ * Category comes from the account because the advertisement cannot supply it:
137
+ * a robot vacuum and a light look identical over Bluetooth.
138
+ */
139
+ async lights(request) {
140
+ const { email, country } = this.getAccount(request);
141
+ const stored = await this.store().getAccount(email);
142
+ if (!stored) {
143
+ throw new RequestError('Authorise your MyDyson account first.');
144
+ }
145
+
146
+ let devices;
147
+ try {
148
+ devices = await new DysonCloud({ country, culture: cultureFor(country) }).getDevices(stored.token);
149
+ } catch (err) {
150
+ throw new RequestError(`Could not list your Dyson devices: ${describeError(err)}`);
151
+ }
152
+
153
+ const lights = devices.filter(isBluetoothLight);
154
+ if (lights.length === 0) {
155
+ return {
156
+ lights: [],
157
+ skipped: devices.map((d) => ({ serial: d.serialNumber, name: d.name, category: d.category })),
158
+ };
159
+ }
160
+
161
+ const addresses = await this.scanForAddresses();
162
+ return {
163
+ lights: lights.map((d) => ({
164
+ serial: d.serialNumber,
165
+ name: d.name,
166
+ model: d.model ?? d.type ?? null,
167
+ mac: addresses.get(String(d.serialNumber).toUpperCase()) ?? null,
168
+ })),
169
+ skipped: devices.filter((d) => !isBluetoothLight(d)).map((d) => ({
170
+ serial: d.serialNumber,
171
+ name: d.name,
172
+ category: d.category,
173
+ })),
174
+ };
175
+ }
176
+
177
+ /** Fetch and store one lamp's long-term key. */
178
+ async pair(request) {
179
+ const { email, country } = this.getAccount(request);
180
+ const serial = typeof request?.serial === 'string' ? request.serial.trim().toUpperCase() : '';
181
+ if (!serial) {
182
+ throw new RequestError('No serial number given.');
183
+ }
184
+ const store = this.store();
185
+ const stored = await store.getAccount(email);
186
+ if (!stored) {
187
+ throw new RequestError('Authorise your MyDyson account first.');
188
+ }
189
+ try {
190
+ const cloud = new DysonCloud({ country, culture: cultureFor(country) });
191
+ const ltk = await cloud.fetchLtk(serial, stored.token);
192
+ await store.set(serial, { ltk, accountId: stored.accountId });
193
+ return { message: `Paired ${serial}. Press Save, then restart Homebridge.` };
194
+ } catch (err) {
195
+ throw new RequestError(
196
+ String(err).includes('404')
197
+ ? `${serial} is not registered to this Dyson account. Add it in the MyDyson app first.`
198
+ : `Could not fetch the key for ${serial}: ${describeError(err)}`,
199
+ );
200
+ }
201
+ }
202
+
203
+ /** Discard the stored session, e.g. to authorise as a different account. */
204
+ async signOut(request) {
205
+ const { email } = this.getAccount(request);
206
+ await this.store().deleteAccount(email);
207
+ return { message: 'Signed out. Request a new code to authorise again.' };
208
+ }
209
+
210
+ /** Report which of the given serials already have stored credentials. */
211
+ async pairStatus(request) {
212
+ const serials = Array.isArray(request?.serials) ? request.serials : [];
213
+ const store = this.store();
214
+ const paired = {};
215
+ for (const serial of serials) {
216
+ if (typeof serial !== 'string' || !serial.trim()) {
217
+ continue;
218
+ }
219
+ const stored = await store.get(serial);
220
+ paired[serial] = stored ? { created: stored.created } : null;
221
+ }
222
+ return { paired };
223
+ }
224
+
225
+ /** Ask Dyson to email a one-time code. */
226
+ async startAuth(request) {
227
+ const { email, country } = this.getAccount(request);
228
+ try {
229
+ const cloud = new DysonCloud({ country, culture: cultureFor(country) });
230
+ const challengeId = await cloud.beginLogin(email);
231
+ this.challenges.set(email, { challengeId, country });
232
+ return { message: 'Dyson has emailed you a code. Check your spam folder too.' };
233
+ } catch (err) {
234
+ throw new RequestError(`Could not request a code: ${describeError(err)}`);
235
+ }
236
+ }
237
+
238
+ /** Exchange the code for a session token and remember it. */
239
+ async finishAuth(request) {
240
+ const { email, country, password } = this.getAccount(request);
241
+ const otpCode = typeof request?.otpCode === 'string' ? request.otpCode.trim() : '';
242
+
243
+ if (!password) {
244
+ throw new RequestError('Enter your MyDyson password.');
245
+ }
246
+ if (!otpCode) {
247
+ throw new RequestError('Enter the code from the Dyson email.');
248
+ }
249
+ const challenge = this.challenges.get(email);
250
+ if (!challenge) {
251
+ throw new RequestError('Request a code first — the previous one is no longer pending.');
252
+ }
253
+
254
+ try {
255
+ const cloud = new DysonCloud({ country, culture: cultureFor(country) });
256
+ const { token, accountId } = await cloud.completeLogin(email, password, challenge.challengeId, otpCode);
257
+ await this.store().setAccount(email, { token, accountId });
258
+ return { message: 'Account authorised. Now find your lights below.' };
259
+ } catch (err) {
260
+ throw new RequestError(`Login failed: ${describeError(err)}`);
261
+ } finally {
262
+ // One code is good for one login, so a retry needs a fresh one either way.
263
+ this.challenges.delete(email);
264
+ }
265
+ }
266
+
267
+ /** Discard a stored key, e.g. before re-pairing against another account. */
268
+ async forget(request) {
269
+ const serial = typeof request?.serial === 'string' ? request.serial.trim() : '';
270
+ if (!serial) {
271
+ throw new RequestError('No serial number given.');
272
+ }
273
+ await this.store().delete(serial);
274
+ return { message: `Removed the stored key for ${serial}.` };
275
+ }
276
+
277
+ /** Account details come from the config block the settings page maintains. */
278
+ getAccount(request) {
279
+ const account = request?.account ?? {};
280
+ const email = typeof account.email === 'string' ? account.email.trim() : '';
281
+ const country =
282
+ typeof account.country === 'string' && account.country.trim() ? account.country.trim().toUpperCase() : 'GB';
283
+ if (!email) {
284
+ throw new RequestError('Enter the email address of your MyDyson account.');
285
+ }
286
+ return { email, country, password: typeof account.password === 'string' ? account.password : '' };
287
+ }
288
+ }
289
+
290
+ /** Dyson wants a BCP 47 culture; derive a reasonable one from the country. */
291
+ function cultureFor(country) {
292
+ const languages = { DE: 'de', AT: 'de', CH: 'de', FR: 'fr', IT: 'it', ES: 'es', NL: 'nl' };
293
+ return `${languages[country] ?? 'en'}-${country}`;
294
+ }
295
+
296
+
297
+ new MorphUiServer();