@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,5 @@
1
+ export * from './client.js';
2
+ export * from './constants.js';
3
+ export * from './device.js';
4
+ export * from './mqtt.js';
5
+ export * from './transport.js';
@@ -0,0 +1,671 @@
1
+ import {type IClientOptions, type MqttClient, connectAsync} from 'mqtt';
2
+
3
+ import {type CloudServer, OAUTH2_CLIENT_ID} from '../backend/index.js';
4
+
5
+ import {
6
+ CLOUD_MQTT_CONNECT_TIMEOUT,
7
+ CLOUD_MQTT_KEEPALIVE,
8
+ CLOUD_MQTT_PORT,
9
+ CLOUD_MQTT_RECONNECT_INTERVAL,
10
+ CLOUD_MQTT_SUBSCRIPTION_BATCH_INTERVAL,
11
+ CLOUD_MQTT_SUBSCRIPTION_BATCH_SIZE,
12
+ getCloudMqttHost,
13
+ } from './constants.js';
14
+
15
+ export class CloudMqttClient {
16
+ private accessToken: string;
17
+
18
+ private mqttClient: MqttClient | undefined;
19
+
20
+ private connectPromise: Promise<void> | undefined;
21
+
22
+ private readyOperation:
23
+ | {
24
+ readonly generation: number;
25
+ readonly promise: Promise<void>;
26
+ }
27
+ | undefined;
28
+
29
+ private nextConnectionGeneration = 0;
30
+
31
+ private activeConnectionGeneration: number | undefined;
32
+
33
+ private operationGeneration = 0;
34
+
35
+ private readyRetryToken: object | undefined;
36
+
37
+ private readyRetryDelayCancel: (() => void) | undefined;
38
+
39
+ private ready = false;
40
+
41
+ private readonly deviceHandlerMap = new Map<
42
+ string,
43
+ CloudMqttDeviceMessageHandler
44
+ >();
45
+
46
+ private readonly subscribedDeviceSet = new Set<string>();
47
+
48
+ private readonly connectionStateListenerSet =
49
+ new Set<CloudMqttConnectionStateListener>();
50
+
51
+ constructor(
52
+ private readonly options: CloudMqttClientOptions,
53
+ private readonly connector: CloudMqttConnector = defaultConnector,
54
+ ) {
55
+ this.accessToken = options.accessToken;
56
+ }
57
+
58
+ updateAccessToken(accessToken: string): void {
59
+ this.accessToken = accessToken;
60
+
61
+ if (this.mqttClient !== undefined) {
62
+ this.mqttClient.options.password = accessToken;
63
+ }
64
+ }
65
+
66
+ async connect(): Promise<void> {
67
+ if (this.ready) {
68
+ return;
69
+ }
70
+
71
+ if (this.mqttClient !== undefined) {
72
+ const mqttClient = this.mqttClient;
73
+ await this.waitUntilConnected(mqttClient);
74
+ const generation = this.startConnectionSession(mqttClient);
75
+ await this.markReady(mqttClient, generation);
76
+ return;
77
+ }
78
+
79
+ let connectPromise = this.connectPromise;
80
+
81
+ if (connectPromise === undefined) {
82
+ connectPromise = this.createConnection();
83
+ this.connectPromise = connectPromise;
84
+ }
85
+
86
+ try {
87
+ await connectPromise;
88
+ } finally {
89
+ if (this.connectPromise === connectPromise) {
90
+ this.connectPromise = undefined;
91
+ }
92
+ }
93
+ }
94
+
95
+ async disconnect(): Promise<void> {
96
+ this.operationGeneration++;
97
+ this.stopReadyRetry();
98
+
99
+ const connectPromise = this.connectPromise;
100
+
101
+ if (connectPromise !== undefined) {
102
+ await connectPromise.catch(() => undefined);
103
+ }
104
+
105
+ const mqttClient = this.mqttClient;
106
+ this.mqttClient = undefined;
107
+ this.activeConnectionGeneration = undefined;
108
+ this.subscribedDeviceSet.clear();
109
+ this.setReady(false);
110
+
111
+ if (mqttClient !== undefined) {
112
+ await mqttClient.endAsync();
113
+ }
114
+ }
115
+
116
+ async subscribeDevice(
117
+ did: string,
118
+ handler: CloudMqttDeviceMessageHandler,
119
+ ): Promise<void> {
120
+ validateDid(did);
121
+ const operationGeneration = this.operationGeneration;
122
+
123
+ const existingHandler = this.deviceHandlerMap.get(did);
124
+
125
+ if (existingHandler !== undefined && existingHandler !== handler) {
126
+ throw new Error(`Cloud MQTT device ${did} is already subscribed.`);
127
+ }
128
+
129
+ this.deviceHandlerMap.set(did, handler);
130
+
131
+ try {
132
+ while (!this.subscribedDeviceSet.has(did)) {
133
+ this.assertOperationGeneration(operationGeneration);
134
+ await this.connect();
135
+ this.assertOperationGeneration(operationGeneration);
136
+
137
+ if (this.subscribedDeviceSet.has(did)) {
138
+ break;
139
+ }
140
+
141
+ const mqttClient = this.mqttClient;
142
+
143
+ if (mqttClient === undefined) {
144
+ continue;
145
+ }
146
+
147
+ const generation = this.startConnectionSession(mqttClient);
148
+
149
+ try {
150
+ await this.subscribeTopics(
151
+ getDeviceTopics(did),
152
+ mqttClient,
153
+ generation,
154
+ );
155
+ } catch (error) {
156
+ if (
157
+ this.mqttClient === mqttClient &&
158
+ !this.isActiveConnectionSession(mqttClient, generation)
159
+ ) {
160
+ continue;
161
+ }
162
+
163
+ throw error;
164
+ }
165
+
166
+ this.assertActiveConnectionSession(mqttClient, generation);
167
+ this.subscribedDeviceSet.add(did);
168
+ }
169
+ } catch (error) {
170
+ if (existingHandler === undefined) {
171
+ this.deviceHandlerMap.delete(did);
172
+ }
173
+
174
+ throw error;
175
+ }
176
+ }
177
+
178
+ async unsubscribeDevice(did: string): Promise<void> {
179
+ this.deviceHandlerMap.delete(did);
180
+
181
+ const readyPromise = this.readyOperation?.promise;
182
+
183
+ if (readyPromise !== undefined) {
184
+ await readyPromise.catch(() => undefined);
185
+ }
186
+
187
+ this.subscribedDeviceSet.delete(did);
188
+
189
+ const mqttClient = this.mqttClient;
190
+
191
+ if (mqttClient !== undefined && mqttClient.connected) {
192
+ await mqttClient.unsubscribeAsync(getDeviceTopics(did));
193
+ }
194
+ }
195
+
196
+ addConnectionStateListener(
197
+ listener: CloudMqttConnectionStateListener,
198
+ ): () => void {
199
+ this.connectionStateListenerSet.add(listener);
200
+
201
+ return () => {
202
+ this.connectionStateListenerSet.delete(listener);
203
+ };
204
+ }
205
+
206
+ private async createConnection(): Promise<void> {
207
+ const mqttClient = await this.connector(
208
+ `mqtts://${getCloudMqttHost(this.options.cloudServer)}:${CLOUD_MQTT_PORT}`,
209
+ {
210
+ clientId: `ha.${this.options.uuid}`,
211
+ username: OAUTH2_CLIENT_ID,
212
+ password: this.accessToken,
213
+ keepalive: CLOUD_MQTT_KEEPALIVE,
214
+ protocolVersion: 5,
215
+ clean: true,
216
+ reconnectPeriod: CLOUD_MQTT_RECONNECT_INTERVAL,
217
+ connectTimeout: CLOUD_MQTT_CONNECT_TIMEOUT,
218
+ resubscribe: false,
219
+ },
220
+ );
221
+ this.mqttClient = mqttClient;
222
+
223
+ mqttClient.on('connect', () => {
224
+ if (this.mqttClient !== mqttClient || !mqttClient.connected) {
225
+ return;
226
+ }
227
+
228
+ const generation = this.startConnectionSession(mqttClient);
229
+ this.startReadyRetry(mqttClient, generation);
230
+ });
231
+ mqttClient.on('message', (topic, payload) => {
232
+ this.handleMessage(topic, payload);
233
+ });
234
+ mqttClient.on('close', () => {
235
+ if (this.mqttClient !== mqttClient) {
236
+ return;
237
+ }
238
+
239
+ this.activeConnectionGeneration = undefined;
240
+ this.stopReadyRetry();
241
+ this.subscribedDeviceSet.clear();
242
+ this.setReady(false);
243
+ });
244
+ mqttClient.on('error', console.error);
245
+
246
+ await this.waitUntilConnected(mqttClient);
247
+ const generation = this.startConnectionSession(mqttClient);
248
+ await this.markReady(mqttClient, generation);
249
+ }
250
+
251
+ private startReadyRetry(mqttClient: MqttClient, generation: number): void {
252
+ if (
253
+ this.ready ||
254
+ this.readyRetryToken !== undefined ||
255
+ !this.isActiveConnectionSession(mqttClient, generation)
256
+ ) {
257
+ return;
258
+ }
259
+
260
+ const token = {};
261
+ this.readyRetryToken = token;
262
+ void this.retryReady(mqttClient, generation, token).finally(() => {
263
+ if (this.readyRetryToken === token) {
264
+ this.readyRetryToken = undefined;
265
+ }
266
+ });
267
+ }
268
+
269
+ private async retryReady(
270
+ mqttClient: MqttClient,
271
+ generation: number,
272
+ token: object,
273
+ ): Promise<void> {
274
+ while (
275
+ this.readyRetryToken === token &&
276
+ this.isActiveConnectionSession(mqttClient, generation) &&
277
+ !this.ready
278
+ ) {
279
+ try {
280
+ await this.markReady(mqttClient, generation);
281
+ } catch (error) {
282
+ if (
283
+ this.readyRetryToken !== token ||
284
+ !this.isActiveConnectionSession(mqttClient, generation) ||
285
+ this.ready
286
+ ) {
287
+ return;
288
+ }
289
+
290
+ console.error(error);
291
+ await this.waitBeforeReadyRetry(token);
292
+ }
293
+ }
294
+ }
295
+
296
+ private waitBeforeReadyRetry(token: object): Promise<void> {
297
+ return new Promise(resolve => {
298
+ const complete = (): void => {
299
+ clearTimeout(timeout);
300
+
301
+ if (this.readyRetryDelayCancel === complete) {
302
+ this.readyRetryDelayCancel = undefined;
303
+ }
304
+
305
+ resolve();
306
+ };
307
+ const timeout = setTimeout(complete, CLOUD_MQTT_RECONNECT_INTERVAL);
308
+
309
+ this.readyRetryDelayCancel = complete;
310
+
311
+ if (this.readyRetryToken !== token) {
312
+ complete();
313
+ }
314
+ });
315
+ }
316
+
317
+ private stopReadyRetry(): void {
318
+ this.readyRetryToken = undefined;
319
+ this.readyRetryDelayCancel?.();
320
+ }
321
+
322
+ private async markReady(
323
+ mqttClient: MqttClient,
324
+ generation: number,
325
+ ): Promise<void> {
326
+ this.assertActiveConnectionSession(mqttClient, generation);
327
+
328
+ if (this.ready) {
329
+ return;
330
+ }
331
+
332
+ let readyOperation = this.readyOperation;
333
+
334
+ if (
335
+ readyOperation === undefined ||
336
+ readyOperation.generation !== generation
337
+ ) {
338
+ readyOperation = {
339
+ generation,
340
+ promise: this.subscribeAllDevices(mqttClient, generation),
341
+ };
342
+ this.readyOperation = readyOperation;
343
+ }
344
+
345
+ try {
346
+ await readyOperation.promise;
347
+
348
+ this.assertActiveConnectionSession(mqttClient, generation);
349
+ this.setReady(true);
350
+ } finally {
351
+ if (this.readyOperation === readyOperation) {
352
+ this.readyOperation = undefined;
353
+ }
354
+ }
355
+ }
356
+
357
+ private async subscribeAllDevices(
358
+ mqttClient: MqttClient,
359
+ generation: number,
360
+ ): Promise<void> {
361
+ const deviceIds = [...this.deviceHandlerMap.keys()];
362
+ const topicBatches = chunk(
363
+ deviceIds.flatMap(getDeviceTopics),
364
+ CLOUD_MQTT_SUBSCRIPTION_BATCH_SIZE,
365
+ );
366
+
367
+ for (const [index, topics] of topicBatches.entries()) {
368
+ await this.subscribeTopics(topics, mqttClient, generation);
369
+
370
+ if (index < topicBatches.length - 1) {
371
+ await delay(CLOUD_MQTT_SUBSCRIPTION_BATCH_INTERVAL);
372
+ this.assertActiveConnectionSession(mqttClient, generation);
373
+ }
374
+ }
375
+
376
+ this.assertActiveConnectionSession(mqttClient, generation);
377
+
378
+ for (const did of deviceIds) {
379
+ if (this.deviceHandlerMap.has(did)) {
380
+ this.subscribedDeviceSet.add(did);
381
+ }
382
+ }
383
+ }
384
+
385
+ private async subscribeTopics(
386
+ topics: readonly string[],
387
+ mqttClient: MqttClient,
388
+ generation: number,
389
+ ): Promise<void> {
390
+ if (topics.length === 0) {
391
+ return;
392
+ }
393
+
394
+ this.assertActiveConnectionSession(mqttClient, generation);
395
+
396
+ const grants = await mqttClient.subscribeAsync([...topics], {qos: 2});
397
+ this.assertActiveConnectionSession(mqttClient, generation);
398
+ const grantedTopicSet = new Set(
399
+ grants.filter(grant => grant.qos !== 128).map(grant => grant.topic),
400
+ );
401
+
402
+ for (const topic of topics) {
403
+ if (!grantedTopicSet.has(topic)) {
404
+ throw new Error(`Cloud MQTT subscription was rejected: ${topic}.`);
405
+ }
406
+ }
407
+ }
408
+
409
+ private startConnectionSession(mqttClient: MqttClient): number {
410
+ if (this.mqttClient !== mqttClient || !mqttClient.connected) {
411
+ throw new Error('Cloud MQTT is not connected.');
412
+ }
413
+
414
+ let generation = this.activeConnectionGeneration;
415
+
416
+ if (generation === undefined) {
417
+ generation = ++this.nextConnectionGeneration;
418
+ this.activeConnectionGeneration = generation;
419
+ }
420
+
421
+ return generation;
422
+ }
423
+
424
+ private isActiveConnectionSession(
425
+ mqttClient: MqttClient,
426
+ generation: number,
427
+ ): boolean {
428
+ return (
429
+ this.mqttClient === mqttClient &&
430
+ this.activeConnectionGeneration === generation &&
431
+ mqttClient.connected
432
+ );
433
+ }
434
+
435
+ private assertActiveConnectionSession(
436
+ mqttClient: MqttClient,
437
+ generation: number,
438
+ ): void {
439
+ if (!this.isActiveConnectionSession(mqttClient, generation)) {
440
+ throw new Error('Cloud MQTT disconnected while subscribing.');
441
+ }
442
+ }
443
+
444
+ private assertOperationGeneration(generation: number): void {
445
+ if (this.operationGeneration !== generation) {
446
+ throw new Error('Cloud MQTT disconnected while subscribing.');
447
+ }
448
+ }
449
+
450
+ private async waitUntilConnected(mqttClient: MqttClient): Promise<void> {
451
+ if (mqttClient.connected) {
452
+ return;
453
+ }
454
+
455
+ await new Promise<void>((resolve, reject) => {
456
+ const timeout = setTimeout(() => {
457
+ cleanup();
458
+ reject(new Error('Cloud MQTT connection timed out.'));
459
+ }, CLOUD_MQTT_CONNECT_TIMEOUT);
460
+
461
+ const onConnect = (): void => {
462
+ cleanup();
463
+ resolve();
464
+ };
465
+
466
+ const cleanup = (): void => {
467
+ clearTimeout(timeout);
468
+ mqttClient.off('connect', onConnect);
469
+ };
470
+
471
+ mqttClient.on('connect', onConnect);
472
+ });
473
+ }
474
+
475
+ private handleMessage(topic: string, payload: Buffer): void {
476
+ try {
477
+ const message = parseCloudMqttMessage(topic, payload);
478
+
479
+ if (message === undefined) {
480
+ return;
481
+ }
482
+
483
+ this.deviceHandlerMap.get(message.did)?.(message);
484
+ } catch (error) {
485
+ console.error(error);
486
+ }
487
+ }
488
+
489
+ private setReady(ready: boolean): void {
490
+ if (this.ready === ready) {
491
+ return;
492
+ }
493
+
494
+ this.ready = ready;
495
+
496
+ if (ready) {
497
+ this.stopReadyRetry();
498
+ }
499
+
500
+ for (const listener of this.connectionStateListenerSet) {
501
+ try {
502
+ listener(ready);
503
+ } catch (error) {
504
+ console.error(error);
505
+ }
506
+ }
507
+ }
508
+ }
509
+
510
+ export type CloudMqttClientOptions = {
511
+ readonly uuid: string;
512
+ readonly accessToken: string;
513
+ readonly cloudServer: CloudServer;
514
+ };
515
+
516
+ export type CloudMqttPropertyMessage = {
517
+ readonly type: 'property';
518
+ readonly did: string;
519
+ readonly siid: number;
520
+ readonly piid: number;
521
+ readonly value: unknown;
522
+ };
523
+
524
+ export type CloudMqttEventMessage = {
525
+ readonly type: 'event';
526
+ readonly did: string;
527
+ readonly siid: number;
528
+ readonly eiid: number;
529
+ readonly arguments: readonly unknown[];
530
+ };
531
+
532
+ export type CloudMqttStateMessage = {
533
+ readonly type: 'state';
534
+ readonly did: string;
535
+ readonly online: boolean;
536
+ };
537
+
538
+ export type CloudMqttDeviceMessage =
539
+ CloudMqttPropertyMessage | CloudMqttEventMessage | CloudMqttStateMessage;
540
+
541
+ export type CloudMqttDeviceMessageHandler = (
542
+ message: CloudMqttDeviceMessage,
543
+ ) => void;
544
+
545
+ export type CloudMqttConnectionStateListener = (connected: boolean) => void;
546
+
547
+ export type CloudMqttConnector = (
548
+ url: string,
549
+ options: IClientOptions,
550
+ ) => Promise<MqttClient>;
551
+
552
+ function defaultConnector(
553
+ url: string,
554
+ options: IClientOptions,
555
+ ): Promise<MqttClient> {
556
+ return connectAsync(url, options, false);
557
+ }
558
+
559
+ function parseCloudMqttMessage(
560
+ topic: string,
561
+ payload: Buffer,
562
+ ): CloudMqttDeviceMessage | undefined {
563
+ const parts = topic.split('/');
564
+
565
+ if (parts[0] !== 'device') {
566
+ return undefined;
567
+ }
568
+
569
+ const did = parts[1];
570
+
571
+ if (did === undefined) {
572
+ return undefined;
573
+ }
574
+
575
+ const message = requireRecord(JSON.parse(payload.toString('utf8')));
576
+
577
+ if (parts[2] === 'up' && parts[3] === 'properties_changed') {
578
+ const params = requireRecord(message.params);
579
+ const siid = requireInteger(params.siid);
580
+ const piid = requireInteger(params.piid);
581
+
582
+ if (!Object.hasOwn(params, 'value')) {
583
+ throw new Error('Cloud MQTT property message has no value.');
584
+ }
585
+
586
+ return {type: 'property', did, siid, piid, value: params.value};
587
+ } else if (parts[2] === 'up' && parts[3] === 'event_occured') {
588
+ const params = requireRecord(message.params);
589
+ const siid = requireInteger(params.siid);
590
+ const eiid = requireInteger(params.eiid);
591
+
592
+ if (!Array.isArray(params.arguments)) {
593
+ throw new Error('Cloud MQTT event message has invalid arguments.');
594
+ }
595
+
596
+ return {type: 'event', did, siid, eiid, arguments: params.arguments};
597
+ } else if (parts[2] === 'state') {
598
+ const deviceId = requireString(message.device_id);
599
+ const event = requireString(message.event);
600
+
601
+ if (deviceId !== did) {
602
+ throw new Error(`Cloud MQTT state message DID mismatch: ${deviceId}.`);
603
+ }
604
+
605
+ if (event !== 'online' && event !== 'offline') {
606
+ throw new Error(`Cloud MQTT state message has invalid event: ${event}.`);
607
+ }
608
+
609
+ return {type: 'state', did, online: event === 'online'};
610
+ }
611
+
612
+ return undefined;
613
+ }
614
+
615
+ function getDeviceTopics(did: string): string[] {
616
+ const topics = [
617
+ `device/${did}/up/properties_changed/#`,
618
+ `device/${did}/up/event_occured/#`,
619
+ ];
620
+
621
+ // Xiaomi cloud does not publish state for these virtual child devices.
622
+ if (!did.startsWith('blt.') && !did.startsWith('proxy.')) {
623
+ topics.push(`device/${did}/state/#`);
624
+ }
625
+
626
+ return topics;
627
+ }
628
+
629
+ function validateDid(did: string): void {
630
+ if (did === '' || did.includes('/')) {
631
+ throw new Error(`Invalid cloud device ID: ${did}.`);
632
+ }
633
+ }
634
+
635
+ function requireRecord(value: unknown): Record<string, unknown> {
636
+ if (typeof value !== 'object' || value === null || Array.isArray(value)) {
637
+ throw new Error('Cloud MQTT message is not an object.');
638
+ }
639
+
640
+ return value as Record<string, unknown>;
641
+ }
642
+
643
+ function requireInteger(value: unknown): number {
644
+ if (typeof value !== 'number' || !Number.isInteger(value)) {
645
+ throw new Error('Cloud MQTT message has an invalid integer.');
646
+ }
647
+
648
+ return value;
649
+ }
650
+
651
+ function requireString(value: unknown): string {
652
+ if (typeof value !== 'string') {
653
+ throw new Error('Cloud MQTT message has an invalid string.');
654
+ }
655
+
656
+ return value;
657
+ }
658
+
659
+ function chunk<T>(values: readonly T[], size: number): T[][] {
660
+ const chunks: T[][] = [];
661
+
662
+ for (let index = 0; index < values.length; index += size) {
663
+ chunks.push(values.slice(index, index + size));
664
+ }
665
+
666
+ return chunks;
667
+ }
668
+
669
+ function delay(milliseconds: number): Promise<void> {
670
+ return new Promise(resolve => setTimeout(resolve, milliseconds));
671
+ }
@@ -0,0 +1,46 @@
1
+ import type {BackendClient} from '../backend/index.js';
2
+ import {MiotEndpointConnectionTransport} from '../endpoint-connection.js';
3
+ import {
4
+ type MiotExecutionRequest,
5
+ type MiotExecutionResult,
6
+ MiotSetPropertyRequest,
7
+ } from '../miot/index.js';
8
+
9
+ export class MiotEndpointConnectionCloudTransport extends MiotEndpointConnectionTransport {
10
+ private readonly backendClient: BackendClient;
11
+
12
+ constructor(backendClient: BackendClient) {
13
+ super();
14
+ this.backendClient = backendClient;
15
+ }
16
+
17
+ override async executeRequest(
18
+ request: MiotExecutionRequest,
19
+ ): Promise<MiotExecutionResult> {
20
+ if (!(request instanceof MiotSetPropertyRequest)) {
21
+ return this.backendClient.invokeAction(request);
22
+ }
23
+
24
+ const results = await this.backendClient.setProperties([request]);
25
+
26
+ if (results.length !== 1) {
27
+ throw new Error(
28
+ `Cloud returned ${results.length} results for one MIoT request.`,
29
+ );
30
+ }
31
+
32
+ const [result] = results;
33
+
34
+ if (result === undefined) {
35
+ throw new Error('Cloud returned no result for a MIoT request.');
36
+ } else if (
37
+ result.did !== request.property.did ||
38
+ result.siid !== request.property.siid ||
39
+ result.piid !== request.property.piid
40
+ ) {
41
+ throw new Error('Cloud returned a result for an unexpected property.');
42
+ }
43
+
44
+ return result;
45
+ }
46
+ }