@homelib/xiaomi 0.0.0-wip.33a9dc48299c
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.
- package/LICENSE +19 -0
- package/README.md +22 -0
- package/bld/library/backend/client.d.ts +68 -0
- package/bld/library/backend/client.js +477 -0
- package/bld/library/backend/client.js.map +1 -0
- package/bld/library/backend/constants.d.ts +7 -0
- package/bld/library/backend/constants.js +11 -0
- package/bld/library/backend/constants.js.map +1 -0
- package/bld/library/backend/index.d.ts +3 -0
- package/bld/library/backend/index.js +4 -0
- package/bld/library/backend/index.js.map +1 -0
- package/bld/library/backend/oauth.d.ts +24 -0
- package/bld/library/backend/oauth.js +121 -0
- package/bld/library/backend/oauth.js.map +1 -0
- package/bld/library/binding.d.ts +44 -0
- package/bld/library/binding.js +212 -0
- package/bld/library/binding.js.map +1 -0
- package/bld/library/cloud/client.d.ts +27 -0
- package/bld/library/cloud/client.js +109 -0
- package/bld/library/cloud/client.js.map +1 -0
- package/bld/library/cloud/constants.d.ts +9 -0
- package/bld/library/cloud/constants.js +11 -0
- package/bld/library/cloud/constants.js.map +1 -0
- package/bld/library/cloud/device.d.ts +84 -0
- package/bld/library/cloud/device.js +686 -0
- package/bld/library/cloud/device.js.map +1 -0
- package/bld/library/cloud/index.d.ts +5 -0
- package/bld/library/cloud/index.js +6 -0
- package/bld/library/cloud/index.js.map +1 -0
- package/bld/library/cloud/mqtt.d.ts +69 -0
- package/bld/library/cloud/mqtt.js +517 -0
- package/bld/library/cloud/mqtt.js.map +1 -0
- package/bld/library/cloud/transport.d.ts +8 -0
- package/bld/library/cloud/transport.js +30 -0
- package/bld/library/cloud/transport.js.map +1 -0
- package/bld/library/command.d.ts +6 -0
- package/bld/library/command.js +6 -0
- package/bld/library/command.js.map +1 -0
- package/bld/library/configuration.d.ts +62 -0
- package/bld/library/configuration.js +303 -0
- package/bld/library/configuration.js.map +1 -0
- package/bld/library/device.d.ts +68 -0
- package/bld/library/device.js +235 -0
- package/bld/library/device.js.map +1 -0
- package/bld/library/devices/air-conditioner.d.ts +48 -0
- package/bld/library/devices/air-conditioner.js +155 -0
- package/bld/library/devices/air-conditioner.js.map +1 -0
- package/bld/library/devices/command-effect.d.ts +35 -0
- package/bld/library/devices/command-effect.js +269 -0
- package/bld/library/devices/command-effect.js.map +1 -0
- package/bld/library/devices/dehumidifier.d.ts +41 -0
- package/bld/library/devices/dehumidifier.js +124 -0
- package/bld/library/devices/dehumidifier.js.map +1 -0
- package/bld/library/devices/fan.d.ts +37 -0
- package/bld/library/devices/fan.js +135 -0
- package/bld/library/devices/fan.js.map +1 -0
- package/bld/library/devices/index.d.ts +7 -0
- package/bld/library/devices/index.js +8 -0
- package/bld/library/devices/index.js.map +1 -0
- package/bld/library/devices/light.d.ts +22 -0
- package/bld/library/devices/light.js +112 -0
- package/bld/library/devices/light.js.map +1 -0
- package/bld/library/devices/placeholder.d.ts +3 -0
- package/bld/library/devices/placeholder.js +4 -0
- package/bld/library/devices/placeholder.js.map +1 -0
- package/bld/library/devices/value-range.d.ts +2 -0
- package/bld/library/devices/value-range.js +6 -0
- package/bld/library/devices/value-range.js.map +1 -0
- package/bld/library/endpoint-connection.d.ts +154 -0
- package/bld/library/endpoint-connection.js +510 -0
- package/bld/library/endpoint-connection.js.map +1 -0
- package/bld/library/index.d.ts +26 -0
- package/bld/library/index.js +31 -0
- package/bld/library/index.js.map +1 -0
- package/bld/library/local/certificate.d.ts +31 -0
- package/bld/library/local/certificate.js +298 -0
- package/bld/library/local/certificate.js.map +1 -0
- package/bld/library/local/controller.d.ts +70 -0
- package/bld/library/local/controller.js +497 -0
- package/bld/library/local/controller.js.map +1 -0
- package/bld/library/local/discovery.d.ts +29 -0
- package/bld/library/local/discovery.js +321 -0
- package/bld/library/local/discovery.js.map +1 -0
- package/bld/library/local/index.d.ts +6 -0
- package/bld/library/local/index.js +7 -0
- package/bld/library/local/index.js.map +1 -0
- package/bld/library/local/message.d.ts +11 -0
- package/bld/library/local/message.js +128 -0
- package/bld/library/local/message.js.map +1 -0
- package/bld/library/local/mqtt.d.ts +113 -0
- package/bld/library/local/mqtt.js +1044 -0
- package/bld/library/local/mqtt.js.map +1 -0
- package/bld/library/local/routed-message-client.d.ts +49 -0
- package/bld/library/local/routed-message-client.js +326 -0
- package/bld/library/local/routed-message-client.js.map +1 -0
- package/bld/library/miot/index.d.ts +4 -0
- package/bld/library/miot/index.js +5 -0
- package/bld/library/miot/index.js.map +1 -0
- package/bld/library/miot/matcher.d.ts +65 -0
- package/bld/library/miot/matcher.js +217 -0
- package/bld/library/miot/matcher.js.map +1 -0
- package/bld/library/miot/request.d.ts +16 -0
- package/bld/library/miot/request.js +27 -0
- package/bld/library/miot/request.js.map +1 -0
- package/bld/library/miot/result.d.ts +4 -0
- package/bld/library/miot/result.js +5 -0
- package/bld/library/miot/result.js.map +1 -0
- package/bld/library/miot/spec.d.ts +74 -0
- package/bld/library/miot/spec.js +78 -0
- package/bld/library/miot/spec.js.map +1 -0
- package/bld/library/provider.d.ts +71 -0
- package/bld/library/provider.js +600 -0
- package/bld/library/provider.js.map +1 -0
- package/bld/library/session-manager.d.ts +34 -0
- package/bld/library/session-manager.js +177 -0
- package/bld/library/session-manager.js.map +1 -0
- package/bld/library/session.d.ts +36 -0
- package/bld/library/session.js +370 -0
- package/bld/library/session.js.map +1 -0
- package/bld/library/storage.d.ts +2 -0
- package/bld/library/storage.js +66 -0
- package/bld/library/storage.js.map +1 -0
- package/bld/library/terminal/bindings.d.ts +3 -0
- package/bld/library/terminal/bindings.js +280 -0
- package/bld/library/terminal/bindings.js.map +1 -0
- package/bld/library/terminal/index.d.ts +2 -0
- package/bld/library/terminal/index.js +3 -0
- package/bld/library/terminal/index.js.map +1 -0
- package/bld/library/terminal/provider-details.d.ts +3 -0
- package/bld/library/terminal/provider-details.js +477 -0
- package/bld/library/terminal/provider-details.js.map +1 -0
- package/package.json +29 -0
- package/src/library/backend/client.ts +713 -0
- package/src/library/backend/constants.ts +17 -0
- package/src/library/backend/index.ts +3 -0
- package/src/library/backend/oauth.ts +170 -0
- package/src/library/binding.ts +387 -0
- package/src/library/cloud/client.ts +155 -0
- package/src/library/cloud/constants.ts +19 -0
- package/src/library/cloud/device.ts +938 -0
- package/src/library/cloud/index.ts +5 -0
- package/src/library/cloud/mqtt.ts +671 -0
- package/src/library/cloud/transport.ts +38 -0
- package/src/library/command.ts +7 -0
- package/src/library/configuration.ts +480 -0
- package/src/library/device.ts +548 -0
- package/src/library/devices/air-conditioner.ts +171 -0
- package/src/library/devices/command-effect.ts +425 -0
- package/src/library/devices/dehumidifier.ts +131 -0
- package/src/library/devices/fan.ts +140 -0
- package/src/library/devices/index.ts +7 -0
- package/src/library/devices/light.ts +119 -0
- package/src/library/devices/placeholder.ts +3 -0
- package/src/library/devices/value-range.ts +14 -0
- package/src/library/endpoint-connection.ts +841 -0
- package/src/library/index.ts +62 -0
- package/src/library/local/certificate.ts +401 -0
- package/src/library/local/controller.ts +692 -0
- package/src/library/local/discovery.ts +485 -0
- package/src/library/local/index.ts +6 -0
- package/src/library/local/message.ts +174 -0
- package/src/library/local/mqtt.ts +1493 -0
- package/src/library/local/routed-message-client.ts +377 -0
- package/src/library/miot/index.ts +4 -0
- package/src/library/miot/matcher.ts +461 -0
- package/src/library/miot/request.ts +30 -0
- package/src/library/miot/result.ts +10 -0
- package/src/library/miot/spec.ts +103 -0
- package/src/library/provider.ts +745 -0
- package/src/library/session-manager.ts +224 -0
- package/src/library/session.ts +528 -0
- package/src/library/storage.ts +83 -0
- package/src/library/terminal/bindings.tsx +612 -0
- package/src/library/terminal/index.ts +2 -0
- package/src/library/terminal/provider-details.tsx +871 -0
|
@@ -0,0 +1,692 @@
|
|
|
1
|
+
import {join} from 'node:path';
|
|
2
|
+
|
|
3
|
+
import type {BackendClient, CloudServer} from '../backend/index.js';
|
|
4
|
+
import {
|
|
5
|
+
MiotEndpointConnectionTransport,
|
|
6
|
+
MiotEndpointConnectionTransportUnavailableError,
|
|
7
|
+
} from '../endpoint-connection.js';
|
|
8
|
+
import type {
|
|
9
|
+
MiotExecutionRequest,
|
|
10
|
+
MiotExecutionResult,
|
|
11
|
+
MiotProperty,
|
|
12
|
+
} from '../miot/index.js';
|
|
13
|
+
|
|
14
|
+
import {
|
|
15
|
+
type LocalCertificate,
|
|
16
|
+
LocalCertificateManager,
|
|
17
|
+
getVirtualDid,
|
|
18
|
+
} from './certificate.js';
|
|
19
|
+
import {
|
|
20
|
+
type CentralGatewayCandidate,
|
|
21
|
+
type CentralRoute,
|
|
22
|
+
discoverCentralRoutes,
|
|
23
|
+
} from './discovery.js';
|
|
24
|
+
import {
|
|
25
|
+
type LocalDeviceInfo,
|
|
26
|
+
LocalMqttClient,
|
|
27
|
+
type LocalMqttClientOptions,
|
|
28
|
+
type LocalPropertyResult,
|
|
29
|
+
} from './mqtt.js';
|
|
30
|
+
|
|
31
|
+
const ROUTE_REFRESH_INTERVAL = 10 * 60_000;
|
|
32
|
+
const INITIAL_RETRY_INTERVAL = 5_000;
|
|
33
|
+
const MAXIMUM_RETRY_INTERVAL = 60_000;
|
|
34
|
+
const DEVICE_LIST_RETRY_INTERVAL = 5_000;
|
|
35
|
+
const CERTIFICATE_FILE_NAME = 'central.json';
|
|
36
|
+
|
|
37
|
+
export class LocalController extends MiotEndpointConnectionTransport {
|
|
38
|
+
private readonly virtualDid: string;
|
|
39
|
+
|
|
40
|
+
private readonly routeRuntimeMap = new Map<string, LocalRouteRuntime>();
|
|
41
|
+
|
|
42
|
+
private readonly routesChangedListenerSet =
|
|
43
|
+
new Set<LocalRoutesChangedListener>();
|
|
44
|
+
|
|
45
|
+
private active = false;
|
|
46
|
+
|
|
47
|
+
private generation = 0;
|
|
48
|
+
|
|
49
|
+
private retryInterval = INITIAL_RETRY_INTERVAL;
|
|
50
|
+
|
|
51
|
+
private refreshPromise: Promise<void> | undefined;
|
|
52
|
+
|
|
53
|
+
private refreshTimeout: ReturnType<typeof setTimeout> | undefined;
|
|
54
|
+
|
|
55
|
+
constructor(
|
|
56
|
+
private readonly options: LocalControllerOptions,
|
|
57
|
+
private readonly dependencies: LocalControllerDependencies = DEFAULT_DEPENDENCIES,
|
|
58
|
+
) {
|
|
59
|
+
super();
|
|
60
|
+
this.virtualDid = dependencies.getVirtualDid(options.session.uuid);
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
get connected(): boolean {
|
|
64
|
+
for (const runtime of this.routeRuntimeMap.values()) {
|
|
65
|
+
if (runtime.client.connected) {
|
|
66
|
+
return true;
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
return false;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
async connect(): Promise<void> {
|
|
74
|
+
this.start();
|
|
75
|
+
|
|
76
|
+
const refreshPromise = this.refreshPromise;
|
|
77
|
+
|
|
78
|
+
if (refreshPromise !== undefined) {
|
|
79
|
+
await refreshPromise;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
if (!this.connected) {
|
|
83
|
+
throw new MiotEndpointConnectionTransportUnavailableError(
|
|
84
|
+
'No local MQTT gateway is connected.',
|
|
85
|
+
);
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
start(): void {
|
|
90
|
+
if (this.active || this.options.session.cloudServer !== 'cn') {
|
|
91
|
+
return;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
this.active = true;
|
|
95
|
+
this.retryInterval = INITIAL_RETRY_INTERVAL;
|
|
96
|
+
this.startRefresh(this.generation);
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
async dispose(): Promise<void> {
|
|
100
|
+
if (!this.active && this.routeRuntimeMap.size === 0) {
|
|
101
|
+
return;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
this.active = false;
|
|
105
|
+
this.generation++;
|
|
106
|
+
this.clearRefreshTimeout();
|
|
107
|
+
const runtimes = [...this.routeRuntimeMap.values()];
|
|
108
|
+
this.routeRuntimeMap.clear();
|
|
109
|
+
this.notifyRoutesChanged();
|
|
110
|
+
const runtimeDisposals = runtimes.map(runtime =>
|
|
111
|
+
this.disposeRuntime(runtime),
|
|
112
|
+
);
|
|
113
|
+
await this.refreshPromise?.catch(() => undefined);
|
|
114
|
+
const results = await Promise.allSettled(runtimeDisposals);
|
|
115
|
+
throwRejectedResults(results, 'Failed to dispose local MQTT routes.');
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
async disconnect(): Promise<void> {
|
|
119
|
+
await this.dispose();
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
addRoutesChangedListener(listener: LocalRoutesChangedListener): () => void {
|
|
123
|
+
this.routesChangedListenerSet.add(listener);
|
|
124
|
+
|
|
125
|
+
return () => {
|
|
126
|
+
this.routesChangedListenerSet.delete(listener);
|
|
127
|
+
};
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
getMessageSource(did: string): LocalMqttClient | undefined {
|
|
131
|
+
for (const runtime of this.routeRuntimeMap.values()) {
|
|
132
|
+
const info = runtime.deviceInfoMap.get(did);
|
|
133
|
+
|
|
134
|
+
if (
|
|
135
|
+
runtime.client.connected &&
|
|
136
|
+
info !== undefined &&
|
|
137
|
+
info.online &&
|
|
138
|
+
info.pushAvailable
|
|
139
|
+
) {
|
|
140
|
+
return runtime.client;
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
return undefined;
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
async getProperties(
|
|
148
|
+
properties: readonly MiotProperty[],
|
|
149
|
+
): Promise<readonly LocalPropertyResult[]> {
|
|
150
|
+
const routes = properties.map(property => ({
|
|
151
|
+
property,
|
|
152
|
+
client: this.getRequestSource(property.did),
|
|
153
|
+
}));
|
|
154
|
+
|
|
155
|
+
if (routes.some(route => route.client === undefined)) {
|
|
156
|
+
throw new MiotEndpointConnectionTransportUnavailableError(
|
|
157
|
+
'No local MQTT route is available for the requested MIoT properties.',
|
|
158
|
+
);
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
const results: LocalPropertyResult[] = [];
|
|
162
|
+
|
|
163
|
+
for (const {property, client} of routes) {
|
|
164
|
+
if (client === undefined) {
|
|
165
|
+
throw new Error('Local MQTT property route disappeared.');
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
results.push(...(await client.getProperties([property])));
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
return results;
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
async getDeviceOnline(did: string): Promise<boolean> {
|
|
175
|
+
for (const runtime of this.routeRuntimeMap.values()) {
|
|
176
|
+
const info = runtime.deviceInfoMap.get(did);
|
|
177
|
+
|
|
178
|
+
if (runtime.client.connected && info !== undefined) {
|
|
179
|
+
return info.online;
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
throw new MiotEndpointConnectionTransportUnavailableError(
|
|
184
|
+
`No local MQTT state route is available for MIoT device ${did}.`,
|
|
185
|
+
);
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
override async executeRequest(
|
|
189
|
+
request: MiotExecutionRequest,
|
|
190
|
+
): Promise<MiotExecutionResult> {
|
|
191
|
+
const did = request.property.did;
|
|
192
|
+
const client = this.getRequestSource(did);
|
|
193
|
+
|
|
194
|
+
if (client !== undefined) {
|
|
195
|
+
return client.executeRequest(request);
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
throw new MiotEndpointConnectionTransportUnavailableError(
|
|
199
|
+
`No local MQTT route is available for MIoT device ${did}.`,
|
|
200
|
+
);
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
private startRefresh(generation: number): void {
|
|
204
|
+
if (!this.isActiveGeneration(generation)) {
|
|
205
|
+
return;
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
const refreshPromise = this.refresh(generation);
|
|
209
|
+
this.refreshPromise = refreshPromise;
|
|
210
|
+
void refreshPromise.then(
|
|
211
|
+
() => {
|
|
212
|
+
this.completeRefresh(refreshPromise, generation, undefined);
|
|
213
|
+
},
|
|
214
|
+
error => {
|
|
215
|
+
this.completeRefresh(refreshPromise, generation, error);
|
|
216
|
+
},
|
|
217
|
+
);
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
private completeRefresh(
|
|
221
|
+
refreshPromise: Promise<void>,
|
|
222
|
+
generation: number,
|
|
223
|
+
error: unknown,
|
|
224
|
+
): void {
|
|
225
|
+
if (this.refreshPromise === refreshPromise) {
|
|
226
|
+
this.refreshPromise = undefined;
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
if (!this.isActiveGeneration(generation)) {
|
|
230
|
+
return;
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
let delay = ROUTE_REFRESH_INTERVAL;
|
|
234
|
+
|
|
235
|
+
if (error === undefined) {
|
|
236
|
+
this.retryInterval = INITIAL_RETRY_INTERVAL;
|
|
237
|
+
} else {
|
|
238
|
+
console.error(error);
|
|
239
|
+
delay = this.retryInterval;
|
|
240
|
+
this.retryInterval = Math.min(
|
|
241
|
+
this.retryInterval * 2,
|
|
242
|
+
MAXIMUM_RETRY_INTERVAL,
|
|
243
|
+
);
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
this.scheduleRefresh(generation, delay);
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
private scheduleRefresh(generation: number, delay: number): void {
|
|
250
|
+
this.clearRefreshTimeout();
|
|
251
|
+
const timeout = setTimeout(() => {
|
|
252
|
+
if (this.refreshTimeout === timeout) {
|
|
253
|
+
this.refreshTimeout = undefined;
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
this.startRefresh(generation);
|
|
257
|
+
}, delay);
|
|
258
|
+
timeout.unref?.();
|
|
259
|
+
this.refreshTimeout = timeout;
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
private async refresh(generation: number): Promise<void> {
|
|
263
|
+
const discovery = await this.options.loadDiscovery();
|
|
264
|
+
this.assertActiveGeneration(generation);
|
|
265
|
+
|
|
266
|
+
if (discovery.userId === undefined || discovery.candidates.length === 0) {
|
|
267
|
+
await this.reconcileRoutes([], undefined, generation);
|
|
268
|
+
return;
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
const certificateManager = this.dependencies.createCertificateManager({
|
|
272
|
+
path: join(
|
|
273
|
+
this.options.certificateDirectory,
|
|
274
|
+
this.options.session.uuid,
|
|
275
|
+
CERTIFICATE_FILE_NAME,
|
|
276
|
+
),
|
|
277
|
+
uuid: this.options.session.uuid,
|
|
278
|
+
userId: discovery.userId,
|
|
279
|
+
getCertificate: request =>
|
|
280
|
+
this.options.backendClient.getCentralCertificate(request),
|
|
281
|
+
});
|
|
282
|
+
const certificate = await certificateManager.ensureCertificate();
|
|
283
|
+
this.assertActiveGeneration(generation);
|
|
284
|
+
const routes = await this.dependencies.discoverCentralRoutes({
|
|
285
|
+
candidates: discovery.candidates,
|
|
286
|
+
userId: discovery.userId,
|
|
287
|
+
virtualDid: this.virtualDid,
|
|
288
|
+
});
|
|
289
|
+
this.assertActiveGeneration(generation);
|
|
290
|
+
|
|
291
|
+
if (routes.length === 0 && this.routeRuntimeMap.size > 0) {
|
|
292
|
+
throw new Error(
|
|
293
|
+
'Local MQTT discovery temporarily returned no existing routes.',
|
|
294
|
+
);
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
await this.reconcileRoutes(routes, certificate, generation);
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
private async reconcileRoutes(
|
|
301
|
+
routes: readonly CentralRoute[],
|
|
302
|
+
certificate: LocalCertificate | undefined,
|
|
303
|
+
generation: number,
|
|
304
|
+
): Promise<void> {
|
|
305
|
+
const routeMap = new Map<string, CentralRoute>();
|
|
306
|
+
|
|
307
|
+
for (const route of routes) {
|
|
308
|
+
routeMap.set(getRouteKey(route), route);
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
const obsoleteRuntimes: LocalRouteRuntime[] = [];
|
|
312
|
+
|
|
313
|
+
for (const [key, runtime] of this.routeRuntimeMap) {
|
|
314
|
+
const route = routeMap.get(key);
|
|
315
|
+
|
|
316
|
+
if (
|
|
317
|
+
route !== undefined &&
|
|
318
|
+
certificate !== undefined &&
|
|
319
|
+
runtime.certificate === certificate.certificate &&
|
|
320
|
+
areRoutesEqual(runtime.route, route)
|
|
321
|
+
) {
|
|
322
|
+
routeMap.delete(key);
|
|
323
|
+
continue;
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
this.routeRuntimeMap.delete(key);
|
|
327
|
+
obsoleteRuntimes.push(runtime);
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
if (obsoleteRuntimes.length > 0) {
|
|
331
|
+
this.notifyRoutesChanged();
|
|
332
|
+
await Promise.allSettled(
|
|
333
|
+
obsoleteRuntimes.map(runtime => this.disposeRuntime(runtime)),
|
|
334
|
+
);
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
this.assertActiveGeneration(generation);
|
|
338
|
+
|
|
339
|
+
if (routeMap.size === 0) {
|
|
340
|
+
return;
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
if (certificate === undefined) {
|
|
344
|
+
throw new Error(
|
|
345
|
+
'Cannot connect local MQTT routes without a certificate.',
|
|
346
|
+
);
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
const outcomes = await Promise.allSettled(
|
|
350
|
+
[...routeMap.values()].map(route =>
|
|
351
|
+
this.addRoute(route, certificate, generation),
|
|
352
|
+
),
|
|
353
|
+
);
|
|
354
|
+
const errors = outcomes
|
|
355
|
+
.filter(
|
|
356
|
+
(outcome): outcome is PromiseRejectedResult =>
|
|
357
|
+
outcome.status === 'rejected',
|
|
358
|
+
)
|
|
359
|
+
.map(outcome => outcome.reason as unknown);
|
|
360
|
+
|
|
361
|
+
if (errors.length > 0) {
|
|
362
|
+
throw new AggregateError(errors, 'Failed to connect local MQTT routes.');
|
|
363
|
+
}
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
private async addRoute(
|
|
367
|
+
route: CentralRoute,
|
|
368
|
+
certificate: LocalCertificate,
|
|
369
|
+
generation: number,
|
|
370
|
+
): Promise<void> {
|
|
371
|
+
const client = this.dependencies.createMqttClient({
|
|
372
|
+
virtualDid: this.virtualDid,
|
|
373
|
+
gatewayDid: route.did,
|
|
374
|
+
host: route.address,
|
|
375
|
+
port: route.port,
|
|
376
|
+
ca: certificate.caCertificate,
|
|
377
|
+
cert: certificate.certificate,
|
|
378
|
+
key: certificate.privateKey,
|
|
379
|
+
});
|
|
380
|
+
const runtime: LocalRouteRuntime = {
|
|
381
|
+
route,
|
|
382
|
+
client,
|
|
383
|
+
certificate: certificate.certificate,
|
|
384
|
+
deviceInfoMap: new Map(),
|
|
385
|
+
deviceListRefreshRequested: false,
|
|
386
|
+
deviceListRetryTimeout: undefined,
|
|
387
|
+
initializing: true,
|
|
388
|
+
disposed: false,
|
|
389
|
+
removeConnectionStateListener: () => undefined,
|
|
390
|
+
removeDeviceListChangedListener: () => undefined,
|
|
391
|
+
};
|
|
392
|
+
runtime.removeConnectionStateListener = client.addConnectionStateListener(
|
|
393
|
+
connected => {
|
|
394
|
+
this.handleConnectionState(runtime, connected);
|
|
395
|
+
},
|
|
396
|
+
);
|
|
397
|
+
runtime.removeDeviceListChangedListener =
|
|
398
|
+
client.addDeviceListChangedListener(() => {
|
|
399
|
+
this.startDeviceListRefresh(runtime);
|
|
400
|
+
});
|
|
401
|
+
const key = getRouteKey(route);
|
|
402
|
+
this.routeRuntimeMap.set(key, runtime);
|
|
403
|
+
|
|
404
|
+
try {
|
|
405
|
+
await client.connect();
|
|
406
|
+
this.assertCurrentRuntime(key, runtime, generation);
|
|
407
|
+
await this.refreshDeviceList(runtime);
|
|
408
|
+
this.assertCurrentRuntime(key, runtime, generation);
|
|
409
|
+
runtime.initializing = false;
|
|
410
|
+
this.notifyRoutesChanged();
|
|
411
|
+
} catch (error) {
|
|
412
|
+
if (this.routeRuntimeMap.get(key) === runtime) {
|
|
413
|
+
this.routeRuntimeMap.delete(key);
|
|
414
|
+
this.notifyRoutesChanged();
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
await this.disposeRuntime(runtime);
|
|
418
|
+
throw error;
|
|
419
|
+
}
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
private handleConnectionState(
|
|
423
|
+
runtime: LocalRouteRuntime,
|
|
424
|
+
connected: boolean,
|
|
425
|
+
): void {
|
|
426
|
+
if (!this.isCurrentRuntime(runtime)) {
|
|
427
|
+
return;
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
if (connected) {
|
|
431
|
+
if (!runtime.initializing) {
|
|
432
|
+
this.startDeviceListRefresh(runtime);
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
return;
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
runtime.deviceInfoMap = new Map();
|
|
439
|
+
this.notifyRoutesChanged();
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
private startDeviceListRefresh(runtime: LocalRouteRuntime): void {
|
|
443
|
+
void this.refreshDeviceList(runtime).catch(error => {
|
|
444
|
+
if (this.isCurrentRuntime(runtime)) {
|
|
445
|
+
console.error(error);
|
|
446
|
+
this.scheduleDeviceListRefresh(runtime);
|
|
447
|
+
}
|
|
448
|
+
});
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
private scheduleDeviceListRefresh(runtime: LocalRouteRuntime): void {
|
|
452
|
+
if (runtime.deviceListRetryTimeout !== undefined) {
|
|
453
|
+
return;
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
const timeout = setTimeout(() => {
|
|
457
|
+
if (runtime.deviceListRetryTimeout === timeout) {
|
|
458
|
+
runtime.deviceListRetryTimeout = undefined;
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
if (this.isCurrentRuntime(runtime)) {
|
|
462
|
+
this.startDeviceListRefresh(runtime);
|
|
463
|
+
}
|
|
464
|
+
}, DEVICE_LIST_RETRY_INTERVAL);
|
|
465
|
+
timeout.unref?.();
|
|
466
|
+
runtime.deviceListRetryTimeout = timeout;
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
private async refreshDeviceList(runtime: LocalRouteRuntime): Promise<void> {
|
|
470
|
+
runtime.deviceListRefreshRequested = true;
|
|
471
|
+
let refreshPromise = runtime.deviceListRefreshPromise;
|
|
472
|
+
|
|
473
|
+
if (refreshPromise === undefined) {
|
|
474
|
+
const newRefreshPromise = this.drainDeviceListRefresh(runtime);
|
|
475
|
+
refreshPromise = newRefreshPromise;
|
|
476
|
+
runtime.deviceListRefreshPromise = newRefreshPromise;
|
|
477
|
+
const complete = (): void => {
|
|
478
|
+
if (runtime.deviceListRefreshPromise !== newRefreshPromise) {
|
|
479
|
+
return;
|
|
480
|
+
}
|
|
481
|
+
|
|
482
|
+
runtime.deviceListRefreshPromise = undefined;
|
|
483
|
+
|
|
484
|
+
if (
|
|
485
|
+
runtime.deviceListRefreshRequested &&
|
|
486
|
+
this.isCurrentRuntime(runtime)
|
|
487
|
+
) {
|
|
488
|
+
this.startDeviceListRefresh(runtime);
|
|
489
|
+
}
|
|
490
|
+
};
|
|
491
|
+
void newRefreshPromise.then(complete, complete);
|
|
492
|
+
}
|
|
493
|
+
|
|
494
|
+
await refreshPromise;
|
|
495
|
+
}
|
|
496
|
+
|
|
497
|
+
private async drainDeviceListRefresh(
|
|
498
|
+
runtime: LocalRouteRuntime,
|
|
499
|
+
): Promise<void> {
|
|
500
|
+
while (
|
|
501
|
+
runtime.deviceListRefreshRequested &&
|
|
502
|
+
this.isCurrentRuntime(runtime)
|
|
503
|
+
) {
|
|
504
|
+
runtime.deviceListRefreshRequested = false;
|
|
505
|
+
await this.loadDeviceList(runtime);
|
|
506
|
+
}
|
|
507
|
+
}
|
|
508
|
+
|
|
509
|
+
private async loadDeviceList(runtime: LocalRouteRuntime): Promise<void> {
|
|
510
|
+
const deviceInfoMap = await runtime.client.getDeviceList();
|
|
511
|
+
|
|
512
|
+
if (!this.isCurrentRuntime(runtime)) {
|
|
513
|
+
return;
|
|
514
|
+
}
|
|
515
|
+
|
|
516
|
+
runtime.deviceInfoMap = deviceInfoMap;
|
|
517
|
+
|
|
518
|
+
if (runtime.deviceListRetryTimeout !== undefined) {
|
|
519
|
+
clearTimeout(runtime.deviceListRetryTimeout);
|
|
520
|
+
runtime.deviceListRetryTimeout = undefined;
|
|
521
|
+
}
|
|
522
|
+
|
|
523
|
+
this.notifyRoutesChanged();
|
|
524
|
+
}
|
|
525
|
+
|
|
526
|
+
private async disposeRuntime(runtime: LocalRouteRuntime): Promise<void> {
|
|
527
|
+
if (runtime.disposed) {
|
|
528
|
+
return;
|
|
529
|
+
}
|
|
530
|
+
|
|
531
|
+
runtime.disposed = true;
|
|
532
|
+
|
|
533
|
+
if (runtime.deviceListRetryTimeout !== undefined) {
|
|
534
|
+
clearTimeout(runtime.deviceListRetryTimeout);
|
|
535
|
+
runtime.deviceListRetryTimeout = undefined;
|
|
536
|
+
}
|
|
537
|
+
|
|
538
|
+
runtime.removeConnectionStateListener();
|
|
539
|
+
runtime.removeDeviceListChangedListener();
|
|
540
|
+
const results = await Promise.allSettled([
|
|
541
|
+
Promise.resolve().then(() => runtime.client.disconnect()),
|
|
542
|
+
runtime.deviceListRefreshPromise ?? Promise.resolve(),
|
|
543
|
+
]);
|
|
544
|
+
throwRejectedResults(results, 'Failed to dispose a local MQTT route.');
|
|
545
|
+
}
|
|
546
|
+
|
|
547
|
+
private isCurrentRuntime(runtime: LocalRouteRuntime): boolean {
|
|
548
|
+
return (
|
|
549
|
+
this.active &&
|
|
550
|
+
!runtime.disposed &&
|
|
551
|
+
this.routeRuntimeMap.get(getRouteKey(runtime.route)) === runtime
|
|
552
|
+
);
|
|
553
|
+
}
|
|
554
|
+
|
|
555
|
+
private assertCurrentRuntime(
|
|
556
|
+
key: string,
|
|
557
|
+
runtime: LocalRouteRuntime,
|
|
558
|
+
generation: number,
|
|
559
|
+
): void {
|
|
560
|
+
this.assertActiveGeneration(generation);
|
|
561
|
+
|
|
562
|
+
if (this.routeRuntimeMap.get(key) !== runtime || runtime.disposed) {
|
|
563
|
+
throw new Error('Local MQTT route was replaced during initialization.');
|
|
564
|
+
}
|
|
565
|
+
}
|
|
566
|
+
|
|
567
|
+
private isActiveGeneration(generation: number): boolean {
|
|
568
|
+
return this.active && this.generation === generation;
|
|
569
|
+
}
|
|
570
|
+
|
|
571
|
+
private assertActiveGeneration(generation: number): void {
|
|
572
|
+
if (!this.isActiveGeneration(generation)) {
|
|
573
|
+
throw new Error('Local MQTT controller operation was cancelled.');
|
|
574
|
+
}
|
|
575
|
+
}
|
|
576
|
+
|
|
577
|
+
private clearRefreshTimeout(): void {
|
|
578
|
+
if (this.refreshTimeout === undefined) {
|
|
579
|
+
return;
|
|
580
|
+
}
|
|
581
|
+
|
|
582
|
+
clearTimeout(this.refreshTimeout);
|
|
583
|
+
this.refreshTimeout = undefined;
|
|
584
|
+
}
|
|
585
|
+
|
|
586
|
+
private notifyRoutesChanged(): void {
|
|
587
|
+
for (const listener of this.routesChangedListenerSet) {
|
|
588
|
+
try {
|
|
589
|
+
listener();
|
|
590
|
+
} catch (error) {
|
|
591
|
+
console.error(error);
|
|
592
|
+
}
|
|
593
|
+
}
|
|
594
|
+
}
|
|
595
|
+
|
|
596
|
+
private getRequestSource(did: string): LocalMqttClient | undefined {
|
|
597
|
+
for (const runtime of this.routeRuntimeMap.values()) {
|
|
598
|
+
const info = runtime.deviceInfoMap.get(did);
|
|
599
|
+
|
|
600
|
+
if (
|
|
601
|
+
runtime.client.connected &&
|
|
602
|
+
info !== undefined &&
|
|
603
|
+
info.online &&
|
|
604
|
+
info.specV2Access
|
|
605
|
+
) {
|
|
606
|
+
return runtime.client;
|
|
607
|
+
}
|
|
608
|
+
}
|
|
609
|
+
|
|
610
|
+
return undefined;
|
|
611
|
+
}
|
|
612
|
+
}
|
|
613
|
+
|
|
614
|
+
export type LocalControllerOptions = {
|
|
615
|
+
readonly session: {
|
|
616
|
+
readonly uuid: string;
|
|
617
|
+
readonly cloudServer: CloudServer;
|
|
618
|
+
};
|
|
619
|
+
readonly backendClient: BackendClient;
|
|
620
|
+
readonly certificateDirectory: string;
|
|
621
|
+
readonly loadDiscovery: () => Promise<LocalControllerDiscovery>;
|
|
622
|
+
};
|
|
623
|
+
|
|
624
|
+
export type LocalControllerDiscovery = {
|
|
625
|
+
readonly userId?: string;
|
|
626
|
+
readonly candidates: readonly CentralGatewayCandidate[];
|
|
627
|
+
};
|
|
628
|
+
|
|
629
|
+
export type LocalRoutesChangedListener = () => void;
|
|
630
|
+
|
|
631
|
+
type LocalControllerDependencies = {
|
|
632
|
+
readonly getVirtualDid: typeof getVirtualDid;
|
|
633
|
+
readonly createCertificateManager: (
|
|
634
|
+
options: ConstructorParameters<typeof LocalCertificateManager>[0],
|
|
635
|
+
) => Pick<LocalCertificateManager, 'ensureCertificate'>;
|
|
636
|
+
readonly discoverCentralRoutes: typeof discoverCentralRoutes;
|
|
637
|
+
readonly createMqttClient: (
|
|
638
|
+
options: LocalMqttClientOptions,
|
|
639
|
+
) => LocalMqttClient;
|
|
640
|
+
};
|
|
641
|
+
|
|
642
|
+
type LocalRouteRuntime = {
|
|
643
|
+
readonly route: CentralRoute;
|
|
644
|
+
readonly client: LocalMqttClient;
|
|
645
|
+
readonly certificate: string;
|
|
646
|
+
deviceInfoMap: ReadonlyMap<string, LocalDeviceInfo>;
|
|
647
|
+
deviceListRefreshRequested: boolean;
|
|
648
|
+
deviceListRetryTimeout: ReturnType<typeof setTimeout> | undefined;
|
|
649
|
+
initializing: boolean;
|
|
650
|
+
disposed: boolean;
|
|
651
|
+
deviceListRefreshPromise?: Promise<void>;
|
|
652
|
+
removeConnectionStateListener: () => void;
|
|
653
|
+
removeDeviceListChangedListener: () => void;
|
|
654
|
+
};
|
|
655
|
+
|
|
656
|
+
const DEFAULT_DEPENDENCIES: LocalControllerDependencies = {
|
|
657
|
+
getVirtualDid,
|
|
658
|
+
createCertificateManager: options => new LocalCertificateManager(options),
|
|
659
|
+
discoverCentralRoutes,
|
|
660
|
+
createMqttClient: options => new LocalMqttClient(options),
|
|
661
|
+
};
|
|
662
|
+
|
|
663
|
+
function getRouteKey(route: CentralRoute): string {
|
|
664
|
+
return `${route.did}\0${route.groupId}`;
|
|
665
|
+
}
|
|
666
|
+
|
|
667
|
+
function areRoutesEqual(left: CentralRoute, right: CentralRoute): boolean {
|
|
668
|
+
return (
|
|
669
|
+
left.did === right.did &&
|
|
670
|
+
left.groupId === right.groupId &&
|
|
671
|
+
left.homeName === right.homeName &&
|
|
672
|
+
left.address === right.address &&
|
|
673
|
+
left.port === right.port
|
|
674
|
+
);
|
|
675
|
+
}
|
|
676
|
+
|
|
677
|
+
function throwRejectedResults(
|
|
678
|
+
results: readonly PromiseSettledResult<unknown>[],
|
|
679
|
+
message: string,
|
|
680
|
+
): void {
|
|
681
|
+
const errors = results
|
|
682
|
+
.filter(
|
|
683
|
+
(result): result is PromiseRejectedResult => result.status === 'rejected',
|
|
684
|
+
)
|
|
685
|
+
.map(result => result.reason as unknown);
|
|
686
|
+
|
|
687
|
+
if (errors.length === 1) {
|
|
688
|
+
throw errors[0];
|
|
689
|
+
} else if (errors.length > 1) {
|
|
690
|
+
throw new AggregateError(errors, message);
|
|
691
|
+
}
|
|
692
|
+
}
|