@homelib/xiaomi 0.0.0-wip.ba4eafa051eb

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (175) hide show
  1. package/LICENSE +19 -0
  2. package/README.md +22 -0
  3. package/bld/library/backend/client.d.ts +68 -0
  4. package/bld/library/backend/client.js +477 -0
  5. package/bld/library/backend/client.js.map +1 -0
  6. package/bld/library/backend/constants.d.ts +7 -0
  7. package/bld/library/backend/constants.js +11 -0
  8. package/bld/library/backend/constants.js.map +1 -0
  9. package/bld/library/backend/index.d.ts +3 -0
  10. package/bld/library/backend/index.js +4 -0
  11. package/bld/library/backend/index.js.map +1 -0
  12. package/bld/library/backend/oauth.d.ts +24 -0
  13. package/bld/library/backend/oauth.js +121 -0
  14. package/bld/library/backend/oauth.js.map +1 -0
  15. package/bld/library/binding.d.ts +44 -0
  16. package/bld/library/binding.js +212 -0
  17. package/bld/library/binding.js.map +1 -0
  18. package/bld/library/cloud/client.d.ts +27 -0
  19. package/bld/library/cloud/client.js +109 -0
  20. package/bld/library/cloud/client.js.map +1 -0
  21. package/bld/library/cloud/constants.d.ts +9 -0
  22. package/bld/library/cloud/constants.js +11 -0
  23. package/bld/library/cloud/constants.js.map +1 -0
  24. package/bld/library/cloud/device.d.ts +84 -0
  25. package/bld/library/cloud/device.js +686 -0
  26. package/bld/library/cloud/device.js.map +1 -0
  27. package/bld/library/cloud/index.d.ts +5 -0
  28. package/bld/library/cloud/index.js +6 -0
  29. package/bld/library/cloud/index.js.map +1 -0
  30. package/bld/library/cloud/mqtt.d.ts +69 -0
  31. package/bld/library/cloud/mqtt.js +517 -0
  32. package/bld/library/cloud/mqtt.js.map +1 -0
  33. package/bld/library/cloud/transport.d.ts +8 -0
  34. package/bld/library/cloud/transport.js +30 -0
  35. package/bld/library/cloud/transport.js.map +1 -0
  36. package/bld/library/command.d.ts +6 -0
  37. package/bld/library/command.js +6 -0
  38. package/bld/library/command.js.map +1 -0
  39. package/bld/library/configuration.d.ts +62 -0
  40. package/bld/library/configuration.js +303 -0
  41. package/bld/library/configuration.js.map +1 -0
  42. package/bld/library/device.d.ts +68 -0
  43. package/bld/library/device.js +235 -0
  44. package/bld/library/device.js.map +1 -0
  45. package/bld/library/devices/air-conditioner.d.ts +48 -0
  46. package/bld/library/devices/air-conditioner.js +155 -0
  47. package/bld/library/devices/air-conditioner.js.map +1 -0
  48. package/bld/library/devices/command-effect.d.ts +35 -0
  49. package/bld/library/devices/command-effect.js +269 -0
  50. package/bld/library/devices/command-effect.js.map +1 -0
  51. package/bld/library/devices/dehumidifier.d.ts +41 -0
  52. package/bld/library/devices/dehumidifier.js +124 -0
  53. package/bld/library/devices/dehumidifier.js.map +1 -0
  54. package/bld/library/devices/fan.d.ts +37 -0
  55. package/bld/library/devices/fan.js +135 -0
  56. package/bld/library/devices/fan.js.map +1 -0
  57. package/bld/library/devices/index.d.ts +7 -0
  58. package/bld/library/devices/index.js +8 -0
  59. package/bld/library/devices/index.js.map +1 -0
  60. package/bld/library/devices/light.d.ts +22 -0
  61. package/bld/library/devices/light.js +112 -0
  62. package/bld/library/devices/light.js.map +1 -0
  63. package/bld/library/devices/placeholder.d.ts +3 -0
  64. package/bld/library/devices/placeholder.js +4 -0
  65. package/bld/library/devices/placeholder.js.map +1 -0
  66. package/bld/library/devices/value-range.d.ts +2 -0
  67. package/bld/library/devices/value-range.js +6 -0
  68. package/bld/library/devices/value-range.js.map +1 -0
  69. package/bld/library/endpoint-connection.d.ts +154 -0
  70. package/bld/library/endpoint-connection.js +510 -0
  71. package/bld/library/endpoint-connection.js.map +1 -0
  72. package/bld/library/index.d.ts +26 -0
  73. package/bld/library/index.js +31 -0
  74. package/bld/library/index.js.map +1 -0
  75. package/bld/library/local/certificate.d.ts +31 -0
  76. package/bld/library/local/certificate.js +298 -0
  77. package/bld/library/local/certificate.js.map +1 -0
  78. package/bld/library/local/controller.d.ts +70 -0
  79. package/bld/library/local/controller.js +497 -0
  80. package/bld/library/local/controller.js.map +1 -0
  81. package/bld/library/local/discovery.d.ts +29 -0
  82. package/bld/library/local/discovery.js +321 -0
  83. package/bld/library/local/discovery.js.map +1 -0
  84. package/bld/library/local/index.d.ts +6 -0
  85. package/bld/library/local/index.js +7 -0
  86. package/bld/library/local/index.js.map +1 -0
  87. package/bld/library/local/message.d.ts +11 -0
  88. package/bld/library/local/message.js +128 -0
  89. package/bld/library/local/message.js.map +1 -0
  90. package/bld/library/local/mqtt.d.ts +113 -0
  91. package/bld/library/local/mqtt.js +1044 -0
  92. package/bld/library/local/mqtt.js.map +1 -0
  93. package/bld/library/local/routed-message-client.d.ts +49 -0
  94. package/bld/library/local/routed-message-client.js +326 -0
  95. package/bld/library/local/routed-message-client.js.map +1 -0
  96. package/bld/library/miot/index.d.ts +4 -0
  97. package/bld/library/miot/index.js +5 -0
  98. package/bld/library/miot/index.js.map +1 -0
  99. package/bld/library/miot/matcher.d.ts +65 -0
  100. package/bld/library/miot/matcher.js +217 -0
  101. package/bld/library/miot/matcher.js.map +1 -0
  102. package/bld/library/miot/request.d.ts +16 -0
  103. package/bld/library/miot/request.js +27 -0
  104. package/bld/library/miot/request.js.map +1 -0
  105. package/bld/library/miot/result.d.ts +4 -0
  106. package/bld/library/miot/result.js +5 -0
  107. package/bld/library/miot/result.js.map +1 -0
  108. package/bld/library/miot/spec.d.ts +74 -0
  109. package/bld/library/miot/spec.js +78 -0
  110. package/bld/library/miot/spec.js.map +1 -0
  111. package/bld/library/provider.d.ts +71 -0
  112. package/bld/library/provider.js +600 -0
  113. package/bld/library/provider.js.map +1 -0
  114. package/bld/library/session-manager.d.ts +34 -0
  115. package/bld/library/session-manager.js +177 -0
  116. package/bld/library/session-manager.js.map +1 -0
  117. package/bld/library/session.d.ts +36 -0
  118. package/bld/library/session.js +370 -0
  119. package/bld/library/session.js.map +1 -0
  120. package/bld/library/storage.d.ts +2 -0
  121. package/bld/library/storage.js +66 -0
  122. package/bld/library/storage.js.map +1 -0
  123. package/bld/library/terminal/bindings.d.ts +3 -0
  124. package/bld/library/terminal/bindings.js +280 -0
  125. package/bld/library/terminal/bindings.js.map +1 -0
  126. package/bld/library/terminal/index.d.ts +2 -0
  127. package/bld/library/terminal/index.js +3 -0
  128. package/bld/library/terminal/index.js.map +1 -0
  129. package/bld/library/terminal/provider-details.d.ts +3 -0
  130. package/bld/library/terminal/provider-details.js +477 -0
  131. package/bld/library/terminal/provider-details.js.map +1 -0
  132. package/package.json +29 -0
  133. package/src/library/backend/client.ts +713 -0
  134. package/src/library/backend/constants.ts +17 -0
  135. package/src/library/backend/index.ts +3 -0
  136. package/src/library/backend/oauth.ts +170 -0
  137. package/src/library/binding.ts +387 -0
  138. package/src/library/cloud/client.ts +155 -0
  139. package/src/library/cloud/constants.ts +19 -0
  140. package/src/library/cloud/device.ts +938 -0
  141. package/src/library/cloud/index.ts +5 -0
  142. package/src/library/cloud/mqtt.ts +671 -0
  143. package/src/library/cloud/transport.ts +38 -0
  144. package/src/library/command.ts +7 -0
  145. package/src/library/configuration.ts +480 -0
  146. package/src/library/device.ts +548 -0
  147. package/src/library/devices/air-conditioner.ts +171 -0
  148. package/src/library/devices/command-effect.ts +425 -0
  149. package/src/library/devices/dehumidifier.ts +131 -0
  150. package/src/library/devices/fan.ts +140 -0
  151. package/src/library/devices/index.ts +7 -0
  152. package/src/library/devices/light.ts +119 -0
  153. package/src/library/devices/placeholder.ts +3 -0
  154. package/src/library/devices/value-range.ts +14 -0
  155. package/src/library/endpoint-connection.ts +841 -0
  156. package/src/library/index.ts +62 -0
  157. package/src/library/local/certificate.ts +401 -0
  158. package/src/library/local/controller.ts +692 -0
  159. package/src/library/local/discovery.ts +485 -0
  160. package/src/library/local/index.ts +6 -0
  161. package/src/library/local/message.ts +174 -0
  162. package/src/library/local/mqtt.ts +1493 -0
  163. package/src/library/local/routed-message-client.ts +377 -0
  164. package/src/library/miot/index.ts +4 -0
  165. package/src/library/miot/matcher.ts +461 -0
  166. package/src/library/miot/request.ts +30 -0
  167. package/src/library/miot/result.ts +10 -0
  168. package/src/library/miot/spec.ts +103 -0
  169. package/src/library/provider.ts +745 -0
  170. package/src/library/session-manager.ts +224 -0
  171. package/src/library/session.ts +528 -0
  172. package/src/library/storage.ts +83 -0
  173. package/src/library/terminal/bindings.tsx +612 -0
  174. package/src/library/terminal/index.ts +2 -0
  175. package/src/library/terminal/provider-details.tsx +871 -0
