@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,1555 @@
1
+ import {X509Certificate, randomInt} from 'node:crypto';
2
+ import type {ConnectionOptions} from 'node:tls';
3
+
4
+ import {type IClientOptions, type MqttClient, connectAsync} from 'mqtt';
5
+
6
+ import {
7
+ MiotEndpointConnectionTransport,
8
+ MiotEndpointConnectionTransportUnavailableError,
9
+ } from '../endpoint-connection.js';
10
+ import {
11
+ type MiotExecutionRequest,
12
+ type MiotExecutionResult,
13
+ type MiotInvokeActionRequest,
14
+ type MiotProperty,
15
+ MiotSetPropertyRequest,
16
+ } from '../miot/index.js';
17
+
18
+ import {isMipsGatewayCertificate} from './certificate.js';
19
+ import {decodeMipsMessage, encodeMipsMessage} from './message.js';
20
+
21
+ const DEFAULT_PORT = 8883;
22
+ const KEEPALIVE_SECONDS = 60;
23
+ const CONNECT_TIMEOUT_MILLISECONDS = 10_000;
24
+ const RECONNECT_INTERVAL_MILLISECONDS = 6_000;
25
+ const REQUEST_TIMEOUT_MILLISECONDS = 10_000;
26
+ const UINT32_RANGE = 0x1_0000_0000;
27
+ const MQTT_QOS = 2;
28
+
29
+ export class LocalMqttClient extends MiotEndpointConnectionTransport {
30
+ private mqttClient: MqttClient | undefined;
31
+
32
+ private connectPromise: Promise<void> | undefined;
33
+
34
+ private readyOperation:
35
+ | {
36
+ readonly generation: number;
37
+ readonly promise: Promise<void>;
38
+ }
39
+ | undefined;
40
+
41
+ private readyRetryTimeout: ReturnType<typeof setTimeout> | undefined;
42
+
43
+ private activeConnectionGeneration: number | undefined;
44
+
45
+ private nextConnectionGeneration = 0;
46
+
47
+ private operationGeneration = 0;
48
+
49
+ private ready = false;
50
+
51
+ private nextMessageId = randomInt(UINT32_RANGE);
52
+
53
+ private readonly pendingRequestMap = new Map<number, PendingRequest>();
54
+
55
+ private readonly propertyListenerMap = new Map<
56
+ string,
57
+ Set<LocalPropertyListenerEntry>
58
+ >();
59
+
60
+ private readonly eventListenerMap = new Map<
61
+ string,
62
+ Set<LocalEventListenerEntry>
63
+ >();
64
+
65
+ private readonly subscribedPropertyDidSet = new Set<string>();
66
+
67
+ private readonly subscribedEventDidSet = new Set<string>();
68
+
69
+ private readonly deviceListChangedListenerSet =
70
+ new Set<LocalDeviceListChangedListener>();
71
+
72
+ private readonly connectionStateListenerSet =
73
+ new Set<LocalMqttConnectionStateListener>();
74
+
75
+ private propertyReadOperation: Promise<void> = Promise.resolve();
76
+
77
+ constructor(private readonly options: LocalMqttClientOptions) {
78
+ super();
79
+ validateOptions(options);
80
+ }
81
+
82
+ get connected(): boolean {
83
+ return this.ready;
84
+ }
85
+
86
+ async connect(): Promise<void> {
87
+ if (this.ready) {
88
+ return;
89
+ }
90
+
91
+ let connectPromise = this.connectPromise;
92
+
93
+ if (connectPromise === undefined) {
94
+ connectPromise = this.ensureConnected(this.operationGeneration);
95
+ this.connectPromise = connectPromise;
96
+ }
97
+
98
+ try {
99
+ await connectPromise;
100
+ } finally {
101
+ if (this.connectPromise === connectPromise) {
102
+ this.connectPromise = undefined;
103
+ }
104
+ }
105
+ }
106
+
107
+ async disconnect(): Promise<void> {
108
+ this.operationGeneration++;
109
+ this.stopReadyRetry();
110
+
111
+ const connectPromise = this.connectPromise;
112
+
113
+ if (connectPromise !== undefined) {
114
+ await connectPromise.catch(() => undefined);
115
+ }
116
+
117
+ this.stopReadyRetry();
118
+
119
+ const mqttClient = this.mqttClient;
120
+ this.mqttClient = undefined;
121
+ this.activeConnectionGeneration = undefined;
122
+ this.subscribedPropertyDidSet.clear();
123
+ this.subscribedEventDidSet.clear();
124
+ this.setReady(false);
125
+ this.rejectPendingRequests(
126
+ new LocalMqttRequestInterruptedError(
127
+ 'Local MQTT disconnected before a response was received.',
128
+ ),
129
+ );
130
+
131
+ if (mqttClient !== undefined) {
132
+ await mqttClient.endAsync(true);
133
+ }
134
+ }
135
+
136
+ addConnectionStateListener(
137
+ listener: LocalMqttConnectionStateListener,
138
+ ): () => void {
139
+ this.connectionStateListenerSet.add(listener);
140
+
141
+ return () => {
142
+ this.connectionStateListenerSet.delete(listener);
143
+ };
144
+ }
145
+
146
+ addDeviceListChangedListener(
147
+ listener: LocalDeviceListChangedListener,
148
+ ): () => void {
149
+ this.deviceListChangedListenerSet.add(listener);
150
+
151
+ return () => {
152
+ this.deviceListChangedListenerSet.delete(listener);
153
+ };
154
+ }
155
+
156
+ async getDeviceList(
157
+ timeoutMilliseconds = REQUEST_TIMEOUT_MILLISECONDS,
158
+ ): Promise<ReadonlyMap<string, LocalDeviceInfo>> {
159
+ const response = requireRecord(
160
+ await this.request('proxy/getDevList', {}, timeoutMilliseconds),
161
+ 'local device list response',
162
+ );
163
+ const deviceList = requireRecord(
164
+ response.devList,
165
+ 'local device list response.devList',
166
+ );
167
+ const result = new Map<string, LocalDeviceInfo>();
168
+
169
+ for (const [did, value] of Object.entries(deviceList)) {
170
+ validateDid(did);
171
+ const device = requireRecord(value, `local device list entry ${did}`);
172
+ result.set(did, {
173
+ online: readOptionalBoolean(device.online, 'online'),
174
+ specV2Access: readOptionalBoolean(device.specV2Access, 'specV2Access'),
175
+ pushAvailable: readOptionalBoolean(
176
+ device.pushAvailable,
177
+ 'pushAvailable',
178
+ ),
179
+ });
180
+ }
181
+
182
+ return result;
183
+ }
184
+
185
+ async getProperties(
186
+ properties: readonly MiotProperty[],
187
+ timeoutMilliseconds = REQUEST_TIMEOUT_MILLISECONDS,
188
+ ): Promise<readonly LocalPropertyResult[]> {
189
+ const operation = this.propertyReadOperation.then(() =>
190
+ this.readProperties(properties, timeoutMilliseconds),
191
+ );
192
+ this.propertyReadOperation = operation.then(
193
+ () => undefined,
194
+ () => undefined,
195
+ );
196
+ return operation;
197
+ }
198
+
199
+ private async readProperties(
200
+ properties: readonly MiotProperty[],
201
+ timeoutMilliseconds: number,
202
+ ): Promise<readonly LocalPropertyResult[]> {
203
+ const results: LocalPropertyResult[] = [];
204
+
205
+ // The gateway can associate concurrent proxy/get replies incorrectly.
206
+ // Sending one request at a time also preserves duplicates and input order.
207
+ for (const property of properties) {
208
+ validateProperty(property);
209
+ const response = requireRecord(
210
+ await this.request('proxy/get', property, timeoutMilliseconds),
211
+ 'local property response',
212
+ );
213
+
214
+ if (Object.hasOwn(response, 'value')) {
215
+ results.push({...property, code: 0, value: response.value});
216
+ continue;
217
+ }
218
+
219
+ const code = readResponseErrorCode(response);
220
+
221
+ if (code === undefined) {
222
+ throw new LocalMqttProtocolError(
223
+ 'Local property response has neither a value nor an error code.',
224
+ );
225
+ }
226
+
227
+ results.push({...property, code});
228
+ }
229
+
230
+ return results;
231
+ }
232
+
233
+ override async executeRequest(
234
+ request: MiotExecutionRequest,
235
+ ): Promise<MiotExecutionResult> {
236
+ const did =
237
+ request instanceof MiotSetPropertyRequest
238
+ ? request.property.did
239
+ : request.action.did;
240
+ const rpc =
241
+ request instanceof MiotSetPropertyRequest
242
+ ? createSetPropertiesRpc(request, this.allocateMessageId())
243
+ : createInvokeActionRpc(request, this.allocateMessageId());
244
+ const response = requireRecord(
245
+ await this.request('proxy/rpcReq', {
246
+ did,
247
+ rpc,
248
+ }),
249
+ 'local command response',
250
+ );
251
+
252
+ if (
253
+ request instanceof MiotSetPropertyRequest &&
254
+ Array.isArray(response.result) &&
255
+ response.result.length === 1
256
+ ) {
257
+ const result = requireRecord(
258
+ response.result[0],
259
+ 'local command response.result[0]',
260
+ );
261
+
262
+ if (result.did !== request.property.did) {
263
+ throw new LocalMqttProtocolError(
264
+ 'Local command response has an unexpected device ID.',
265
+ );
266
+ }
267
+
268
+ return {code: requireInteger(result.code, 'local command result code')};
269
+ } else if (
270
+ !(request instanceof MiotSetPropertyRequest) &&
271
+ response.result !== undefined
272
+ ) {
273
+ const result = requireRecord(response.result, 'local action response');
274
+
275
+ return {code: requireInteger(result.code, 'local action result code')};
276
+ }
277
+
278
+ const code = readResponseErrorCode(response);
279
+
280
+ if (code === undefined) {
281
+ throw new LocalMqttProtocolError(
282
+ 'Local command response has no execution result.',
283
+ );
284
+ }
285
+
286
+ return {code};
287
+ }
288
+
289
+ async subscribeProperties(
290
+ did: string,
291
+ listener: LocalPropertyListener,
292
+ ): Promise<LocalMqttPropertySubscription> {
293
+ validateDid(did);
294
+
295
+ let listenerSet = this.propertyListenerMap.get(did);
296
+ const firstListener = listenerSet === undefined;
297
+
298
+ if (listenerSet === undefined) {
299
+ listenerSet = new Set();
300
+ this.propertyListenerMap.set(did, listenerSet);
301
+ }
302
+
303
+ const listenerEntry = {listener};
304
+ listenerSet.add(listenerEntry);
305
+
306
+ try {
307
+ if (firstListener && this.ready) {
308
+ await this.subscribePropertyDid(did);
309
+ }
310
+ } catch (error) {
311
+ listenerSet.delete(listenerEntry);
312
+
313
+ if (listenerSet.size === 0) {
314
+ this.propertyListenerMap.delete(did);
315
+ }
316
+
317
+ throw error;
318
+ }
319
+
320
+ let disposed = false;
321
+
322
+ return {
323
+ dispose: async () => {
324
+ if (disposed) {
325
+ return;
326
+ }
327
+
328
+ disposed = true;
329
+ await this.removePropertyListener(did, listenerEntry);
330
+ },
331
+ };
332
+ }
333
+
334
+ async subscribeEvents(
335
+ did: string,
336
+ listener: LocalEventListener,
337
+ ): Promise<LocalMqttEventSubscription> {
338
+ validateDid(did);
339
+
340
+ let listenerSet = this.eventListenerMap.get(did);
341
+ const firstListener = listenerSet === undefined;
342
+
343
+ if (listenerSet === undefined) {
344
+ listenerSet = new Set();
345
+ this.eventListenerMap.set(did, listenerSet);
346
+ }
347
+
348
+ const listenerEntry = {listener};
349
+ listenerSet.add(listenerEntry);
350
+
351
+ try {
352
+ if (firstListener && this.ready) {
353
+ await this.subscribeEventDid(did);
354
+ }
355
+ } catch (error) {
356
+ listenerSet.delete(listenerEntry);
357
+
358
+ if (listenerSet.size === 0) {
359
+ this.eventListenerMap.delete(did);
360
+ }
361
+
362
+ throw error;
363
+ }
364
+
365
+ let disposed = false;
366
+
367
+ return {
368
+ dispose: async () => {
369
+ if (disposed) {
370
+ return;
371
+ }
372
+
373
+ disposed = true;
374
+ await this.removeEventListener(did, listenerEntry);
375
+ },
376
+ };
377
+ }
378
+
379
+ private async ensureConnected(operationGeneration: number): Promise<void> {
380
+ let mqttClient = this.mqttClient;
381
+
382
+ if (mqttClient === undefined) {
383
+ mqttClient = await this.createConnection(operationGeneration);
384
+ }
385
+
386
+ this.assertOperationGeneration(operationGeneration);
387
+ await this.waitUntilConnected(mqttClient);
388
+ this.assertOperationGeneration(operationGeneration);
389
+ const generation = this.startConnectionSession(mqttClient);
390
+ try {
391
+ await this.markReady(mqttClient, generation);
392
+ } catch (error) {
393
+ this.scheduleReadyRetry(mqttClient, generation);
394
+ throw error;
395
+ }
396
+
397
+ this.assertOperationGeneration(operationGeneration);
398
+ this.assertActiveConnectionSession(mqttClient, generation);
399
+ }
400
+
401
+ private async createConnection(
402
+ operationGeneration: number,
403
+ ): Promise<MqttClient> {
404
+ const connector = this.options.connector ?? defaultConnector;
405
+ const mqttClient = await connector(
406
+ getBrokerUrl(this.options.host, this.options.port ?? DEFAULT_PORT),
407
+ createMqttOptions(this.options),
408
+ );
409
+
410
+ if (this.operationGeneration !== operationGeneration) {
411
+ await mqttClient.endAsync(true);
412
+ throw new Error('Local MQTT connection was cancelled.');
413
+ }
414
+
415
+ this.mqttClient = mqttClient;
416
+ mqttClient.on('connect', () => {
417
+ if (this.mqttClient !== mqttClient || !mqttClient.connected) {
418
+ return;
419
+ }
420
+
421
+ const generation = this.startConnectionSession(mqttClient);
422
+ void this.markReady(mqttClient, generation).catch(error => {
423
+ if (this.isActiveConnectionSession(mqttClient, generation)) {
424
+ console.error(error);
425
+ this.scheduleReadyRetry(mqttClient, generation);
426
+ }
427
+ });
428
+ });
429
+ mqttClient.on('message', (topic, payload) => {
430
+ this.handleMessage(topic, payload);
431
+ });
432
+ mqttClient.on('close', () => {
433
+ if (this.mqttClient !== mqttClient) {
434
+ return;
435
+ }
436
+
437
+ this.activeConnectionGeneration = undefined;
438
+ this.stopReadyRetry();
439
+ this.subscribedPropertyDidSet.clear();
440
+ this.subscribedEventDidSet.clear();
441
+ this.setReady(false);
442
+ this.rejectPendingRequests(
443
+ new LocalMqttRequestInterruptedError(
444
+ 'Local MQTT connection closed before a response was received.',
445
+ ),
446
+ );
447
+ });
448
+ mqttClient.on('error', error => {
449
+ if (this.mqttClient === mqttClient) {
450
+ console.error(error);
451
+ }
452
+ });
453
+
454
+ return mqttClient;
455
+ }
456
+
457
+ private async markReady(
458
+ mqttClient: MqttClient,
459
+ generation: number,
460
+ ): Promise<void> {
461
+ this.assertActiveConnectionSession(mqttClient, generation);
462
+
463
+ if (this.ready) {
464
+ return;
465
+ }
466
+
467
+ let readyOperation = this.readyOperation;
468
+
469
+ if (
470
+ readyOperation === undefined ||
471
+ readyOperation.generation !== generation
472
+ ) {
473
+ readyOperation = {
474
+ generation,
475
+ promise: this.restoreSubscriptions(mqttClient, generation),
476
+ };
477
+ this.readyOperation = readyOperation;
478
+ }
479
+
480
+ try {
481
+ await readyOperation.promise;
482
+ this.assertActiveConnectionSession(mqttClient, generation);
483
+ this.setReady(true);
484
+ } finally {
485
+ if (this.readyOperation === readyOperation) {
486
+ this.readyOperation = undefined;
487
+ }
488
+ }
489
+ }
490
+
491
+ private scheduleReadyRetry(mqttClient: MqttClient, generation: number): void {
492
+ if (
493
+ this.readyRetryTimeout !== undefined ||
494
+ !this.isActiveConnectionSession(mqttClient, generation)
495
+ ) {
496
+ return;
497
+ }
498
+
499
+ const timeout = setTimeout(() => {
500
+ if (this.readyRetryTimeout === timeout) {
501
+ this.readyRetryTimeout = undefined;
502
+ }
503
+
504
+ if (!this.isActiveConnectionSession(mqttClient, generation)) {
505
+ return;
506
+ }
507
+
508
+ void this.markReady(mqttClient, generation).catch(error => {
509
+ if (this.isActiveConnectionSession(mqttClient, generation)) {
510
+ console.error(error);
511
+ this.scheduleReadyRetry(mqttClient, generation);
512
+ }
513
+ });
514
+ }, RECONNECT_INTERVAL_MILLISECONDS);
515
+ timeout.unref();
516
+ this.readyRetryTimeout = timeout;
517
+ }
518
+
519
+ private stopReadyRetry(): void {
520
+ if (this.readyRetryTimeout === undefined) {
521
+ return;
522
+ }
523
+
524
+ clearTimeout(this.readyRetryTimeout);
525
+ this.readyRetryTimeout = undefined;
526
+ }
527
+
528
+ private async restoreSubscriptions(
529
+ mqttClient: MqttClient,
530
+ generation: number,
531
+ ): Promise<void> {
532
+ this.setReady(false);
533
+ this.subscribedPropertyDidSet.clear();
534
+ this.subscribedEventDidSet.clear();
535
+ await this.subscribeTopics(
536
+ [this.receiveTopic, 'master/appMsg/devListChange'],
537
+ mqttClient,
538
+ generation,
539
+ );
540
+
541
+ while (true) {
542
+ this.assertActiveConnectionSession(mqttClient, generation);
543
+ const dids = [...this.propertyListenerMap.keys()].filter(
544
+ did => !this.subscribedPropertyDidSet.has(did),
545
+ );
546
+ const eventDids = [...this.eventListenerMap.keys()].filter(
547
+ did => !this.subscribedEventDidSet.has(did),
548
+ );
549
+
550
+ if (dids.length === 0 && eventDids.length === 0) {
551
+ return;
552
+ }
553
+
554
+ await this.subscribeTopics(
555
+ [
556
+ ...dids.map(getPropertyPublishTopic),
557
+ ...eventDids.map(getEventPublishTopic),
558
+ ],
559
+ mqttClient,
560
+ generation,
561
+ );
562
+
563
+ for (const did of dids) {
564
+ if (this.propertyListenerMap.has(did)) {
565
+ this.subscribedPropertyDidSet.add(did);
566
+ }
567
+ }
568
+
569
+ for (const did of eventDids) {
570
+ if (this.eventListenerMap.has(did)) {
571
+ this.subscribedEventDidSet.add(did);
572
+ }
573
+ }
574
+ }
575
+ }
576
+
577
+ private async subscribePropertyDid(did: string): Promise<void> {
578
+ if (this.subscribedPropertyDidSet.has(did)) {
579
+ return;
580
+ }
581
+
582
+ const mqttClient = this.mqttClient;
583
+ const generation = this.activeConnectionGeneration;
584
+
585
+ if (mqttClient === undefined || generation === undefined) {
586
+ throw new MiotEndpointConnectionTransportUnavailableError(
587
+ 'Local MQTT is not connected.',
588
+ );
589
+ }
590
+
591
+ await this.subscribeTopics(
592
+ [getPropertyPublishTopic(did)],
593
+ mqttClient,
594
+ generation,
595
+ );
596
+ this.subscribedPropertyDidSet.add(did);
597
+ }
598
+
599
+ private async subscribeEventDid(did: string): Promise<void> {
600
+ if (this.subscribedEventDidSet.has(did)) {
601
+ return;
602
+ }
603
+
604
+ const mqttClient = this.mqttClient;
605
+ const generation = this.activeConnectionGeneration;
606
+
607
+ if (mqttClient === undefined || generation === undefined) {
608
+ throw new MiotEndpointConnectionTransportUnavailableError(
609
+ 'Local MQTT is not connected.',
610
+ );
611
+ }
612
+
613
+ await this.subscribeTopics(
614
+ [getEventPublishTopic(did)],
615
+ mqttClient,
616
+ generation,
617
+ );
618
+ this.subscribedEventDidSet.add(did);
619
+ }
620
+
621
+ private async subscribeTopics(
622
+ topics: readonly string[],
623
+ mqttClient: MqttClient,
624
+ generation: number,
625
+ ): Promise<void> {
626
+ if (topics.length === 0) {
627
+ return;
628
+ }
629
+
630
+ this.assertActiveConnectionSession(mqttClient, generation);
631
+ const grants = await mqttClient.subscribeAsync([...topics], {
632
+ qos: MQTT_QOS,
633
+ });
634
+ this.assertActiveConnectionSession(mqttClient, generation);
635
+ const grantedQosMap = new Map(
636
+ grants.map(grant => [grant.topic, grant.qos]),
637
+ );
638
+
639
+ for (const topic of topics) {
640
+ if (grantedQosMap.get(topic) !== MQTT_QOS) {
641
+ throw new Error(
642
+ `Local MQTT QoS 2 subscription was rejected: ${topic}.`,
643
+ );
644
+ }
645
+ }
646
+ }
647
+
648
+ private async removePropertyListener(
649
+ did: string,
650
+ listenerEntry: LocalPropertyListenerEntry,
651
+ ): Promise<void> {
652
+ const listenerSet = this.propertyListenerMap.get(did);
653
+
654
+ if (listenerSet === undefined) {
655
+ return;
656
+ }
657
+
658
+ listenerSet.delete(listenerEntry);
659
+
660
+ if (listenerSet.size > 0) {
661
+ return;
662
+ }
663
+
664
+ this.propertyListenerMap.delete(did);
665
+
666
+ if (!this.subscribedPropertyDidSet.delete(did)) {
667
+ return;
668
+ }
669
+
670
+ const mqttClient = this.mqttClient;
671
+
672
+ if (mqttClient === undefined || !mqttClient.connected) {
673
+ return;
674
+ }
675
+
676
+ await mqttClient.unsubscribeAsync(getPropertyPublishTopic(did));
677
+ }
678
+
679
+ private async removeEventListener(
680
+ did: string,
681
+ listenerEntry: LocalEventListenerEntry,
682
+ ): Promise<void> {
683
+ const listenerSet = this.eventListenerMap.get(did);
684
+
685
+ if (listenerSet === undefined) {
686
+ return;
687
+ }
688
+
689
+ listenerSet.delete(listenerEntry);
690
+
691
+ if (listenerSet.size > 0) {
692
+ return;
693
+ }
694
+
695
+ this.eventListenerMap.delete(did);
696
+
697
+ if (!this.subscribedEventDidSet.delete(did)) {
698
+ return;
699
+ }
700
+
701
+ const mqttClient = this.mqttClient;
702
+
703
+ if (mqttClient === undefined || !mqttClient.connected) {
704
+ return;
705
+ }
706
+
707
+ await mqttClient.unsubscribeAsync(getEventPublishTopic(did));
708
+ }
709
+
710
+ private request(
711
+ operation: string,
712
+ body: unknown,
713
+ timeoutMilliseconds = REQUEST_TIMEOUT_MILLISECONDS,
714
+ ): Promise<unknown> {
715
+ validateTimeout(timeoutMilliseconds);
716
+ const mqttClient = this.mqttClient;
717
+
718
+ if (mqttClient === undefined || !mqttClient.connected || !this.ready) {
719
+ throw new MiotEndpointConnectionTransportUnavailableError(
720
+ 'Local MQTT is not connected.',
721
+ );
722
+ }
723
+
724
+ const id = this.allocateMessageId();
725
+ const pending = createPendingRequest(
726
+ id,
727
+ operation,
728
+ timeoutMilliseconds,
729
+ error => {
730
+ this.rejectPendingRequest(id, error);
731
+ },
732
+ );
733
+ this.pendingRequestMap.set(id, pending);
734
+ const payload = encodeMipsMessage({
735
+ id,
736
+ from: 'local',
737
+ returnTopic: this.replyTopic,
738
+ payload: JSON.stringify(body),
739
+ });
740
+ let publishPromise: Promise<unknown>;
741
+
742
+ try {
743
+ publishPromise = mqttClient.publishAsync(`master/${operation}`, payload, {
744
+ qos: MQTT_QOS,
745
+ });
746
+ } catch (error) {
747
+ this.rejectPendingRequest(
748
+ id,
749
+ new LocalMqttRequestInterruptedError(
750
+ 'Local MQTT failed after command publication began.',
751
+ {cause: error},
752
+ ),
753
+ );
754
+ return pending.promise;
755
+ }
756
+
757
+ void publishPromise.catch(error => {
758
+ this.rejectPendingRequest(
759
+ id,
760
+ new LocalMqttRequestInterruptedError(
761
+ 'Local MQTT failed after command publication began.',
762
+ {cause: error},
763
+ ),
764
+ );
765
+ });
766
+
767
+ return pending.promise;
768
+ }
769
+
770
+ private handleMessage(topic: string, payload: Buffer): void {
771
+ try {
772
+ const message = decodeMipsMessage(payload);
773
+
774
+ if (topic === this.replyTopic) {
775
+ if (message.payload === undefined) {
776
+ this.rejectPendingRequest(
777
+ message.id,
778
+ new LocalMqttProtocolError(
779
+ 'Local MQTT response has no JSON payload.',
780
+ ),
781
+ );
782
+ return;
783
+ }
784
+
785
+ let value: unknown;
786
+
787
+ try {
788
+ value = JSON.parse(message.payload);
789
+ } catch (error) {
790
+ this.rejectPendingRequest(
791
+ message.id,
792
+ new LocalMqttProtocolError(
793
+ 'Local MQTT response is not valid JSON.',
794
+ {cause: error},
795
+ ),
796
+ );
797
+ return;
798
+ }
799
+
800
+ this.resolvePendingRequest(message.id, value);
801
+ return;
802
+ }
803
+
804
+ if (topic === `${this.options.virtualDid}/appMsg/devListChange`) {
805
+ this.handleDeviceListChangedMessage(message.payload);
806
+ return;
807
+ }
808
+
809
+ this.handleNotificationMessage(topic, message.payload);
810
+ } catch (error) {
811
+ console.error(error);
812
+ }
813
+ }
814
+
815
+ private handleDeviceListChangedMessage(payload: string | undefined): void {
816
+ const message = requireRecord(
817
+ parseJsonPayload(payload, 'local device list change'),
818
+ 'local device list change',
819
+ );
820
+
821
+ if (!Array.isArray(message.devList)) {
822
+ throw new LocalMqttProtocolError(
823
+ 'Local device list change has an invalid devList.',
824
+ );
825
+ }
826
+
827
+ const dids = message.devList.map((value, index) => {
828
+ if (typeof value !== 'string') {
829
+ throw new LocalMqttProtocolError(
830
+ `Local device list change devList[${index}] is not a string.`,
831
+ );
832
+ }
833
+
834
+ validateDid(value);
835
+ return value;
836
+ });
837
+
838
+ for (const listener of this.deviceListChangedListenerSet) {
839
+ try {
840
+ listener(dids);
841
+ } catch (error) {
842
+ console.error(error);
843
+ }
844
+ }
845
+ }
846
+
847
+ private handleNotificationMessage(
848
+ topic: string,
849
+ payload: string | undefined,
850
+ ): void {
851
+ const prefix = `${this.options.virtualDid}/appMsg/notify/iot/`;
852
+
853
+ if (!topic.startsWith(prefix)) {
854
+ return;
855
+ }
856
+
857
+ const parts = topic.slice(prefix.length).split('/');
858
+
859
+ if (parts.length !== 3) {
860
+ return;
861
+ }
862
+
863
+ const did = parts[0];
864
+ const kind = parts[1];
865
+ const instance = parts[2];
866
+
867
+ if (did === undefined || kind === undefined || instance === undefined) {
868
+ return;
869
+ }
870
+
871
+ if (kind === 'property') {
872
+ this.handlePropertyNotification(did, instance, payload);
873
+ } else if (kind === 'event') {
874
+ this.handleEventNotification(did, instance, payload);
875
+ }
876
+ }
877
+
878
+ private handlePropertyNotification(
879
+ did: string,
880
+ instance: string,
881
+ payload: string | undefined,
882
+ ): void {
883
+ const message = requireRecord(
884
+ parseJsonPayload(payload, 'local property notification'),
885
+ 'local property notification',
886
+ );
887
+ const messageDid = requireString(
888
+ message.did,
889
+ 'local property notification DID',
890
+ );
891
+ const notificationInstance = resolveNotificationInstance(
892
+ instance,
893
+ message.siid,
894
+ message.piid,
895
+ 'local property notification',
896
+ );
897
+
898
+ if (notificationInstance === undefined) {
899
+ return;
900
+ }
901
+
902
+ const [siid, piid] = notificationInstance;
903
+
904
+ if (messageDid !== did) {
905
+ throw new LocalMqttProtocolError(
906
+ 'Local property notification does not match its topic.',
907
+ );
908
+ }
909
+
910
+ if (!Object.hasOwn(message, 'value')) {
911
+ throw new LocalMqttProtocolError(
912
+ 'Local property notification has no value.',
913
+ );
914
+ }
915
+
916
+ const listeners = this.propertyListenerMap.get(did);
917
+
918
+ if (listeners === undefined) {
919
+ return;
920
+ }
921
+
922
+ const update: LocalPropertyUpdate = {
923
+ did,
924
+ siid,
925
+ piid,
926
+ value: message.value,
927
+ };
928
+
929
+ for (const {listener} of listeners) {
930
+ try {
931
+ listener(update);
932
+ } catch (error) {
933
+ console.error(error);
934
+ }
935
+ }
936
+ }
937
+
938
+ private handleEventNotification(
939
+ did: string,
940
+ instance: string,
941
+ payload: string | undefined,
942
+ ): void {
943
+ const message = requireRecord(
944
+ parseJsonPayload(payload, 'local event notification'),
945
+ 'local event notification',
946
+ );
947
+ const messageDid = requireString(
948
+ message.did,
949
+ 'local event notification DID',
950
+ );
951
+ const notificationInstance = resolveNotificationInstance(
952
+ instance,
953
+ message.siid,
954
+ message.eiid,
955
+ 'local event notification',
956
+ );
957
+
958
+ if (notificationInstance === undefined) {
959
+ return;
960
+ }
961
+
962
+ const [siid, eiid] = notificationInstance;
963
+
964
+ if (messageDid !== did) {
965
+ throw new LocalMqttProtocolError(
966
+ 'Local event notification does not match its topic.',
967
+ );
968
+ }
969
+
970
+ const eventArguments = message.arguments ?? [];
971
+
972
+ if (!Array.isArray(eventArguments)) {
973
+ throw new LocalMqttProtocolError(
974
+ 'Local event notification has invalid arguments.',
975
+ );
976
+ }
977
+
978
+ const listeners = this.eventListenerMap.get(did);
979
+
980
+ if (listeners === undefined) {
981
+ return;
982
+ }
983
+
984
+ const update: LocalEventUpdate = {
985
+ did,
986
+ siid,
987
+ eiid,
988
+ arguments: eventArguments,
989
+ };
990
+
991
+ for (const {listener} of listeners) {
992
+ try {
993
+ listener(update);
994
+ } catch (error) {
995
+ console.error(error);
996
+ }
997
+ }
998
+ }
999
+
1000
+ private resolvePendingRequest(id: number, value: unknown): void {
1001
+ const pending = this.pendingRequestMap.get(id);
1002
+
1003
+ if (pending === undefined) {
1004
+ return;
1005
+ }
1006
+
1007
+ this.pendingRequestMap.delete(id);
1008
+ clearTimeout(pending.timeout);
1009
+ pending.resolve(value);
1010
+ }
1011
+
1012
+ private rejectPendingRequest(id: number, error: Error): void {
1013
+ const pending = this.pendingRequestMap.get(id);
1014
+
1015
+ if (pending === undefined) {
1016
+ return;
1017
+ }
1018
+
1019
+ this.pendingRequestMap.delete(id);
1020
+ clearTimeout(pending.timeout);
1021
+ pending.reject(error);
1022
+ }
1023
+
1024
+ private rejectPendingRequests(error: Error): void {
1025
+ for (const id of [...this.pendingRequestMap.keys()]) {
1026
+ this.rejectPendingRequest(id, error);
1027
+ }
1028
+ }
1029
+
1030
+ private allocateMessageId(): number {
1031
+ const initialId = this.nextMessageId;
1032
+
1033
+ while (this.pendingRequestMap.has(this.nextMessageId)) {
1034
+ this.nextMessageId = (this.nextMessageId + 1) % UINT32_RANGE;
1035
+
1036
+ if (this.nextMessageId === initialId) {
1037
+ throw new Error('Local MQTT message ID space is exhausted.');
1038
+ }
1039
+ }
1040
+
1041
+ const id = this.nextMessageId;
1042
+ this.nextMessageId = (this.nextMessageId + 1) % UINT32_RANGE;
1043
+ return id;
1044
+ }
1045
+
1046
+ private startConnectionSession(mqttClient: MqttClient): number {
1047
+ if (this.mqttClient !== mqttClient || !mqttClient.connected) {
1048
+ throw new Error('Local MQTT is not connected.');
1049
+ }
1050
+
1051
+ let generation = this.activeConnectionGeneration;
1052
+
1053
+ if (generation === undefined) {
1054
+ generation = ++this.nextConnectionGeneration;
1055
+ this.activeConnectionGeneration = generation;
1056
+ }
1057
+
1058
+ return generation;
1059
+ }
1060
+
1061
+ private isActiveConnectionSession(
1062
+ mqttClient: MqttClient,
1063
+ generation: number,
1064
+ ): boolean {
1065
+ return (
1066
+ this.mqttClient === mqttClient &&
1067
+ this.activeConnectionGeneration === generation &&
1068
+ mqttClient.connected
1069
+ );
1070
+ }
1071
+
1072
+ private assertActiveConnectionSession(
1073
+ mqttClient: MqttClient,
1074
+ generation: number,
1075
+ ): void {
1076
+ if (!this.isActiveConnectionSession(mqttClient, generation)) {
1077
+ throw new Error('Local MQTT disconnected while subscribing.');
1078
+ }
1079
+ }
1080
+
1081
+ private assertOperationGeneration(generation: number): void {
1082
+ if (this.operationGeneration !== generation) {
1083
+ throw new Error('Local MQTT connection operation was cancelled.');
1084
+ }
1085
+ }
1086
+
1087
+ private waitUntilConnected(mqttClient: MqttClient): Promise<void> {
1088
+ if (mqttClient.connected) {
1089
+ return Promise.resolve();
1090
+ }
1091
+
1092
+ return new Promise<void>((resolve, reject) => {
1093
+ const timeout = setTimeout(() => {
1094
+ cleanup();
1095
+ reject(new Error('Local MQTT connection timed out.'));
1096
+ }, CONNECT_TIMEOUT_MILLISECONDS);
1097
+
1098
+ const onConnect = (): void => {
1099
+ cleanup();
1100
+ resolve();
1101
+ };
1102
+
1103
+ const cleanup = (): void => {
1104
+ clearTimeout(timeout);
1105
+ mqttClient.off('connect', onConnect);
1106
+ };
1107
+
1108
+ mqttClient.on('connect', onConnect);
1109
+ });
1110
+ }
1111
+
1112
+ private setReady(ready: boolean): void {
1113
+ if (this.ready === ready) {
1114
+ return;
1115
+ }
1116
+
1117
+ this.ready = ready;
1118
+
1119
+ if (ready) {
1120
+ this.stopReadyRetry();
1121
+ }
1122
+
1123
+ for (const listener of this.connectionStateListenerSet) {
1124
+ try {
1125
+ listener(ready);
1126
+ } catch (error) {
1127
+ console.error(error);
1128
+ }
1129
+ }
1130
+ }
1131
+
1132
+ private get receiveTopic(): string {
1133
+ return `${this.options.virtualDid}/#`;
1134
+ }
1135
+
1136
+ private get replyTopic(): string {
1137
+ return `${this.options.virtualDid}/reply`;
1138
+ }
1139
+ }
1140
+
1141
+ export type LocalMqttClientOptions = {
1142
+ readonly virtualDid: string;
1143
+ readonly gatewayDid: string;
1144
+ readonly host: string;
1145
+ readonly port?: number;
1146
+ readonly ca: LocalMqttTlsValue;
1147
+ readonly cert: LocalMqttTlsValue;
1148
+ readonly key: LocalMqttTlsValue;
1149
+ readonly connector?: LocalMqttConnector;
1150
+ };
1151
+
1152
+ export type LocalMqttTlsValue = string | Buffer | string[] | Buffer[];
1153
+
1154
+ export type LocalDeviceInfo = {
1155
+ readonly online: boolean;
1156
+ readonly specV2Access: boolean;
1157
+ readonly pushAvailable: boolean;
1158
+ };
1159
+
1160
+ export type LocalPropertyResult = MiotProperty & {
1161
+ readonly code: number;
1162
+ readonly value?: unknown;
1163
+ };
1164
+
1165
+ export type LocalPropertyUpdate = MiotProperty & {
1166
+ readonly value: unknown;
1167
+ };
1168
+
1169
+ export type LocalPropertyListener = (update: LocalPropertyUpdate) => void;
1170
+
1171
+ export type LocalEventUpdate = {
1172
+ readonly did: string;
1173
+ readonly siid: number;
1174
+ readonly eiid: number;
1175
+ readonly arguments: readonly unknown[];
1176
+ };
1177
+
1178
+ export type LocalEventListener = (update: LocalEventUpdate) => void;
1179
+
1180
+ export type LocalDeviceListChangedListener = (dids: readonly string[]) => void;
1181
+
1182
+ export type LocalMqttConnectionStateListener = (connected: boolean) => void;
1183
+
1184
+ export type LocalMqttPropertySubscription = {
1185
+ dispose(): Promise<void>;
1186
+ };
1187
+
1188
+ export type LocalMqttEventSubscription = {
1189
+ dispose(): Promise<void>;
1190
+ };
1191
+
1192
+ export type LocalMqttConnector = (
1193
+ url: string,
1194
+ options: IClientOptions,
1195
+ ) => Promise<MqttClient>;
1196
+
1197
+ export class LocalMqttProtocolError extends Error {
1198
+ override readonly name = 'LocalMqttProtocolError';
1199
+ }
1200
+
1201
+ export class LocalMqttRequestTimeoutError extends Error {
1202
+ override readonly name = 'LocalMqttRequestTimeoutError';
1203
+ }
1204
+
1205
+ export class LocalMqttRequestInterruptedError extends Error {
1206
+ override readonly name = 'LocalMqttRequestInterruptedError';
1207
+ }
1208
+
1209
+ type PendingRequest = {
1210
+ readonly promise: Promise<unknown>;
1211
+ readonly resolve: (value: unknown) => void;
1212
+ readonly reject: (error: Error) => void;
1213
+ readonly timeout: ReturnType<typeof setTimeout>;
1214
+ };
1215
+
1216
+ type LocalPropertyListenerEntry = {
1217
+ readonly listener: LocalPropertyListener;
1218
+ };
1219
+
1220
+ type LocalEventListenerEntry = {
1221
+ readonly listener: LocalEventListener;
1222
+ };
1223
+
1224
+ function createMqttOptions(options: LocalMqttClientOptions): IClientOptions {
1225
+ const mqttOptions: IClientOptions &
1226
+ Pick<ConnectionOptions, 'checkServerIdentity'> = {
1227
+ clientId: options.virtualDid,
1228
+ protocolVersion: 5,
1229
+ clean: true,
1230
+ keepalive: KEEPALIVE_SECONDS,
1231
+ reconnectPeriod: RECONNECT_INTERVAL_MILLISECONDS,
1232
+ connectTimeout: CONNECT_TIMEOUT_MILLISECONDS,
1233
+ resubscribe: false,
1234
+ // Gateways are addressed by their discovered IP, so replace generic host
1235
+ // name matching with the expected MIPS service identity for this DID.
1236
+ rejectUnauthorized: true,
1237
+ checkServerIdentity: (_hostname, certificate) => {
1238
+ try {
1239
+ if (
1240
+ certificate.raw !== undefined &&
1241
+ isMipsGatewayCertificate(
1242
+ new X509Certificate(certificate.raw),
1243
+ options.gatewayDid,
1244
+ )
1245
+ ) {
1246
+ return undefined;
1247
+ }
1248
+ } catch {
1249
+ // Return the fixed identity error below.
1250
+ }
1251
+
1252
+ return new Error('Local MQTT gateway certificate identity is invalid.');
1253
+ },
1254
+ ca: options.ca,
1255
+ cert: options.cert,
1256
+ key: options.key,
1257
+ };
1258
+
1259
+ return mqttOptions;
1260
+ }
1261
+
1262
+ function defaultConnector(
1263
+ url: string,
1264
+ options: IClientOptions,
1265
+ ): Promise<MqttClient> {
1266
+ return connectAsync(url, options, false);
1267
+ }
1268
+
1269
+ function createPendingRequest(
1270
+ id: number,
1271
+ operation: string,
1272
+ timeoutMilliseconds: number,
1273
+ onTimeout: (error: LocalMqttRequestTimeoutError) => void,
1274
+ ): PendingRequest {
1275
+ let resolvePromise: (value: unknown) => void = () => undefined;
1276
+ let rejectPromise: (error: Error) => void = () => undefined;
1277
+ const promise = new Promise<unknown>((resolve, reject) => {
1278
+ resolvePromise = resolve;
1279
+ rejectPromise = reject;
1280
+ });
1281
+ // A response timeout may occur while the QoS 2 publish handshake is still
1282
+ // pending, so attach a handler immediately and let the caller await it.
1283
+ void promise.catch(() => undefined);
1284
+ const timeout = setTimeout(() => {
1285
+ onTimeout(
1286
+ new LocalMqttRequestTimeoutError(
1287
+ `Local MQTT ${operation} request ${id} timed out after publication began.`,
1288
+ ),
1289
+ );
1290
+ }, timeoutMilliseconds);
1291
+
1292
+ return {
1293
+ promise,
1294
+ resolve: resolvePromise,
1295
+ reject: rejectPromise,
1296
+ timeout,
1297
+ };
1298
+ }
1299
+
1300
+ function getBrokerUrl(host: string, port: number): string {
1301
+ const formattedHost =
1302
+ host.includes(':') && !host.startsWith('[') ? `[${host}]` : host;
1303
+ return `mqtts://${formattedHost}:${port}`;
1304
+ }
1305
+
1306
+ function getPropertyPublishTopic(did: string): string {
1307
+ return `master/appMsg/notify/iot/${did}/property/#`;
1308
+ }
1309
+
1310
+ function getEventPublishTopic(did: string): string {
1311
+ return `master/appMsg/notify/iot/${did}/event/#`;
1312
+ }
1313
+
1314
+ function validateOptions(options: LocalMqttClientOptions): void {
1315
+ validateDid(options.virtualDid);
1316
+ validateDecimalDid(options.gatewayDid, 'gateway');
1317
+
1318
+ if (
1319
+ options.host === '' ||
1320
+ /[\s/?#@]/u.test(options.host) ||
1321
+ options.host.includes('\0') ||
1322
+ ((options.host.includes('[') || options.host.includes(']')) &&
1323
+ !/^\[[\da-f:.]+\]$/iu.test(options.host))
1324
+ ) {
1325
+ throw new TypeError('Invalid local MQTT host.');
1326
+ }
1327
+
1328
+ const port = options.port ?? DEFAULT_PORT;
1329
+
1330
+ if (!Number.isInteger(port) || port < 1 || port > 65_535) {
1331
+ throw new TypeError('Invalid local MQTT port.');
1332
+ }
1333
+ }
1334
+
1335
+ function validateDecimalDid(did: string, name: string): void {
1336
+ if (!/^(?:0|[1-9]\d*)$/u.test(did)) {
1337
+ throw new TypeError(`Invalid local MQTT ${name} DID.`);
1338
+ }
1339
+ }
1340
+
1341
+ function validateDid(did: string): void {
1342
+ if (
1343
+ did === '' ||
1344
+ did.includes('/') ||
1345
+ did.includes('#') ||
1346
+ did.includes('+') ||
1347
+ did.includes('\0')
1348
+ ) {
1349
+ throw new TypeError(`Invalid local MQTT device ID: ${did}.`);
1350
+ }
1351
+ }
1352
+
1353
+ function validateProperty(property: MiotProperty): void {
1354
+ validateDid(property.did);
1355
+ requirePositiveInteger(property.siid, 'MIoT property SIID');
1356
+ requirePositiveInteger(property.piid, 'MIoT property PIID');
1357
+ }
1358
+
1359
+ function createSetPropertiesRpc(
1360
+ request: MiotSetPropertyRequest,
1361
+ id: number,
1362
+ ): {
1363
+ readonly id: number;
1364
+ readonly method: 'set_properties';
1365
+ readonly params: readonly [Record<string, unknown>];
1366
+ } {
1367
+ validateProperty(request.property);
1368
+
1369
+ return {
1370
+ id,
1371
+ method: 'set_properties',
1372
+ params: [{...request.property, value: request.value}],
1373
+ };
1374
+ }
1375
+
1376
+ function createInvokeActionRpc(
1377
+ request: MiotInvokeActionRequest,
1378
+ id: number,
1379
+ ): {
1380
+ readonly id: number;
1381
+ readonly method: 'action';
1382
+ readonly params: {
1383
+ readonly did: string;
1384
+ readonly siid: number;
1385
+ readonly aiid: number;
1386
+ readonly in: readonly {readonly piid: number; readonly value: unknown}[];
1387
+ };
1388
+ } {
1389
+ const {did, siid, aiid} = request.action;
1390
+
1391
+ validateDid(did);
1392
+ requirePositiveInteger(siid, 'MIoT action SIID');
1393
+ requirePositiveInteger(aiid, 'MIoT action AIID');
1394
+
1395
+ for (const input of request.inputs) {
1396
+ requirePositiveInteger(input.piid, 'MIoT action input PIID');
1397
+ }
1398
+
1399
+ return {
1400
+ id,
1401
+ method: 'action',
1402
+ params: {did, siid, aiid, in: request.inputs},
1403
+ };
1404
+ }
1405
+
1406
+ function validateTimeout(timeoutMilliseconds: number): void {
1407
+ if (!Number.isFinite(timeoutMilliseconds) || timeoutMilliseconds <= 0) {
1408
+ throw new TypeError('Invalid local MQTT request timeout.');
1409
+ }
1410
+ }
1411
+
1412
+ function parseJsonPayload(payload: string | undefined, name: string): unknown {
1413
+ if (payload === undefined) {
1414
+ throw new LocalMqttProtocolError(`${name} has no JSON payload.`);
1415
+ }
1416
+
1417
+ try {
1418
+ return JSON.parse(payload);
1419
+ } catch (error) {
1420
+ throw new LocalMqttProtocolError(`${name} is not valid JSON.`, {
1421
+ cause: error,
1422
+ });
1423
+ }
1424
+ }
1425
+
1426
+ function requireRecord(value: unknown, name: string): Record<string, unknown> {
1427
+ if (typeof value !== 'object' || value === null || Array.isArray(value)) {
1428
+ throw new LocalMqttProtocolError(`${name} is not an object.`);
1429
+ }
1430
+
1431
+ return value as Record<string, unknown>;
1432
+ }
1433
+
1434
+ function requireInteger(value: unknown, name: string): number {
1435
+ if (typeof value !== 'number' || !Number.isInteger(value)) {
1436
+ throw new LocalMqttProtocolError(`${name} is not an integer.`);
1437
+ }
1438
+
1439
+ return value;
1440
+ }
1441
+
1442
+ function requirePositiveInteger(value: unknown, name: string): number {
1443
+ const integer = requireInteger(value, name);
1444
+
1445
+ if (integer <= 0) {
1446
+ throw new LocalMqttProtocolError(`${name} is not positive.`);
1447
+ }
1448
+
1449
+ return integer;
1450
+ }
1451
+
1452
+ function readNotificationIdentifier(value: unknown): number | undefined {
1453
+ // Some central-gateway firmware serializes notification IIDs as decimal
1454
+ // JSON strings even though request/response IIDs are numbers.
1455
+ if (typeof value === 'number') {
1456
+ if (Number.isSafeInteger(value) && value > 0) {
1457
+ return value;
1458
+ }
1459
+ } else if (typeof value === 'string' && /^[1-9]\d*$/u.test(value)) {
1460
+ const integer = Number(value);
1461
+
1462
+ if (Number.isSafeInteger(integer)) {
1463
+ return integer;
1464
+ }
1465
+ }
1466
+
1467
+ return undefined;
1468
+ }
1469
+
1470
+ function readNotificationTopicInstance(
1471
+ instance: string,
1472
+ ): readonly [number, number] | undefined {
1473
+ const match = /^([1-9]\d*)\.([1-9]\d*)$/u.exec(instance);
1474
+
1475
+ if (match === null) {
1476
+ return undefined;
1477
+ }
1478
+
1479
+ const first = readNotificationIdentifier(match[1]);
1480
+ const second = readNotificationIdentifier(match[2]);
1481
+
1482
+ return first === undefined || second === undefined
1483
+ ? undefined
1484
+ : [first, second];
1485
+ }
1486
+
1487
+ function resolveNotificationInstance(
1488
+ topicInstance: string,
1489
+ firstValue: unknown,
1490
+ secondValue: unknown,
1491
+ name: string,
1492
+ ): readonly [number, number] | undefined {
1493
+ const topic = readNotificationTopicInstance(topicInstance);
1494
+ const first = readNotificationIdentifier(firstValue);
1495
+ const second = readNotificationIdentifier(secondValue);
1496
+
1497
+ if (topic === undefined) {
1498
+ return first === undefined || second === undefined
1499
+ ? undefined
1500
+ : [first, second];
1501
+ }
1502
+
1503
+ if (
1504
+ (firstValue !== undefined && first === undefined) ||
1505
+ (secondValue !== undefined && second === undefined)
1506
+ ) {
1507
+ return undefined;
1508
+ }
1509
+
1510
+ if (
1511
+ (first !== undefined && first !== topic[0]) ||
1512
+ (second !== undefined && second !== topic[1])
1513
+ ) {
1514
+ throw new LocalMqttProtocolError(`${name} does not match its topic.`);
1515
+ }
1516
+
1517
+ return topic;
1518
+ }
1519
+
1520
+ function requireString(value: unknown, name: string): string {
1521
+ if (typeof value !== 'string') {
1522
+ throw new LocalMqttProtocolError(`${name} is not a string.`);
1523
+ }
1524
+
1525
+ return value;
1526
+ }
1527
+
1528
+ function readOptionalBoolean(value: unknown, name: string): boolean {
1529
+ if (value === undefined) {
1530
+ return false;
1531
+ }
1532
+
1533
+ if (typeof value !== 'boolean') {
1534
+ throw new LocalMqttProtocolError(
1535
+ `Local device list ${name} is not a boolean.`,
1536
+ );
1537
+ }
1538
+
1539
+ return value;
1540
+ }
1541
+
1542
+ function readResponseErrorCode(
1543
+ response: Record<string, unknown>,
1544
+ ): number | undefined {
1545
+ if (typeof response.code === 'number' && Number.isInteger(response.code)) {
1546
+ return response.code;
1547
+ }
1548
+
1549
+ if (response.error === undefined) {
1550
+ return undefined;
1551
+ }
1552
+
1553
+ const error = requireRecord(response.error, 'local response error');
1554
+ return requireInteger(error.code, 'local response error code');
1555
+ }