@homelib/xiaomi 0.0.0-wip.ba4eafa051eb

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 (175) hide show
  1. package/LICENSE +19 -0
  2. package/README.md +22 -0
  3. package/bld/library/backend/client.d.ts +68 -0
  4. package/bld/library/backend/client.js +477 -0
  5. package/bld/library/backend/client.js.map +1 -0
  6. package/bld/library/backend/constants.d.ts +7 -0
  7. package/bld/library/backend/constants.js +11 -0
  8. package/bld/library/backend/constants.js.map +1 -0
  9. package/bld/library/backend/index.d.ts +3 -0
  10. package/bld/library/backend/index.js +4 -0
  11. package/bld/library/backend/index.js.map +1 -0
  12. package/bld/library/backend/oauth.d.ts +24 -0
  13. package/bld/library/backend/oauth.js +121 -0
  14. package/bld/library/backend/oauth.js.map +1 -0
  15. package/bld/library/binding.d.ts +44 -0
  16. package/bld/library/binding.js +212 -0
  17. package/bld/library/binding.js.map +1 -0
  18. package/bld/library/cloud/client.d.ts +27 -0
  19. package/bld/library/cloud/client.js +109 -0
  20. package/bld/library/cloud/client.js.map +1 -0
  21. package/bld/library/cloud/constants.d.ts +9 -0
  22. package/bld/library/cloud/constants.js +11 -0
  23. package/bld/library/cloud/constants.js.map +1 -0
  24. package/bld/library/cloud/device.d.ts +84 -0
  25. package/bld/library/cloud/device.js +686 -0
  26. package/bld/library/cloud/device.js.map +1 -0
  27. package/bld/library/cloud/index.d.ts +5 -0
  28. package/bld/library/cloud/index.js +6 -0
  29. package/bld/library/cloud/index.js.map +1 -0
  30. package/bld/library/cloud/mqtt.d.ts +69 -0
  31. package/bld/library/cloud/mqtt.js +517 -0
  32. package/bld/library/cloud/mqtt.js.map +1 -0
  33. package/bld/library/cloud/transport.d.ts +8 -0
  34. package/bld/library/cloud/transport.js +30 -0
  35. package/bld/library/cloud/transport.js.map +1 -0
  36. package/bld/library/command.d.ts +6 -0
  37. package/bld/library/command.js +6 -0
  38. package/bld/library/command.js.map +1 -0
  39. package/bld/library/configuration.d.ts +62 -0
  40. package/bld/library/configuration.js +303 -0
  41. package/bld/library/configuration.js.map +1 -0
  42. package/bld/library/device.d.ts +68 -0
  43. package/bld/library/device.js +235 -0
  44. package/bld/library/device.js.map +1 -0
  45. package/bld/library/devices/air-conditioner.d.ts +48 -0
  46. package/bld/library/devices/air-conditioner.js +155 -0
  47. package/bld/library/devices/air-conditioner.js.map +1 -0
  48. package/bld/library/devices/command-effect.d.ts +35 -0
  49. package/bld/library/devices/command-effect.js +269 -0
  50. package/bld/library/devices/command-effect.js.map +1 -0
  51. package/bld/library/devices/dehumidifier.d.ts +41 -0
  52. package/bld/library/devices/dehumidifier.js +124 -0
  53. package/bld/library/devices/dehumidifier.js.map +1 -0
  54. package/bld/library/devices/fan.d.ts +37 -0
  55. package/bld/library/devices/fan.js +135 -0
  56. package/bld/library/devices/fan.js.map +1 -0
  57. package/bld/library/devices/index.d.ts +7 -0
  58. package/bld/library/devices/index.js +8 -0
  59. package/bld/library/devices/index.js.map +1 -0
  60. package/bld/library/devices/light.d.ts +22 -0
  61. package/bld/library/devices/light.js +112 -0
  62. package/bld/library/devices/light.js.map +1 -0
  63. package/bld/library/devices/placeholder.d.ts +3 -0
  64. package/bld/library/devices/placeholder.js +4 -0
  65. package/bld/library/devices/placeholder.js.map +1 -0
  66. package/bld/library/devices/value-range.d.ts +2 -0
  67. package/bld/library/devices/value-range.js +6 -0
  68. package/bld/library/devices/value-range.js.map +1 -0
  69. package/bld/library/endpoint-connection.d.ts +154 -0
  70. package/bld/library/endpoint-connection.js +510 -0
  71. package/bld/library/endpoint-connection.js.map +1 -0
  72. package/bld/library/index.d.ts +26 -0
  73. package/bld/library/index.js +31 -0
  74. package/bld/library/index.js.map +1 -0
  75. package/bld/library/local/certificate.d.ts +31 -0
  76. package/bld/library/local/certificate.js +298 -0
  77. package/bld/library/local/certificate.js.map +1 -0
  78. package/bld/library/local/controller.d.ts +70 -0
  79. package/bld/library/local/controller.js +497 -0
  80. package/bld/library/local/controller.js.map +1 -0
  81. package/bld/library/local/discovery.d.ts +29 -0
  82. package/bld/library/local/discovery.js +321 -0
  83. package/bld/library/local/discovery.js.map +1 -0
  84. package/bld/library/local/index.d.ts +6 -0
  85. package/bld/library/local/index.js +7 -0
  86. package/bld/library/local/index.js.map +1 -0
  87. package/bld/library/local/message.d.ts +11 -0
  88. package/bld/library/local/message.js +128 -0
  89. package/bld/library/local/message.js.map +1 -0
  90. package/bld/library/local/mqtt.d.ts +113 -0
  91. package/bld/library/local/mqtt.js +1044 -0
  92. package/bld/library/local/mqtt.js.map +1 -0
  93. package/bld/library/local/routed-message-client.d.ts +49 -0
  94. package/bld/library/local/routed-message-client.js +326 -0
  95. package/bld/library/local/routed-message-client.js.map +1 -0
  96. package/bld/library/miot/index.d.ts +4 -0
  97. package/bld/library/miot/index.js +5 -0
  98. package/bld/library/miot/index.js.map +1 -0
  99. package/bld/library/miot/matcher.d.ts +65 -0
  100. package/bld/library/miot/matcher.js +217 -0
  101. package/bld/library/miot/matcher.js.map +1 -0
  102. package/bld/library/miot/request.d.ts +16 -0
  103. package/bld/library/miot/request.js +27 -0
  104. package/bld/library/miot/request.js.map +1 -0
  105. package/bld/library/miot/result.d.ts +4 -0
  106. package/bld/library/miot/result.js +5 -0
  107. package/bld/library/miot/result.js.map +1 -0
  108. package/bld/library/miot/spec.d.ts +74 -0
  109. package/bld/library/miot/spec.js +78 -0
  110. package/bld/library/miot/spec.js.map +1 -0
  111. package/bld/library/provider.d.ts +71 -0
  112. package/bld/library/provider.js +600 -0
  113. package/bld/library/provider.js.map +1 -0
  114. package/bld/library/session-manager.d.ts +34 -0
  115. package/bld/library/session-manager.js +177 -0
  116. package/bld/library/session-manager.js.map +1 -0
  117. package/bld/library/session.d.ts +36 -0
  118. package/bld/library/session.js +370 -0
  119. package/bld/library/session.js.map +1 -0
  120. package/bld/library/storage.d.ts +2 -0
  121. package/bld/library/storage.js +66 -0
  122. package/bld/library/storage.js.map +1 -0
  123. package/bld/library/terminal/bindings.d.ts +3 -0
  124. package/bld/library/terminal/bindings.js +280 -0
  125. package/bld/library/terminal/bindings.js.map +1 -0
  126. package/bld/library/terminal/index.d.ts +2 -0
  127. package/bld/library/terminal/index.js +3 -0
  128. package/bld/library/terminal/index.js.map +1 -0
  129. package/bld/library/terminal/provider-details.d.ts +3 -0
  130. package/bld/library/terminal/provider-details.js +477 -0
  131. package/bld/library/terminal/provider-details.js.map +1 -0
  132. package/package.json +29 -0
  133. package/src/library/backend/client.ts +713 -0
  134. package/src/library/backend/constants.ts +17 -0
  135. package/src/library/backend/index.ts +3 -0
  136. package/src/library/backend/oauth.ts +170 -0
  137. package/src/library/binding.ts +387 -0
  138. package/src/library/cloud/client.ts +155 -0
  139. package/src/library/cloud/constants.ts +19 -0
  140. package/src/library/cloud/device.ts +938 -0
  141. package/src/library/cloud/index.ts +5 -0
  142. package/src/library/cloud/mqtt.ts +671 -0
  143. package/src/library/cloud/transport.ts +38 -0
  144. package/src/library/command.ts +7 -0
  145. package/src/library/configuration.ts +480 -0
  146. package/src/library/device.ts +548 -0
  147. package/src/library/devices/air-conditioner.ts +171 -0
  148. package/src/library/devices/command-effect.ts +425 -0
  149. package/src/library/devices/dehumidifier.ts +131 -0
  150. package/src/library/devices/fan.ts +140 -0
  151. package/src/library/devices/index.ts +7 -0
  152. package/src/library/devices/light.ts +119 -0
  153. package/src/library/devices/placeholder.ts +3 -0
  154. package/src/library/devices/value-range.ts +14 -0
  155. package/src/library/endpoint-connection.ts +841 -0
  156. package/src/library/index.ts +62 -0
  157. package/src/library/local/certificate.ts +401 -0
  158. package/src/library/local/controller.ts +692 -0
  159. package/src/library/local/discovery.ts +485 -0
  160. package/src/library/local/index.ts +6 -0
  161. package/src/library/local/message.ts +174 -0
  162. package/src/library/local/mqtt.ts +1493 -0
  163. package/src/library/local/routed-message-client.ts +377 -0
  164. package/src/library/miot/index.ts +4 -0
  165. package/src/library/miot/matcher.ts +461 -0
  166. package/src/library/miot/request.ts +30 -0
  167. package/src/library/miot/result.ts +10 -0
  168. package/src/library/miot/spec.ts +103 -0
  169. package/src/library/provider.ts +745 -0
  170. package/src/library/session-manager.ts +224 -0
  171. package/src/library/session.ts +528 -0
  172. package/src/library/storage.ts +83 -0
  173. package/src/library/terminal/bindings.tsx +612 -0
  174. package/src/library/terminal/index.ts +2 -0
  175. package/src/library/terminal/provider-details.tsx +871 -0