@@ -0,0 +1,745 @@
1
+ import {rm} from 'node:fs/promises';
2
+ import {join} from 'node:path';
3
+
4
+ import {
5
+ $constructor,
6
+ type Device,
7
+ type DeviceConstructor,
8
+ type EndpointConnectionBinding,
9
+ type EndpointConnectionBindingPlan,
10
+ type EndpointReference,
11
+ ExponentialBackoff,
12
+ Provider,
13
+ getEnvironmentDirectory,
14
+ register,
15
+ uniqueName,
16
+ } from '@homelib/core';
17
+ import {action, observable} from 'mobx';
18
+
19
+ import type {CloudServer} from './backend/index.js';
20
+ import {BackendClient} from './backend/index.js';
21
+ import {
22
+ CloudClient,
23
+ type CloudDeviceSubscription,
24
+ CloudMqttClient,
25
+ MiotEndpointConnectionCloudTransport,
26
+ } from './cloud/index.js';
27
+ import {
28
+ MiotProviderConfiguration,
29
+ type MiotProviderConfigurationAuthorizationDependency,
30
+ type MiotProviderConfigurationDiscovery,
31
+ } from './configuration.js';
32
+ import {
33
+ type MiotEndpointConnectionConstructor,
34
+ createMiotDeviceEndpointConnectionBinding,
35
+ getMiotEndpointConnectionConstructor,
36
+ resolveMiotEndpointConnectionMetadata,
37
+ } from './device.js';
38
+ import {
39
+ type MiotEndpointConnection,
40
+ MiotEndpointConnectionMetadata,
41
+ type MiotEndpointConnectionResolvedMetadata,
42
+ getMiotEndpointConnectionResourceKeys,
43
+ normalizeMiotEndpointConnectionMetadata,
44
+ } from './endpoint-connection.js';
45
+ import {
46
+ LocalController,
47
+ type LocalControllerDiscovery,
48
+ RoutedDeviceMessageClient,
49
+ } from './local/index.js';
50
+ import type {MiotProperty} from './miot/index.js';
51
+ import {OAuthSessionManager} from './session-manager.js';
52
+ import {
53
+ type OAuthSession,
54
+ type OAuthSessionAuthorization,
55
+ OAuthSessionMissingError,
56
+ beginOAuthSessionAuthorization,
57
+ } from './session.js';
58
+
59
+ export const MIOT_NAMESPACE = 'miot';
60
+
61
+ export class MiotProvider extends Provider<MiotEndpointConnectionMetadata> {
62
+ override readonly EndpointConnectionMetadata = MiotEndpointConnectionMetadata;
63
+
64
+ readonly configuration: MiotProviderConfiguration;
65
+
66
+ @observable.shallow
67
+ private accessor endpointConnectionValues: MiotEndpointConnection<never>[] =
68
+ [];
69
+
70
+ private readonly endpointConnectionSubscriptionMap = new Map<
71
+ MiotEndpointConnection<never>,
72
+ CloudDeviceSubscription
73
+ >();
74
+
75
+ private readonly endpointConnectionRuntimeMap = new Map<
76
+ MiotEndpointConnection<never>,
77
+ MiotEndpointConnectionRuntime
78
+ >();
79
+
80
+ private endpointConnectionCreationCount = 0;
81
+
82
+ private endpointConnectionDisposalCount = 0;
83
+
84
+ private cloudPromise: Promise<MiotProviderCloud> | undefined;
85
+
86
+ private cloudValue: MiotProviderCloud | undefined;
87
+
88
+ private readonly discoveryBackendClientSet = new Set<BackendClient>();
89
+
90
+ private authorizationInProgress = false;
91
+
92
+ private authorization: OAuthSessionAuthorization | undefined;
93
+
94
+ private authorizationSetupPromise:
95
+ Promise<OAuthSessionAuthorization> | undefined;
96
+
97
+ private authorizationGeneration = 0;
98
+
99
+ private forgetAuthorizationPromise: Promise<void> | undefined;
100
+
101
+ private readonly sessionPath: string;
102
+
103
+ private readonly oauthUuidPath: string;
104
+
105
+ private readonly localCertificateDirectory: string;
106
+
107
+ private readonly providerDirectory: string;
108
+
109
+ private readonly sessionManager: OAuthSessionManager;
110
+
111
+ constructor(name: string) {
112
+ super(name);
113
+
114
+ const environmentDirectory = getEnvironmentDirectory();
115
+ this.providerDirectory = join(
116
+ environmentDirectory,
117
+ 'providers',
118
+ MIOT_NAMESPACE,
119
+ );
120
+
121
+ this.sessionPath = join(this.providerDirectory, `${name}.json`);
122
+ this.oauthUuidPath = join(
123
+ this.providerDirectory,
124
+ 'identity',
125
+ `${name}.json`,
126
+ );
127
+ this.localCertificateDirectory = join(
128
+ this.providerDirectory,
129
+ 'certificates',
130
+ name,
131
+ );
132
+ this.sessionManager = new OAuthSessionManager({
133
+ sessionPath: this.sessionPath,
134
+ applyAccessToken: accessToken => {
135
+ this.cloudValue?.client.updateAccessToken(accessToken);
136
+
137
+ for (const backendClient of this.discoveryBackendClientSet) {
138
+ backendClient.updateAccessToken(accessToken);
139
+ }
140
+ },
141
+ });
142
+ this.configuration = new MiotProviderConfiguration({
143
+ providerName: name,
144
+ environmentDirectory,
145
+ dependencies: {
146
+ discoverDevices: () => this.discoverConfigurationDevices(),
147
+ beginAuthorization: cloudServer =>
148
+ this.beginConfigurationAuthorization(cloudServer),
149
+ forgetAuthorization: () => this.forgetConfigurationAuthorization(),
150
+ },
151
+ });
152
+ }
153
+
154
+ override get endpointConnections(): readonly MiotEndpointConnection<never>[] {
155
+ return this.endpointConnectionValues;
156
+ }
157
+
158
+ protected override createEndpointConnectionBindingPlanFromMetadata(
159
+ endpoint: EndpointReference,
160
+ deviceConstructors: readonly DeviceConstructor<Device>[],
161
+ metadata: MiotEndpointConnectionMetadata,
162
+ ): EndpointConnectionBindingPlan {
163
+ const Connection = getMiotEndpointConnectionConstructor(
164
+ deviceConstructors,
165
+ endpoint,
166
+ );
167
+
168
+ if (Connection === undefined) {
169
+ throw new TypeError('Unsupported MIoT endpoint.');
170
+ }
171
+
172
+ const normalizedMetadata =
173
+ normalizeMiotEndpointConnectionMetadata(metadata);
174
+ const resolvedMetadata = resolveMiotEndpointConnectionMetadata(
175
+ Connection,
176
+ normalizedMetadata,
177
+ );
178
+
179
+ return {
180
+ resourceKeys: getMiotEndpointConnectionResourceKeys(normalizedMetadata),
181
+ create: () =>
182
+ this.createEndpointConnectionBinding(
183
+ Connection,
184
+ endpoint,
185
+ resolvedMetadata,
186
+ ),
187
+ };
188
+ }
189
+
190
+ private async createEndpointConnectionBinding(
191
+ Connection: MiotEndpointConnectionConstructor,
192
+ endpoint: EndpointReference,
193
+ metadata: MiotEndpointConnectionResolvedMetadata,
194
+ ): Promise<EndpointConnectionBinding> {
195
+ this.endpointConnectionCreationCount++;
196
+ let cloud: MiotProviderCloud | undefined;
197
+ let outcome: BindingCreationOutcome;
198
+
199
+ try {
200
+ cloud = await this.getCloud();
201
+ await cloud.client.connect();
202
+ const {connection, binding} = createMiotDeviceEndpointConnectionBinding(
203
+ Connection,
204
+ this,
205
+ endpoint,
206
+ metadata,
207
+ [cloud.localController, cloud.transport],
208
+ value => this.disposeEndpointConnection(value),
209
+ );
210
+ const stateProperties = connection.stateProperties;
211
+ const runtime: MiotEndpointConnectionRuntime = {
212
+ active: true,
213
+ backoff: new ExponentialBackoff(1_000, 60_000),
214
+ };
215
+
216
+ this.addEndpointConnection(connection);
217
+ this.endpointConnectionRuntimeMap.set(connection, runtime);
218
+ const subscriptionPromise = this.subscribeEndpointConnection(
219
+ connection,
220
+ stateProperties,
221
+ cloud.client,
222
+ runtime,
223
+ );
224
+ runtime.subscriptionPromise = subscriptionPromise;
225
+ void subscriptionPromise.catch(console.error);
226
+
227
+ outcome = {type: 'success', binding};
228
+ } catch (error) {
229
+ outcome = {type: 'error', error};
230
+ }
231
+
232
+ this.endpointConnectionCreationCount--;
233
+
234
+ if (outcome.type === 'success') {
235
+ return outcome.binding;
236
+ }
237
+
238
+ const errors = [outcome.error];
239
+
240
+ if (cloud !== undefined) {
241
+ try {
242
+ await this.disposeCloudIfUnused(cloud);
243
+ } catch (error) {
244
+ errors.push(error);
245
+ }
246
+ }
247
+
248
+ if (errors.length === 1) {
249
+ throw errors[0];
250
+ }
251
+
252
+ throw new AggregateError(errors, 'Failed to create MIoT connection.');
253
+ }
254
+
255
+ private getCloud(): Promise<MiotProviderCloud> {
256
+ if (this.authorizationInProgress) {
257
+ throw new Error(
258
+ 'Cannot start MIoT connections while authorization is in progress.',
259
+ );
260
+ }
261
+
262
+ let cloudPromise = this.cloudPromise;
263
+
264
+ if (cloudPromise === undefined) {
265
+ cloudPromise = this.createCloud();
266
+ this.cloudPromise = cloudPromise;
267
+ void cloudPromise.catch(() => {
268
+ if (this.cloudPromise === cloudPromise) {
269
+ this.cloudPromise = undefined;
270
+ }
271
+ });
272
+ }
273
+
274
+ return cloudPromise;
275
+ }
276
+
277
+ private async createCloud(): Promise<MiotProviderCloud> {
278
+ const authorizationGeneration = this.authorizationGeneration;
279
+ const session = await this.sessionManager.getSession();
280
+
281
+ this.assertAuthorizationGeneration(authorizationGeneration);
282
+
283
+ const backendClient = createBackendClient(session);
284
+ const localController = new LocalController({
285
+ session,
286
+ backendClient,
287
+ certificateDirectory: this.localCertificateDirectory,
288
+ loadDiscovery: () => this.loadLocalControllerDiscovery(),
289
+ });
290
+ const cloudMqttClient = new CloudMqttClient({
291
+ uuid: backendClient.uuid,
292
+ accessToken: backendClient.accessToken,
293
+ cloudServer: backendClient.cloudServer,
294
+ });
295
+ const messageClient = new RoutedDeviceMessageClient(
296
+ cloudMqttClient,
297
+ localController,
298
+ );
299
+ const cloud = {
300
+ client: new CloudClient(backendClient, messageClient, localController),
301
+ localController,
302
+ transport: new MiotEndpointConnectionCloudTransport(backendClient),
303
+ };
304
+
305
+ this.cloudValue = cloud;
306
+ return cloud;
307
+ }
308
+
309
+ private async loadLocalControllerDiscovery(): Promise<LocalControllerDiscovery> {
310
+ const discovery = await this.configuration.discoverDevices();
311
+
312
+ if (discovery === undefined || discovery.account.userId === null) {
313
+ return {candidates: []};
314
+ }
315
+
316
+ const candidates = discovery.devices.flatMap(device => {
317
+ if (
318
+ device.source !== 'owned' ||
319
+ device.homeId === undefined ||
320
+ device.homeName === undefined ||
321
+ !isCentralGatewayCandidateModel(device.model) ||
322
+ !isUnsignedDecimal(device.did)
323
+ ) {
324
+ return [];
325
+ }
326
+
327
+ return [
328
+ {
329
+ did: device.did,
330
+ homeId: device.homeId,
331
+ homeName: device.homeName,
332
+ },
333
+ ];
334
+ });
335
+
336
+ return {userId: discovery.account.userId, candidates};
337
+ }
338
+
339
+ private async discoverConfigurationDevices(): Promise<
340
+ MiotProviderConfigurationDiscovery | undefined
341
+ > {
342
+ if (this.authorizationInProgress) {
343
+ throw new Error(
344
+ 'Cannot discover MIoT devices while authorization is in progress.',
345
+ );
346
+ }
347
+
348
+ const authorizationGeneration = this.authorizationGeneration;
349
+ let session: OAuthSession;
350
+
351
+ try {
352
+ session = await this.sessionManager.getSession();
353
+ } catch (error) {
354
+ if (error instanceof OAuthSessionMissingError) {
355
+ return undefined;
356
+ }
357
+
358
+ throw error;
359
+ }
360
+
361
+ this.assertAuthorizationGeneration(authorizationGeneration);
362
+
363
+ const backendClient = createBackendClient(session);
364
+ this.discoveryBackendClientSet.add(backendClient);
365
+
366
+ let discovery;
367
+
368
+ try {
369
+ discovery = await backendClient.discoverDevices();
370
+ } finally {
371
+ this.discoveryBackendClientSet.delete(backendClient);
372
+ }
373
+
374
+ this.assertAuthorizationGeneration(authorizationGeneration);
375
+
376
+ return {
377
+ account: {
378
+ cloudServer: session.cloudServer,
379
+ userId: discovery.userId ?? null,
380
+ },
381
+ homes: discovery.homes,
382
+ devices: discovery.devices,
383
+ };
384
+ }
385
+
386
+ private async beginConfigurationAuthorization(
387
+ cloudServer: CloudServer,
388
+ ): Promise<MiotProviderConfigurationAuthorizationDependency> {
389
+ if (this.authorizationInProgress) {
390
+ throw new Error('MIoT provider authorization is already in progress.');
391
+ } else if (
392
+ this.cloudPromise !== undefined ||
393
+ this.endpointConnectionValues.length > 0
394
+ ) {
395
+ throw new Error(
396
+ 'Cannot authorize a MIoT provider after its connections have started.',
397
+ );
398
+ }
399
+
400
+ const generation = ++this.authorizationGeneration;
401
+ this.authorizationInProgress = true;
402
+
403
+ let authorization: OAuthSessionAuthorization;
404
+
405
+ try {
406
+ await this.sessionManager.reset();
407
+
408
+ if (this.authorizationGeneration !== generation) {
409
+ throw new Error('MIoT provider authorization was cancelled.');
410
+ }
411
+
412
+ const setupPromise = beginOAuthSessionAuthorization({
413
+ sessionPath: this.sessionPath,
414
+ uuidPath: this.oauthUuidPath,
415
+ cloudServer,
416
+ });
417
+ this.authorizationSetupPromise = setupPromise;
418
+
419
+ try {
420
+ authorization = await setupPromise;
421
+ } finally {
422
+ if (this.authorizationSetupPromise === setupPromise) {
423
+ this.authorizationSetupPromise = undefined;
424
+ }
425
+ }
426
+
427
+ if (this.authorizationGeneration !== generation) {
428
+ await authorization.cancel();
429
+ throw new Error('MIoT provider authorization was cancelled.');
430
+ }
431
+
432
+ this.authorization = authorization;
433
+ } catch (error) {
434
+ if (this.authorizationGeneration === generation) {
435
+ this.authorizationInProgress = false;
436
+ }
437
+
438
+ throw error;
439
+ }
440
+
441
+ const completion = (async () => {
442
+ try {
443
+ const session = await authorization.wait();
444
+
445
+ if (this.authorization === authorization) {
446
+ this.sessionManager.useSession(session);
447
+ }
448
+ } finally {
449
+ if (this.authorization === authorization) {
450
+ this.authorization = undefined;
451
+ this.authorizationInProgress = false;
452
+ }
453
+ }
454
+ })();
455
+
456
+ void completion.catch(() => undefined);
457
+ return {
458
+ url: authorization.url,
459
+ wait: () => completion,
460
+ submitCallbackUrl: callbackUrl =>
461
+ authorization.submitCallbackUrl(callbackUrl),
462
+ cancel: () => authorization.cancel(),
463
+ };
464
+ }
465
+
466
+ private forgetConfigurationAuthorization(): Promise<void> {
467
+ if (
468
+ this.cloudPromise !== undefined ||
469
+ this.endpointConnectionValues.length > 0
470
+ ) {
471
+ throw new Error(
472
+ 'Cannot forget a MIoT provider after its connections have started.',
473
+ );
474
+ }
475
+
476
+ let forgetPromise = this.forgetAuthorizationPromise;
477
+
478
+ if (forgetPromise === undefined) {
479
+ const newForgetPromise = this.performForgetConfigurationAuthorization();
480
+ forgetPromise = newForgetPromise;
481
+ this.forgetAuthorizationPromise = newForgetPromise;
482
+ void newForgetPromise.then(
483
+ () => {
484
+ this.completeForgetConfigurationAuthorization(newForgetPromise);
485
+ },
486
+ () => {
487
+ this.completeForgetConfigurationAuthorization(newForgetPromise);
488
+ },
489
+ );
490
+ }
491
+
492
+ return forgetPromise;
493
+ }
494
+
495
+ private async performForgetConfigurationAuthorization(): Promise<void> {
496
+ const generation = ++this.authorizationGeneration;
497
+ let authorization = this.authorization;
498
+ const authorizationSetupPromise = this.authorizationSetupPromise;
499
+ this.authorization = undefined;
500
+ this.authorizationInProgress = true;
501
+
502
+ try {
503
+ await this.sessionManager.reset();
504
+
505
+ if (
506
+ authorization === undefined &&
507
+ authorizationSetupPromise !== undefined
508
+ ) {
509
+ authorization = await authorizationSetupPromise.catch(() => undefined);
510
+ }
511
+
512
+ if (authorization !== undefined) {
513
+ await authorization.cancel();
514
+ await authorization.wait().catch(() => undefined);
515
+ await this.sessionManager.reset();
516
+ }
517
+
518
+ await rm(this.sessionPath, {force: true});
519
+ await rm(this.localCertificateDirectory, {
520
+ recursive: true,
521
+ force: true,
522
+ });
523
+ } finally {
524
+ if (this.authorizationGeneration === generation) {
525
+ this.authorizationInProgress = false;
526
+ }
527
+ }
528
+ }
529
+
530
+ private completeForgetConfigurationAuthorization(
531
+ forgetPromise: Promise<void>,
532
+ ): void {
533
+ if (this.forgetAuthorizationPromise === forgetPromise) {
534
+ this.forgetAuthorizationPromise = undefined;
535
+ }
536
+ }
537
+
538
+ private assertAuthorizationGeneration(generation: number): void {
539
+ if (
540
+ this.authorizationInProgress ||
541
+ this.authorizationGeneration !== generation
542
+ ) {
543
+ throw new Error('MIoT provider authorization changed during operation.');
544
+ }
545
+ }
546
+
547
+ private async subscribeEndpointConnection(
548
+ connection: MiotEndpointConnection<never>,
549
+ properties: readonly MiotProperty[],
550
+ cloudClient: CloudClient,
551
+ runtime: MiotEndpointConnectionRuntime,
552
+ ): Promise<void> {
553
+ while (runtime.active) {
554
+ try {
555
+ const subscription = await cloudClient.subscribeDevice(
556
+ connection.metadata.device.did,
557
+ properties,
558
+ {
559
+ onStateChanged: state => {
560
+ connection.handleStateUpdate(state);
561
+ },
562
+ onPropertyChanged: update => {
563
+ connection.handlePropertyUpdate(update);
564
+ },
565
+ onError: console.error,
566
+ },
567
+ );
568
+
569
+ if (!runtime.active) {
570
+ await subscription.dispose();
571
+ return;
572
+ }
573
+
574
+ this.endpointConnectionSubscriptionMap.set(connection, subscription);
575
+ return;
576
+ } catch (error) {
577
+ if (!runtime.active) {
578
+ return;
579
+ }
580
+
581
+ console.error(error);
582
+ await runtime.backoff;
583
+ }
584
+ }
585
+ }
586
+
587
+ private async disposeEndpointConnection(
588
+ connection: MiotEndpointConnection<never>,
589
+ ): Promise<void> {
590
+ const runtime = this.endpointConnectionRuntimeMap.get(connection);
591
+
592
+ if (runtime === undefined) {
593
+ return;
594
+ }
595
+
596
+ this.endpointConnectionDisposalCount++;
597
+ runtime.active = false;
598
+ runtime.backoff.reset();
599
+ const errors: unknown[] = [];
600
+
601
+ try {
602
+ await runtime.subscriptionPromise;
603
+ } catch (error) {
604
+ errors.push(error);
605
+ }
606
+
607
+ const subscription = this.endpointConnectionSubscriptionMap.get(connection);
608
+ this.endpointConnectionSubscriptionMap.delete(connection);
609
+
610
+ try {
611
+ await subscription?.dispose();
612
+ } catch (error) {
613
+ errors.push(error);
614
+ }
615
+
616
+ this.endpointConnectionRuntimeMap.delete(connection);
617
+
618
+ try {
619
+ this.removeEndpointConnection(connection);
620
+ } catch (error) {
621
+ errors.push(error);
622
+ }
623
+
624
+ this.endpointConnectionDisposalCount--;
625
+
626
+ try {
627
+ await this.disposeCloudIfUnused();
628
+ } catch (error) {
629
+ errors.push(error);
630
+ }
631
+
632
+ if (errors.length === 1) {
633
+ throw errors[0];
634
+ } else if (errors.length > 1) {
635
+ throw new AggregateError(errors, 'Failed to dispose MIoT connection.');
636
+ }
637
+ }
638
+
639
+ private async disposeCloudIfUnused(
640
+ expectedCloud?: MiotProviderCloud,
641
+ ): Promise<void> {
642
+ if (
643
+ this.endpointConnectionCreationCount > 0 ||
644
+ this.endpointConnectionDisposalCount > 0 ||
645
+ this.endpointConnectionRuntimeMap.size > 0 ||
646
+ (expectedCloud !== undefined && this.cloudValue !== expectedCloud)
647
+ ) {
648
+ return;
649
+ }
650
+
651
+ const cloud = this.cloudValue;
652
+ this.cloudValue = undefined;
653
+ this.cloudPromise = undefined;
654
+ const errors: unknown[] = [];
655
+
656
+ try {
657
+ await cloud?.client.disconnect();
658
+ } catch (error) {
659
+ errors.push(error);
660
+ }
661
+
662
+ if (
663
+ this.endpointConnectionCreationCount === 0 &&
664
+ this.endpointConnectionDisposalCount === 0 &&
665
+ this.endpointConnectionRuntimeMap.size === 0 &&
666
+ this.cloudValue === undefined &&
667
+ this.cloudPromise === undefined
668
+ ) {
669
+ try {
670
+ await this.sessionManager.reset();
671
+ } catch (error) {
672
+ errors.push(error);
673
+ }
674
+ }
675
+
676
+ if (errors.length === 1) {
677
+ throw errors[0];
678
+ } else if (errors.length > 1) {
679
+ throw new AggregateError(errors, 'Failed to dispose MIoT cloud.');
680
+ }
681
+ }
682
+
683
+ @action
684
+ private addEndpointConnection(
685
+ connection: MiotEndpointConnection<never>,
686
+ ): void {
687
+ this.endpointConnectionValues.push(connection);
688
+ }
689
+
690
+ @action
691
+ private removeEndpointConnection(
692
+ connection: MiotEndpointConnection<never>,
693
+ ): void {
694
+ const index = this.endpointConnectionValues.indexOf(connection);
695
+
696
+ if (index >= 0) {
697
+ this.endpointConnectionValues.splice(index, 1);
698
+ }
699
+ }
700
+ }
701
+
702
+ export const $xiaomi = $constructor(MiotProvider)
703
+ .build(uniqueName('provider'))
704
+ .build(provider => {
705
+ register(MIOT_NAMESPACE, provider);
706
+ });
707
+
708
+ type MiotProviderCloud = {
709
+ readonly client: CloudClient;
710
+ readonly localController: LocalController;
711
+ readonly transport: MiotEndpointConnectionCloudTransport;
712
+ };
713
+
714
+ type MiotEndpointConnectionRuntime = {
715
+ active: boolean;
716
+ readonly backoff: ExponentialBackoff;
717
+ subscriptionPromise?: Promise<void>;
718
+ };
719
+
720
+ type BindingCreationOutcome =
721
+ | {readonly type: 'success'; readonly binding: EndpointConnectionBinding}
722
+ | {readonly type: 'error'; readonly error: unknown};
723
+
724
+ function createBackendClient(session: OAuthSession): BackendClient {
725
+ return new BackendClient({
726
+ uuid: session.uuid,
727
+ accessToken: session.token.accessToken,
728
+ cloudServer: session.cloudServer,
729
+ });
730
+ }
731
+
732
+ function isUnsignedDecimal(value: string): boolean {
733
+ return /^(?:0|[1-9]\d*)$/u.test(value);
734
+ }
735
+
736
+ function isCentralGatewayCandidateModel(model: string | undefined): boolean {
737
+ return (
738
+ model
739
+ ?.split('.')
740
+ .some(
741
+ part =>
742
+ part === 'controller' || part === 'gateway' || part === 'router',
743
+ ) ?? false
744
+ );
745
+ }