@improv-wifi/serial-sdk 0.0.0-stage → 3.0.0
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 +201 -0
- package/README.md +114 -2
- package/dist/const.d.ts +56 -0
- package/dist/const.js +37 -0
- package/dist/provision.d.ts +2 -0
- package/dist/provision.js +26 -0
- package/dist/serial-launch-button.d.ts +7 -0
- package/dist/serial-launch-button.js +79 -0
- package/dist/serial-provision-dialog.d.ts +53 -0
- package/dist/serial-provision-dialog.js +691 -0
- package/dist/serial.d.ts +143 -0
- package/dist/serial.js +626 -0
- package/dist/util/fire-event.d.ts +5 -0
- package/dist/util/fire-event.js +12 -0
- package/dist/util/hex-formatter.d.ts +1 -0
- package/dist/util/hex-formatter.js +2 -0
- package/dist/util/to-hex.d.ts +1 -0
- package/dist/util/to-hex.js +9 -0
- package/dist/web/serial-launch-button.js +1 -0
- package/dist/web/serial-provision-dialog-DR-raZEr.js +803 -0
- package/package.json +41 -4
package/dist/serial.js
ADDED
|
@@ -0,0 +1,626 @@
|
|
|
1
|
+
import { ERROR_MSGS, ImprovSerialCurrentState, ImprovSerialMessageType, PortNotReady, SERIAL_PACKET_HEADER, } from "./const.js";
|
|
2
|
+
import { hexFormatter } from "./util/hex-formatter";
|
|
3
|
+
const sortSsids = (ssids) => ssids.sort((a, b) => a.name.toLocaleLowerCase().localeCompare(b.name.toLocaleLowerCase()));
|
|
4
|
+
/** Merge two scans, keyed by name (newest values win), sorted alphabetically. */
|
|
5
|
+
const mergeSsids = (previous, latest) => {
|
|
6
|
+
const byName = new Map();
|
|
7
|
+
for (const ssid of previous) {
|
|
8
|
+
byName.set(ssid.name, ssid);
|
|
9
|
+
}
|
|
10
|
+
for (const ssid of latest) {
|
|
11
|
+
byName.set(ssid.name, ssid);
|
|
12
|
+
}
|
|
13
|
+
return sortSsids(Array.from(byName.values()));
|
|
14
|
+
};
|
|
15
|
+
/** Delay between Wi-Fi scans while subscribed. */
|
|
16
|
+
const SCAN_INTERVAL = 3000;
|
|
17
|
+
/** Delay between network state polls. */
|
|
18
|
+
const NETWORK_STATE_POLL_INTERVAL = 2500;
|
|
19
|
+
/** Per-poll timeout; small so a busy device only costs a tick — the next poll recovers. */
|
|
20
|
+
const NETWORK_STATE_POLL_TIMEOUT = 500;
|
|
21
|
+
/**
|
|
22
|
+
* Timeout for each scan while subscribed. Generous compared to a real scan
|
|
23
|
+
* (a few seconds) so it only trips when the device stops responding, turning a
|
|
24
|
+
* silent hang into an error the subscriber is told about.
|
|
25
|
+
*/
|
|
26
|
+
const SCAN_TIMEOUT = 30000;
|
|
27
|
+
/**
|
|
28
|
+
* Default timeout for an RPC command that receives feedback. Generous, since
|
|
29
|
+
* it's only a safety net: it guarantees every command eventually settles so the
|
|
30
|
+
* command queue can't wedge on a device that stopped responding.
|
|
31
|
+
*/
|
|
32
|
+
const DEFAULT_RPC_TIMEOUT = 30000;
|
|
33
|
+
/** Whether two network states carry the same flags and URLs. */
|
|
34
|
+
const networkStatesEqual = (a, b) => a.online === b.online &&
|
|
35
|
+
a.supportsWifi === b.supportsWifi &&
|
|
36
|
+
a.supportsEthernet === b.supportsEthernet &&
|
|
37
|
+
a.supportsThread === b.supportsThread &&
|
|
38
|
+
a.supportsModem === b.supportsModem &&
|
|
39
|
+
a.urls.length === b.urls.length &&
|
|
40
|
+
a.urls.every((url, i) => url === b.urls[i]);
|
|
41
|
+
/** Whether two (alphabetically sorted) SSID lists differ in any value. */
|
|
42
|
+
const ssidsChanged = (a, b) => {
|
|
43
|
+
if (a.length !== b.length) {
|
|
44
|
+
return true;
|
|
45
|
+
}
|
|
46
|
+
return a.some((ssid, i) => ssid.name !== b[i].name ||
|
|
47
|
+
ssid.rssi !== b[i].rssi ||
|
|
48
|
+
ssid.secured !== b[i].secured);
|
|
49
|
+
};
|
|
50
|
+
export class ImprovSerial extends EventTarget {
|
|
51
|
+
/** Last device error (or local timeout). Assigning dispatches `error-changed`. */
|
|
52
|
+
get error() {
|
|
53
|
+
return this._error;
|
|
54
|
+
}
|
|
55
|
+
set error(error) {
|
|
56
|
+
this._error = error;
|
|
57
|
+
this.dispatchEvent(new CustomEvent("error-changed", { detail: this._error }));
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* Last known network state: `undefined` until a request succeeds, `null` once
|
|
61
|
+
* the device reports the command unsupported. Changes dispatch `network-state-changed`.
|
|
62
|
+
*/
|
|
63
|
+
get networkState() {
|
|
64
|
+
return this._networkState;
|
|
65
|
+
}
|
|
66
|
+
constructor(port, logger) {
|
|
67
|
+
super();
|
|
68
|
+
this.port = port;
|
|
69
|
+
this.logger = logger;
|
|
70
|
+
this._error = 0 /* ImprovSerialErrorState.NO_ERROR */;
|
|
71
|
+
// Improv devices handle one RPC command at a time, so commands are serialized
|
|
72
|
+
// here: each waits for the previous to settle. Every command is bounded by a
|
|
73
|
+
// timeout, so the queue can't wedge on an unresponsive device.
|
|
74
|
+
this._rpcLock = Promise.resolve();
|
|
75
|
+
if (port.readable === null) {
|
|
76
|
+
throw new Error("Port is not readable");
|
|
77
|
+
}
|
|
78
|
+
if (port.writable === null) {
|
|
79
|
+
throw new Error("Port is not writable");
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
/**
|
|
83
|
+
* Detect Improv Serial, fetch the state and return the next URL if provisioned.
|
|
84
|
+
* @param timeout Timeout in ms to wait for the device to respond. Default to 1000ms.
|
|
85
|
+
*/
|
|
86
|
+
async initialize(timeout = 1000) {
|
|
87
|
+
this.logger.log("Initializing Improv Serial");
|
|
88
|
+
// Grabs the reader before its first await, so it is set (or failed to be
|
|
89
|
+
// set) by the time this returns.
|
|
90
|
+
this._processInput();
|
|
91
|
+
if (this._reader === undefined) {
|
|
92
|
+
throw new PortNotReady();
|
|
93
|
+
}
|
|
94
|
+
// The device might still be booting (e.g. right after being flashed) and
|
|
95
|
+
// miss our request, so re-send it every second until it responds.
|
|
96
|
+
let retryInterval;
|
|
97
|
+
try {
|
|
98
|
+
await new Promise(async (resolve, reject) => {
|
|
99
|
+
setTimeout(() => reject(new Error("Improv Wi-Fi Serial not detected")), timeout);
|
|
100
|
+
retryInterval = setInterval(() => this._sendRPC(2 /* ImprovSerialRPCCommand.REQUEST_CURRENT_STATE */, []), 1000);
|
|
101
|
+
await this.requestCurrentState();
|
|
102
|
+
resolve(undefined);
|
|
103
|
+
});
|
|
104
|
+
clearInterval(retryInterval);
|
|
105
|
+
await this.requestInfo();
|
|
106
|
+
}
|
|
107
|
+
catch (err) {
|
|
108
|
+
await this.close();
|
|
109
|
+
throw err;
|
|
110
|
+
}
|
|
111
|
+
finally {
|
|
112
|
+
clearInterval(retryInterval);
|
|
113
|
+
}
|
|
114
|
+
return this.info;
|
|
115
|
+
}
|
|
116
|
+
async close() {
|
|
117
|
+
this.stopNetworkStatePolling();
|
|
118
|
+
if (!this._reader) {
|
|
119
|
+
return;
|
|
120
|
+
}
|
|
121
|
+
await new Promise((resolve) => {
|
|
122
|
+
this._reader.cancel();
|
|
123
|
+
this.addEventListener("disconnect", resolve, { once: true });
|
|
124
|
+
});
|
|
125
|
+
}
|
|
126
|
+
/**
|
|
127
|
+
* This command will trigger at least one packet,
|
|
128
|
+
* the Current State and if already provisioned,
|
|
129
|
+
* the same response you would get if device provisioning
|
|
130
|
+
* was successful (see below).
|
|
131
|
+
*
|
|
132
|
+
* A caller polling an intermittently-unresponsive device (e.g. one rebooting
|
|
133
|
+
* to switch network interfaces) can pass a timeout shorter than the default
|
|
134
|
+
* so each poll settles quickly.
|
|
135
|
+
*/
|
|
136
|
+
async requestCurrentState(timeout) {
|
|
137
|
+
var _a;
|
|
138
|
+
// Every device reports its state; a provisioned one also returns the next
|
|
139
|
+
// URL. Attach the listener before sending, then wait for the state change;
|
|
140
|
+
// the RPC promise is only used to surface a command error.
|
|
141
|
+
const abort = new AbortController();
|
|
142
|
+
let rpcResult;
|
|
143
|
+
try {
|
|
144
|
+
await new Promise((resolve, reject) => {
|
|
145
|
+
this.addEventListener("state-changed", () => {
|
|
146
|
+
var _a;
|
|
147
|
+
// Ignore state changes unrelated to this state request
|
|
148
|
+
if (((_a = this._rpcFeedback) === null || _a === void 0 ? void 0 : _a.command) === 2 /* ImprovSerialRPCCommand.REQUEST_CURRENT_STATE */) {
|
|
149
|
+
resolve();
|
|
150
|
+
}
|
|
151
|
+
}, { signal: abort.signal });
|
|
152
|
+
rpcResult = this._sendRPCWithResponse(2 /* ImprovSerialRPCCommand.REQUEST_CURRENT_STATE */, [], timeout);
|
|
153
|
+
rpcResult.catch(reject);
|
|
154
|
+
});
|
|
155
|
+
}
|
|
156
|
+
catch (err) {
|
|
157
|
+
throw new Error(`Error fetching current state: ${err}`);
|
|
158
|
+
}
|
|
159
|
+
finally {
|
|
160
|
+
abort.abort(); // drop the state-change listener if it never fired
|
|
161
|
+
}
|
|
162
|
+
// Only a provisioned device sends an RPC result. For anything else, settle
|
|
163
|
+
// the pending command ourselves so it releases the lock now.
|
|
164
|
+
if (this.state !== ImprovSerialCurrentState.PROVISIONED) {
|
|
165
|
+
(_a = this._rpcFeedback) === null || _a === void 0 ? void 0 : _a.resolve([]);
|
|
166
|
+
return;
|
|
167
|
+
}
|
|
168
|
+
this.nextUrl = (await rpcResult)[0];
|
|
169
|
+
}
|
|
170
|
+
async requestInfo(timeout) {
|
|
171
|
+
const response = await this._sendRPCWithResponse(3 /* ImprovSerialRPCCommand.REQUEST_INFO */, [], timeout);
|
|
172
|
+
this.info = {
|
|
173
|
+
firmware: response[0],
|
|
174
|
+
version: response[1],
|
|
175
|
+
name: response[3],
|
|
176
|
+
chipFamily: response[2],
|
|
177
|
+
osName: response.length > 4 ? response[4] : null,
|
|
178
|
+
osVersion: response.length > 5 ? response[5] : null,
|
|
179
|
+
};
|
|
180
|
+
}
|
|
181
|
+
async provision(ssid, password, timeout) {
|
|
182
|
+
const encoder = new TextEncoder();
|
|
183
|
+
const ssidEncoded = encoder.encode(ssid);
|
|
184
|
+
const pwEncoded = encoder.encode(password);
|
|
185
|
+
const data = [
|
|
186
|
+
ssidEncoded.length,
|
|
187
|
+
...ssidEncoded,
|
|
188
|
+
pwEncoded.length,
|
|
189
|
+
...pwEncoded,
|
|
190
|
+
];
|
|
191
|
+
const response = await this._sendRPCWithResponse(1 /* ImprovSerialRPCCommand.SEND_WIFI_SETTINGS */, data, timeout);
|
|
192
|
+
this.nextUrl = response[0];
|
|
193
|
+
}
|
|
194
|
+
async scan(timeout) {
|
|
195
|
+
const results = await this._sendRPCWithMultipleResponses(4 /* ImprovSerialRPCCommand.REQUEST_WIFI_NETWORKS */, [], timeout);
|
|
196
|
+
const ssids = results.map(([name, rssi, secured]) => ({
|
|
197
|
+
name,
|
|
198
|
+
rssi: parseInt(rssi),
|
|
199
|
+
secured: secured !== "NO",
|
|
200
|
+
}));
|
|
201
|
+
return sortSsids(ssids);
|
|
202
|
+
}
|
|
203
|
+
/**
|
|
204
|
+
* Continuously scan for Wi-Fi networks, calling `onChange` whenever the list
|
|
205
|
+
* of networks changes.
|
|
206
|
+
*
|
|
207
|
+
* Results are merged with previous scans (networks are keyed by name and kept
|
|
208
|
+
* sorted alphabetically), so a network missing from a single scan won't
|
|
209
|
+
* immediately disappear. `onChange` is only called when a value in the list
|
|
210
|
+
* actually changes.
|
|
211
|
+
*
|
|
212
|
+
* Scanning stops on the first error or when the returned function is called.
|
|
213
|
+
* If the first scan fails (e.g. the device doesn't support scanning, or stops
|
|
214
|
+
* responding), `onChange` is called once with `null` to signal that networks
|
|
215
|
+
* are unavailable.
|
|
216
|
+
*
|
|
217
|
+
* The returned function resolves once the in-flight scan has settled, so it
|
|
218
|
+
* can be awaited before sending another RPC command (such as provisioning).
|
|
219
|
+
*/
|
|
220
|
+
subscribeSSIDs(onChange) {
|
|
221
|
+
let active = true;
|
|
222
|
+
let current;
|
|
223
|
+
let wake;
|
|
224
|
+
const loop = (async () => {
|
|
225
|
+
while (active) {
|
|
226
|
+
let ssids;
|
|
227
|
+
try {
|
|
228
|
+
ssids = await this.scan(SCAN_TIMEOUT);
|
|
229
|
+
}
|
|
230
|
+
catch (err) {
|
|
231
|
+
this.logger.error("Error while scanning for Wi-Fi networks", err);
|
|
232
|
+
// Only signal unavailability if we never got a result. Once we have
|
|
233
|
+
// networks, scanning is clearly supported, so keep the last list on a
|
|
234
|
+
// transient failure. Either way, stop scanning.
|
|
235
|
+
if (active && current === undefined) {
|
|
236
|
+
onChange(null);
|
|
237
|
+
}
|
|
238
|
+
break;
|
|
239
|
+
}
|
|
240
|
+
if (!active) {
|
|
241
|
+
break;
|
|
242
|
+
}
|
|
243
|
+
const merged = current === undefined ? ssids : mergeSsids(current, ssids);
|
|
244
|
+
if (current === undefined || ssidsChanged(current, merged)) {
|
|
245
|
+
current = merged;
|
|
246
|
+
onChange(merged);
|
|
247
|
+
}
|
|
248
|
+
// Wait before the next scan, but wake immediately if unsubscribed.
|
|
249
|
+
await new Promise((resolve) => {
|
|
250
|
+
wake = resolve;
|
|
251
|
+
setTimeout(resolve, SCAN_INTERVAL);
|
|
252
|
+
});
|
|
253
|
+
}
|
|
254
|
+
})();
|
|
255
|
+
return () => {
|
|
256
|
+
active = false;
|
|
257
|
+
wake === null || wake === void 0 ? void 0 : wake();
|
|
258
|
+
return loop;
|
|
259
|
+
};
|
|
260
|
+
}
|
|
261
|
+
/**
|
|
262
|
+
* Get the current hostname of the device.
|
|
263
|
+
*/
|
|
264
|
+
async getHostname(timeout) {
|
|
265
|
+
const response = await this._sendRPCWithResponse(5 /* ImprovSerialRPCCommand.HOSTNAME */, [], timeout);
|
|
266
|
+
return response[0];
|
|
267
|
+
}
|
|
268
|
+
/**
|
|
269
|
+
* Set the hostname of the device. Returns the hostname as set by the device.
|
|
270
|
+
*
|
|
271
|
+
* Hostnames need to conform to RFC 1123: letters, numbers and hyphens, up to
|
|
272
|
+
* 255 characters. The device rejects other hostnames with a BAD_HOSTNAME error.
|
|
273
|
+
*/
|
|
274
|
+
async setHostname(hostname, timeout) {
|
|
275
|
+
const encoder = new TextEncoder();
|
|
276
|
+
const response = await this._sendRPCWithResponse(5 /* ImprovSerialRPCCommand.HOSTNAME */, [...encoder.encode(hostname)], timeout);
|
|
277
|
+
return response[0];
|
|
278
|
+
}
|
|
279
|
+
/**
|
|
280
|
+
* Get the current device name. This is the same value as `info.name`.
|
|
281
|
+
*/
|
|
282
|
+
async getDeviceName(timeout) {
|
|
283
|
+
const response = await this._sendRPCWithResponse(6 /* ImprovSerialRPCCommand.DEVICE_NAME */, [], timeout);
|
|
284
|
+
return response[0];
|
|
285
|
+
}
|
|
286
|
+
/**
|
|
287
|
+
* Set the device name. Returns the device name as set by the device.
|
|
288
|
+
*
|
|
289
|
+
* When setting both the device name and the hostname, set the device name
|
|
290
|
+
* first, as it can change the default hostname.
|
|
291
|
+
*/
|
|
292
|
+
async setDeviceName(deviceName, timeout) {
|
|
293
|
+
const encoder = new TextEncoder();
|
|
294
|
+
const response = await this._sendRPCWithResponse(6 /* ImprovSerialRPCCommand.DEVICE_NAME */, [...encoder.encode(deviceName)], timeout);
|
|
295
|
+
if (this.info) {
|
|
296
|
+
this.info.name = response[0];
|
|
297
|
+
}
|
|
298
|
+
return response[0];
|
|
299
|
+
}
|
|
300
|
+
/**
|
|
301
|
+
* Request the device's network connectivity and supported interfaces.
|
|
302
|
+
*
|
|
303
|
+
* This is independent of the Wi-Fi provisioning state: a device already
|
|
304
|
+
* online over Ethernet reports that here without Wi-Fi provisioning. The
|
|
305
|
+
* first response string is the network flags as a decimal-encoded byte, and
|
|
306
|
+
* when online the reachable device URL(s) follow.
|
|
307
|
+
*
|
|
308
|
+
* This command is optional. Devices that do not implement it respond with
|
|
309
|
+
* UNKNOWN_RPC_COMMAND, so this rejects with that error for such devices.
|
|
310
|
+
*/
|
|
311
|
+
requestNetworkState(timeout) {
|
|
312
|
+
return this._requestNetworkState(timeout, false);
|
|
313
|
+
}
|
|
314
|
+
/**
|
|
315
|
+
* Poll the device's network state, keeping `networkState` fresh. Idempotent;
|
|
316
|
+
* stopped by `stopNetworkStatePolling()`, `close()`, a disconnect, or the
|
|
317
|
+
* device reporting the command unsupported. A failed poll keeps the last
|
|
318
|
+
* known state, leaves `error` untouched and retries on the next tick.
|
|
319
|
+
*/
|
|
320
|
+
startNetworkStatePolling(interval = NETWORK_STATE_POLL_INTERVAL, timeout = NETWORK_STATE_POLL_TIMEOUT) {
|
|
321
|
+
if (this._stopNetworkStatePolling ||
|
|
322
|
+
this.networkState === null ||
|
|
323
|
+
!this._reader) {
|
|
324
|
+
return;
|
|
325
|
+
}
|
|
326
|
+
let active = true;
|
|
327
|
+
let wake;
|
|
328
|
+
this._stopNetworkStatePolling = () => {
|
|
329
|
+
active = false;
|
|
330
|
+
wake === null || wake === void 0 ? void 0 : wake();
|
|
331
|
+
};
|
|
332
|
+
(async () => {
|
|
333
|
+
while (active) {
|
|
334
|
+
try {
|
|
335
|
+
await this._requestNetworkState(timeout, true);
|
|
336
|
+
}
|
|
337
|
+
catch (err) {
|
|
338
|
+
if (this.networkState === null) {
|
|
339
|
+
break;
|
|
340
|
+
}
|
|
341
|
+
this.logger.debug(`Failed to fetch network state: ${err}`);
|
|
342
|
+
}
|
|
343
|
+
if (!active) {
|
|
344
|
+
break;
|
|
345
|
+
}
|
|
346
|
+
// Wait before the next poll, but wake immediately when stopped.
|
|
347
|
+
await new Promise((resolve) => {
|
|
348
|
+
wake = resolve;
|
|
349
|
+
setTimeout(resolve, interval);
|
|
350
|
+
});
|
|
351
|
+
}
|
|
352
|
+
// Self-exit (unsupported device): drop the handle so a start can work again.
|
|
353
|
+
if (active) {
|
|
354
|
+
this._stopNetworkStatePolling = undefined;
|
|
355
|
+
}
|
|
356
|
+
})();
|
|
357
|
+
}
|
|
358
|
+
stopNetworkStatePolling() {
|
|
359
|
+
var _a;
|
|
360
|
+
(_a = this._stopNetworkStatePolling) === null || _a === void 0 ? void 0 : _a.call(this);
|
|
361
|
+
this._stopNetworkStatePolling = undefined;
|
|
362
|
+
}
|
|
363
|
+
async _requestNetworkState(timeout, quiet) {
|
|
364
|
+
let response;
|
|
365
|
+
try {
|
|
366
|
+
response = await this._sendRPCWithResponse(7 /* ImprovSerialRPCCommand.REQUEST_NETWORK_STATE */, [], timeout, quiet);
|
|
367
|
+
}
|
|
368
|
+
catch (err) {
|
|
369
|
+
// Not `this.error`: a later error can overwrite it before this catch runs.
|
|
370
|
+
if (err === ERROR_MSGS[2 /* ImprovSerialErrorState.UNKNOWN_RPC_COMMAND */]) {
|
|
371
|
+
this._setNetworkState(null);
|
|
372
|
+
}
|
|
373
|
+
throw err;
|
|
374
|
+
}
|
|
375
|
+
const flags = parseInt(response[0]);
|
|
376
|
+
const networkState = {
|
|
377
|
+
online: (flags & 1 /* ImprovNetworkFlag.IS_ONLINE */) !== 0,
|
|
378
|
+
supportsWifi: (flags & 2 /* ImprovNetworkFlag.SUPPORTS_WIFI */) !== 0,
|
|
379
|
+
supportsEthernet: (flags & 4 /* ImprovNetworkFlag.SUPPORTS_ETHERNET */) !== 0,
|
|
380
|
+
supportsThread: (flags & 8 /* ImprovNetworkFlag.SUPPORTS_THREAD */) !== 0,
|
|
381
|
+
supportsModem: (flags & 16 /* ImprovNetworkFlag.SUPPORTS_MODEM */) !== 0,
|
|
382
|
+
urls: response.slice(1),
|
|
383
|
+
};
|
|
384
|
+
this._setNetworkState(networkState);
|
|
385
|
+
return networkState;
|
|
386
|
+
}
|
|
387
|
+
_setNetworkState(networkState) {
|
|
388
|
+
const previous = this._networkState;
|
|
389
|
+
this._networkState = networkState;
|
|
390
|
+
if (previous === networkState ||
|
|
391
|
+
(previous != null &&
|
|
392
|
+
networkState != null &&
|
|
393
|
+
networkStatesEqual(previous, networkState))) {
|
|
394
|
+
return;
|
|
395
|
+
}
|
|
396
|
+
this.dispatchEvent(new CustomEvent("network-state-changed", { detail: networkState }));
|
|
397
|
+
}
|
|
398
|
+
_sendRPC(command, data) {
|
|
399
|
+
this.writePacketToStream(ImprovSerialMessageType.RPC, [
|
|
400
|
+
command,
|
|
401
|
+
data.length,
|
|
402
|
+
...data,
|
|
403
|
+
]);
|
|
404
|
+
}
|
|
405
|
+
/**
|
|
406
|
+
* Run an RPC command once the previous one has settled, so devices that
|
|
407
|
+
* handle a single command at a time never see two at once. The chain is kept
|
|
408
|
+
* alive regardless of each command's outcome.
|
|
409
|
+
*/
|
|
410
|
+
_enqueueRPC(send, timeout) {
|
|
411
|
+
const run = () => this._awaitRPCResultWithTimeout(send(), timeout).finally(() => {
|
|
412
|
+
this._rpcFeedback = undefined;
|
|
413
|
+
});
|
|
414
|
+
const result = this._rpcLock.then(run, run);
|
|
415
|
+
this._rpcLock = result.catch(() => { });
|
|
416
|
+
return result;
|
|
417
|
+
}
|
|
418
|
+
_sendRPCWithResponse(command, data, timeout = DEFAULT_RPC_TIMEOUT, quiet = false) {
|
|
419
|
+
return this._enqueueRPC(() => new Promise((resolve, reject) => {
|
|
420
|
+
this._rpcFeedback = { command, resolve, reject, quiet };
|
|
421
|
+
this._sendRPC(command, data);
|
|
422
|
+
}), timeout);
|
|
423
|
+
}
|
|
424
|
+
_sendRPCWithMultipleResponses(command, data, timeout = DEFAULT_RPC_TIMEOUT) {
|
|
425
|
+
return this._enqueueRPC(() => new Promise((resolve, reject) => {
|
|
426
|
+
this._rpcFeedback = { command, resolve, reject, receivedData: [] };
|
|
427
|
+
this._sendRPC(command, data);
|
|
428
|
+
}), timeout);
|
|
429
|
+
}
|
|
430
|
+
async _awaitRPCResultWithTimeout(sendRPCPromise, timeout) {
|
|
431
|
+
if (!timeout) {
|
|
432
|
+
return await sendRPCPromise;
|
|
433
|
+
}
|
|
434
|
+
const timeoutRPC = setTimeout(() => this._setError(254 /* ImprovSerialErrorState.TIMEOUT */), timeout);
|
|
435
|
+
try {
|
|
436
|
+
return await sendRPCPromise;
|
|
437
|
+
}
|
|
438
|
+
finally {
|
|
439
|
+
clearTimeout(timeoutRPC);
|
|
440
|
+
}
|
|
441
|
+
}
|
|
442
|
+
async _processInput() {
|
|
443
|
+
// read the data from serial port.
|
|
444
|
+
// current state, error state, rpc result
|
|
445
|
+
this.logger.debug("Starting read loop");
|
|
446
|
+
this._reader = this.port.readable.getReader();
|
|
447
|
+
try {
|
|
448
|
+
let line = [];
|
|
449
|
+
// undefined = not sure if improv packet
|
|
450
|
+
let isImprov;
|
|
451
|
+
// length of improv bytes that we expect
|
|
452
|
+
let improvLength = 0;
|
|
453
|
+
while (true) {
|
|
454
|
+
const { value, done } = await this._reader.read();
|
|
455
|
+
if (done) {
|
|
456
|
+
break;
|
|
457
|
+
}
|
|
458
|
+
if (!value || value.length === 0) {
|
|
459
|
+
continue;
|
|
460
|
+
}
|
|
461
|
+
for (const byte of value) {
|
|
462
|
+
if (isImprov === false) {
|
|
463
|
+
// When it wasn't an improv line, discard everything unti we find new line char
|
|
464
|
+
if (byte === 10) {
|
|
465
|
+
isImprov = undefined;
|
|
466
|
+
}
|
|
467
|
+
continue;
|
|
468
|
+
}
|
|
469
|
+
if (isImprov === true) {
|
|
470
|
+
line.push(byte);
|
|
471
|
+
if (line.length === improvLength) {
|
|
472
|
+
this._handleIncomingPacket(line);
|
|
473
|
+
isImprov = undefined;
|
|
474
|
+
line = [];
|
|
475
|
+
}
|
|
476
|
+
continue;
|
|
477
|
+
}
|
|
478
|
+
if (byte === 10) {
|
|
479
|
+
line = [];
|
|
480
|
+
continue;
|
|
481
|
+
}
|
|
482
|
+
line.push(byte);
|
|
483
|
+
if (line.length !== 9) {
|
|
484
|
+
continue;
|
|
485
|
+
}
|
|
486
|
+
// Check if it's improv
|
|
487
|
+
isImprov = String.fromCharCode(...line.slice(0, 6)) === "IMPROV";
|
|
488
|
+
if (!isImprov) {
|
|
489
|
+
line = [];
|
|
490
|
+
continue;
|
|
491
|
+
}
|
|
492
|
+
// Format:
|
|
493
|
+
// I M P R O V <VERSION> <TYPE> <LENGTH> <DATA> <CHECKSUM>
|
|
494
|
+
// Once we have 9 bytes, we can check if it's an improv packet
|
|
495
|
+
// and extract how much more we need to fetch.
|
|
496
|
+
const packetLength = line[8];
|
|
497
|
+
improvLength = 9 + packetLength + 1; // header + data length + checksum
|
|
498
|
+
}
|
|
499
|
+
}
|
|
500
|
+
}
|
|
501
|
+
catch (err) {
|
|
502
|
+
this.logger.error("Error while reading serial port", err);
|
|
503
|
+
}
|
|
504
|
+
finally {
|
|
505
|
+
this._reader.releaseLock();
|
|
506
|
+
this._reader = undefined;
|
|
507
|
+
}
|
|
508
|
+
this.logger.debug("Finished read loop");
|
|
509
|
+
this.stopNetworkStatePolling();
|
|
510
|
+
this.dispatchEvent(new Event("disconnect"));
|
|
511
|
+
}
|
|
512
|
+
_handleIncomingPacket(line) {
|
|
513
|
+
const payload = line.slice(6);
|
|
514
|
+
const version = payload[0];
|
|
515
|
+
const packetType = payload[1];
|
|
516
|
+
const packetLength = payload[2];
|
|
517
|
+
const data = payload.slice(3, 3 + packetLength);
|
|
518
|
+
this.logger.debug("PROCESS", {
|
|
519
|
+
version,
|
|
520
|
+
packetType,
|
|
521
|
+
packetLength,
|
|
522
|
+
data: hexFormatter(data),
|
|
523
|
+
});
|
|
524
|
+
if (version !== 1) {
|
|
525
|
+
this.logger.error("Received unsupported version", version);
|
|
526
|
+
return;
|
|
527
|
+
}
|
|
528
|
+
// Verify checksum
|
|
529
|
+
let packetChecksum = payload[3 + packetLength];
|
|
530
|
+
let calculatedChecksum = 0;
|
|
531
|
+
for (let i = 0; i < line.length - 1; i++) {
|
|
532
|
+
calculatedChecksum += line[i];
|
|
533
|
+
}
|
|
534
|
+
calculatedChecksum = calculatedChecksum & 0xff;
|
|
535
|
+
if (calculatedChecksum !== packetChecksum) {
|
|
536
|
+
this.logger.error(`Received invalid checksum ${packetChecksum}. Expected ${calculatedChecksum}`);
|
|
537
|
+
return;
|
|
538
|
+
}
|
|
539
|
+
if (packetType === ImprovSerialMessageType.CURRENT_STATE) {
|
|
540
|
+
this.state = data[0];
|
|
541
|
+
if (this.state !== ImprovSerialCurrentState.PROVISIONED) {
|
|
542
|
+
// The URL from a successful provision is only valid while provisioned.
|
|
543
|
+
// A device that leaves that state (e.g. it detected an Ethernet link
|
|
544
|
+
// and rebooted with Wi-Fi disabled) must not keep advertising it.
|
|
545
|
+
this.nextUrl = undefined;
|
|
546
|
+
}
|
|
547
|
+
this.dispatchEvent(new CustomEvent("state-changed", {
|
|
548
|
+
detail: this.state,
|
|
549
|
+
}));
|
|
550
|
+
}
|
|
551
|
+
else if (packetType === ImprovSerialMessageType.ERROR_STATE) {
|
|
552
|
+
this._setError(data[0]);
|
|
553
|
+
}
|
|
554
|
+
else if (packetType === ImprovSerialMessageType.RPC_RESULT) {
|
|
555
|
+
if (!this._rpcFeedback) {
|
|
556
|
+
this.logger.error("Received result while not waiting for one");
|
|
557
|
+
return;
|
|
558
|
+
}
|
|
559
|
+
const rpcCommand = data[0];
|
|
560
|
+
if (rpcCommand !== this._rpcFeedback.command) {
|
|
561
|
+
this.logger.error(`Received result for command ${rpcCommand} but expected ${this._rpcFeedback.command}`);
|
|
562
|
+
return;
|
|
563
|
+
}
|
|
564
|
+
// Chop off rpc command and checksum
|
|
565
|
+
const result = [];
|
|
566
|
+
const totalLength = data[1];
|
|
567
|
+
const decoder = new TextDecoder("utf-8");
|
|
568
|
+
let idx = 2;
|
|
569
|
+
while (idx < 2 + totalLength) {
|
|
570
|
+
result.push(decoder.decode(new Uint8Array(data.slice(idx + 1, idx + data[idx] + 1))));
|
|
571
|
+
idx += data[idx] + 1;
|
|
572
|
+
}
|
|
573
|
+
if ("receivedData" in this._rpcFeedback) {
|
|
574
|
+
if (result.length > 0) {
|
|
575
|
+
this._rpcFeedback.receivedData.push(result);
|
|
576
|
+
}
|
|
577
|
+
else {
|
|
578
|
+
// Result of 0 means we're done.
|
|
579
|
+
this._rpcFeedback.resolve(this._rpcFeedback.receivedData);
|
|
580
|
+
}
|
|
581
|
+
}
|
|
582
|
+
else {
|
|
583
|
+
this._rpcFeedback.resolve(result);
|
|
584
|
+
}
|
|
585
|
+
}
|
|
586
|
+
else {
|
|
587
|
+
this.logger.error("Unable to handle packet", payload);
|
|
588
|
+
}
|
|
589
|
+
}
|
|
590
|
+
/**
|
|
591
|
+
* Add header + checksum and write packet to stream
|
|
592
|
+
*/
|
|
593
|
+
async writePacketToStream(type, data) {
|
|
594
|
+
const payload = new Uint8Array([
|
|
595
|
+
...SERIAL_PACKET_HEADER,
|
|
596
|
+
type,
|
|
597
|
+
data.length,
|
|
598
|
+
...data,
|
|
599
|
+
0, // Will be checksum
|
|
600
|
+
0, // Will be newline
|
|
601
|
+
]);
|
|
602
|
+
// Calculate checksum
|
|
603
|
+
payload[payload.length - 2] =
|
|
604
|
+
payload.reduce((sum, cur) => sum + cur, 0) & 0xff;
|
|
605
|
+
payload[payload.length - 1] = 10; // Newline
|
|
606
|
+
this.logger.debug("Writing to stream:", hexFormatter(new Array(...payload)));
|
|
607
|
+
const writer = this.port.writable.getWriter();
|
|
608
|
+
await writer.write(payload);
|
|
609
|
+
try {
|
|
610
|
+
writer.releaseLock();
|
|
611
|
+
}
|
|
612
|
+
catch (err) {
|
|
613
|
+
console.error("Ignoring release lock error", err);
|
|
614
|
+
}
|
|
615
|
+
}
|
|
616
|
+
// Error is either received from device or is a timeout
|
|
617
|
+
_setError(error) {
|
|
618
|
+
if (error > 0 && this._rpcFeedback) {
|
|
619
|
+
this._rpcFeedback.reject(ERROR_MSGS[error] || `UNKNOWN_ERROR (${error})`);
|
|
620
|
+
if (this._rpcFeedback.quiet) {
|
|
621
|
+
return;
|
|
622
|
+
}
|
|
623
|
+
}
|
|
624
|
+
this.error = error;
|
|
625
|
+
}
|
|
626
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
export const fireEvent = (eventTarget, type,
|
|
2
|
+
// @ts-ignore
|
|
3
|
+
detail, options) => {
|
|
4
|
+
options = options || {};
|
|
5
|
+
const event = new CustomEvent(type, {
|
|
6
|
+
bubbles: options.bubbles === undefined ? true : options.bubbles,
|
|
7
|
+
cancelable: Boolean(options.cancelable),
|
|
8
|
+
composed: options.composed === undefined ? true : options.composed,
|
|
9
|
+
detail,
|
|
10
|
+
});
|
|
11
|
+
eventTarget.dispatchEvent(event);
|
|
12
|
+
};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare const hexFormatter: (bytes: number[] | Uint8Array) => string;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare const toHex: (value: number, size?: number) => string;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const e=(e,o,t,n)=>{n=n||{};const r=new CustomEvent(o,{bubbles:void 0===n.bubbles||n.bubbles,cancelable:Boolean(n.cancelable),composed:void 0===n.composed||n.composed,detail:t});e.dispatchEvent(r)};class o extends HTMLElement{connectedCallback(){if(this.renderRoot)return;if(this.renderRoot=this.attachShadow({mode:"open"}),!o.isSupported||!o.isAllowed)return this.toggleAttribute("not-supported",!0),void(this.renderRoot.innerHTML=o.isAllowed?"<slot name='unsupported'>Your browser does not support serial provisioning. Use Google Chrome, Microsoft Edge or Mozilla Firefox.</slot>":"<slot name='not-allowed'>You can only use Improv on HTTPS sites or localhost.</slot>");this.toggleAttribute("supported",!0);const t=document.createElement("slot");t.name="activate";const n=document.createElement("button");if(n.innerText="Connect device to Wi-Fi",t.append(n),t.addEventListener("click",async o=>{o.preventDefault(),(async o=>{let t;import("./serial-provision-dialog-DR-raZEr.js");try{t=await navigator.serial.requestPort()}catch(e){if("NotFoundError"===e.name)return;return void alert(`Error: ${e.message}`)}if(!t)return;await t.open({baudRate:115200});const n=document.createElement("improv-wifi-serial-provision-dialog");n.port=t,n.addEventListener("closed",async n=>{await t.close(),e(o,"closed",n.detail)},{once:!0}),document.body.appendChild(n)})(this)}),"adoptedStyleSheets"in Document.prototype&&"replaceSync"in CSSStyleSheet.prototype){const e=new CSSStyleSheet;e.replaceSync(o.style),this.renderRoot.adoptedStyleSheets=[e]}else{const e=document.createElement("style");e.innerText=o.style,this.renderRoot.append(e)}this.renderRoot.append(t)}}o.isSupported="serial"in navigator,o.isAllowed=window.isSecureContext,o.style='\n button {\n position: relative;\n cursor: pointer;\n font-size: 14px;\n padding: 8px 28px;\n color: var(--improv-on-primary-color, #fff);\n background-color: var(--improv-primary-color, #03a9f4);\n border: none;\n border-radius: 4px;\n box-shadow: 0 2px 2px 0 rgba(0,0,0,.14), 0 3px 1px -2px rgba(0,0,0,.12), 0 1px 5px 0 rgba(0,0,0,.2);\n }\n button::before {\n content: " ";\n position: absolute;\n top: 0;\n bottom: 0;\n left: 0;\n right: 0;\n opacity: 0.2;\n border-radius: 4px;\n }\n button:hover {\n box-shadow: 0 4px 8px 0 rgba(0,0,0,.14), 0 1px 7px 0 rgba(0,0,0,.12), 0 3px 1px -1px rgba(0,0,0,.2);\n }\n button:hover::before {\n background-color: rgba(255,255,255,.8);\n }\n button:focus {\n outline: none;\n }\n button:focus::before {\n background-color: white;\n }\n button:active::before {\n background-color: grey;\n }\n',customElements.define("improv-wifi-serial-launch-button",o);export{e as f};
|