@@ -0,0 +1,938 @@
1
+ import type {MiotProperty} from '../miot/index.js';
2
+
3
+ import {CLOUD_MQTT_RECONNECT_INTERVAL} from './constants.js';
4
+ import type {
5
+ CloudMqttDeviceMessage,
6
+ CloudMqttDeviceMessageHandler,
7
+ } from './mqtt.js';
8
+
9
+ export class CloudDeviceChannel {
10
+ private readonly listenerEntrySet = new Set<CloudDeviceListenerEntry>();
11
+
12
+ private readonly propertyCacheMap = new Map<string, CloudPropertyUpdate>();
13
+
14
+ private readonly propertyRevisionMap = new Map<string, number>();
15
+
16
+ private readonly propertyRefreshSequenceMap = new Map<string, number>();
17
+
18
+ private revision = 0;
19
+
20
+ private refreshSequence = 0;
21
+
22
+ private stateGeneration = 0;
23
+
24
+ private online: boolean | undefined;
25
+
26
+ private onlineRefreshSequence = 0;
27
+
28
+ private subscribed = false;
29
+
30
+ private subscribePromise: Promise<void> | undefined;
31
+
32
+ private unsubscribePromise: Promise<void> | undefined;
33
+
34
+ private stateRefreshRequest: CloudDeviceStateRefreshRequest | undefined;
35
+
36
+ private brokerConnected = true;
37
+
38
+ private stateRefreshPromise: Promise<void> | undefined;
39
+
40
+ private stateRefreshRetryTimeout: ReturnType<typeof setTimeout> | undefined;
41
+
42
+ private readonly messageHandler: CloudMqttDeviceMessageHandler;
43
+
44
+ constructor(
45
+ readonly did: string,
46
+ private readonly messageSource: CloudDeviceMessageSource,
47
+ private readonly readProperties: CloudPropertyReader,
48
+ private readonly readOnline: CloudOnlineReader,
49
+ private readonly onEmpty: () => void,
50
+ ) {
51
+ this.messageHandler = message => {
52
+ this.handleMessage(message);
53
+ };
54
+ }
55
+
56
+ async subscribe(
57
+ properties: readonly MiotProperty[],
58
+ listener: CloudDeviceListener,
59
+ ): Promise<CloudDeviceSubscription> {
60
+ const listenerEntry: CloudDeviceListenerEntry = {
61
+ propertyMap: createPropertyMap(this.did, properties),
62
+ listener,
63
+ initialized: false,
64
+ };
65
+
66
+ this.listenerEntrySet.add(listenerEntry);
67
+
68
+ try {
69
+ await this.ensureSubscribed();
70
+
71
+ if (!listenerEntry.initialized) {
72
+ if (listenerEntry.refreshOperation === undefined) {
73
+ void this.refreshEntries([listenerEntry]).catch(() => undefined);
74
+ }
75
+
76
+ await this.waitForEntryRefresh(listenerEntry);
77
+ }
78
+
79
+ if (!listenerEntry.initialized) {
80
+ throw new Error(`Cloud device ${this.did} state was not initialized.`);
81
+ }
82
+ } catch (error) {
83
+ await this.removeListener(listenerEntry);
84
+ throw error;
85
+ }
86
+
87
+ let disposed = false;
88
+
89
+ return {
90
+ refresh: async () => {
91
+ if (disposed) {
92
+ throw new Error(`Cloud device subscription ${this.did} is disposed.`);
93
+ }
94
+
95
+ void this.refreshEntries([listenerEntry]).catch(() => undefined);
96
+ await this.waitForEntryRefresh(listenerEntry);
97
+ },
98
+ dispose: async () => {
99
+ if (disposed) {
100
+ return;
101
+ }
102
+
103
+ disposed = true;
104
+ await this.removeListener(listenerEntry);
105
+ },
106
+ };
107
+ }
108
+
109
+ handleConnectionState(connected: boolean): void {
110
+ if (!connected) {
111
+ this.stateGeneration++;
112
+ this.brokerConnected = false;
113
+ this.requestStateRefresh();
114
+ return;
115
+ }
116
+
117
+ this.brokerConnected = true;
118
+ this.startStateRefresh();
119
+ }
120
+
121
+ private requestStateRefresh(onlineOverride?: boolean): void {
122
+ this.stateRefreshRequest = {onlineOverride};
123
+ this.stopStateRefresh();
124
+ this.startStateRefresh();
125
+ }
126
+
127
+ private startStateRefresh(): void {
128
+ const request = this.stateRefreshRequest;
129
+
130
+ if (
131
+ request === undefined ||
132
+ !this.brokerConnected ||
133
+ this.listenerEntrySet.size === 0 ||
134
+ this.stateRefreshPromise !== undefined ||
135
+ this.stateRefreshRetryTimeout !== undefined
136
+ ) {
137
+ return;
138
+ }
139
+
140
+ const entries = [...this.listenerEntrySet];
141
+
142
+ void this.refreshEntries(entries, request.onlineOverride).catch(
143
+ () => undefined,
144
+ );
145
+
146
+ const promise = Promise.all(
147
+ entries.map(entry => this.waitForEntryRefresh(entry)),
148
+ ).then(() => undefined);
149
+ this.stateRefreshPromise = promise;
150
+
151
+ void promise.then(
152
+ () => {
153
+ if (this.stateRefreshPromise !== promise) {
154
+ return;
155
+ }
156
+
157
+ this.stateRefreshPromise = undefined;
158
+
159
+ if (this.stateRefreshRequest === request) {
160
+ this.stateRefreshRequest = undefined;
161
+ }
162
+ },
163
+ error => {
164
+ if (this.stateRefreshPromise !== promise) {
165
+ return;
166
+ }
167
+
168
+ this.stateRefreshPromise = undefined;
169
+
170
+ if (
171
+ this.stateRefreshRequest !== request ||
172
+ !this.brokerConnected ||
173
+ this.listenerEntrySet.size === 0
174
+ ) {
175
+ return;
176
+ }
177
+
178
+ this.notifyError(error);
179
+ this.scheduleStateRefresh();
180
+ },
181
+ );
182
+ }
183
+
184
+ private scheduleStateRefresh(): void {
185
+ if (
186
+ this.stateRefreshRetryTimeout !== undefined ||
187
+ this.stateRefreshRequest === undefined ||
188
+ !this.brokerConnected ||
189
+ this.listenerEntrySet.size === 0
190
+ ) {
191
+ return;
192
+ }
193
+
194
+ this.stateRefreshRetryTimeout = setTimeout(() => {
195
+ this.stateRefreshRetryTimeout = undefined;
196
+ this.startStateRefresh();
197
+ }, CLOUD_MQTT_RECONNECT_INTERVAL);
198
+ }
199
+
200
+ private stopStateRefresh(): void {
201
+ this.stateRefreshPromise = undefined;
202
+
203
+ if (this.stateRefreshRetryTimeout !== undefined) {
204
+ clearTimeout(this.stateRefreshRetryTimeout);
205
+ this.stateRefreshRetryTimeout = undefined;
206
+ }
207
+ }
208
+
209
+ private async ensureSubscribed(): Promise<void> {
210
+ const unsubscribePromise = this.unsubscribePromise;
211
+
212
+ if (unsubscribePromise !== undefined) {
213
+ await unsubscribePromise;
214
+ }
215
+
216
+ if (this.subscribed) {
217
+ return;
218
+ }
219
+
220
+ let subscribePromise = this.subscribePromise;
221
+
222
+ if (subscribePromise === undefined) {
223
+ subscribePromise = this.messageSource
224
+ .subscribeDevice(this.did, this.messageHandler)
225
+ .then(() => {
226
+ this.subscribed = true;
227
+ });
228
+ this.subscribePromise = subscribePromise;
229
+ }
230
+
231
+ try {
232
+ await subscribePromise;
233
+ } finally {
234
+ if (this.subscribePromise === subscribePromise) {
235
+ this.subscribePromise = undefined;
236
+ }
237
+ }
238
+ }
239
+
240
+ private refreshEntries(
241
+ requestedEntries: readonly CloudDeviceListenerEntry[],
242
+ onlineOverride?: boolean,
243
+ ): Promise<void> {
244
+ const entries = requestedEntries.filter(entry =>
245
+ this.listenerEntrySet.has(entry),
246
+ );
247
+
248
+ if (entries.length === 0) {
249
+ return Promise.resolve();
250
+ }
251
+
252
+ const token = {};
253
+ const sequence = ++this.refreshSequence;
254
+ let resolvePromise!: () => void;
255
+ let rejectPromise!: (error: unknown) => void;
256
+ const promise = new Promise<void>((resolve, reject) => {
257
+ resolvePromise = resolve;
258
+ rejectPromise = reject;
259
+ });
260
+
261
+ for (const entry of entries) {
262
+ entry.refreshOperation?.replace();
263
+ entry.refreshOperation = createRefreshOperation(token, promise);
264
+ }
265
+
266
+ void this.readAndPublishState(
267
+ entries,
268
+ token,
269
+ sequence,
270
+ onlineOverride,
271
+ ).then(resolvePromise, rejectPromise);
272
+
273
+ return promise;
274
+ }
275
+
276
+ private async waitForEntryRefresh(
277
+ entry: CloudDeviceListenerEntry,
278
+ ): Promise<void> {
279
+ while (true) {
280
+ const operation = entry.refreshOperation;
281
+
282
+ if (operation === undefined) {
283
+ return;
284
+ }
285
+
286
+ const outcome = await Promise.race([
287
+ operation.promise.then(
288
+ () => ({type: 'completed'}) as const,
289
+ error => ({type: 'failed', error}) as const,
290
+ ),
291
+ operation.replaced.then(() => ({type: 'replaced'}) as const),
292
+ ]);
293
+
294
+ if (!this.listenerEntrySet.has(entry)) {
295
+ return;
296
+ } else if (
297
+ outcome.type === 'replaced' ||
298
+ entry.refreshOperation?.token !== operation.token
299
+ ) {
300
+ continue;
301
+ } else if (outcome.type === 'failed') {
302
+ throw outcome.error;
303
+ }
304
+
305
+ return;
306
+ }
307
+ }
308
+
309
+ private async readAndPublishState(
310
+ entries: readonly CloudDeviceListenerEntry[],
311
+ refreshToken: object,
312
+ refreshSequence: number,
313
+ onlineOverride: boolean | undefined,
314
+ ): Promise<void> {
315
+ const propertyMap = createEntryPropertyMap(entries);
316
+ const propertyBaselineMap = this.captureRevisions(propertyMap);
317
+ const generation = this.stateGeneration;
318
+ const propertyRead = settlePromise(
319
+ onlineOverride === false || propertyMap.size === 0
320
+ ? Promise.resolve([])
321
+ : Promise.resolve().then(() =>
322
+ this.readProperties([...propertyMap.values()]),
323
+ ),
324
+ );
325
+ let requestedOnline: boolean;
326
+
327
+ try {
328
+ requestedOnline =
329
+ onlineOverride ??
330
+ (await Promise.resolve().then(() => this.readOnline()));
331
+ } catch (error) {
332
+ if (!this.isRefreshCurrent(entries, refreshToken, generation)) {
333
+ return;
334
+ }
335
+
336
+ throw error;
337
+ }
338
+
339
+ let currentEntries = this.getCurrentRefreshEntries(
340
+ entries,
341
+ refreshToken,
342
+ generation,
343
+ );
344
+
345
+ if (currentEntries.length === 0) {
346
+ return;
347
+ } else if (typeof requestedOnline !== 'boolean') {
348
+ throw new TypeError(
349
+ `Cloud device ${this.did} returned invalid online state.`,
350
+ );
351
+ }
352
+
353
+ let online = this.resolveRefreshOnline(requestedOnline, refreshSequence);
354
+
355
+ if (!online) {
356
+ this.commitRefreshOnline(false, refreshSequence);
357
+ this.publishState(currentEntries, false, new Map());
358
+ return;
359
+ }
360
+
361
+ const propertyOutcome = await propertyRead;
362
+
363
+ currentEntries = this.getCurrentRefreshEntries(
364
+ entries,
365
+ refreshToken,
366
+ generation,
367
+ );
368
+
369
+ if (currentEntries.length === 0) {
370
+ return;
371
+ }
372
+
373
+ online = this.resolveRefreshOnline(requestedOnline, refreshSequence);
374
+
375
+ if (!online) {
376
+ this.publishState(currentEntries, false, new Map());
377
+ return;
378
+ } else if (propertyOutcome.status === 'rejected') {
379
+ throw propertyOutcome.reason;
380
+ }
381
+
382
+ const currentPropertyMap = createEntryPropertyMap(currentEntries);
383
+ const {resultMap, resultErrorMap, errors} = collectSnapshotResults(
384
+ this.did,
385
+ currentPropertyMap,
386
+ propertyOutcome.value,
387
+ );
388
+
389
+ for (const error of errors) {
390
+ this.notifyError(error);
391
+ }
392
+
393
+ const propertyErrorMap = new Map<string, unknown>();
394
+ const propertyUpdateMap = new Map<
395
+ string,
396
+ {readonly property: MiotProperty; readonly value: unknown}
397
+ >();
398
+
399
+ for (const [key, property] of currentPropertyMap) {
400
+ const baseline = propertyBaselineMap.get(key) ?? 0;
401
+ const currentRevision = this.propertyRevisionMap.get(key) ?? 0;
402
+ const cachedProperty = this.propertyCacheMap.get(key);
403
+ const cachedRefreshSequence =
404
+ this.propertyRefreshSequenceMap.get(key) ?? 0;
405
+
406
+ if (
407
+ currentRevision !== baseline &&
408
+ cachedProperty !== undefined &&
409
+ (cachedProperty.source === 'mqtt' ||
410
+ cachedRefreshSequence > refreshSequence)
411
+ ) {
412
+ continue;
413
+ }
414
+
415
+ const resultError = resultErrorMap.get(key);
416
+
417
+ if (resultError !== undefined) {
418
+ propertyErrorMap.set(key, resultError);
419
+ continue;
420
+ }
421
+
422
+ const result = resultMap.get(key);
423
+
424
+ if (result === undefined) {
425
+ propertyErrorMap.set(
426
+ key,
427
+ new Error(`Cloud snapshot omitted property ${key}.`),
428
+ );
429
+ } else if (result.code !== 0 && result.code !== 1) {
430
+ propertyErrorMap.set(
431
+ key,
432
+ new Error(`Cloud snapshot property ${key} failed: ${result.code}.`),
433
+ );
434
+ } else if (!Object.hasOwn(result, 'value')) {
435
+ propertyErrorMap.set(
436
+ key,
437
+ new Error(`Cloud snapshot property ${key} has no value.`),
438
+ );
439
+ } else {
440
+ propertyUpdateMap.set(key, {property, value: result.value});
441
+ }
442
+ }
443
+
444
+ const successfulEntries: CloudDeviceListenerEntry[] = [];
445
+ const refreshErrors: unknown[] = [];
446
+
447
+ for (const entry of currentEntries) {
448
+ const entryErrors = [...entry.propertyMap.keys()].flatMap(key => {
449
+ const error = propertyErrorMap.get(key);
450
+
451
+ if (error === undefined) {
452
+ return [];
453
+ }
454
+
455
+ const baseline = propertyBaselineMap.get(key) ?? 0;
456
+ const currentRevision = this.propertyRevisionMap.get(key) ?? 0;
457
+
458
+ const cachedProperty = this.propertyCacheMap.get(key);
459
+ const cachedRefreshSequence =
460
+ this.propertyRefreshSequenceMap.get(key) ?? 0;
461
+
462
+ return currentRevision !== baseline &&
463
+ cachedProperty !== undefined &&
464
+ (cachedProperty.source === 'mqtt' ||
465
+ cachedRefreshSequence > refreshSequence)
466
+ ? []
467
+ : [error];
468
+ });
469
+
470
+ if (entryErrors.length > 0) {
471
+ refreshErrors.push(...entryErrors);
472
+ continue;
473
+ }
474
+
475
+ successfulEntries.push(entry);
476
+ }
477
+
478
+ const successfulPropertyKeySet = new Set(
479
+ successfulEntries.flatMap(entry => [...entry.propertyMap.keys()]),
480
+ );
481
+
482
+ for (const [key, update] of propertyUpdateMap) {
483
+ if (successfulPropertyKeySet.has(key)) {
484
+ this.cacheProperty(
485
+ update.property,
486
+ update.value,
487
+ 'snapshot',
488
+ refreshSequence,
489
+ );
490
+ }
491
+ }
492
+
493
+ if (successfulEntries.length > 0) {
494
+ this.commitRefreshOnline(true, refreshSequence);
495
+
496
+ for (const entry of successfulEntries) {
497
+ const properties = [...entry.propertyMap.keys()].map(key => {
498
+ const property = this.propertyCacheMap.get(key);
499
+
500
+ if (property === undefined) {
501
+ throw new TypeError(
502
+ `Cloud device state is missing property ${key}.`,
503
+ );
504
+ }
505
+
506
+ return property;
507
+ });
508
+
509
+ try {
510
+ publishListenerState(entry, {
511
+ did: this.did,
512
+ online: true,
513
+ properties,
514
+ });
515
+ } catch (error) {
516
+ refreshErrors.push(error);
517
+ }
518
+ }
519
+ }
520
+
521
+ if (refreshErrors.length > 0) {
522
+ throw refreshErrors[0];
523
+ }
524
+ }
525
+
526
+ private getCurrentRefreshEntries(
527
+ entries: readonly CloudDeviceListenerEntry[],
528
+ refreshToken: object,
529
+ generation: number,
530
+ ): CloudDeviceListenerEntry[] {
531
+ if (generation !== this.stateGeneration) {
532
+ return [];
533
+ }
534
+
535
+ return entries.filter(
536
+ entry =>
537
+ this.listenerEntrySet.has(entry) &&
538
+ entry.refreshOperation?.token === refreshToken,
539
+ );
540
+ }
541
+
542
+ private isRefreshCurrent(
543
+ entries: readonly CloudDeviceListenerEntry[],
544
+ refreshToken: object,
545
+ generation: number,
546
+ ): boolean {
547
+ return (
548
+ this.getCurrentRefreshEntries(entries, refreshToken, generation).length >
549
+ 0
550
+ );
551
+ }
552
+
553
+ private resolveRefreshOnline(
554
+ requestedOnline: boolean,
555
+ refreshSequence: number,
556
+ ): boolean {
557
+ return refreshSequence < this.onlineRefreshSequence
558
+ ? (this.online ?? requestedOnline)
559
+ : requestedOnline;
560
+ }
561
+
562
+ private commitRefreshOnline(online: boolean, refreshSequence: number): void {
563
+ if (refreshSequence < this.onlineRefreshSequence) {
564
+ return;
565
+ }
566
+
567
+ this.online = online;
568
+ this.onlineRefreshSequence = refreshSequence;
569
+ }
570
+
571
+ private publishState(
572
+ entries: readonly CloudDeviceListenerEntry[],
573
+ online: false,
574
+ propertyMap: ReadonlyMap<string, CloudPropertyUpdate>,
575
+ ): void {
576
+ const errors: unknown[] = [];
577
+
578
+ for (const entry of entries) {
579
+ const properties = [...entry.propertyMap.keys()].flatMap(key => {
580
+ const property = propertyMap.get(key);
581
+ return property === undefined ? [] : [property];
582
+ });
583
+
584
+ try {
585
+ publishListenerState(entry, {did: this.did, online, properties});
586
+ } catch (error) {
587
+ errors.push(error);
588
+ }
589
+ }
590
+
591
+ if (errors.length > 0) {
592
+ throw errors[0];
593
+ }
594
+ }
595
+
596
+ private handleMessage(message: CloudMqttDeviceMessage): void {
597
+ if (message.did !== this.did) {
598
+ this.notifyError(
599
+ new Error(`Cloud MQTT routed unexpected device ${message.did}.`),
600
+ );
601
+ return;
602
+ }
603
+
604
+ if (message.type === 'property') {
605
+ const update = this.cacheProperty(
606
+ {did: message.did, siid: message.siid, piid: message.piid},
607
+ message.value,
608
+ 'mqtt',
609
+ );
610
+ const key = getPropertyKey(update);
611
+
612
+ for (const entry of this.listenerEntrySet) {
613
+ if (entry.initialized && entry.propertyMap.has(key)) {
614
+ callListener(entry.listener, 'onPropertyChanged', update);
615
+ }
616
+ }
617
+ } else if (message.type === 'event') {
618
+ const event: CloudEvent = {
619
+ did: message.did,
620
+ siid: message.siid,
621
+ eiid: message.eiid,
622
+ arguments: message.arguments,
623
+ };
624
+
625
+ for (const {listener} of this.listenerEntrySet) {
626
+ callListener(listener, 'onEventOccurred', event);
627
+ }
628
+ } else {
629
+ this.stateGeneration++;
630
+ this.requestStateRefresh(message.online);
631
+ }
632
+ }
633
+
634
+ private cacheProperty(
635
+ property: MiotProperty,
636
+ value: unknown,
637
+ source: CloudPropertyUpdateSource,
638
+ refreshSequence?: number,
639
+ ): CloudPropertyUpdate {
640
+ const key = getPropertyKey(property);
641
+ const revision = ++this.revision;
642
+ const update: CloudPropertyUpdate = {
643
+ ...property,
644
+ value,
645
+ revision,
646
+ source,
647
+ };
648
+
649
+ this.propertyCacheMap.set(key, update);
650
+ this.propertyRevisionMap.set(key, revision);
651
+
652
+ if (refreshSequence !== undefined) {
653
+ this.propertyRefreshSequenceMap.set(key, refreshSequence);
654
+ }
655
+
656
+ return update;
657
+ }
658
+
659
+ private async removeListener(
660
+ listenerEntry: CloudDeviceListenerEntry,
661
+ ): Promise<void> {
662
+ if (!this.listenerEntrySet.delete(listenerEntry)) {
663
+ return;
664
+ }
665
+
666
+ listenerEntry.refreshOperation?.replace();
667
+ listenerEntry.refreshOperation = undefined;
668
+
669
+ const subscribePromise = this.subscribePromise;
670
+
671
+ if (subscribePromise !== undefined) {
672
+ await subscribePromise.catch(() => undefined);
673
+ }
674
+
675
+ if (this.listenerEntrySet.size > 0) {
676
+ return;
677
+ }
678
+
679
+ this.stateRefreshRequest = undefined;
680
+ this.stopStateRefresh();
681
+
682
+ if (!this.subscribed) {
683
+ this.onEmpty();
684
+ return;
685
+ }
686
+
687
+ this.subscribed = false;
688
+ const unsubscribePromise = this.messageSource.unsubscribeDevice(this.did);
689
+ this.unsubscribePromise = unsubscribePromise;
690
+
691
+ try {
692
+ await unsubscribePromise;
693
+ } finally {
694
+ if (this.unsubscribePromise === unsubscribePromise) {
695
+ this.unsubscribePromise = undefined;
696
+ }
697
+
698
+ if (this.listenerEntrySet.size === 0) {
699
+ this.onEmpty();
700
+ }
701
+ }
702
+ }
703
+
704
+ private captureRevisions(
705
+ propertyMap: ReadonlyMap<string, MiotProperty>,
706
+ ): ReadonlyMap<string, number> {
707
+ return new Map(
708
+ [...propertyMap.keys()].map(key => [
709
+ key,
710
+ this.propertyRevisionMap.get(key) ?? 0,
711
+ ]),
712
+ );
713
+ }
714
+
715
+ private notifyError(error: unknown): void {
716
+ for (const {listener} of this.listenerEntrySet) {
717
+ notifyListenerError(listener, error);
718
+ }
719
+ }
720
+ }
721
+
722
+ export type CloudDeviceSubscription = {
723
+ refresh(): Promise<void>;
724
+ dispose(): Promise<void>;
725
+ };
726
+
727
+ export type CloudDeviceListener = {
728
+ readonly onStateChanged?: (state: CloudDeviceState) => void;
729
+ readonly onPropertyChanged?: (update: CloudPropertyUpdate) => void;
730
+ readonly onEventOccurred?: (event: CloudEvent) => void;
731
+ readonly onError?: (error: unknown) => void;
732
+ };
733
+
734
+ export type CloudDeviceState = {
735
+ readonly did: string;
736
+ readonly online: boolean;
737
+ readonly properties: readonly CloudPropertyUpdate[];
738
+ };
739
+
740
+ export type CloudPropertyUpdate = MiotProperty & {
741
+ readonly value: unknown;
742
+ readonly revision: number;
743
+ readonly source: CloudPropertyUpdateSource;
744
+ };
745
+
746
+ export type CloudPropertyUpdateSource = 'snapshot' | 'mqtt';
747
+
748
+ export type CloudEvent = {
749
+ readonly did: string;
750
+ readonly siid: number;
751
+ readonly eiid: number;
752
+ readonly arguments: readonly unknown[];
753
+ };
754
+
755
+ export type CloudPropertySnapshot = MiotProperty & {
756
+ readonly value?: unknown;
757
+ readonly code: number;
758
+ };
759
+
760
+ export type CloudPropertyReader = (
761
+ properties: readonly MiotProperty[],
762
+ ) => Promise<readonly CloudPropertySnapshot[]>;
763
+
764
+ export type CloudOnlineReader = () => Promise<boolean>;
765
+
766
+ export type CloudDeviceMessageSource = {
767
+ subscribeDevice(
768
+ did: string,
769
+ handler: CloudMqttDeviceMessageHandler,
770
+ ): Promise<void>;
771
+ unsubscribeDevice(did: string): Promise<void>;
772
+ };
773
+
774
+ type CloudDeviceListenerEntry = {
775
+ readonly propertyMap: ReadonlyMap<string, MiotProperty>;
776
+ readonly listener: CloudDeviceListener;
777
+ initialized: boolean;
778
+ refreshOperation?: CloudDeviceRefreshOperation;
779
+ };
780
+
781
+ type CloudDeviceStateRefreshRequest = {
782
+ readonly onlineOverride: boolean | undefined;
783
+ };
784
+
785
+ type CloudDeviceRefreshOperation = {
786
+ readonly token: object;
787
+ readonly promise: Promise<void>;
788
+ readonly replaced: Promise<void>;
789
+ replace(): void;
790
+ };
791
+
792
+ function createRefreshOperation(
793
+ token: object,
794
+ promise: Promise<void>,
795
+ ): CloudDeviceRefreshOperation {
796
+ let replace: () => void = () => undefined;
797
+ const replaced = new Promise<void>(resolve => {
798
+ replace = resolve;
799
+ });
800
+
801
+ return {token, promise, replaced, replace};
802
+ }
803
+
804
+ function settlePromise<T>(promise: Promise<T>): Promise<PromiseOutcome<T>> {
805
+ return promise.then(
806
+ value => ({status: 'fulfilled', value}),
807
+ reason => ({status: 'rejected', reason}),
808
+ );
809
+ }
810
+
811
+ function createEntryPropertyMap(
812
+ entries: readonly CloudDeviceListenerEntry[],
813
+ ): Map<string, MiotProperty> {
814
+ const propertyMap = new Map<string, MiotProperty>();
815
+
816
+ for (const entry of entries) {
817
+ for (const [key, property] of entry.propertyMap) {
818
+ propertyMap.set(key, property);
819
+ }
820
+ }
821
+
822
+ return propertyMap;
823
+ }
824
+
825
+ function collectSnapshotResults(
826
+ did: string,
827
+ propertyMap: ReadonlyMap<string, MiotProperty>,
828
+ results: readonly CloudPropertySnapshot[],
829
+ ): {
830
+ readonly resultMap: ReadonlyMap<string, CloudPropertySnapshot>;
831
+ readonly resultErrorMap: ReadonlyMap<string, Error>;
832
+ readonly errors: readonly Error[];
833
+ } {
834
+ const resultMap = new Map<string, CloudPropertySnapshot>();
835
+ const resultErrorMap = new Map<string, Error>();
836
+ const errors: Error[] = [];
837
+
838
+ for (const result of results) {
839
+ if (result.did !== did) {
840
+ errors.push(
841
+ new Error(`Cloud snapshot returned unexpected device ${result.did}.`),
842
+ );
843
+ continue;
844
+ }
845
+
846
+ const key = getPropertyKey(result);
847
+
848
+ if (!propertyMap.has(key)) {
849
+ errors.push(
850
+ new Error(`Cloud snapshot returned unexpected property ${key}.`),
851
+ );
852
+ } else if (resultMap.has(key) || resultErrorMap.has(key)) {
853
+ resultMap.delete(key);
854
+ resultErrorMap.set(
855
+ key,
856
+ new Error(`Cloud snapshot returned duplicate property ${key}.`),
857
+ );
858
+ } else {
859
+ resultMap.set(key, result);
860
+ }
861
+ }
862
+
863
+ return {resultMap, resultErrorMap, errors};
864
+ }
865
+
866
+ function createPropertyMap(
867
+ did: string,
868
+ properties: readonly MiotProperty[],
869
+ ): Map<string, MiotProperty> {
870
+ const propertyMap = new Map<string, MiotProperty>();
871
+
872
+ for (const property of properties) {
873
+ if (property.did !== did) {
874
+ throw new Error(
875
+ `Cloud device ${did} cannot subscribe to property for ${property.did}.`,
876
+ );
877
+ }
878
+
879
+ propertyMap.set(getPropertyKey(property), property);
880
+ }
881
+
882
+ return propertyMap;
883
+ }
884
+
885
+ function getPropertyKey(property: {
886
+ readonly siid: number;
887
+ readonly piid: number;
888
+ }): string {
889
+ return `${property.siid}.${property.piid}`;
890
+ }
891
+
892
+ function callListener<TName extends 'onPropertyChanged' | 'onEventOccurred'>(
893
+ listener: CloudDeviceListener,
894
+ name: TName,
895
+ value: Parameters<NonNullable<CloudDeviceListener[TName]>>[0],
896
+ ): void {
897
+ const callback = listener[name] as
898
+ | ((value: Parameters<NonNullable<CloudDeviceListener[TName]>>[0]) => void)
899
+ | undefined;
900
+
901
+ if (callback === undefined) {
902
+ return;
903
+ }
904
+
905
+ try {
906
+ callback(value);
907
+ } catch (error) {
908
+ notifyListenerError(listener, error);
909
+ }
910
+ }
911
+
912
+ function publishListenerState(
913
+ entry: CloudDeviceListenerEntry,
914
+ state: CloudDeviceState,
915
+ ): void {
916
+ entry.listener.onStateChanged?.(state);
917
+ entry.initialized = true;
918
+ }
919
+
920
+ function notifyListenerError(
921
+ listener: CloudDeviceListener,
922
+ error: unknown,
923
+ ): void {
924
+ if (listener.onError === undefined) {
925
+ console.error(error);
926
+ return;
927
+ }
928
+
929
+ try {
930
+ listener.onError(error);
931
+ } catch (listenerError) {
932
+ console.error(listenerError);
933
+ }
934
+ }
935
+
936
+ type PromiseOutcome<T> =
937
+ | {readonly status: 'fulfilled'; readonly value: T}
938
+ | {readonly status: 'rejected'; readonly reason: unknown};