@homelib/xiaomi 0.0.0-wip.01265bf1cc90

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 (183) hide show
  1. package/LICENSE +19 -0
  2. package/README.md +26 -0
  3. package/bld/library/backend/client.d.ts +73 -0
  4. package/bld/library/backend/client.js +490 -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 +34 -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 +69 -0
  43. package/bld/library/device.js +266 -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 +9 -0
  58. package/bld/library/devices/index.js +10 -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/pet-feeder.d.ts +36 -0
  64. package/bld/library/devices/pet-feeder.js +116 -0
  65. package/bld/library/devices/pet-feeder.js.map +1 -0
  66. package/bld/library/devices/placeholder.d.ts +3 -0
  67. package/bld/library/devices/placeholder.js +4 -0
  68. package/bld/library/devices/placeholder.js.map +1 -0
  69. package/bld/library/devices/temperature-humidity-sensor.d.ts +14 -0
  70. package/bld/library/devices/temperature-humidity-sensor.js +56 -0
  71. package/bld/library/devices/temperature-humidity-sensor.js.map +1 -0
  72. package/bld/library/devices/value-range.d.ts +2 -0
  73. package/bld/library/devices/value-range.js +6 -0
  74. package/bld/library/devices/value-range.js.map +1 -0
  75. package/bld/library/endpoint-connection.d.ts +168 -0
  76. package/bld/library/endpoint-connection.js +510 -0
  77. package/bld/library/endpoint-connection.js.map +1 -0
  78. package/bld/library/index.d.ts +26 -0
  79. package/bld/library/index.js +33 -0
  80. package/bld/library/index.js.map +1 -0
  81. package/bld/library/local/certificate.d.ts +31 -0
  82. package/bld/library/local/certificate.js +298 -0
  83. package/bld/library/local/certificate.js.map +1 -0
  84. package/bld/library/local/controller.d.ts +70 -0
  85. package/bld/library/local/controller.js +498 -0
  86. package/bld/library/local/controller.js.map +1 -0
  87. package/bld/library/local/discovery.d.ts +29 -0
  88. package/bld/library/local/discovery.js +321 -0
  89. package/bld/library/local/discovery.js.map +1 -0
  90. package/bld/library/local/index.d.ts +6 -0
  91. package/bld/library/local/index.js +7 -0
  92. package/bld/library/local/index.js.map +1 -0
  93. package/bld/library/local/message.d.ts +11 -0
  94. package/bld/library/local/message.js +128 -0
  95. package/bld/library/local/message.js.map +1 -0
  96. package/bld/library/local/mqtt.d.ts +113 -0
  97. package/bld/library/local/mqtt.js +1074 -0
  98. package/bld/library/local/mqtt.js.map +1 -0
  99. package/bld/library/local/routed-message-client.d.ts +49 -0
  100. package/bld/library/local/routed-message-client.js +326 -0
  101. package/bld/library/local/routed-message-client.js.map +1 -0
  102. package/bld/library/miot/index.d.ts +4 -0
  103. package/bld/library/miot/index.js +5 -0
  104. package/bld/library/miot/index.js.map +1 -0
  105. package/bld/library/miot/matcher.d.ts +84 -0
  106. package/bld/library/miot/matcher.js +326 -0
  107. package/bld/library/miot/matcher.js.map +1 -0
  108. package/bld/library/miot/request.d.ts +33 -0
  109. package/bld/library/miot/request.js +57 -0
  110. package/bld/library/miot/request.js.map +1 -0
  111. package/bld/library/miot/result.d.ts +8 -0
  112. package/bld/library/miot/result.js +5 -0
  113. package/bld/library/miot/result.js.map +1 -0
  114. package/bld/library/miot/spec.d.ts +96 -0
  115. package/bld/library/miot/spec.js +86 -0
  116. package/bld/library/miot/spec.js.map +1 -0
  117. package/bld/library/provider.d.ts +78 -0
  118. package/bld/library/provider.js +600 -0
  119. package/bld/library/provider.js.map +1 -0
  120. package/bld/library/session-manager.d.ts +34 -0
  121. package/bld/library/session-manager.js +177 -0
  122. package/bld/library/session-manager.js.map +1 -0
  123. package/bld/library/session.d.ts +36 -0
  124. package/bld/library/session.js +370 -0
  125. package/bld/library/session.js.map +1 -0
  126. package/bld/library/storage.d.ts +2 -0
  127. package/bld/library/storage.js +66 -0
  128. package/bld/library/storage.js.map +1 -0
  129. package/bld/library/terminal/bindings.d.ts +3 -0
  130. package/bld/library/terminal/bindings.js +306 -0
  131. package/bld/library/terminal/bindings.js.map +1 -0
  132. package/bld/library/terminal/index.d.ts +2 -0
  133. package/bld/library/terminal/index.js +3 -0
  134. package/bld/library/terminal/index.js.map +1 -0
  135. package/bld/library/terminal/provider-details.d.ts +3 -0
  136. package/bld/library/terminal/provider-details.js +477 -0
  137. package/bld/library/terminal/provider-details.js.map +1 -0
  138. package/package.json +29 -0
  139. package/src/library/backend/client.ts +737 -0
  140. package/src/library/backend/constants.ts +17 -0
  141. package/src/library/backend/index.ts +3 -0
  142. package/src/library/backend/oauth.ts +170 -0
  143. package/src/library/binding.ts +387 -0
  144. package/src/library/cloud/client.ts +155 -0
  145. package/src/library/cloud/constants.ts +19 -0
  146. package/src/library/cloud/device.ts +938 -0
  147. package/src/library/cloud/index.ts +5 -0
  148. package/src/library/cloud/mqtt.ts +671 -0
  149. package/src/library/cloud/transport.ts +46 -0
  150. package/src/library/command.ts +7 -0
  151. package/src/library/configuration.ts +480 -0
  152. package/src/library/device.ts +601 -0
  153. package/src/library/devices/air-conditioner.ts +171 -0
  154. package/src/library/devices/command-effect.ts +425 -0
  155. package/src/library/devices/dehumidifier.ts +131 -0
  156. package/src/library/devices/fan.ts +140 -0
  157. package/src/library/devices/index.ts +9 -0
  158. package/src/library/devices/light.ts +119 -0
  159. package/src/library/devices/pet-feeder.ts +129 -0
  160. package/src/library/devices/placeholder.ts +3 -0
  161. package/src/library/devices/temperature-humidity-sensor.ts +49 -0
  162. package/src/library/devices/value-range.ts +14 -0
  163. package/src/library/endpoint-connection.ts +841 -0
  164. package/src/library/index.ts +71 -0
  165. package/src/library/local/certificate.ts +401 -0
  166. package/src/library/local/controller.ts +693 -0
  167. package/src/library/local/discovery.ts +485 -0
  168. package/src/library/local/index.ts +6 -0
  169. package/src/library/local/message.ts +174 -0
  170. package/src/library/local/mqtt.ts +1555 -0
  171. package/src/library/local/routed-message-client.ts +377 -0
  172. package/src/library/miot/index.ts +4 -0
  173. package/src/library/miot/matcher.ts +683 -0
  174. package/src/library/miot/request.ts +70 -0
  175. package/src/library/miot/result.ts +14 -0
  176. package/src/library/miot/spec.ts +114 -0
  177. package/src/library/provider.ts +745 -0
  178. package/src/library/session-manager.ts +224 -0
  179. package/src/library/session.ts +528 -0
  180. package/src/library/storage.ts +83 -0
  181. package/src/library/terminal/bindings.tsx +692 -0
  182. package/src/library/terminal/index.ts +2 -0
  183. package/src/library/terminal/provider-details.tsx +871 -0
