@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.
- package/LICENSE +19 -0
- package/README.md +26 -0
- package/bld/library/backend/client.d.ts +73 -0
- package/bld/library/backend/client.js +490 -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 +34 -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 +69 -0
- package/bld/library/device.js +266 -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 +9 -0
- package/bld/library/devices/index.js +10 -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/pet-feeder.d.ts +36 -0
- package/bld/library/devices/pet-feeder.js +116 -0
- package/bld/library/devices/pet-feeder.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/temperature-humidity-sensor.d.ts +14 -0
- package/bld/library/devices/temperature-humidity-sensor.js +56 -0
- package/bld/library/devices/temperature-humidity-sensor.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 +168 -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 +33 -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 +498 -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 +1074 -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 +84 -0
- package/bld/library/miot/matcher.js +326 -0
- package/bld/library/miot/matcher.js.map +1 -0
- package/bld/library/miot/request.d.ts +33 -0
- package/bld/library/miot/request.js +57 -0
- package/bld/library/miot/request.js.map +1 -0
- package/bld/library/miot/result.d.ts +8 -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 +96 -0
- package/bld/library/miot/spec.js +86 -0
- package/bld/library/miot/spec.js.map +1 -0
- package/bld/library/provider.d.ts +78 -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 +306 -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 +737 -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 +46 -0
- package/src/library/command.ts +7 -0
- package/src/library/configuration.ts +480 -0
- package/src/library/device.ts +601 -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 +9 -0
- package/src/library/devices/light.ts +119 -0
- package/src/library/devices/pet-feeder.ts +129 -0
- package/src/library/devices/placeholder.ts +3 -0
- package/src/library/devices/temperature-humidity-sensor.ts +49 -0
- package/src/library/devices/value-range.ts +14 -0
- package/src/library/endpoint-connection.ts +841 -0
- package/src/library/index.ts +71 -0
- package/src/library/local/certificate.ts +401 -0
- package/src/library/local/controller.ts +693 -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 +1555 -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 +683 -0
- package/src/library/miot/request.ts +70 -0
- package/src/library/miot/result.ts +14 -0
- package/src/library/miot/spec.ts +114 -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 +692 -0
- package/src/library/terminal/index.ts +2 -0
- package/src/library/terminal/provider-details.tsx +871 -0
|
@@ -0,0 +1,1074 @@
|
|
|
1
|
+
import { X509Certificate, randomInt } from 'node:crypto';
|
|
2
|
+
import { connectAsync } from 'mqtt';
|
|
3
|
+
import { MiotEndpointConnectionTransport, MiotEndpointConnectionTransportUnavailableError, } from '../endpoint-connection.js';
|
|
4
|
+
import { MiotSetPropertyRequest, } from '../miot/index.js';
|
|
5
|
+
import { isMipsGatewayCertificate } from './certificate.js';
|
|
6
|
+
import { decodeMipsMessage, encodeMipsMessage } from './message.js';
|
|
7
|
+
const DEFAULT_PORT = 8883;
|
|
8
|
+
const KEEPALIVE_SECONDS = 60;
|
|
9
|
+
const CONNECT_TIMEOUT_MILLISECONDS = 10000;
|
|
10
|
+
const RECONNECT_INTERVAL_MILLISECONDS = 6000;
|
|
11
|
+
const REQUEST_TIMEOUT_MILLISECONDS = 10000;
|
|
12
|
+
const UINT32_RANGE = 4294967296;
|
|
13
|
+
const MQTT_QOS = 2;
|
|
14
|
+
export class LocalMqttClient extends MiotEndpointConnectionTransport {
|
|
15
|
+
constructor(options) {
|
|
16
|
+
super();
|
|
17
|
+
Object.defineProperty(this, "options", {
|
|
18
|
+
enumerable: true,
|
|
19
|
+
configurable: true,
|
|
20
|
+
writable: true,
|
|
21
|
+
value: options
|
|
22
|
+
});
|
|
23
|
+
Object.defineProperty(this, "mqttClient", {
|
|
24
|
+
enumerable: true,
|
|
25
|
+
configurable: true,
|
|
26
|
+
writable: true,
|
|
27
|
+
value: void 0
|
|
28
|
+
});
|
|
29
|
+
Object.defineProperty(this, "connectPromise", {
|
|
30
|
+
enumerable: true,
|
|
31
|
+
configurable: true,
|
|
32
|
+
writable: true,
|
|
33
|
+
value: void 0
|
|
34
|
+
});
|
|
35
|
+
Object.defineProperty(this, "readyOperation", {
|
|
36
|
+
enumerable: true,
|
|
37
|
+
configurable: true,
|
|
38
|
+
writable: true,
|
|
39
|
+
value: void 0
|
|
40
|
+
});
|
|
41
|
+
Object.defineProperty(this, "readyRetryTimeout", {
|
|
42
|
+
enumerable: true,
|
|
43
|
+
configurable: true,
|
|
44
|
+
writable: true,
|
|
45
|
+
value: void 0
|
|
46
|
+
});
|
|
47
|
+
Object.defineProperty(this, "activeConnectionGeneration", {
|
|
48
|
+
enumerable: true,
|
|
49
|
+
configurable: true,
|
|
50
|
+
writable: true,
|
|
51
|
+
value: void 0
|
|
52
|
+
});
|
|
53
|
+
Object.defineProperty(this, "nextConnectionGeneration", {
|
|
54
|
+
enumerable: true,
|
|
55
|
+
configurable: true,
|
|
56
|
+
writable: true,
|
|
57
|
+
value: 0
|
|
58
|
+
});
|
|
59
|
+
Object.defineProperty(this, "operationGeneration", {
|
|
60
|
+
enumerable: true,
|
|
61
|
+
configurable: true,
|
|
62
|
+
writable: true,
|
|
63
|
+
value: 0
|
|
64
|
+
});
|
|
65
|
+
Object.defineProperty(this, "ready", {
|
|
66
|
+
enumerable: true,
|
|
67
|
+
configurable: true,
|
|
68
|
+
writable: true,
|
|
69
|
+
value: false
|
|
70
|
+
});
|
|
71
|
+
Object.defineProperty(this, "nextMessageId", {
|
|
72
|
+
enumerable: true,
|
|
73
|
+
configurable: true,
|
|
74
|
+
writable: true,
|
|
75
|
+
value: randomInt(UINT32_RANGE)
|
|
76
|
+
});
|
|
77
|
+
Object.defineProperty(this, "pendingRequestMap", {
|
|
78
|
+
enumerable: true,
|
|
79
|
+
configurable: true,
|
|
80
|
+
writable: true,
|
|
81
|
+
value: new Map()
|
|
82
|
+
});
|
|
83
|
+
Object.defineProperty(this, "propertyListenerMap", {
|
|
84
|
+
enumerable: true,
|
|
85
|
+
configurable: true,
|
|
86
|
+
writable: true,
|
|
87
|
+
value: new Map()
|
|
88
|
+
});
|
|
89
|
+
Object.defineProperty(this, "eventListenerMap", {
|
|
90
|
+
enumerable: true,
|
|
91
|
+
configurable: true,
|
|
92
|
+
writable: true,
|
|
93
|
+
value: new Map()
|
|
94
|
+
});
|
|
95
|
+
Object.defineProperty(this, "subscribedPropertyDidSet", {
|
|
96
|
+
enumerable: true,
|
|
97
|
+
configurable: true,
|
|
98
|
+
writable: true,
|
|
99
|
+
value: new Set()
|
|
100
|
+
});
|
|
101
|
+
Object.defineProperty(this, "subscribedEventDidSet", {
|
|
102
|
+
enumerable: true,
|
|
103
|
+
configurable: true,
|
|
104
|
+
writable: true,
|
|
105
|
+
value: new Set()
|
|
106
|
+
});
|
|
107
|
+
Object.defineProperty(this, "deviceListChangedListenerSet", {
|
|
108
|
+
enumerable: true,
|
|
109
|
+
configurable: true,
|
|
110
|
+
writable: true,
|
|
111
|
+
value: new Set()
|
|
112
|
+
});
|
|
113
|
+
Object.defineProperty(this, "connectionStateListenerSet", {
|
|
114
|
+
enumerable: true,
|
|
115
|
+
configurable: true,
|
|
116
|
+
writable: true,
|
|
117
|
+
value: new Set()
|
|
118
|
+
});
|
|
119
|
+
Object.defineProperty(this, "propertyReadOperation", {
|
|
120
|
+
enumerable: true,
|
|
121
|
+
configurable: true,
|
|
122
|
+
writable: true,
|
|
123
|
+
value: Promise.resolve()
|
|
124
|
+
});
|
|
125
|
+
validateOptions(options);
|
|
126
|
+
}
|
|
127
|
+
get connected() {
|
|
128
|
+
return this.ready;
|
|
129
|
+
}
|
|
130
|
+
async connect() {
|
|
131
|
+
if (this.ready) {
|
|
132
|
+
return;
|
|
133
|
+
}
|
|
134
|
+
let connectPromise = this.connectPromise;
|
|
135
|
+
if (connectPromise === undefined) {
|
|
136
|
+
connectPromise = this.ensureConnected(this.operationGeneration);
|
|
137
|
+
this.connectPromise = connectPromise;
|
|
138
|
+
}
|
|
139
|
+
try {
|
|
140
|
+
await connectPromise;
|
|
141
|
+
}
|
|
142
|
+
finally {
|
|
143
|
+
if (this.connectPromise === connectPromise) {
|
|
144
|
+
this.connectPromise = undefined;
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
async disconnect() {
|
|
149
|
+
this.operationGeneration++;
|
|
150
|
+
this.stopReadyRetry();
|
|
151
|
+
const connectPromise = this.connectPromise;
|
|
152
|
+
if (connectPromise !== undefined) {
|
|
153
|
+
await connectPromise.catch(() => undefined);
|
|
154
|
+
}
|
|
155
|
+
this.stopReadyRetry();
|
|
156
|
+
const mqttClient = this.mqttClient;
|
|
157
|
+
this.mqttClient = undefined;
|
|
158
|
+
this.activeConnectionGeneration = undefined;
|
|
159
|
+
this.subscribedPropertyDidSet.clear();
|
|
160
|
+
this.subscribedEventDidSet.clear();
|
|
161
|
+
this.setReady(false);
|
|
162
|
+
this.rejectPendingRequests(new LocalMqttRequestInterruptedError('Local MQTT disconnected before a response was received.'));
|
|
163
|
+
if (mqttClient !== undefined) {
|
|
164
|
+
await mqttClient.endAsync(true);
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
addConnectionStateListener(listener) {
|
|
168
|
+
this.connectionStateListenerSet.add(listener);
|
|
169
|
+
return () => {
|
|
170
|
+
this.connectionStateListenerSet.delete(listener);
|
|
171
|
+
};
|
|
172
|
+
}
|
|
173
|
+
addDeviceListChangedListener(listener) {
|
|
174
|
+
this.deviceListChangedListenerSet.add(listener);
|
|
175
|
+
return () => {
|
|
176
|
+
this.deviceListChangedListenerSet.delete(listener);
|
|
177
|
+
};
|
|
178
|
+
}
|
|
179
|
+
async getDeviceList(timeoutMilliseconds = REQUEST_TIMEOUT_MILLISECONDS) {
|
|
180
|
+
const response = requireRecord(await this.request('proxy/getDevList', {}, timeoutMilliseconds), 'local device list response');
|
|
181
|
+
const deviceList = requireRecord(response.devList, 'local device list response.devList');
|
|
182
|
+
const result = new Map();
|
|
183
|
+
for (const [did, value] of Object.entries(deviceList)) {
|
|
184
|
+
validateDid(did);
|
|
185
|
+
const device = requireRecord(value, `local device list entry ${did}`);
|
|
186
|
+
result.set(did, {
|
|
187
|
+
online: readOptionalBoolean(device.online, 'online'),
|
|
188
|
+
specV2Access: readOptionalBoolean(device.specV2Access, 'specV2Access'),
|
|
189
|
+
pushAvailable: readOptionalBoolean(device.pushAvailable, 'pushAvailable'),
|
|
190
|
+
});
|
|
191
|
+
}
|
|
192
|
+
return result;
|
|
193
|
+
}
|
|
194
|
+
async getProperties(properties, timeoutMilliseconds = REQUEST_TIMEOUT_MILLISECONDS) {
|
|
195
|
+
const operation = this.propertyReadOperation.then(() => this.readProperties(properties, timeoutMilliseconds));
|
|
196
|
+
this.propertyReadOperation = operation.then(() => undefined, () => undefined);
|
|
197
|
+
return operation;
|
|
198
|
+
}
|
|
199
|
+
async readProperties(properties, timeoutMilliseconds) {
|
|
200
|
+
const results = [];
|
|
201
|
+
// The gateway can associate concurrent proxy/get replies incorrectly.
|
|
202
|
+
// Sending one request at a time also preserves duplicates and input order.
|
|
203
|
+
for (const property of properties) {
|
|
204
|
+
validateProperty(property);
|
|
205
|
+
const response = requireRecord(await this.request('proxy/get', property, timeoutMilliseconds), 'local property response');
|
|
206
|
+
if (Object.hasOwn(response, 'value')) {
|
|
207
|
+
results.push({ ...property, code: 0, value: response.value });
|
|
208
|
+
continue;
|
|
209
|
+
}
|
|
210
|
+
const code = readResponseErrorCode(response);
|
|
211
|
+
if (code === undefined) {
|
|
212
|
+
throw new LocalMqttProtocolError('Local property response has neither a value nor an error code.');
|
|
213
|
+
}
|
|
214
|
+
results.push({ ...property, code });
|
|
215
|
+
}
|
|
216
|
+
return results;
|
|
217
|
+
}
|
|
218
|
+
async executeRequest(request) {
|
|
219
|
+
const did = request instanceof MiotSetPropertyRequest
|
|
220
|
+
? request.property.did
|
|
221
|
+
: request.action.did;
|
|
222
|
+
const rpc = request instanceof MiotSetPropertyRequest
|
|
223
|
+
? createSetPropertiesRpc(request, this.allocateMessageId())
|
|
224
|
+
: createInvokeActionRpc(request, this.allocateMessageId());
|
|
225
|
+
const response = requireRecord(await this.request('proxy/rpcReq', {
|
|
226
|
+
did,
|
|
227
|
+
rpc,
|
|
228
|
+
}), 'local command response');
|
|
229
|
+
if (request instanceof MiotSetPropertyRequest &&
|
|
230
|
+
Array.isArray(response.result) &&
|
|
231
|
+
response.result.length === 1) {
|
|
232
|
+
const result = requireRecord(response.result[0], 'local command response.result[0]');
|
|
233
|
+
if (result.did !== request.property.did) {
|
|
234
|
+
throw new LocalMqttProtocolError('Local command response has an unexpected device ID.');
|
|
235
|
+
}
|
|
236
|
+
return { code: requireInteger(result.code, 'local command result code') };
|
|
237
|
+
}
|
|
238
|
+
else if (!(request instanceof MiotSetPropertyRequest) &&
|
|
239
|
+
response.result !== undefined) {
|
|
240
|
+
const result = requireRecord(response.result, 'local action response');
|
|
241
|
+
return { code: requireInteger(result.code, 'local action result code') };
|
|
242
|
+
}
|
|
243
|
+
const code = readResponseErrorCode(response);
|
|
244
|
+
if (code === undefined) {
|
|
245
|
+
throw new LocalMqttProtocolError('Local command response has no execution result.');
|
|
246
|
+
}
|
|
247
|
+
return { code };
|
|
248
|
+
}
|
|
249
|
+
async subscribeProperties(did, listener) {
|
|
250
|
+
validateDid(did);
|
|
251
|
+
let listenerSet = this.propertyListenerMap.get(did);
|
|
252
|
+
const firstListener = listenerSet === undefined;
|
|
253
|
+
if (listenerSet === undefined) {
|
|
254
|
+
listenerSet = new Set();
|
|
255
|
+
this.propertyListenerMap.set(did, listenerSet);
|
|
256
|
+
}
|
|
257
|
+
const listenerEntry = { listener };
|
|
258
|
+
listenerSet.add(listenerEntry);
|
|
259
|
+
try {
|
|
260
|
+
if (firstListener && this.ready) {
|
|
261
|
+
await this.subscribePropertyDid(did);
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
catch (error) {
|
|
265
|
+
listenerSet.delete(listenerEntry);
|
|
266
|
+
if (listenerSet.size === 0) {
|
|
267
|
+
this.propertyListenerMap.delete(did);
|
|
268
|
+
}
|
|
269
|
+
throw error;
|
|
270
|
+
}
|
|
271
|
+
let disposed = false;
|
|
272
|
+
return {
|
|
273
|
+
dispose: async () => {
|
|
274
|
+
if (disposed) {
|
|
275
|
+
return;
|
|
276
|
+
}
|
|
277
|
+
disposed = true;
|
|
278
|
+
await this.removePropertyListener(did, listenerEntry);
|
|
279
|
+
},
|
|
280
|
+
};
|
|
281
|
+
}
|
|
282
|
+
async subscribeEvents(did, listener) {
|
|
283
|
+
validateDid(did);
|
|
284
|
+
let listenerSet = this.eventListenerMap.get(did);
|
|
285
|
+
const firstListener = listenerSet === undefined;
|
|
286
|
+
if (listenerSet === undefined) {
|
|
287
|
+
listenerSet = new Set();
|
|
288
|
+
this.eventListenerMap.set(did, listenerSet);
|
|
289
|
+
}
|
|
290
|
+
const listenerEntry = { listener };
|
|
291
|
+
listenerSet.add(listenerEntry);
|
|
292
|
+
try {
|
|
293
|
+
if (firstListener && this.ready) {
|
|
294
|
+
await this.subscribeEventDid(did);
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
catch (error) {
|
|
298
|
+
listenerSet.delete(listenerEntry);
|
|
299
|
+
if (listenerSet.size === 0) {
|
|
300
|
+
this.eventListenerMap.delete(did);
|
|
301
|
+
}
|
|
302
|
+
throw error;
|
|
303
|
+
}
|
|
304
|
+
let disposed = false;
|
|
305
|
+
return {
|
|
306
|
+
dispose: async () => {
|
|
307
|
+
if (disposed) {
|
|
308
|
+
return;
|
|
309
|
+
}
|
|
310
|
+
disposed = true;
|
|
311
|
+
await this.removeEventListener(did, listenerEntry);
|
|
312
|
+
},
|
|
313
|
+
};
|
|
314
|
+
}
|
|
315
|
+
async ensureConnected(operationGeneration) {
|
|
316
|
+
let mqttClient = this.mqttClient;
|
|
317
|
+
if (mqttClient === undefined) {
|
|
318
|
+
mqttClient = await this.createConnection(operationGeneration);
|
|
319
|
+
}
|
|
320
|
+
this.assertOperationGeneration(operationGeneration);
|
|
321
|
+
await this.waitUntilConnected(mqttClient);
|
|
322
|
+
this.assertOperationGeneration(operationGeneration);
|
|
323
|
+
const generation = this.startConnectionSession(mqttClient);
|
|
324
|
+
try {
|
|
325
|
+
await this.markReady(mqttClient, generation);
|
|
326
|
+
}
|
|
327
|
+
catch (error) {
|
|
328
|
+
this.scheduleReadyRetry(mqttClient, generation);
|
|
329
|
+
throw error;
|
|
330
|
+
}
|
|
331
|
+
this.assertOperationGeneration(operationGeneration);
|
|
332
|
+
this.assertActiveConnectionSession(mqttClient, generation);
|
|
333
|
+
}
|
|
334
|
+
async createConnection(operationGeneration) {
|
|
335
|
+
var _a, _b;
|
|
336
|
+
const connector = (_a = this.options.connector) !== null && _a !== void 0 ? _a : defaultConnector;
|
|
337
|
+
const mqttClient = await connector(getBrokerUrl(this.options.host, (_b = this.options.port) !== null && _b !== void 0 ? _b : DEFAULT_PORT), createMqttOptions(this.options));
|
|
338
|
+
if (this.operationGeneration !== operationGeneration) {
|
|
339
|
+
await mqttClient.endAsync(true);
|
|
340
|
+
throw new Error('Local MQTT connection was cancelled.');
|
|
341
|
+
}
|
|
342
|
+
this.mqttClient = mqttClient;
|
|
343
|
+
mqttClient.on('connect', () => {
|
|
344
|
+
if (this.mqttClient !== mqttClient || !mqttClient.connected) {
|
|
345
|
+
return;
|
|
346
|
+
}
|
|
347
|
+
const generation = this.startConnectionSession(mqttClient);
|
|
348
|
+
void this.markReady(mqttClient, generation).catch(error => {
|
|
349
|
+
if (this.isActiveConnectionSession(mqttClient, generation)) {
|
|
350
|
+
console.error(error);
|
|
351
|
+
this.scheduleReadyRetry(mqttClient, generation);
|
|
352
|
+
}
|
|
353
|
+
});
|
|
354
|
+
});
|
|
355
|
+
mqttClient.on('message', (topic, payload) => {
|
|
356
|
+
this.handleMessage(topic, payload);
|
|
357
|
+
});
|
|
358
|
+
mqttClient.on('close', () => {
|
|
359
|
+
if (this.mqttClient !== mqttClient) {
|
|
360
|
+
return;
|
|
361
|
+
}
|
|
362
|
+
this.activeConnectionGeneration = undefined;
|
|
363
|
+
this.stopReadyRetry();
|
|
364
|
+
this.subscribedPropertyDidSet.clear();
|
|
365
|
+
this.subscribedEventDidSet.clear();
|
|
366
|
+
this.setReady(false);
|
|
367
|
+
this.rejectPendingRequests(new LocalMqttRequestInterruptedError('Local MQTT connection closed before a response was received.'));
|
|
368
|
+
});
|
|
369
|
+
mqttClient.on('error', error => {
|
|
370
|
+
if (this.mqttClient === mqttClient) {
|
|
371
|
+
console.error(error);
|
|
372
|
+
}
|
|
373
|
+
});
|
|
374
|
+
return mqttClient;
|
|
375
|
+
}
|
|
376
|
+
async markReady(mqttClient, generation) {
|
|
377
|
+
this.assertActiveConnectionSession(mqttClient, generation);
|
|
378
|
+
if (this.ready) {
|
|
379
|
+
return;
|
|
380
|
+
}
|
|
381
|
+
let readyOperation = this.readyOperation;
|
|
382
|
+
if (readyOperation === undefined ||
|
|
383
|
+
readyOperation.generation !== generation) {
|
|
384
|
+
readyOperation = {
|
|
385
|
+
generation,
|
|
386
|
+
promise: this.restoreSubscriptions(mqttClient, generation),
|
|
387
|
+
};
|
|
388
|
+
this.readyOperation = readyOperation;
|
|
389
|
+
}
|
|
390
|
+
try {
|
|
391
|
+
await readyOperation.promise;
|
|
392
|
+
this.assertActiveConnectionSession(mqttClient, generation);
|
|
393
|
+
this.setReady(true);
|
|
394
|
+
}
|
|
395
|
+
finally {
|
|
396
|
+
if (this.readyOperation === readyOperation) {
|
|
397
|
+
this.readyOperation = undefined;
|
|
398
|
+
}
|
|
399
|
+
}
|
|
400
|
+
}
|
|
401
|
+
scheduleReadyRetry(mqttClient, generation) {
|
|
402
|
+
if (this.readyRetryTimeout !== undefined ||
|
|
403
|
+
!this.isActiveConnectionSession(mqttClient, generation)) {
|
|
404
|
+
return;
|
|
405
|
+
}
|
|
406
|
+
const timeout = setTimeout(() => {
|
|
407
|
+
if (this.readyRetryTimeout === timeout) {
|
|
408
|
+
this.readyRetryTimeout = undefined;
|
|
409
|
+
}
|
|
410
|
+
if (!this.isActiveConnectionSession(mqttClient, generation)) {
|
|
411
|
+
return;
|
|
412
|
+
}
|
|
413
|
+
void this.markReady(mqttClient, generation).catch(error => {
|
|
414
|
+
if (this.isActiveConnectionSession(mqttClient, generation)) {
|
|
415
|
+
console.error(error);
|
|
416
|
+
this.scheduleReadyRetry(mqttClient, generation);
|
|
417
|
+
}
|
|
418
|
+
});
|
|
419
|
+
}, RECONNECT_INTERVAL_MILLISECONDS);
|
|
420
|
+
timeout.unref();
|
|
421
|
+
this.readyRetryTimeout = timeout;
|
|
422
|
+
}
|
|
423
|
+
stopReadyRetry() {
|
|
424
|
+
if (this.readyRetryTimeout === undefined) {
|
|
425
|
+
return;
|
|
426
|
+
}
|
|
427
|
+
clearTimeout(this.readyRetryTimeout);
|
|
428
|
+
this.readyRetryTimeout = undefined;
|
|
429
|
+
}
|
|
430
|
+
async restoreSubscriptions(mqttClient, generation) {
|
|
431
|
+
this.setReady(false);
|
|
432
|
+
this.subscribedPropertyDidSet.clear();
|
|
433
|
+
this.subscribedEventDidSet.clear();
|
|
434
|
+
await this.subscribeTopics([this.receiveTopic, 'master/appMsg/devListChange'], mqttClient, generation);
|
|
435
|
+
while (true) {
|
|
436
|
+
this.assertActiveConnectionSession(mqttClient, generation);
|
|
437
|
+
const dids = [...this.propertyListenerMap.keys()].filter(did => !this.subscribedPropertyDidSet.has(did));
|
|
438
|
+
const eventDids = [...this.eventListenerMap.keys()].filter(did => !this.subscribedEventDidSet.has(did));
|
|
439
|
+
if (dids.length === 0 && eventDids.length === 0) {
|
|
440
|
+
return;
|
|
441
|
+
}
|
|
442
|
+
await this.subscribeTopics([
|
|
443
|
+
...dids.map(getPropertyPublishTopic),
|
|
444
|
+
...eventDids.map(getEventPublishTopic),
|
|
445
|
+
], mqttClient, generation);
|
|
446
|
+
for (const did of dids) {
|
|
447
|
+
if (this.propertyListenerMap.has(did)) {
|
|
448
|
+
this.subscribedPropertyDidSet.add(did);
|
|
449
|
+
}
|
|
450
|
+
}
|
|
451
|
+
for (const did of eventDids) {
|
|
452
|
+
if (this.eventListenerMap.has(did)) {
|
|
453
|
+
this.subscribedEventDidSet.add(did);
|
|
454
|
+
}
|
|
455
|
+
}
|
|
456
|
+
}
|
|
457
|
+
}
|
|
458
|
+
async subscribePropertyDid(did) {
|
|
459
|
+
if (this.subscribedPropertyDidSet.has(did)) {
|
|
460
|
+
return;
|
|
461
|
+
}
|
|
462
|
+
const mqttClient = this.mqttClient;
|
|
463
|
+
const generation = this.activeConnectionGeneration;
|
|
464
|
+
if (mqttClient === undefined || generation === undefined) {
|
|
465
|
+
throw new MiotEndpointConnectionTransportUnavailableError('Local MQTT is not connected.');
|
|
466
|
+
}
|
|
467
|
+
await this.subscribeTopics([getPropertyPublishTopic(did)], mqttClient, generation);
|
|
468
|
+
this.subscribedPropertyDidSet.add(did);
|
|
469
|
+
}
|
|
470
|
+
async subscribeEventDid(did) {
|
|
471
|
+
if (this.subscribedEventDidSet.has(did)) {
|
|
472
|
+
return;
|
|
473
|
+
}
|
|
474
|
+
const mqttClient = this.mqttClient;
|
|
475
|
+
const generation = this.activeConnectionGeneration;
|
|
476
|
+
if (mqttClient === undefined || generation === undefined) {
|
|
477
|
+
throw new MiotEndpointConnectionTransportUnavailableError('Local MQTT is not connected.');
|
|
478
|
+
}
|
|
479
|
+
await this.subscribeTopics([getEventPublishTopic(did)], mqttClient, generation);
|
|
480
|
+
this.subscribedEventDidSet.add(did);
|
|
481
|
+
}
|
|
482
|
+
async subscribeTopics(topics, mqttClient, generation) {
|
|
483
|
+
if (topics.length === 0) {
|
|
484
|
+
return;
|
|
485
|
+
}
|
|
486
|
+
this.assertActiveConnectionSession(mqttClient, generation);
|
|
487
|
+
const grants = await mqttClient.subscribeAsync([...topics], {
|
|
488
|
+
qos: MQTT_QOS,
|
|
489
|
+
});
|
|
490
|
+
this.assertActiveConnectionSession(mqttClient, generation);
|
|
491
|
+
const grantedQosMap = new Map(grants.map(grant => [grant.topic, grant.qos]));
|
|
492
|
+
for (const topic of topics) {
|
|
493
|
+
if (grantedQosMap.get(topic) !== MQTT_QOS) {
|
|
494
|
+
throw new Error(`Local MQTT QoS 2 subscription was rejected: ${topic}.`);
|
|
495
|
+
}
|
|
496
|
+
}
|
|
497
|
+
}
|
|
498
|
+
async removePropertyListener(did, listenerEntry) {
|
|
499
|
+
const listenerSet = this.propertyListenerMap.get(did);
|
|
500
|
+
if (listenerSet === undefined) {
|
|
501
|
+
return;
|
|
502
|
+
}
|
|
503
|
+
listenerSet.delete(listenerEntry);
|
|
504
|
+
if (listenerSet.size > 0) {
|
|
505
|
+
return;
|
|
506
|
+
}
|
|
507
|
+
this.propertyListenerMap.delete(did);
|
|
508
|
+
if (!this.subscribedPropertyDidSet.delete(did)) {
|
|
509
|
+
return;
|
|
510
|
+
}
|
|
511
|
+
const mqttClient = this.mqttClient;
|
|
512
|
+
if (mqttClient === undefined || !mqttClient.connected) {
|
|
513
|
+
return;
|
|
514
|
+
}
|
|
515
|
+
await mqttClient.unsubscribeAsync(getPropertyPublishTopic(did));
|
|
516
|
+
}
|
|
517
|
+
async removeEventListener(did, listenerEntry) {
|
|
518
|
+
const listenerSet = this.eventListenerMap.get(did);
|
|
519
|
+
if (listenerSet === undefined) {
|
|
520
|
+
return;
|
|
521
|
+
}
|
|
522
|
+
listenerSet.delete(listenerEntry);
|
|
523
|
+
if (listenerSet.size > 0) {
|
|
524
|
+
return;
|
|
525
|
+
}
|
|
526
|
+
this.eventListenerMap.delete(did);
|
|
527
|
+
if (!this.subscribedEventDidSet.delete(did)) {
|
|
528
|
+
return;
|
|
529
|
+
}
|
|
530
|
+
const mqttClient = this.mqttClient;
|
|
531
|
+
if (mqttClient === undefined || !mqttClient.connected) {
|
|
532
|
+
return;
|
|
533
|
+
}
|
|
534
|
+
await mqttClient.unsubscribeAsync(getEventPublishTopic(did));
|
|
535
|
+
}
|
|
536
|
+
request(operation, body, timeoutMilliseconds = REQUEST_TIMEOUT_MILLISECONDS) {
|
|
537
|
+
validateTimeout(timeoutMilliseconds);
|
|
538
|
+
const mqttClient = this.mqttClient;
|
|
539
|
+
if (mqttClient === undefined || !mqttClient.connected || !this.ready) {
|
|
540
|
+
throw new MiotEndpointConnectionTransportUnavailableError('Local MQTT is not connected.');
|
|
541
|
+
}
|
|
542
|
+
const id = this.allocateMessageId();
|
|
543
|
+
const pending = createPendingRequest(id, operation, timeoutMilliseconds, error => {
|
|
544
|
+
this.rejectPendingRequest(id, error);
|
|
545
|
+
});
|
|
546
|
+
this.pendingRequestMap.set(id, pending);
|
|
547
|
+
const payload = encodeMipsMessage({
|
|
548
|
+
id,
|
|
549
|
+
from: 'local',
|
|
550
|
+
returnTopic: this.replyTopic,
|
|
551
|
+
payload: JSON.stringify(body),
|
|
552
|
+
});
|
|
553
|
+
let publishPromise;
|
|
554
|
+
try {
|
|
555
|
+
publishPromise = mqttClient.publishAsync(`master/${operation}`, payload, {
|
|
556
|
+
qos: MQTT_QOS,
|
|
557
|
+
});
|
|
558
|
+
}
|
|
559
|
+
catch (error) {
|
|
560
|
+
this.rejectPendingRequest(id, new LocalMqttRequestInterruptedError('Local MQTT failed after command publication began.', { cause: error }));
|
|
561
|
+
return pending.promise;
|
|
562
|
+
}
|
|
563
|
+
void publishPromise.catch(error => {
|
|
564
|
+
this.rejectPendingRequest(id, new LocalMqttRequestInterruptedError('Local MQTT failed after command publication began.', { cause: error }));
|
|
565
|
+
});
|
|
566
|
+
return pending.promise;
|
|
567
|
+
}
|
|
568
|
+
handleMessage(topic, payload) {
|
|
569
|
+
try {
|
|
570
|
+
const message = decodeMipsMessage(payload);
|
|
571
|
+
if (topic === this.replyTopic) {
|
|
572
|
+
if (message.payload === undefined) {
|
|
573
|
+
this.rejectPendingRequest(message.id, new LocalMqttProtocolError('Local MQTT response has no JSON payload.'));
|
|
574
|
+
return;
|
|
575
|
+
}
|
|
576
|
+
let value;
|
|
577
|
+
try {
|
|
578
|
+
value = JSON.parse(message.payload);
|
|
579
|
+
}
|
|
580
|
+
catch (error) {
|
|
581
|
+
this.rejectPendingRequest(message.id, new LocalMqttProtocolError('Local MQTT response is not valid JSON.', { cause: error }));
|
|
582
|
+
return;
|
|
583
|
+
}
|
|
584
|
+
this.resolvePendingRequest(message.id, value);
|
|
585
|
+
return;
|
|
586
|
+
}
|
|
587
|
+
if (topic === `${this.options.virtualDid}/appMsg/devListChange`) {
|
|
588
|
+
this.handleDeviceListChangedMessage(message.payload);
|
|
589
|
+
return;
|
|
590
|
+
}
|
|
591
|
+
this.handleNotificationMessage(topic, message.payload);
|
|
592
|
+
}
|
|
593
|
+
catch (error) {
|
|
594
|
+
console.error(error);
|
|
595
|
+
}
|
|
596
|
+
}
|
|
597
|
+
handleDeviceListChangedMessage(payload) {
|
|
598
|
+
const message = requireRecord(parseJsonPayload(payload, 'local device list change'), 'local device list change');
|
|
599
|
+
if (!Array.isArray(message.devList)) {
|
|
600
|
+
throw new LocalMqttProtocolError('Local device list change has an invalid devList.');
|
|
601
|
+
}
|
|
602
|
+
const dids = message.devList.map((value, index) => {
|
|
603
|
+
if (typeof value !== 'string') {
|
|
604
|
+
throw new LocalMqttProtocolError(`Local device list change devList[${index}] is not a string.`);
|
|
605
|
+
}
|
|
606
|
+
validateDid(value);
|
|
607
|
+
return value;
|
|
608
|
+
});
|
|
609
|
+
for (const listener of this.deviceListChangedListenerSet) {
|
|
610
|
+
try {
|
|
611
|
+
listener(dids);
|
|
612
|
+
}
|
|
613
|
+
catch (error) {
|
|
614
|
+
console.error(error);
|
|
615
|
+
}
|
|
616
|
+
}
|
|
617
|
+
}
|
|
618
|
+
handleNotificationMessage(topic, payload) {
|
|
619
|
+
const prefix = `${this.options.virtualDid}/appMsg/notify/iot/`;
|
|
620
|
+
if (!topic.startsWith(prefix)) {
|
|
621
|
+
return;
|
|
622
|
+
}
|
|
623
|
+
const parts = topic.slice(prefix.length).split('/');
|
|
624
|
+
if (parts.length !== 3) {
|
|
625
|
+
return;
|
|
626
|
+
}
|
|
627
|
+
const did = parts[0];
|
|
628
|
+
const kind = parts[1];
|
|
629
|
+
const instance = parts[2];
|
|
630
|
+
if (did === undefined || kind === undefined || instance === undefined) {
|
|
631
|
+
return;
|
|
632
|
+
}
|
|
633
|
+
if (kind === 'property') {
|
|
634
|
+
this.handlePropertyNotification(did, instance, payload);
|
|
635
|
+
}
|
|
636
|
+
else if (kind === 'event') {
|
|
637
|
+
this.handleEventNotification(did, instance, payload);
|
|
638
|
+
}
|
|
639
|
+
}
|
|
640
|
+
handlePropertyNotification(did, instance, payload) {
|
|
641
|
+
const message = requireRecord(parseJsonPayload(payload, 'local property notification'), 'local property notification');
|
|
642
|
+
const messageDid = requireString(message.did, 'local property notification DID');
|
|
643
|
+
const notificationInstance = resolveNotificationInstance(instance, message.siid, message.piid, 'local property notification');
|
|
644
|
+
if (notificationInstance === undefined) {
|
|
645
|
+
return;
|
|
646
|
+
}
|
|
647
|
+
const [siid, piid] = notificationInstance;
|
|
648
|
+
if (messageDid !== did) {
|
|
649
|
+
throw new LocalMqttProtocolError('Local property notification does not match its topic.');
|
|
650
|
+
}
|
|
651
|
+
if (!Object.hasOwn(message, 'value')) {
|
|
652
|
+
throw new LocalMqttProtocolError('Local property notification has no value.');
|
|
653
|
+
}
|
|
654
|
+
const listeners = this.propertyListenerMap.get(did);
|
|
655
|
+
if (listeners === undefined) {
|
|
656
|
+
return;
|
|
657
|
+
}
|
|
658
|
+
const update = {
|
|
659
|
+
did,
|
|
660
|
+
siid,
|
|
661
|
+
piid,
|
|
662
|
+
value: message.value,
|
|
663
|
+
};
|
|
664
|
+
for (const { listener } of listeners) {
|
|
665
|
+
try {
|
|
666
|
+
listener(update);
|
|
667
|
+
}
|
|
668
|
+
catch (error) {
|
|
669
|
+
console.error(error);
|
|
670
|
+
}
|
|
671
|
+
}
|
|
672
|
+
}
|
|
673
|
+
handleEventNotification(did, instance, payload) {
|
|
674
|
+
var _a;
|
|
675
|
+
const message = requireRecord(parseJsonPayload(payload, 'local event notification'), 'local event notification');
|
|
676
|
+
const messageDid = requireString(message.did, 'local event notification DID');
|
|
677
|
+
const notificationInstance = resolveNotificationInstance(instance, message.siid, message.eiid, 'local event notification');
|
|
678
|
+
if (notificationInstance === undefined) {
|
|
679
|
+
return;
|
|
680
|
+
}
|
|
681
|
+
const [siid, eiid] = notificationInstance;
|
|
682
|
+
if (messageDid !== did) {
|
|
683
|
+
throw new LocalMqttProtocolError('Local event notification does not match its topic.');
|
|
684
|
+
}
|
|
685
|
+
const eventArguments = (_a = message.arguments) !== null && _a !== void 0 ? _a : [];
|
|
686
|
+
if (!Array.isArray(eventArguments)) {
|
|
687
|
+
throw new LocalMqttProtocolError('Local event notification has invalid arguments.');
|
|
688
|
+
}
|
|
689
|
+
const listeners = this.eventListenerMap.get(did);
|
|
690
|
+
if (listeners === undefined) {
|
|
691
|
+
return;
|
|
692
|
+
}
|
|
693
|
+
const update = {
|
|
694
|
+
did,
|
|
695
|
+
siid,
|
|
696
|
+
eiid,
|
|
697
|
+
arguments: eventArguments,
|
|
698
|
+
};
|
|
699
|
+
for (const { listener } of listeners) {
|
|
700
|
+
try {
|
|
701
|
+
listener(update);
|
|
702
|
+
}
|
|
703
|
+
catch (error) {
|
|
704
|
+
console.error(error);
|
|
705
|
+
}
|
|
706
|
+
}
|
|
707
|
+
}
|
|
708
|
+
resolvePendingRequest(id, value) {
|
|
709
|
+
const pending = this.pendingRequestMap.get(id);
|
|
710
|
+
if (pending === undefined) {
|
|
711
|
+
return;
|
|
712
|
+
}
|
|
713
|
+
this.pendingRequestMap.delete(id);
|
|
714
|
+
clearTimeout(pending.timeout);
|
|
715
|
+
pending.resolve(value);
|
|
716
|
+
}
|
|
717
|
+
rejectPendingRequest(id, error) {
|
|
718
|
+
const pending = this.pendingRequestMap.get(id);
|
|
719
|
+
if (pending === undefined) {
|
|
720
|
+
return;
|
|
721
|
+
}
|
|
722
|
+
this.pendingRequestMap.delete(id);
|
|
723
|
+
clearTimeout(pending.timeout);
|
|
724
|
+
pending.reject(error);
|
|
725
|
+
}
|
|
726
|
+
rejectPendingRequests(error) {
|
|
727
|
+
for (const id of [...this.pendingRequestMap.keys()]) {
|
|
728
|
+
this.rejectPendingRequest(id, error);
|
|
729
|
+
}
|
|
730
|
+
}
|
|
731
|
+
allocateMessageId() {
|
|
732
|
+
const initialId = this.nextMessageId;
|
|
733
|
+
while (this.pendingRequestMap.has(this.nextMessageId)) {
|
|
734
|
+
this.nextMessageId = (this.nextMessageId + 1) % UINT32_RANGE;
|
|
735
|
+
if (this.nextMessageId === initialId) {
|
|
736
|
+
throw new Error('Local MQTT message ID space is exhausted.');
|
|
737
|
+
}
|
|
738
|
+
}
|
|
739
|
+
const id = this.nextMessageId;
|
|
740
|
+
this.nextMessageId = (this.nextMessageId + 1) % UINT32_RANGE;
|
|
741
|
+
return id;
|
|
742
|
+
}
|
|
743
|
+
startConnectionSession(mqttClient) {
|
|
744
|
+
if (this.mqttClient !== mqttClient || !mqttClient.connected) {
|
|
745
|
+
throw new Error('Local MQTT is not connected.');
|
|
746
|
+
}
|
|
747
|
+
let generation = this.activeConnectionGeneration;
|
|
748
|
+
if (generation === undefined) {
|
|
749
|
+
generation = ++this.nextConnectionGeneration;
|
|
750
|
+
this.activeConnectionGeneration = generation;
|
|
751
|
+
}
|
|
752
|
+
return generation;
|
|
753
|
+
}
|
|
754
|
+
isActiveConnectionSession(mqttClient, generation) {
|
|
755
|
+
return (this.mqttClient === mqttClient &&
|
|
756
|
+
this.activeConnectionGeneration === generation &&
|
|
757
|
+
mqttClient.connected);
|
|
758
|
+
}
|
|
759
|
+
assertActiveConnectionSession(mqttClient, generation) {
|
|
760
|
+
if (!this.isActiveConnectionSession(mqttClient, generation)) {
|
|
761
|
+
throw new Error('Local MQTT disconnected while subscribing.');
|
|
762
|
+
}
|
|
763
|
+
}
|
|
764
|
+
assertOperationGeneration(generation) {
|
|
765
|
+
if (this.operationGeneration !== generation) {
|
|
766
|
+
throw new Error('Local MQTT connection operation was cancelled.');
|
|
767
|
+
}
|
|
768
|
+
}
|
|
769
|
+
waitUntilConnected(mqttClient) {
|
|
770
|
+
if (mqttClient.connected) {
|
|
771
|
+
return Promise.resolve();
|
|
772
|
+
}
|
|
773
|
+
return new Promise((resolve, reject) => {
|
|
774
|
+
const timeout = setTimeout(() => {
|
|
775
|
+
cleanup();
|
|
776
|
+
reject(new Error('Local MQTT connection timed out.'));
|
|
777
|
+
}, CONNECT_TIMEOUT_MILLISECONDS);
|
|
778
|
+
const onConnect = () => {
|
|
779
|
+
cleanup();
|
|
780
|
+
resolve();
|
|
781
|
+
};
|
|
782
|
+
const cleanup = () => {
|
|
783
|
+
clearTimeout(timeout);
|
|
784
|
+
mqttClient.off('connect', onConnect);
|
|
785
|
+
};
|
|
786
|
+
mqttClient.on('connect', onConnect);
|
|
787
|
+
});
|
|
788
|
+
}
|
|
789
|
+
setReady(ready) {
|
|
790
|
+
if (this.ready === ready) {
|
|
791
|
+
return;
|
|
792
|
+
}
|
|
793
|
+
this.ready = ready;
|
|
794
|
+
if (ready) {
|
|
795
|
+
this.stopReadyRetry();
|
|
796
|
+
}
|
|
797
|
+
for (const listener of this.connectionStateListenerSet) {
|
|
798
|
+
try {
|
|
799
|
+
listener(ready);
|
|
800
|
+
}
|
|
801
|
+
catch (error) {
|
|
802
|
+
console.error(error);
|
|
803
|
+
}
|
|
804
|
+
}
|
|
805
|
+
}
|
|
806
|
+
get receiveTopic() {
|
|
807
|
+
return `${this.options.virtualDid}/#`;
|
|
808
|
+
}
|
|
809
|
+
get replyTopic() {
|
|
810
|
+
return `${this.options.virtualDid}/reply`;
|
|
811
|
+
}
|
|
812
|
+
}
|
|
813
|
+
export class LocalMqttProtocolError extends Error {
|
|
814
|
+
constructor() {
|
|
815
|
+
super(...arguments);
|
|
816
|
+
Object.defineProperty(this, "name", {
|
|
817
|
+
enumerable: true,
|
|
818
|
+
configurable: true,
|
|
819
|
+
writable: true,
|
|
820
|
+
value: 'LocalMqttProtocolError'
|
|
821
|
+
});
|
|
822
|
+
}
|
|
823
|
+
}
|
|
824
|
+
export class LocalMqttRequestTimeoutError extends Error {
|
|
825
|
+
constructor() {
|
|
826
|
+
super(...arguments);
|
|
827
|
+
Object.defineProperty(this, "name", {
|
|
828
|
+
enumerable: true,
|
|
829
|
+
configurable: true,
|
|
830
|
+
writable: true,
|
|
831
|
+
value: 'LocalMqttRequestTimeoutError'
|
|
832
|
+
});
|
|
833
|
+
}
|
|
834
|
+
}
|
|
835
|
+
export class LocalMqttRequestInterruptedError extends Error {
|
|
836
|
+
constructor() {
|
|
837
|
+
super(...arguments);
|
|
838
|
+
Object.defineProperty(this, "name", {
|
|
839
|
+
enumerable: true,
|
|
840
|
+
configurable: true,
|
|
841
|
+
writable: true,
|
|
842
|
+
value: 'LocalMqttRequestInterruptedError'
|
|
843
|
+
});
|
|
844
|
+
}
|
|
845
|
+
}
|
|
846
|
+
function createMqttOptions(options) {
|
|
847
|
+
const mqttOptions = {
|
|
848
|
+
clientId: options.virtualDid,
|
|
849
|
+
protocolVersion: 5,
|
|
850
|
+
clean: true,
|
|
851
|
+
keepalive: KEEPALIVE_SECONDS,
|
|
852
|
+
reconnectPeriod: RECONNECT_INTERVAL_MILLISECONDS,
|
|
853
|
+
connectTimeout: CONNECT_TIMEOUT_MILLISECONDS,
|
|
854
|
+
resubscribe: false,
|
|
855
|
+
// Gateways are addressed by their discovered IP, so replace generic host
|
|
856
|
+
// name matching with the expected MIPS service identity for this DID.
|
|
857
|
+
rejectUnauthorized: true,
|
|
858
|
+
checkServerIdentity: (_hostname, certificate) => {
|
|
859
|
+
try {
|
|
860
|
+
if (certificate.raw !== undefined &&
|
|
861
|
+
isMipsGatewayCertificate(new X509Certificate(certificate.raw), options.gatewayDid)) {
|
|
862
|
+
return undefined;
|
|
863
|
+
}
|
|
864
|
+
}
|
|
865
|
+
catch (_a) {
|
|
866
|
+
// Return the fixed identity error below.
|
|
867
|
+
}
|
|
868
|
+
return new Error('Local MQTT gateway certificate identity is invalid.');
|
|
869
|
+
},
|
|
870
|
+
ca: options.ca,
|
|
871
|
+
cert: options.cert,
|
|
872
|
+
key: options.key,
|
|
873
|
+
};
|
|
874
|
+
return mqttOptions;
|
|
875
|
+
}
|
|
876
|
+
function defaultConnector(url, options) {
|
|
877
|
+
return connectAsync(url, options, false);
|
|
878
|
+
}
|
|
879
|
+
function createPendingRequest(id, operation, timeoutMilliseconds, onTimeout) {
|
|
880
|
+
let resolvePromise = () => undefined;
|
|
881
|
+
let rejectPromise = () => undefined;
|
|
882
|
+
const promise = new Promise((resolve, reject) => {
|
|
883
|
+
resolvePromise = resolve;
|
|
884
|
+
rejectPromise = reject;
|
|
885
|
+
});
|
|
886
|
+
// A response timeout may occur while the QoS 2 publish handshake is still
|
|
887
|
+
// pending, so attach a handler immediately and let the caller await it.
|
|
888
|
+
void promise.catch(() => undefined);
|
|
889
|
+
const timeout = setTimeout(() => {
|
|
890
|
+
onTimeout(new LocalMqttRequestTimeoutError(`Local MQTT ${operation} request ${id} timed out after publication began.`));
|
|
891
|
+
}, timeoutMilliseconds);
|
|
892
|
+
return {
|
|
893
|
+
promise,
|
|
894
|
+
resolve: resolvePromise,
|
|
895
|
+
reject: rejectPromise,
|
|
896
|
+
timeout,
|
|
897
|
+
};
|
|
898
|
+
}
|
|
899
|
+
function getBrokerUrl(host, port) {
|
|
900
|
+
const formattedHost = host.includes(':') && !host.startsWith('[') ? `[${host}]` : host;
|
|
901
|
+
return `mqtts://${formattedHost}:${port}`;
|
|
902
|
+
}
|
|
903
|
+
function getPropertyPublishTopic(did) {
|
|
904
|
+
return `master/appMsg/notify/iot/${did}/property/#`;
|
|
905
|
+
}
|
|
906
|
+
function getEventPublishTopic(did) {
|
|
907
|
+
return `master/appMsg/notify/iot/${did}/event/#`;
|
|
908
|
+
}
|
|
909
|
+
function validateOptions(options) {
|
|
910
|
+
var _a;
|
|
911
|
+
validateDid(options.virtualDid);
|
|
912
|
+
validateDecimalDid(options.gatewayDid, 'gateway');
|
|
913
|
+
if (options.host === '' ||
|
|
914
|
+
/[\s/?#@]/u.test(options.host) ||
|
|
915
|
+
options.host.includes('\0') ||
|
|
916
|
+
((options.host.includes('[') || options.host.includes(']')) &&
|
|
917
|
+
!/^\[[\da-f:.]+\]$/iu.test(options.host))) {
|
|
918
|
+
throw new TypeError('Invalid local MQTT host.');
|
|
919
|
+
}
|
|
920
|
+
const port = (_a = options.port) !== null && _a !== void 0 ? _a : DEFAULT_PORT;
|
|
921
|
+
if (!Number.isInteger(port) || port < 1 || port > 65535) {
|
|
922
|
+
throw new TypeError('Invalid local MQTT port.');
|
|
923
|
+
}
|
|
924
|
+
}
|
|
925
|
+
function validateDecimalDid(did, name) {
|
|
926
|
+
if (!/^(?:0|[1-9]\d*)$/u.test(did)) {
|
|
927
|
+
throw new TypeError(`Invalid local MQTT ${name} DID.`);
|
|
928
|
+
}
|
|
929
|
+
}
|
|
930
|
+
function validateDid(did) {
|
|
931
|
+
if (did === '' ||
|
|
932
|
+
did.includes('/') ||
|
|
933
|
+
did.includes('#') ||
|
|
934
|
+
did.includes('+') ||
|
|
935
|
+
did.includes('\0')) {
|
|
936
|
+
throw new TypeError(`Invalid local MQTT device ID: ${did}.`);
|
|
937
|
+
}
|
|
938
|
+
}
|
|
939
|
+
function validateProperty(property) {
|
|
940
|
+
validateDid(property.did);
|
|
941
|
+
requirePositiveInteger(property.siid, 'MIoT property SIID');
|
|
942
|
+
requirePositiveInteger(property.piid, 'MIoT property PIID');
|
|
943
|
+
}
|
|
944
|
+
function createSetPropertiesRpc(request, id) {
|
|
945
|
+
validateProperty(request.property);
|
|
946
|
+
return {
|
|
947
|
+
id,
|
|
948
|
+
method: 'set_properties',
|
|
949
|
+
params: [{ ...request.property, value: request.value }],
|
|
950
|
+
};
|
|
951
|
+
}
|
|
952
|
+
function createInvokeActionRpc(request, id) {
|
|
953
|
+
const { did, siid, aiid } = request.action;
|
|
954
|
+
validateDid(did);
|
|
955
|
+
requirePositiveInteger(siid, 'MIoT action SIID');
|
|
956
|
+
requirePositiveInteger(aiid, 'MIoT action AIID');
|
|
957
|
+
for (const input of request.inputs) {
|
|
958
|
+
requirePositiveInteger(input.piid, 'MIoT action input PIID');
|
|
959
|
+
}
|
|
960
|
+
return {
|
|
961
|
+
id,
|
|
962
|
+
method: 'action',
|
|
963
|
+
params: { did, siid, aiid, in: request.inputs },
|
|
964
|
+
};
|
|
965
|
+
}
|
|
966
|
+
function validateTimeout(timeoutMilliseconds) {
|
|
967
|
+
if (!Number.isFinite(timeoutMilliseconds) || timeoutMilliseconds <= 0) {
|
|
968
|
+
throw new TypeError('Invalid local MQTT request timeout.');
|
|
969
|
+
}
|
|
970
|
+
}
|
|
971
|
+
function parseJsonPayload(payload, name) {
|
|
972
|
+
if (payload === undefined) {
|
|
973
|
+
throw new LocalMqttProtocolError(`${name} has no JSON payload.`);
|
|
974
|
+
}
|
|
975
|
+
try {
|
|
976
|
+
return JSON.parse(payload);
|
|
977
|
+
}
|
|
978
|
+
catch (error) {
|
|
979
|
+
throw new LocalMqttProtocolError(`${name} is not valid JSON.`, {
|
|
980
|
+
cause: error,
|
|
981
|
+
});
|
|
982
|
+
}
|
|
983
|
+
}
|
|
984
|
+
function requireRecord(value, name) {
|
|
985
|
+
if (typeof value !== 'object' || value === null || Array.isArray(value)) {
|
|
986
|
+
throw new LocalMqttProtocolError(`${name} is not an object.`);
|
|
987
|
+
}
|
|
988
|
+
return value;
|
|
989
|
+
}
|
|
990
|
+
function requireInteger(value, name) {
|
|
991
|
+
if (typeof value !== 'number' || !Number.isInteger(value)) {
|
|
992
|
+
throw new LocalMqttProtocolError(`${name} is not an integer.`);
|
|
993
|
+
}
|
|
994
|
+
return value;
|
|
995
|
+
}
|
|
996
|
+
function requirePositiveInteger(value, name) {
|
|
997
|
+
const integer = requireInteger(value, name);
|
|
998
|
+
if (integer <= 0) {
|
|
999
|
+
throw new LocalMqttProtocolError(`${name} is not positive.`);
|
|
1000
|
+
}
|
|
1001
|
+
return integer;
|
|
1002
|
+
}
|
|
1003
|
+
function readNotificationIdentifier(value) {
|
|
1004
|
+
// Some central-gateway firmware serializes notification IIDs as decimal
|
|
1005
|
+
// JSON strings even though request/response IIDs are numbers.
|
|
1006
|
+
if (typeof value === 'number') {
|
|
1007
|
+
if (Number.isSafeInteger(value) && value > 0) {
|
|
1008
|
+
return value;
|
|
1009
|
+
}
|
|
1010
|
+
}
|
|
1011
|
+
else if (typeof value === 'string' && /^[1-9]\d*$/u.test(value)) {
|
|
1012
|
+
const integer = Number(value);
|
|
1013
|
+
if (Number.isSafeInteger(integer)) {
|
|
1014
|
+
return integer;
|
|
1015
|
+
}
|
|
1016
|
+
}
|
|
1017
|
+
return undefined;
|
|
1018
|
+
}
|
|
1019
|
+
function readNotificationTopicInstance(instance) {
|
|
1020
|
+
const match = /^([1-9]\d*)\.([1-9]\d*)$/u.exec(instance);
|
|
1021
|
+
if (match === null) {
|
|
1022
|
+
return undefined;
|
|
1023
|
+
}
|
|
1024
|
+
const first = readNotificationIdentifier(match[1]);
|
|
1025
|
+
const second = readNotificationIdentifier(match[2]);
|
|
1026
|
+
return first === undefined || second === undefined
|
|
1027
|
+
? undefined
|
|
1028
|
+
: [first, second];
|
|
1029
|
+
}
|
|
1030
|
+
function resolveNotificationInstance(topicInstance, firstValue, secondValue, name) {
|
|
1031
|
+
const topic = readNotificationTopicInstance(topicInstance);
|
|
1032
|
+
const first = readNotificationIdentifier(firstValue);
|
|
1033
|
+
const second = readNotificationIdentifier(secondValue);
|
|
1034
|
+
if (topic === undefined) {
|
|
1035
|
+
return first === undefined || second === undefined
|
|
1036
|
+
? undefined
|
|
1037
|
+
: [first, second];
|
|
1038
|
+
}
|
|
1039
|
+
if ((firstValue !== undefined && first === undefined) ||
|
|
1040
|
+
(secondValue !== undefined && second === undefined)) {
|
|
1041
|
+
return undefined;
|
|
1042
|
+
}
|
|
1043
|
+
if ((first !== undefined && first !== topic[0]) ||
|
|
1044
|
+
(second !== undefined && second !== topic[1])) {
|
|
1045
|
+
throw new LocalMqttProtocolError(`${name} does not match its topic.`);
|
|
1046
|
+
}
|
|
1047
|
+
return topic;
|
|
1048
|
+
}
|
|
1049
|
+
function requireString(value, name) {
|
|
1050
|
+
if (typeof value !== 'string') {
|
|
1051
|
+
throw new LocalMqttProtocolError(`${name} is not a string.`);
|
|
1052
|
+
}
|
|
1053
|
+
return value;
|
|
1054
|
+
}
|
|
1055
|
+
function readOptionalBoolean(value, name) {
|
|
1056
|
+
if (value === undefined) {
|
|
1057
|
+
return false;
|
|
1058
|
+
}
|
|
1059
|
+
if (typeof value !== 'boolean') {
|
|
1060
|
+
throw new LocalMqttProtocolError(`Local device list ${name} is not a boolean.`);
|
|
1061
|
+
}
|
|
1062
|
+
return value;
|
|
1063
|
+
}
|
|
1064
|
+
function readResponseErrorCode(response) {
|
|
1065
|
+
if (typeof response.code === 'number' && Number.isInteger(response.code)) {
|
|
1066
|
+
return response.code;
|
|
1067
|
+
}
|
|
1068
|
+
if (response.error === undefined) {
|
|
1069
|
+
return undefined;
|
|
1070
|
+
}
|
|
1071
|
+
const error = requireRecord(response.error, 'local response error');
|
|
1072
|
+
return requireInteger(error.code, 'local response error code');
|
|
1073
|
+
}
|
|
1074
|
+
//# sourceMappingURL=mqtt.js.map
|