@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,841 @@
1
+ import {
2
+ type Command,
3
+ CommandError,
4
+ type CommandExecution,
5
+ type EndpointConnection,
6
+ EndpointConnectionError,
7
+ type EndpointConnectionMetadata,
8
+ Temperature,
9
+ } from '@homelib/core';
10
+ import {action, computed, observable} from 'mobx';
11
+ import * as x from 'x-value';
12
+
13
+ import {
14
+ type MiotExecutionRequest,
15
+ type MiotExecutionResult,
16
+ type MiotProperty,
17
+ type MiotPropertySchema,
18
+ type MiotPropertySchemaProperties,
19
+ type MiotResolvedSpecProperty,
20
+ type MiotSpecProperty,
21
+ MiotSpecService,
22
+ type MiotSpecValueList,
23
+ type MiotSpecValueRange,
24
+ isSuccessfulMiotExecutionResult,
25
+ isValidMiotSpecValueList,
26
+ isValidMiotSpecValueRange,
27
+ } from './miot/index.js';
28
+ import type {MiotProvider} from './provider.js';
29
+
30
+ /** A MIoT service snapshot claimed by one logical endpoint. */
31
+ export const MiotEndpointConnectionResource = x.object({
32
+ service: MiotSpecService,
33
+ });
34
+
35
+ export const MiotEndpointConnectionMetadata = x
36
+ .object({
37
+ device: x.object({
38
+ did: x.string,
39
+ model: x.string.optional(),
40
+ urn: x.string,
41
+ }),
42
+ resources: x.array(MiotEndpointConnectionResource),
43
+ })
44
+ .refined(metadata => {
45
+ assertMiotEndpointConnectionResources(metadata.resources);
46
+ return metadata;
47
+ });
48
+
49
+ export function normalizeMiotEndpointConnectionMetadata(
50
+ value: unknown,
51
+ ): MiotEndpointConnectionMetadata {
52
+ return MiotEndpointConnectionMetadata.sanitize(value);
53
+ }
54
+
55
+ export function getMiotEndpointConnectionProperty(
56
+ metadata: MiotEndpointConnectionResolvedMetadata,
57
+ name: string,
58
+ ): {
59
+ readonly service: MiotSpecService;
60
+ readonly property: MiotResolvedSpecProperty;
61
+ } {
62
+ for (const {service, properties} of metadata.resources) {
63
+ const property = properties[name];
64
+
65
+ if (property !== undefined) {
66
+ return {service, property};
67
+ }
68
+ }
69
+
70
+ throw new TypeError(`Unknown MIoT endpoint property: ${name}.`);
71
+ }
72
+
73
+ export function getMiotEndpointConnectionResourceKeys(
74
+ metadata: MiotEndpointConnectionMetadata,
75
+ ): readonly string[] {
76
+ // Every service selected by one endpoint is exclusive for now.
77
+ return metadata.resources
78
+ .toSorted(compareMiotEndpointResources)
79
+ .map(resource => getMiotResourceKey(metadata.device.did, resource));
80
+ }
81
+
82
+ export abstract class MiotEndpointConnection<
83
+ in TCommand extends Command,
84
+ TSchema extends MiotPropertySchema = {},
85
+ > implements EndpointConnection<TCommand> {
86
+ @observable.shallow private accessor stateMap = new Map<string, unknown>();
87
+
88
+ @observable private accessor readyValue = false;
89
+
90
+ @observable private accessor stateRevisionValue = 0;
91
+
92
+ private readonly observationRevisionMap = new Map<string, number>();
93
+
94
+ protected readonly properties: MiotEndpointConnectionSchemaProperties<TSchema>;
95
+
96
+ protected readonly transports: MiotEndpointConnectionTransports;
97
+
98
+ @computed
99
+ get ready(): boolean {
100
+ return this.readyValue;
101
+ }
102
+
103
+ @computed
104
+ get stateRevision(): number {
105
+ return this.stateRevisionValue;
106
+ }
107
+
108
+ get stateProperties(): readonly MiotProperty[] {
109
+ const {metadata} = this;
110
+ return metadata.resources.flatMap(resource => {
111
+ return Object.values(resource.properties).map(property => {
112
+ return {
113
+ did: metadata.device.did,
114
+ siid: resource.service.iid,
115
+ piid: property.iid,
116
+ };
117
+ });
118
+ });
119
+ }
120
+
121
+ /** Returns the latest observation revision among the resolved aliases. */
122
+ getObservationRevision(names: Iterable<string>): number {
123
+ let revision = 0;
124
+
125
+ for (const name of names) {
126
+ revision = Math.max(revision, this.observationRevisionMap.get(name) ?? 0);
127
+ }
128
+
129
+ return revision;
130
+ }
131
+
132
+ /** @internal Returns the latest raw MIoT state for a resolved alias. */
133
+ getCommandEffectState(name: string): unknown {
134
+ return this.stateMap.get(name);
135
+ }
136
+
137
+ constructor(
138
+ readonly provider: MiotProvider,
139
+ readonly metadata: MiotEndpointConnectionResolvedMetadata,
140
+ transports: MiotEndpointConnectionTransports,
141
+ ) {
142
+ this.transports = transports;
143
+ this.properties =
144
+ this.createProperties() as MiotEndpointConnectionSchemaProperties<TSchema>;
145
+ }
146
+
147
+ @action
148
+ handlePropertyUpdate(update: MiotPropertyUpdate): void {
149
+ const [state] = this.prepareStateUpdates([update]);
150
+
151
+ if (state === undefined) {
152
+ throw new TypeError('Missing MIoT endpoint property update.');
153
+ }
154
+
155
+ this.stateMap.set(state.name, state.value);
156
+ this.stateRevisionValue++;
157
+ this.observationRevisionMap.set(state.name, this.stateRevisionValue);
158
+ }
159
+
160
+ @action
161
+ handleStateUpdate(update: MiotEndpointStateUpdate): void {
162
+ if (update.did !== this.metadata.device.did) {
163
+ throw new TypeError('Unexpected MIoT endpoint state update.');
164
+ }
165
+
166
+ if (!update.online) {
167
+ this.readyValue = false;
168
+ this.stateRevisionValue++;
169
+ return;
170
+ }
171
+
172
+ const states = this.prepareStateUpdates(update.properties);
173
+
174
+ if (states.length !== getMiotEndpointPropertyCount(this.metadata)) {
175
+ throw new TypeError('Incomplete MIoT endpoint state update.');
176
+ }
177
+
178
+ for (const {name, value} of states) {
179
+ this.stateMap.set(name, value);
180
+ }
181
+
182
+ this.readyValue = true;
183
+ this.stateRevisionValue++;
184
+
185
+ for (const {name} of states) {
186
+ this.observationRevisionMap.set(name, this.stateRevisionValue);
187
+ }
188
+ }
189
+
190
+ abstract prepareCommand(command: TCommand): CommandExecution;
191
+
192
+ protected getBooleanPropertyState<
193
+ const TName extends Extract<
194
+ keyof MiotEndpointConnectionSchemaProperties<TSchema>,
195
+ string
196
+ >,
197
+ >(name: TName): boolean | undefined;
198
+ protected getBooleanPropertyState<
199
+ const TName extends Extract<
200
+ keyof MiotEndpointConnectionSchemaProperties<TSchema>,
201
+ string
202
+ >,
203
+ >(
204
+ name: TName,
205
+ initial: boolean,
206
+ ): MiotEndpointConnectionPropertyState<
207
+ MiotEndpointConnectionSchemaProperties<TSchema>[TName],
208
+ boolean
209
+ >;
210
+ protected getBooleanPropertyState(
211
+ name: string,
212
+ initial?: boolean,
213
+ ): boolean | undefined {
214
+ const property = this.getProperty(name);
215
+
216
+ if (property === undefined) {
217
+ return undefined;
218
+ }
219
+
220
+ const value = this.getCommandEffectState(name);
221
+
222
+ if (value === undefined) {
223
+ return initial;
224
+ }
225
+
226
+ if (typeof value !== 'boolean') {
227
+ throw new TypeError(`Invalid MIoT boolean property state: ${name}.`);
228
+ }
229
+
230
+ return value;
231
+ }
232
+
233
+ protected getNumberPropertyState<
234
+ const TName extends Extract<
235
+ keyof MiotEndpointConnectionSchemaProperties<TSchema>,
236
+ string
237
+ >,
238
+ >(name: TName): number | undefined;
239
+ protected getNumberPropertyState<
240
+ const TName extends Extract<
241
+ keyof MiotEndpointConnectionSchemaProperties<TSchema>,
242
+ string
243
+ >,
244
+ >(
245
+ name: TName,
246
+ initial: number,
247
+ ): MiotEndpointConnectionPropertyState<
248
+ MiotEndpointConnectionSchemaProperties<TSchema>[TName],
249
+ number
250
+ >;
251
+ protected getNumberPropertyState(
252
+ name: string,
253
+ initial?: number,
254
+ ): number | undefined {
255
+ const property = this.getProperty(name);
256
+
257
+ if (property === undefined) {
258
+ return undefined;
259
+ }
260
+
261
+ const value = this.getCommandEffectState(name);
262
+
263
+ if (value === undefined) {
264
+ return initial;
265
+ }
266
+
267
+ if (typeof value !== 'number' || !Number.isFinite(value)) {
268
+ throw new TypeError(`Invalid MIoT numeric property state: ${name}.`);
269
+ }
270
+
271
+ return value;
272
+ }
273
+
274
+ protected getEnumPropertyState<
275
+ const TName extends MiotEndpointConnectionEnumPropertyName<
276
+ MiotEndpointConnectionSchemaProperties<TSchema>
277
+ >,
278
+ >(
279
+ name: TName,
280
+ ):
281
+ | MiotPropertyEnumName<
282
+ MiotEndpointConnectionSchemaProperties<TSchema>[TName]
283
+ >
284
+ | undefined;
285
+ protected getEnumPropertyState<
286
+ const TName extends MiotEndpointConnectionEnumPropertyName<
287
+ MiotEndpointConnectionSchemaProperties<TSchema>
288
+ >,
289
+ >(
290
+ name: TName,
291
+ initial: MiotPropertyEnumInitial<
292
+ MiotEndpointConnectionSchemaProperties<TSchema>[TName]
293
+ >,
294
+ ): MiotEndpointConnectionPropertyState<
295
+ MiotEndpointConnectionSchemaProperties<TSchema>[TName],
296
+ MiotPropertyEnumName<MiotEndpointConnectionSchemaProperties<TSchema>[TName]>
297
+ >;
298
+ protected getEnumPropertyState(
299
+ name: string,
300
+ initial?: string,
301
+ ): string | undefined {
302
+ const property = this.getProperty(name);
303
+
304
+ if (property === undefined) {
305
+ return undefined;
306
+ }
307
+
308
+ if (property.enum === undefined) {
309
+ throw new TypeError(`Missing MIoT property enum: ${name}.`);
310
+ }
311
+
312
+ const value = this.getCommandEffectState(name);
313
+
314
+ if (value === undefined) {
315
+ if (initial !== undefined && !Object.hasOwn(property.enum, initial)) {
316
+ throw new TypeError(
317
+ `Unsupported MIoT property enum initial value: ${name}=${initial}.`,
318
+ );
319
+ }
320
+
321
+ return initial;
322
+ }
323
+
324
+ if (typeof value !== 'number' || !Number.isFinite(value)) {
325
+ throw new TypeError(`Invalid MIoT enum property state: ${name}.`);
326
+ }
327
+
328
+ const enumName = Object.entries(property.enum).find(
329
+ ([, enumValue]) => enumValue === value,
330
+ )?.[0];
331
+
332
+ if (enumName === undefined) {
333
+ throw new TypeError(
334
+ `Unknown MIoT enum property state: ${name}=${value}.`,
335
+ );
336
+ }
337
+
338
+ return enumName;
339
+ }
340
+
341
+ protected getTemperaturePropertyState<
342
+ const TName extends Extract<
343
+ keyof MiotEndpointConnectionSchemaProperties<TSchema>,
344
+ string
345
+ >,
346
+ >(
347
+ name: TName,
348
+ initial: Temperature,
349
+ ): MiotEndpointConnectionPropertyState<
350
+ MiotEndpointConnectionSchemaProperties<TSchema>[TName],
351
+ Temperature
352
+ > {
353
+ const property = this.getProperty(name);
354
+
355
+ if (property === undefined) {
356
+ return undefined as MiotEndpointConnectionPropertyState<
357
+ MiotEndpointConnectionSchemaProperties<TSchema>[TName],
358
+ Temperature
359
+ >;
360
+ }
361
+
362
+ const value = this.getCommandEffectState(name);
363
+
364
+ if (value === undefined) {
365
+ return initial as MiotEndpointConnectionPropertyState<
366
+ MiotEndpointConnectionSchemaProperties<TSchema>[TName],
367
+ Temperature
368
+ >;
369
+ }
370
+
371
+ if (typeof value !== 'number' || !Number.isFinite(value)) {
372
+ throw new TypeError(`Invalid MIoT numeric property state: ${name}.`);
373
+ }
374
+
375
+ let temperature: Temperature;
376
+
377
+ switch (property.unit) {
378
+ case 'celsius':
379
+ temperature = Temperature.fromCelsius(value);
380
+ break;
381
+ case 'fahrenheit':
382
+ temperature = Temperature.fromFahrenheit(value);
383
+ break;
384
+ case 'kelvin':
385
+ temperature = Temperature.fromKelvin(value);
386
+ break;
387
+ default:
388
+ throw new TypeError(
389
+ `Unsupported MIoT temperature property unit: ${property.name} (${property.unit ?? 'none'}).`,
390
+ );
391
+ }
392
+
393
+ return temperature as MiotEndpointConnectionPropertyState<
394
+ MiotEndpointConnectionSchemaProperties<TSchema>[TName],
395
+ Temperature
396
+ >;
397
+ }
398
+
399
+ private createProperties(): MiotEndpointConnectionProperties {
400
+ const properties: Record<string, MiotEndpointConnectionProperty> = {};
401
+
402
+ for (const resource of this.metadata.resources) {
403
+ for (const [name, property] of Object.entries(resource.properties)) {
404
+ properties[name] = {...property, name};
405
+ }
406
+ }
407
+
408
+ return properties;
409
+ }
410
+
411
+ private getProperty(
412
+ name: string,
413
+ ): MiotEndpointConnectionProperty | undefined {
414
+ const properties: MiotEndpointConnectionProperties = this.properties;
415
+ return properties[name];
416
+ }
417
+
418
+ protected getPropertyValueRange(
419
+ property: MiotEndpointConnectionProperty,
420
+ ): MiotSpecValueRange {
421
+ const valueRange = property['value-range'];
422
+
423
+ if (!isValidMiotSpecValueRange(valueRange, property.format)) {
424
+ throw new TypeError(
425
+ `Invalid MIoT property value range: ${property.name}.`,
426
+ );
427
+ }
428
+
429
+ return valueRange;
430
+ }
431
+
432
+ protected getPropertyValueList(
433
+ property: MiotEndpointConnectionProperty,
434
+ ): MiotSpecValueList {
435
+ const valueList = property['value-list'];
436
+
437
+ if (!isValidMiotSpecValueList(valueList)) {
438
+ throw new TypeError(
439
+ `Invalid MIoT property value list: ${property.name}.`,
440
+ );
441
+ }
442
+
443
+ return valueList;
444
+ }
445
+
446
+ toLogString(): string {
447
+ const {device} = this.metadata;
448
+ const serviceIids = this.metadata.resources
449
+ .toSorted(compareMiotEndpointResources)
450
+ .map(({service}) => service.iid);
451
+
452
+ return `miot ${this.provider.name} · did ${device.did} · services ${serviceIids.join(',')}`;
453
+ }
454
+
455
+ protected async executeRequest(request: MiotExecutionRequest): Promise<void> {
456
+ let lastUnavailableError:
457
+ MiotEndpointConnectionTransportUnavailableError | undefined;
458
+
459
+ for (const transport of this.transports) {
460
+ let result: MiotExecutionResult;
461
+
462
+ try {
463
+ result = await transport.executeRequest(request);
464
+ } catch (error) {
465
+ if (error instanceof MiotEndpointConnectionTransportUnavailableError) {
466
+ lastUnavailableError = error;
467
+ continue;
468
+ }
469
+
470
+ throw createMiotEndpointConnectionTransportError(error);
471
+ }
472
+
473
+ if (!isSuccessfulMiotExecutionResult(result)) {
474
+ throw new CommandError(`MIoT request failed: ${result.code}.`);
475
+ }
476
+
477
+ return;
478
+ }
479
+
480
+ throw createMiotEndpointConnectionError(lastUnavailableError);
481
+ }
482
+
483
+ private prepareStateUpdates(
484
+ updates: readonly MiotPropertyUpdate[],
485
+ ): Array<{readonly name: string; readonly value: unknown}> {
486
+ const states: Array<{readonly name: string; readonly value: unknown}> = [];
487
+ const stateNameSet = new Set<string>();
488
+
489
+ for (const update of updates) {
490
+ const state = this.getStateUpdate(update);
491
+
492
+ if (stateNameSet.has(state.name)) {
493
+ throw new TypeError('Duplicate MIoT endpoint property update.');
494
+ }
495
+
496
+ stateNameSet.add(state.name);
497
+ states.push(state);
498
+ }
499
+
500
+ return states;
501
+ }
502
+
503
+ private getStateUpdate(update: MiotPropertyUpdate): {
504
+ readonly name: string;
505
+ readonly value: unknown;
506
+ } {
507
+ const {metadata} = this;
508
+
509
+ if (update.did !== metadata.device.did) {
510
+ throw new TypeError('Unexpected MIoT endpoint property update.');
511
+ }
512
+
513
+ const resource = metadata.resources.find(candidate => {
514
+ return candidate.service.iid === update.siid;
515
+ });
516
+
517
+ if (resource === undefined) {
518
+ throw new TypeError('Unexpected MIoT endpoint property update.');
519
+ }
520
+
521
+ let stateName: string | undefined;
522
+ let stateProperty: MiotResolvedSpecProperty | undefined;
523
+
524
+ for (const [name, property] of Object.entries(resource.properties)) {
525
+ if (property.iid !== update.piid) {
526
+ continue;
527
+ }
528
+
529
+ if (stateName !== undefined) {
530
+ throw new TypeError('Ambiguous MIoT endpoint property update.');
531
+ }
532
+
533
+ stateName = name;
534
+ stateProperty = property;
535
+ }
536
+
537
+ if (stateName === undefined || stateProperty === undefined) {
538
+ throw new TypeError('Unexpected MIoT endpoint property update.');
539
+ }
540
+
541
+ assertMiotPropertyValue(stateProperty, update.value, stateName, update);
542
+ return {name: stateName, value: update.value};
543
+ }
544
+ }
545
+
546
+ export abstract class MiotEndpointConnectionTransport {
547
+ abstract executeRequest(
548
+ request: MiotExecutionRequest,
549
+ ): Promise<MiotExecutionResult>;
550
+ }
551
+
552
+ /**
553
+ * Signals that a transport could not route a request before publishing it.
554
+ *
555
+ * A transport must not throw this error after the request may have been sent,
556
+ * because endpoint connections use it as the only safe signal to try the next
557
+ * transport.
558
+ */
559
+ export class MiotEndpointConnectionTransportUnavailableError extends Error {
560
+ constructor(message: string) {
561
+ super(message);
562
+ this.name = new.target.name;
563
+ }
564
+ }
565
+
566
+ /**
567
+ * Signals that a transport failed after a request may have been published.
568
+ *
569
+ * Unlike {@link MiotEndpointConnectionTransportUnavailableError}, this error
570
+ * must not trigger transport fallback or automatic command retries.
571
+ */
572
+ export class MiotEndpointConnectionTransportError extends Error {
573
+ constructor(message: string) {
574
+ super(message);
575
+ this.name = new.target.name;
576
+ }
577
+ }
578
+
579
+ export type MiotEndpointConnectionTransports = readonly [
580
+ MiotEndpointConnectionTransport,
581
+ ...MiotEndpointConnectionTransport[],
582
+ ];
583
+
584
+ export type MiotEndpointConnectionMetadata = EndpointConnectionMetadata &
585
+ Readonly<x.TypeOf<typeof MiotEndpointConnectionMetadata>>;
586
+
587
+ export type MiotEndpointConnectionResource = Readonly<
588
+ x.TypeOf<typeof MiotEndpointConnectionResource>
589
+ >;
590
+
591
+ /** A physical resource enriched with resolved endpoint property aliases. */
592
+ export type MiotEndpointConnectionResolvedResource = Omit<
593
+ MiotEndpointConnectionResource,
594
+ 'properties'
595
+ > & {
596
+ readonly properties: Readonly<Record<string, MiotResolvedSpecProperty>>;
597
+ };
598
+
599
+ export type MiotEndpointConnectionResolvedMetadata = Omit<
600
+ MiotEndpointConnectionMetadata,
601
+ 'resources'
602
+ > & {
603
+ readonly resources: readonly MiotEndpointConnectionResolvedResource[];
604
+ };
605
+
606
+ type MiotEndpointConnectionProperty = MiotResolvedSpecProperty & {
607
+ readonly name: string;
608
+ };
609
+
610
+ type MiotEndpointConnectionEnumProperty = MiotEndpointConnectionProperty & {
611
+ readonly enum: Readonly<Record<string, number>>;
612
+ };
613
+
614
+ type MiotEndpointConnectionProperties = Readonly<
615
+ Record<string, MiotEndpointConnectionProperty | undefined>
616
+ >;
617
+
618
+ type MiotEndpointConnectionSchemaProperties<
619
+ TSchema extends MiotPropertySchema,
620
+ > = MiotPropertySchemaProperties<TSchema>;
621
+
622
+ type MiotEndpointConnectionPropertyState<TProperty, TValue> =
623
+ undefined extends TProperty ? TValue | undefined : TValue;
624
+
625
+ type MiotEndpointConnectionEnumPropertyName<TProperties> = Extract<
626
+ {
627
+ [TName in keyof TProperties]-?: NonNullable<
628
+ TProperties[TName]
629
+ > extends MiotEndpointConnectionEnumProperty
630
+ ? TName
631
+ : never;
632
+ }[keyof TProperties],
633
+ string
634
+ >;
635
+
636
+ type MiotPropertyEnumName<TProperty> = TProperty extends {
637
+ readonly enum: infer TEnum;
638
+ }
639
+ ? TEnum extends Readonly<Record<string, number>>
640
+ ? Extract<keyof TEnum, string>
641
+ : never
642
+ : never;
643
+
644
+ type MiotPropertyEnumInitial<TProperty> =
645
+ NonNullable<TProperty> extends {
646
+ readonly enum: infer TEnum extends Readonly<Record<string, number>>;
647
+ }
648
+ ? Extract<keyof TEnum, string>
649
+ : never;
650
+
651
+ export function createMiotEndpointConnectionResolvedMetadata(
652
+ metadata: MiotEndpointConnectionMetadata,
653
+ resources: readonly MiotEndpointConnectionResolvedResource[],
654
+ ): MiotEndpointConnectionResolvedMetadata {
655
+ const physicalResourceMap = new Map(
656
+ metadata.resources.map(resource => [resource.service.iid, resource]),
657
+ );
658
+ const resolvedServiceIidSet = new Set<number>();
659
+ const stateNameSet = new Set<string>();
660
+ const propertyKeySet = new Set<string>();
661
+
662
+ if (resources.length !== metadata.resources.length) {
663
+ throw new TypeError('Invalid resolved MIoT endpoint resources.');
664
+ }
665
+
666
+ const resolvedResources = resources.map(resource => {
667
+ if (resolvedServiceIidSet.has(resource.service.iid)) {
668
+ throw new TypeError('Duplicate resolved MIoT endpoint resource.');
669
+ }
670
+
671
+ resolvedServiceIidSet.add(resource.service.iid);
672
+ const physicalResource = physicalResourceMap.get(resource.service.iid);
673
+
674
+ if (physicalResource === undefined) {
675
+ throw new TypeError('Invalid resolved MIoT endpoint resource.');
676
+ }
677
+
678
+ for (const [name, property] of Object.entries(resource.properties)) {
679
+ const propertyKey = JSON.stringify([resource.service.iid, property.iid]);
680
+
681
+ if (stateNameSet.has(name) || propertyKeySet.has(propertyKey)) {
682
+ throw new TypeError('Ambiguous resolved MIoT endpoint property.');
683
+ }
684
+
685
+ if (
686
+ !physicalResource.service.properties?.some(candidate =>
687
+ miotSpecPropertiesEqual(candidate, property),
688
+ )
689
+ ) {
690
+ throw new TypeError(
691
+ 'Resolved MIoT endpoint property does not belong to its service.',
692
+ );
693
+ }
694
+
695
+ stateNameSet.add(name);
696
+ propertyKeySet.add(propertyKey);
697
+ }
698
+
699
+ return {
700
+ service: physicalResource.service,
701
+ properties: resource.properties,
702
+ };
703
+ });
704
+
705
+ return {device: metadata.device, resources: resolvedResources};
706
+ }
707
+
708
+ export type MiotPropertyUpdate = MiotProperty & {
709
+ readonly value: unknown;
710
+ };
711
+
712
+ export type MiotEndpointStateUpdate = {
713
+ readonly did: string;
714
+ readonly online: boolean;
715
+ readonly properties: readonly MiotPropertyUpdate[];
716
+ };
717
+
718
+ function assertMiotEndpointConnectionResources(
719
+ resources: readonly MiotEndpointConnectionResource[],
720
+ ): void {
721
+ if (resources.length === 0) {
722
+ throw new TypeError(
723
+ 'MIoT endpoint metadata requires at least one resource.',
724
+ );
725
+ }
726
+
727
+ const serviceIidSet = new Set<number>();
728
+ for (const resource of resources) {
729
+ if (serviceIidSet.has(resource.service.iid)) {
730
+ throw new TypeError('Duplicate MIoT endpoint metadata service.');
731
+ }
732
+
733
+ serviceIidSet.add(resource.service.iid);
734
+ }
735
+ }
736
+
737
+ function miotSpecPropertiesEqual(
738
+ left: MiotSpecProperty,
739
+ right: MiotSpecProperty,
740
+ ): boolean {
741
+ return left.iid === right.iid && left.type === right.type;
742
+ }
743
+
744
+ function getMiotResourceKey(
745
+ did: string,
746
+ resource: MiotEndpointConnectionResource,
747
+ ): string {
748
+ return JSON.stringify([did, resource.service.iid]);
749
+ }
750
+
751
+ function compareMiotEndpointResources(
752
+ left: {readonly service: {readonly iid: number}},
753
+ right: {readonly service: {readonly iid: number}},
754
+ ): number {
755
+ return left.service.iid - right.service.iid;
756
+ }
757
+
758
+ function getMiotEndpointPropertyCount(
759
+ metadata: MiotEndpointConnectionResolvedMetadata,
760
+ ): number {
761
+ return metadata.resources.reduce((count, resource) => {
762
+ return count + Object.keys(resource.properties).length;
763
+ }, 0);
764
+ }
765
+
766
+ function createMiotEndpointConnectionTransportError(
767
+ error: unknown,
768
+ ): MiotEndpointConnectionTransportError {
769
+ const message =
770
+ error instanceof Error
771
+ ? `MIoT transport failed: ${error.message}`
772
+ : 'MIoT transport failed.';
773
+ return new MiotEndpointConnectionTransportError(message);
774
+ }
775
+
776
+ function createMiotEndpointConnectionError(
777
+ error: unknown,
778
+ ): EndpointConnectionError {
779
+ const message =
780
+ error instanceof Error
781
+ ? `MIoT transport failed: ${error.message}`
782
+ : 'MIoT transport failed.';
783
+ return new EndpointConnectionError(message);
784
+ }
785
+
786
+ function assertMiotPropertyValue(
787
+ property: MiotResolvedSpecProperty,
788
+ value: unknown,
789
+ stateName: string,
790
+ update: MiotPropertyUpdate,
791
+ ): void {
792
+ const {format} = property;
793
+ let numericValue: number | undefined;
794
+
795
+ if (format === 'bool') {
796
+ if (typeof value !== 'boolean') {
797
+ throw new TypeError('Invalid MIoT boolean property state.');
798
+ }
799
+ } else if (format === 'string') {
800
+ if (typeof value !== 'string') {
801
+ throw new TypeError('Invalid MIoT string property state.');
802
+ }
803
+ } else {
804
+ if (typeof value !== 'number' || !Number.isFinite(value)) {
805
+ throw new TypeError('Invalid MIoT numeric property state.');
806
+ }
807
+
808
+ if (/^(?:u?int(?:8|16|32))$/.test(format) && !Number.isInteger(value)) {
809
+ throw new TypeError('Invalid MIoT integer property state.');
810
+ }
811
+
812
+ numericValue = value;
813
+ }
814
+
815
+ const valueList = property['value-list'];
816
+
817
+ if (valueList !== undefined) {
818
+ if (
819
+ !isValidMiotSpecValueList(valueList) ||
820
+ !valueList.some(entry => entry.value === numericValue)
821
+ ) {
822
+ throw new TypeError('Invalid MIoT value-list property state.');
823
+ }
824
+ }
825
+
826
+ const valueRange = property['value-range'];
827
+
828
+ if (valueRange === undefined || numericValue === undefined) {
829
+ return;
830
+ }
831
+
832
+ // The third value describes control precision. A device may report a finer
833
+ // sensor value, so state validation only applies the declared boundaries.
834
+ const [minimum, maximum] = valueRange;
835
+
836
+ if (numericValue < minimum || numericValue > maximum) {
837
+ throw new TypeError(
838
+ `Invalid MIoT ranged property state. ${stateName}=${numericValue} at did ${update.did}, siid ${update.siid}, piid ${update.piid}; expected ${minimum}..${maximum}.`,
839
+ );
840
+ }
841
+ }