@@ -0,0 +1,686 @@
1
+ import { CLOUD_MQTT_RECONNECT_INTERVAL } from './constants.js';
2
+ export class CloudDeviceChannel {
3
+ constructor(did, messageSource, readProperties, readOnline, onEmpty) {
4
+ Object.defineProperty(this, "did", {
5
+ enumerable: true,
6
+ configurable: true,
7
+ writable: true,
8
+ value: did
9
+ });
10
+ Object.defineProperty(this, "messageSource", {
11
+ enumerable: true,
12
+ configurable: true,
13
+ writable: true,
14
+ value: messageSource
15
+ });
16
+ Object.defineProperty(this, "readProperties", {
17
+ enumerable: true,
18
+ configurable: true,
19
+ writable: true,
20
+ value: readProperties
21
+ });
22
+ Object.defineProperty(this, "readOnline", {
23
+ enumerable: true,
24
+ configurable: true,
25
+ writable: true,
26
+ value: readOnline
27
+ });
28
+ Object.defineProperty(this, "onEmpty", {
29
+ enumerable: true,
30
+ configurable: true,
31
+ writable: true,
32
+ value: onEmpty
33
+ });
34
+ Object.defineProperty(this, "listenerEntrySet", {
35
+ enumerable: true,
36
+ configurable: true,
37
+ writable: true,
38
+ value: new Set()
39
+ });
40
+ Object.defineProperty(this, "propertyCacheMap", {
41
+ enumerable: true,
42
+ configurable: true,
43
+ writable: true,
44
+ value: new Map()
45
+ });
46
+ Object.defineProperty(this, "propertyRevisionMap", {
47
+ enumerable: true,
48
+ configurable: true,
49
+ writable: true,
50
+ value: new Map()
51
+ });
52
+ Object.defineProperty(this, "propertyRefreshSequenceMap", {
53
+ enumerable: true,
54
+ configurable: true,
55
+ writable: true,
56
+ value: new Map()
57
+ });
58
+ Object.defineProperty(this, "revision", {
59
+ enumerable: true,
60
+ configurable: true,
61
+ writable: true,
62
+ value: 0
63
+ });
64
+ Object.defineProperty(this, "refreshSequence", {
65
+ enumerable: true,
66
+ configurable: true,
67
+ writable: true,
68
+ value: 0
69
+ });
70
+ Object.defineProperty(this, "stateGeneration", {
71
+ enumerable: true,
72
+ configurable: true,
73
+ writable: true,
74
+ value: 0
75
+ });
76
+ Object.defineProperty(this, "online", {
77
+ enumerable: true,
78
+ configurable: true,
79
+ writable: true,
80
+ value: void 0
81
+ });
82
+ Object.defineProperty(this, "onlineRefreshSequence", {
83
+ enumerable: true,
84
+ configurable: true,
85
+ writable: true,
86
+ value: 0
87
+ });
88
+ Object.defineProperty(this, "subscribed", {
89
+ enumerable: true,
90
+ configurable: true,
91
+ writable: true,
92
+ value: false
93
+ });
94
+ Object.defineProperty(this, "subscribePromise", {
95
+ enumerable: true,
96
+ configurable: true,
97
+ writable: true,
98
+ value: void 0
99
+ });
100
+ Object.defineProperty(this, "unsubscribePromise", {
101
+ enumerable: true,
102
+ configurable: true,
103
+ writable: true,
104
+ value: void 0
105
+ });
106
+ Object.defineProperty(this, "stateRefreshRequest", {
107
+ enumerable: true,
108
+ configurable: true,
109
+ writable: true,
110
+ value: void 0
111
+ });
112
+ Object.defineProperty(this, "brokerConnected", {
113
+ enumerable: true,
114
+ configurable: true,
115
+ writable: true,
116
+ value: true
117
+ });
118
+ Object.defineProperty(this, "stateRefreshPromise", {
119
+ enumerable: true,
120
+ configurable: true,
121
+ writable: true,
122
+ value: void 0
123
+ });
124
+ Object.defineProperty(this, "stateRefreshRetryTimeout", {
125
+ enumerable: true,
126
+ configurable: true,
127
+ writable: true,
128
+ value: void 0
129
+ });
130
+ Object.defineProperty(this, "messageHandler", {
131
+ enumerable: true,
132
+ configurable: true,
133
+ writable: true,
134
+ value: void 0
135
+ });
136
+ this.messageHandler = message => {
137
+ this.handleMessage(message);
138
+ };
139
+ }
140
+ async subscribe(properties, listener) {
141
+ const listenerEntry = {
142
+ propertyMap: createPropertyMap(this.did, properties),
143
+ listener,
144
+ initialized: false,
145
+ };
146
+ this.listenerEntrySet.add(listenerEntry);
147
+ try {
148
+ await this.ensureSubscribed();
149
+ if (!listenerEntry.initialized) {
150
+ if (listenerEntry.refreshOperation === undefined) {
151
+ void this.refreshEntries([listenerEntry]).catch(() => undefined);
152
+ }
153
+ await this.waitForEntryRefresh(listenerEntry);
154
+ }
155
+ if (!listenerEntry.initialized) {
156
+ throw new Error(`Cloud device ${this.did} state was not initialized.`);
157
+ }
158
+ }
159
+ catch (error) {
160
+ await this.removeListener(listenerEntry);
161
+ throw error;
162
+ }
163
+ let disposed = false;
164
+ return {
165
+ refresh: async () => {
166
+ if (disposed) {
167
+ throw new Error(`Cloud device subscription ${this.did} is disposed.`);
168
+ }
169
+ void this.refreshEntries([listenerEntry]).catch(() => undefined);
170
+ await this.waitForEntryRefresh(listenerEntry);
171
+ },
172
+ dispose: async () => {
173
+ if (disposed) {
174
+ return;
175
+ }
176
+ disposed = true;
177
+ await this.removeListener(listenerEntry);
178
+ },
179
+ };
180
+ }
181
+ handleConnectionState(connected) {
182
+ if (!connected) {
183
+ this.stateGeneration++;
184
+ this.brokerConnected = false;
185
+ this.requestStateRefresh();
186
+ return;
187
+ }
188
+ this.brokerConnected = true;
189
+ this.startStateRefresh();
190
+ }
191
+ requestStateRefresh(onlineOverride) {
192
+ this.stateRefreshRequest = { onlineOverride };
193
+ this.stopStateRefresh();
194
+ this.startStateRefresh();
195
+ }
196
+ startStateRefresh() {
197
+ const request = this.stateRefreshRequest;
198
+ if (request === undefined ||
199
+ !this.brokerConnected ||
200
+ this.listenerEntrySet.size === 0 ||
201
+ this.stateRefreshPromise !== undefined ||
202
+ this.stateRefreshRetryTimeout !== undefined) {
203
+ return;
204
+ }
205
+ const entries = [...this.listenerEntrySet];
206
+ void this.refreshEntries(entries, request.onlineOverride).catch(() => undefined);
207
+ const promise = Promise.all(entries.map(entry => this.waitForEntryRefresh(entry))).then(() => undefined);
208
+ this.stateRefreshPromise = promise;
209
+ void promise.then(() => {
210
+ if (this.stateRefreshPromise !== promise) {
211
+ return;
212
+ }
213
+ this.stateRefreshPromise = undefined;
214
+ if (this.stateRefreshRequest === request) {
215
+ this.stateRefreshRequest = undefined;
216
+ }
217
+ }, error => {
218
+ if (this.stateRefreshPromise !== promise) {
219
+ return;
220
+ }
221
+ this.stateRefreshPromise = undefined;
222
+ if (this.stateRefreshRequest !== request ||
223
+ !this.brokerConnected ||
224
+ this.listenerEntrySet.size === 0) {
225
+ return;
226
+ }
227
+ this.notifyError(error);
228
+ this.scheduleStateRefresh();
229
+ });
230
+ }
231
+ scheduleStateRefresh() {
232
+ if (this.stateRefreshRetryTimeout !== undefined ||
233
+ this.stateRefreshRequest === undefined ||
234
+ !this.brokerConnected ||
235
+ this.listenerEntrySet.size === 0) {
236
+ return;
237
+ }
238
+ this.stateRefreshRetryTimeout = setTimeout(() => {
239
+ this.stateRefreshRetryTimeout = undefined;
240
+ this.startStateRefresh();
241
+ }, CLOUD_MQTT_RECONNECT_INTERVAL);
242
+ }
243
+ stopStateRefresh() {
244
+ this.stateRefreshPromise = undefined;
245
+ if (this.stateRefreshRetryTimeout !== undefined) {
246
+ clearTimeout(this.stateRefreshRetryTimeout);
247
+ this.stateRefreshRetryTimeout = undefined;
248
+ }
249
+ }
250
+ async ensureSubscribed() {
251
+ const unsubscribePromise = this.unsubscribePromise;
252
+ if (unsubscribePromise !== undefined) {
253
+ await unsubscribePromise;
254
+ }
255
+ if (this.subscribed) {
256
+ return;
257
+ }
258
+ let subscribePromise = this.subscribePromise;
259
+ if (subscribePromise === undefined) {
260
+ subscribePromise = this.messageSource
261
+ .subscribeDevice(this.did, this.messageHandler)
262
+ .then(() => {
263
+ this.subscribed = true;
264
+ });
265
+ this.subscribePromise = subscribePromise;
266
+ }
267
+ try {
268
+ await subscribePromise;
269
+ }
270
+ finally {
271
+ if (this.subscribePromise === subscribePromise) {
272
+ this.subscribePromise = undefined;
273
+ }
274
+ }
275
+ }
276
+ refreshEntries(requestedEntries, onlineOverride) {
277
+ var _a;
278
+ const entries = requestedEntries.filter(entry => this.listenerEntrySet.has(entry));
279
+ if (entries.length === 0) {
280
+ return Promise.resolve();
281
+ }
282
+ const token = {};
283
+ const sequence = ++this.refreshSequence;
284
+ let resolvePromise;
285
+ let rejectPromise;
286
+ const promise = new Promise((resolve, reject) => {
287
+ resolvePromise = resolve;
288
+ rejectPromise = reject;
289
+ });
290
+ for (const entry of entries) {
291
+ (_a = entry.refreshOperation) === null || _a === void 0 ? void 0 : _a.replace();
292
+ entry.refreshOperation = createRefreshOperation(token, promise);
293
+ }
294
+ void this.readAndPublishState(entries, token, sequence, onlineOverride).then(resolvePromise, rejectPromise);
295
+ return promise;
296
+ }
297
+ async waitForEntryRefresh(entry) {
298
+ var _a;
299
+ while (true) {
300
+ const operation = entry.refreshOperation;
301
+ if (operation === undefined) {
302
+ return;
303
+ }
304
+ const outcome = await Promise.race([
305
+ operation.promise.then(() => ({ type: 'completed' }), error => ({ type: 'failed', error })),
306
+ operation.replaced.then(() => ({ type: 'replaced' })),
307
+ ]);
308
+ if (!this.listenerEntrySet.has(entry)) {
309
+ return;
310
+ }
311
+ else if (outcome.type === 'replaced' ||
312
+ ((_a = entry.refreshOperation) === null || _a === void 0 ? void 0 : _a.token) !== operation.token) {
313
+ continue;
314
+ }
315
+ else if (outcome.type === 'failed') {
316
+ throw outcome.error;
317
+ }
318
+ return;
319
+ }
320
+ }
321
+ async readAndPublishState(entries, refreshToken, refreshSequence, onlineOverride) {
322
+ var _a, _b, _c;
323
+ const propertyMap = createEntryPropertyMap(entries);
324
+ const propertyBaselineMap = this.captureRevisions(propertyMap);
325
+ const generation = this.stateGeneration;
326
+ const propertyRead = settlePromise(onlineOverride === false || propertyMap.size === 0
327
+ ? Promise.resolve([])
328
+ : Promise.resolve().then(() => this.readProperties([...propertyMap.values()])));
329
+ let requestedOnline;
330
+ try {
331
+ requestedOnline =
332
+ onlineOverride !== null && onlineOverride !== void 0 ? onlineOverride : (await Promise.resolve().then(() => this.readOnline()));
333
+ }
334
+ catch (error) {
335
+ if (!this.isRefreshCurrent(entries, refreshToken, generation)) {
336
+ return;
337
+ }
338
+ throw error;
339
+ }
340
+ let currentEntries = this.getCurrentRefreshEntries(entries, refreshToken, generation);
341
+ if (currentEntries.length === 0) {
342
+ return;
343
+ }
344
+ else if (typeof requestedOnline !== 'boolean') {
345
+ throw new TypeError(`Cloud device ${this.did} returned invalid online state.`);
346
+ }
347
+ let online = this.resolveRefreshOnline(requestedOnline, refreshSequence);
348
+ if (!online) {
349
+ this.commitRefreshOnline(false, refreshSequence);
350
+ this.publishState(currentEntries, false, new Map());
351
+ return;
352
+ }
353
+ const propertyOutcome = await propertyRead;
354
+ currentEntries = this.getCurrentRefreshEntries(entries, refreshToken, generation);
355
+ if (currentEntries.length === 0) {
356
+ return;
357
+ }
358
+ online = this.resolveRefreshOnline(requestedOnline, refreshSequence);
359
+ if (!online) {
360
+ this.publishState(currentEntries, false, new Map());
361
+ return;
362
+ }
363
+ else if (propertyOutcome.status === 'rejected') {
364
+ throw propertyOutcome.reason;
365
+ }
366
+ const currentPropertyMap = createEntryPropertyMap(currentEntries);
367
+ const { resultMap, resultErrorMap, errors } = collectSnapshotResults(this.did, currentPropertyMap, propertyOutcome.value);
368
+ for (const error of errors) {
369
+ this.notifyError(error);
370
+ }
371
+ const propertyErrorMap = new Map();
372
+ const propertyUpdateMap = new Map();
373
+ for (const [key, property] of currentPropertyMap) {
374
+ const baseline = (_a = propertyBaselineMap.get(key)) !== null && _a !== void 0 ? _a : 0;
375
+ const currentRevision = (_b = this.propertyRevisionMap.get(key)) !== null && _b !== void 0 ? _b : 0;
376
+ const cachedProperty = this.propertyCacheMap.get(key);
377
+ const cachedRefreshSequence = (_c = this.propertyRefreshSequenceMap.get(key)) !== null && _c !== void 0 ? _c : 0;
378
+ if (currentRevision !== baseline &&
379
+ cachedProperty !== undefined &&
380
+ (cachedProperty.source === 'mqtt' ||
381
+ cachedRefreshSequence > refreshSequence)) {
382
+ continue;
383
+ }
384
+ const resultError = resultErrorMap.get(key);
385
+ if (resultError !== undefined) {
386
+ propertyErrorMap.set(key, resultError);
387
+ continue;
388
+ }
389
+ const result = resultMap.get(key);
390
+ if (result === undefined) {
391
+ propertyErrorMap.set(key, new Error(`Cloud snapshot omitted property ${key}.`));
392
+ }
393
+ else if (result.code !== 0 && result.code !== 1) {
394
+ propertyErrorMap.set(key, new Error(`Cloud snapshot property ${key} failed: ${result.code}.`));
395
+ }
396
+ else if (!Object.hasOwn(result, 'value')) {
397
+ propertyErrorMap.set(key, new Error(`Cloud snapshot property ${key} has no value.`));
398
+ }
399
+ else {
400
+ propertyUpdateMap.set(key, { property, value: result.value });
401
+ }
402
+ }
403
+ const successfulEntries = [];
404
+ const refreshErrors = [];
405
+ for (const entry of currentEntries) {
406
+ const entryErrors = [...entry.propertyMap.keys()].flatMap(key => {
407
+ var _a, _b, _c;
408
+ const error = propertyErrorMap.get(key);
409
+ if (error === undefined) {
410
+ return [];
411
+ }
412
+ const baseline = (_a = propertyBaselineMap.get(key)) !== null && _a !== void 0 ? _a : 0;
413
+ const currentRevision = (_b = this.propertyRevisionMap.get(key)) !== null && _b !== void 0 ? _b : 0;
414
+ const cachedProperty = this.propertyCacheMap.get(key);
415
+ const cachedRefreshSequence = (_c = this.propertyRefreshSequenceMap.get(key)) !== null && _c !== void 0 ? _c : 0;
416
+ return currentRevision !== baseline &&
417
+ cachedProperty !== undefined &&
418
+ (cachedProperty.source === 'mqtt' ||
419
+ cachedRefreshSequence > refreshSequence)
420
+ ? []
421
+ : [error];
422
+ });
423
+ if (entryErrors.length > 0) {
424
+ refreshErrors.push(...entryErrors);
425
+ continue;
426
+ }
427
+ successfulEntries.push(entry);
428
+ }
429
+ const successfulPropertyKeySet = new Set(successfulEntries.flatMap(entry => [...entry.propertyMap.keys()]));
430
+ for (const [key, update] of propertyUpdateMap) {
431
+ if (successfulPropertyKeySet.has(key)) {
432
+ this.cacheProperty(update.property, update.value, 'snapshot', refreshSequence);
433
+ }
434
+ }
435
+ if (successfulEntries.length > 0) {
436
+ this.commitRefreshOnline(true, refreshSequence);
437
+ for (const entry of successfulEntries) {
438
+ const properties = [...entry.propertyMap.keys()].map(key => {
439
+ const property = this.propertyCacheMap.get(key);
440
+ if (property === undefined) {
441
+ throw new TypeError(`Cloud device state is missing property ${key}.`);
442
+ }
443
+ return property;
444
+ });
445
+ try {
446
+ publishListenerState(entry, {
447
+ did: this.did,
448
+ online: true,
449
+ properties,
450
+ });
451
+ }
452
+ catch (error) {
453
+ refreshErrors.push(error);
454
+ }
455
+ }
456
+ }
457
+ if (refreshErrors.length > 0) {
458
+ throw refreshErrors[0];
459
+ }
460
+ }
461
+ getCurrentRefreshEntries(entries, refreshToken, generation) {
462
+ if (generation !== this.stateGeneration) {
463
+ return [];
464
+ }
465
+ return entries.filter(entry => {
466
+ var _a;
467
+ return this.listenerEntrySet.has(entry) &&
468
+ ((_a = entry.refreshOperation) === null || _a === void 0 ? void 0 : _a.token) === refreshToken;
469
+ });
470
+ }
471
+ isRefreshCurrent(entries, refreshToken, generation) {
472
+ return (this.getCurrentRefreshEntries(entries, refreshToken, generation).length >
473
+ 0);
474
+ }
475
+ resolveRefreshOnline(requestedOnline, refreshSequence) {
476
+ var _a;
477
+ return refreshSequence < this.onlineRefreshSequence
478
+ ? ((_a = this.online) !== null && _a !== void 0 ? _a : requestedOnline)
479
+ : requestedOnline;
480
+ }
481
+ commitRefreshOnline(online, refreshSequence) {
482
+ if (refreshSequence < this.onlineRefreshSequence) {
483
+ return;
484
+ }
485
+ this.online = online;
486
+ this.onlineRefreshSequence = refreshSequence;
487
+ }
488
+ publishState(entries, online, propertyMap) {
489
+ const errors = [];
490
+ for (const entry of entries) {
491
+ const properties = [...entry.propertyMap.keys()].flatMap(key => {
492
+ const property = propertyMap.get(key);
493
+ return property === undefined ? [] : [property];
494
+ });
495
+ try {
496
+ publishListenerState(entry, { did: this.did, online, properties });
497
+ }
498
+ catch (error) {
499
+ errors.push(error);
500
+ }
501
+ }
502
+ if (errors.length > 0) {
503
+ throw errors[0];
504
+ }
505
+ }
506
+ handleMessage(message) {
507
+ if (message.did !== this.did) {
508
+ this.notifyError(new Error(`Cloud MQTT routed unexpected device ${message.did}.`));
509
+ return;
510
+ }
511
+ if (message.type === 'property') {
512
+ const update = this.cacheProperty({ did: message.did, siid: message.siid, piid: message.piid }, message.value, 'mqtt');
513
+ const key = getPropertyKey(update);
514
+ for (const entry of this.listenerEntrySet) {
515
+ if (entry.initialized && entry.propertyMap.has(key)) {
516
+ callListener(entry.listener, 'onPropertyChanged', update);
517
+ }
518
+ }
519
+ }
520
+ else if (message.type === 'event') {
521
+ const event = {
522
+ did: message.did,
523
+ siid: message.siid,
524
+ eiid: message.eiid,
525
+ arguments: message.arguments,
526
+ };
527
+ for (const { listener } of this.listenerEntrySet) {
528
+ callListener(listener, 'onEventOccurred', event);
529
+ }
530
+ }
531
+ else {
532
+ this.stateGeneration++;
533
+ this.requestStateRefresh(message.online);
534
+ }
535
+ }
536
+ cacheProperty(property, value, source, refreshSequence) {
537
+ const key = getPropertyKey(property);
538
+ const revision = ++this.revision;
539
+ const update = {
540
+ ...property,
541
+ value,
542
+ revision,
543
+ source,
544
+ };
545
+ this.propertyCacheMap.set(key, update);
546
+ this.propertyRevisionMap.set(key, revision);
547
+ if (refreshSequence !== undefined) {
548
+ this.propertyRefreshSequenceMap.set(key, refreshSequence);
549
+ }
550
+ return update;
551
+ }
552
+ async removeListener(listenerEntry) {
553
+ var _a;
554
+ if (!this.listenerEntrySet.delete(listenerEntry)) {
555
+ return;
556
+ }
557
+ (_a = listenerEntry.refreshOperation) === null || _a === void 0 ? void 0 : _a.replace();
558
+ listenerEntry.refreshOperation = undefined;
559
+ const subscribePromise = this.subscribePromise;
560
+ if (subscribePromise !== undefined) {
561
+ await subscribePromise.catch(() => undefined);
562
+ }
563
+ if (this.listenerEntrySet.size > 0) {
564
+ return;
565
+ }
566
+ this.stateRefreshRequest = undefined;
567
+ this.stopStateRefresh();
568
+ if (!this.subscribed) {
569
+ this.onEmpty();
570
+ return;
571
+ }
572
+ this.subscribed = false;
573
+ const unsubscribePromise = this.messageSource.unsubscribeDevice(this.did);
574
+ this.unsubscribePromise = unsubscribePromise;
575
+ try {
576
+ await unsubscribePromise;
577
+ }
578
+ finally {
579
+ if (this.unsubscribePromise === unsubscribePromise) {
580
+ this.unsubscribePromise = undefined;
581
+ }
582
+ if (this.listenerEntrySet.size === 0) {
583
+ this.onEmpty();
584
+ }
585
+ }
586
+ }
587
+ captureRevisions(propertyMap) {
588
+ return new Map([...propertyMap.keys()].map(key => {
589
+ var _a;
590
+ return [
591
+ key,
592
+ (_a = this.propertyRevisionMap.get(key)) !== null && _a !== void 0 ? _a : 0,
593
+ ];
594
+ }));
595
+ }
596
+ notifyError(error) {
597
+ for (const { listener } of this.listenerEntrySet) {
598
+ notifyListenerError(listener, error);
599
+ }
600
+ }
601
+ }
602
+ function createRefreshOperation(token, promise) {
603
+ let replace = () => undefined;
604
+ const replaced = new Promise(resolve => {
605
+ replace = resolve;
606
+ });
607
+ return { token, promise, replaced, replace };
608
+ }
609
+ function settlePromise(promise) {
610
+ return promise.then(value => ({ status: 'fulfilled', value }), reason => ({ status: 'rejected', reason }));
611
+ }
612
+ function createEntryPropertyMap(entries) {
613
+ const propertyMap = new Map();
614
+ for (const entry of entries) {
615
+ for (const [key, property] of entry.propertyMap) {
616
+ propertyMap.set(key, property);
617
+ }
618
+ }
619
+ return propertyMap;
620
+ }
621
+ function collectSnapshotResults(did, propertyMap, results) {
622
+ const resultMap = new Map();
623
+ const resultErrorMap = new Map();
624
+ const errors = [];
625
+ for (const result of results) {
626
+ if (result.did !== did) {
627
+ errors.push(new Error(`Cloud snapshot returned unexpected device ${result.did}.`));
628
+ continue;
629
+ }
630
+ const key = getPropertyKey(result);
631
+ if (!propertyMap.has(key)) {
632
+ errors.push(new Error(`Cloud snapshot returned unexpected property ${key}.`));
633
+ }
634
+ else if (resultMap.has(key) || resultErrorMap.has(key)) {
635
+ resultMap.delete(key);
636
+ resultErrorMap.set(key, new Error(`Cloud snapshot returned duplicate property ${key}.`));
637
+ }
638
+ else {
639
+ resultMap.set(key, result);
640
+ }
641
+ }
642
+ return { resultMap, resultErrorMap, errors };
643
+ }
644
+ function createPropertyMap(did, properties) {
645
+ const propertyMap = new Map();
646
+ for (const property of properties) {
647
+ if (property.did !== did) {
648
+ throw new Error(`Cloud device ${did} cannot subscribe to property for ${property.did}.`);
649
+ }
650
+ propertyMap.set(getPropertyKey(property), property);
651
+ }
652
+ return propertyMap;
653
+ }
654
+ function getPropertyKey(property) {
655
+ return `${property.siid}.${property.piid}`;
656
+ }
657
+ function callListener(listener, name, value) {
658
+ const callback = listener[name];
659
+ if (callback === undefined) {
660
+ return;
661
+ }
662
+ try {
663
+ callback(value);
664
+ }
665
+ catch (error) {
666
+ notifyListenerError(listener, error);
667
+ }
668
+ }
669
+ function publishListenerState(entry, state) {
670
+ var _a, _b;
671
+ (_b = (_a = entry.listener).onStateChanged) === null || _b === void 0 ? void 0 : _b.call(_a, state);
672
+ entry.initialized = true;
673
+ }
674
+ function notifyListenerError(listener, error) {
675
+ if (listener.onError === undefined) {
676
+ console.error(error);
677
+ return;
678
+ }
679
+ try {
680
+ listener.onError(error);
681
+ }
682
+ catch (listenerError) {
683
+ console.error(listenerError);
684
+ }
685
+ }
686
+ //# sourceMappingURL=device.js.map