ember-router 1.1.0 → 1.3.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/README.md +21 -3
- package/index.js +169 -38
- package/package.json +1 -1
- package/request-socket.js +102 -0
- package/router.js +53 -6
package/README.md
CHANGED
|
@@ -33,10 +33,18 @@ ember-router reset -p <path> --yes [options]
|
|
|
33
33
|
- `-r, --rtscts` to enable hardware flow control.
|
|
34
34
|
- `-m, --manufacturer-code <code>` for the ZCL enum name, decimal value, or `0x` value (default `SILICON_LABORATORIES`). Pass the override again on resume when needed.
|
|
35
35
|
- `--timeout <ms>` for scan and network callbacks (default `45000`).
|
|
36
|
-
-
|
|
36
|
+
- `--read-timeout <ms>` for `read` and `run --socket` to set the ZCL reply timeout (default `5000`, range `100`–`300000`).
|
|
37
37
|
- `--write-timeout <ms>` for `run`, `write`, and `read` to set the APS delivery timeout (default `15000`).
|
|
38
|
-
- `--
|
|
39
|
-
- `--
|
|
38
|
+
- `--expect <commandId>` for `read` and `run --socket` to select the ZCL reply command by decimal or `0x` value.
|
|
39
|
+
- `--socket <path>` for `run` to accept requests over a local Unix domain socket or a Windows named pipe.
|
|
40
|
+
- `-g, --graceful` for `run` and `write` to attempt one reconnect after adapter loss. Repeat as `-gg` to keep retrying.
|
|
41
|
+
- `-v, --verbose` for more diagnostics on stderr. Repeat for debug output during `run`.
|
|
42
|
+
|
|
43
|
+
#### Graceful reconnect
|
|
44
|
+
|
|
45
|
+
After a session starts, `-g` waits 5 seconds and makes one recovery attempt per adapter loss. `-gg` continues with exponential backoff capped at 120 seconds. Recovery resumes the network saved on the adapter. Initial startup failures still exit with an error.
|
|
46
|
+
|
|
47
|
+
Stdin, stdout, stderr, and local socket clients stay open during recovery. Interrupted requests and requests submitted while offline fail. Socket requests return `null` and writes report errors on stderr. Once the adapter reconnects, the router can handle new requests. `write` still exits after EOF and reports any failed packets in its exit status.
|
|
40
48
|
|
|
41
49
|
#### Joining networks
|
|
42
50
|
|
|
@@ -119,3 +127,13 @@ The router automatically expects Read Attributes Response (`0x01`) or Write Attr
|
|
|
119
127
|
```json
|
|
120
128
|
{"type":"aps","source":4660,"sourceEndpoint":1,"destinationEndpoint":1,"profileId":260,"clusterId":513,"lqi":180,"payload":"180101120000299e07"}
|
|
121
129
|
```
|
|
130
|
+
|
|
131
|
+
### Local socket
|
|
132
|
+
|
|
133
|
+
```sh
|
|
134
|
+
ember-router run -p tcp://192.168.1.42:6638 --socket /path/to/private/ember-router.sock
|
|
135
|
+
```
|
|
136
|
+
|
|
137
|
+
Send one packet per JSON line and receive one reply per line in the same order. A failed request returns `null` and logs the error on stderr. Keep the connection open until replies arrive. The socket supports 16 clients and 8192 bytes per line, with one request active on the adapter at a time.
|
|
138
|
+
|
|
139
|
+
Use a private directory for the Unix socket. If a crash leaves a stale socket, confirm it is unused before removing it. On Windows, use a named pipe such as `\\.\pipe\ember-router`.
|
package/index.js
CHANGED
|
@@ -1,8 +1,10 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import { once } from 'node:events';
|
|
2
|
+
import { addAbortListener, once } from 'node:events';
|
|
3
3
|
import { createInterface } from 'node:readline';
|
|
4
|
+
import { setTimeout as delay } from 'node:timers/promises';
|
|
4
5
|
import { Command, InvalidArgumentError, Option } from 'commander';
|
|
5
6
|
import packageJson from './package.json' with { type: 'json' };
|
|
7
|
+
import { openRequestSocket } from './request-socket.js';
|
|
6
8
|
import { attachNetwork, capture, openRouter, resetRouter, sendPacket, SLStatus, Zcl } from './router.js';
|
|
7
9
|
|
|
8
10
|
function integer(min, max) {
|
|
@@ -43,7 +45,26 @@ function parsePacket(line) {
|
|
|
43
45
|
return packet;
|
|
44
46
|
}
|
|
45
47
|
|
|
46
|
-
|
|
48
|
+
function createSender(ezsp, timeout, signal) {
|
|
49
|
+
let tag = 0;
|
|
50
|
+
let pending = Promise.resolve();
|
|
51
|
+
return (packet, expect, clientSignal) => {
|
|
52
|
+
const requestSignal = clientSignal ? AbortSignal.any([signal, clientSignal]) : signal;
|
|
53
|
+
const operation = pending.then(() => {
|
|
54
|
+
requestSignal.throwIfAborted();
|
|
55
|
+
tag = (tag + 1) & 0x7f;
|
|
56
|
+
return sendPacket(ezsp, packet, tag, timeout, requestSignal, expect);
|
|
57
|
+
});
|
|
58
|
+
pending = operation.catch(() => {});
|
|
59
|
+
// Release the caller on abort while the adapter queue drains.
|
|
60
|
+
return new Promise((resolve, reject) => {
|
|
61
|
+
const abort = addAbortListener(requestSignal, () => reject(requestSignal.reason));
|
|
62
|
+
operation.then(resolve, reject).finally(() => abort[Symbol.dispose]());
|
|
63
|
+
});
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
async function readWrites(send, signal) {
|
|
47
68
|
const { stdin } = process;
|
|
48
69
|
if (stdin.readableEnded || stdin.destroyed) {
|
|
49
70
|
return;
|
|
@@ -66,7 +87,7 @@ async function readWrites(ezsp, timeout, signal) {
|
|
|
66
87
|
}
|
|
67
88
|
|
|
68
89
|
try {
|
|
69
|
-
await
|
|
90
|
+
await send(parsePacket(line));
|
|
70
91
|
} catch (error) {
|
|
71
92
|
if (signal.aborted) {
|
|
72
93
|
break;
|
|
@@ -104,8 +125,33 @@ async function readOnce(options) {
|
|
|
104
125
|
process.stdout.write(`${JSON.stringify(reply)}\n`);
|
|
105
126
|
}
|
|
106
127
|
|
|
128
|
+
async function closeSession(session) {
|
|
129
|
+
try {
|
|
130
|
+
await session.close();
|
|
131
|
+
} catch (error) {
|
|
132
|
+
writeLog('warning', `Could not close adapter: ${error.message}`);
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
async function reconnect(connect, graceful, signal) {
|
|
137
|
+
for (let backoff = 5000; ; backoff = Math.min(backoff * 2, 120_000)) {
|
|
138
|
+
writeLog('info', `Reconnecting to adapter in ${backoff / 1000} seconds.`);
|
|
139
|
+
await delay(backoff, undefined, { signal });
|
|
140
|
+
try {
|
|
141
|
+
return await connect();
|
|
142
|
+
} catch (error) {
|
|
143
|
+
signal.throwIfAborted();
|
|
144
|
+
if (graceful < 2 || ['NO_SAVED_NETWORK', 'WRONG_NODE_TYPE', 'NETWORK_CHANGED'].includes(error.code)) {
|
|
145
|
+
throw error;
|
|
146
|
+
}
|
|
147
|
+
writeLog('warning', `Could not reconnect to adapter: ${error.message}`);
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
|
|
107
152
|
async function run(options, mode, packet) {
|
|
108
153
|
const join = mode === 'join';
|
|
154
|
+
const streaming = mode === 'run' || mode === 'write';
|
|
109
155
|
const stop = new AbortController();
|
|
110
156
|
const { signal } = stop;
|
|
111
157
|
const interrupt = () => stop.abort();
|
|
@@ -122,52 +168,122 @@ async function run(options, mode, packet) {
|
|
|
122
168
|
writeLog(level, message, namespace);
|
|
123
169
|
}
|
|
124
170
|
};
|
|
171
|
+
|
|
172
|
+
let networkId;
|
|
173
|
+
const connect = async () => {
|
|
174
|
+
const disconnected = new AbortController();
|
|
175
|
+
const sessionSignal = AbortSignal.any([signal, disconnected.signal]);
|
|
176
|
+
const adapter = await openRouter(options, log, error => disconnected.abort(error), sessionSignal);
|
|
177
|
+
const { ezsp } = adapter;
|
|
178
|
+
let captureReady = !networkId;
|
|
179
|
+
try {
|
|
180
|
+
sessionSignal.throwIfAborted();
|
|
181
|
+
if (mode !== 'reset') {
|
|
182
|
+
ezsp.on('stackStatus', status => {
|
|
183
|
+
if (status === SLStatus.NETWORK_DOWN) {
|
|
184
|
+
disconnected.abort(new Error('Network went down.'));
|
|
185
|
+
}
|
|
186
|
+
});
|
|
187
|
+
if (streaming) {
|
|
188
|
+
capture(ezsp, record => {
|
|
189
|
+
if (!captureReady || sessionSignal.aborted) {
|
|
190
|
+
return;
|
|
191
|
+
}
|
|
192
|
+
process.stdout.write(`${JSON.stringify(record)}\n`);
|
|
193
|
+
if (process.stdout.writableLength > 1024 * 1024) {
|
|
194
|
+
stop.abort(new Error('JSON output consumer is too slow.'));
|
|
195
|
+
}
|
|
196
|
+
});
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
const network = await attachNetwork(ezsp, options, join, sessionSignal);
|
|
200
|
+
sessionSignal.throwIfAborted();
|
|
201
|
+
if (options.graceful) {
|
|
202
|
+
const id = Buffer.from(network.extendedPanId);
|
|
203
|
+
if (networkId && !networkId.equals(id)) {
|
|
204
|
+
throw Object.assign(new Error('Adapter resumed a different Zigbee network.'), { code: 'NETWORK_CHANGED' });
|
|
205
|
+
}
|
|
206
|
+
networkId = id;
|
|
207
|
+
}
|
|
208
|
+
captureReady = true;
|
|
209
|
+
writeLog('info', `${join ? 'Joined' : 'Resumed'} PAN 0x${network.panId.toString(16)} on channel ${network.radioChannel}.`);
|
|
210
|
+
}
|
|
211
|
+
return {
|
|
212
|
+
...adapter,
|
|
213
|
+
signal: sessionSignal,
|
|
214
|
+
send: streaming ? createSender(ezsp, options.writeTimeout, sessionSignal) : undefined,
|
|
215
|
+
};
|
|
216
|
+
} catch (error) {
|
|
217
|
+
await closeSession(adapter);
|
|
218
|
+
throw error;
|
|
219
|
+
}
|
|
220
|
+
};
|
|
221
|
+
|
|
222
|
+
let session;
|
|
223
|
+
let closeSocket;
|
|
224
|
+
let monitor;
|
|
225
|
+
const watchSession = async () => {
|
|
226
|
+
for (;;) {
|
|
227
|
+
if (!session.signal.aborted) {
|
|
228
|
+
await once(session.signal, 'abort');
|
|
229
|
+
}
|
|
230
|
+
signal.throwIfAborted();
|
|
231
|
+
const error = session.signal.reason;
|
|
232
|
+
if (!options.graceful || error.code !== 'ADAPTER_DISCONNECTED') {
|
|
233
|
+
throw error;
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
const previous = session;
|
|
237
|
+
session = undefined;
|
|
238
|
+
writeLog('warning', error.message);
|
|
239
|
+
await closeSession(previous);
|
|
240
|
+
signal.throwIfAborted();
|
|
241
|
+
session = await reconnect(connect, options.graceful, signal);
|
|
242
|
+
}
|
|
243
|
+
};
|
|
244
|
+
|
|
125
245
|
process.on('SIGINT', interrupt);
|
|
126
246
|
process.on('SIGTERM', interrupt);
|
|
127
247
|
process.stdout.on('error', brokenPipe);
|
|
128
|
-
let session;
|
|
129
248
|
try {
|
|
130
|
-
session = await
|
|
131
|
-
signal.throwIfAborted();
|
|
132
|
-
const { ezsp } = session;
|
|
133
|
-
ezsp.on('ncpNeedsResetAndInit', () => stop.abort(new Error('Adapter needs a reset. Restart ember-router to resume.')));
|
|
249
|
+
session = await connect();
|
|
250
|
+
session.signal.throwIfAborted();
|
|
134
251
|
if (mode === 'reset') {
|
|
135
|
-
const eui64 = await resetRouter(ezsp, options, signal);
|
|
252
|
+
const eui64 = await resetRouter(session.ezsp, options, session.signal);
|
|
136
253
|
writeLog('info', 'Reset NVM3 tokens.');
|
|
137
254
|
writeLog('info', `Adapter EUI64: ${eui64}`);
|
|
138
255
|
return;
|
|
139
256
|
}
|
|
140
|
-
|
|
141
|
-
ezsp.on('stackStatus', status => {
|
|
142
|
-
if (status === SLStatus.NETWORK_DOWN && !signal.aborted) {
|
|
143
|
-
stop.abort(new Error('Network went down.'));
|
|
144
|
-
}
|
|
145
|
-
});
|
|
146
|
-
if (mode === 'run' || mode === 'write') {
|
|
147
|
-
capture(ezsp, record => {
|
|
148
|
-
if (signal.aborted) {
|
|
149
|
-
return;
|
|
150
|
-
}
|
|
151
|
-
process.stdout.write(`${JSON.stringify(record)}\n`);
|
|
152
|
-
if (process.stdout.writableLength > 1024 * 1024) {
|
|
153
|
-
stop.abort(new Error('JSON output consumer is too slow.'));
|
|
154
|
-
}
|
|
155
|
-
});
|
|
156
|
-
}
|
|
157
|
-
|
|
158
|
-
const network = await attachNetwork(ezsp, options, join, signal);
|
|
159
|
-
writeLog('info', `${join ? 'Joined' : 'Resumed'} PAN 0x${network.panId.toString(16)} on channel ${network.radioChannel}.`);
|
|
160
257
|
if (join) {
|
|
161
258
|
return;
|
|
162
259
|
}
|
|
163
260
|
|
|
164
|
-
|
|
261
|
+
const expect = { commandId: options.expect, timeout: options.readTimeout };
|
|
165
262
|
if (mode === 'read') {
|
|
166
|
-
|
|
167
|
-
return await sendPacket(ezsp, packet, 1, options.writeTimeout, signal, expect);
|
|
263
|
+
return await sendPacket(session.ezsp, packet, 1, options.writeTimeout, session.signal, expect);
|
|
168
264
|
}
|
|
169
265
|
|
|
170
|
-
|
|
266
|
+
monitor = watchSession().catch(error => stop.abort(error));
|
|
267
|
+
const send = (packet, expect, requestSignal) => {
|
|
268
|
+
if (!session) {
|
|
269
|
+
throw new Error('Adapter is reconnecting.');
|
|
270
|
+
}
|
|
271
|
+
return session.send(packet, expect, requestSignal);
|
|
272
|
+
};
|
|
273
|
+
if (options.socket !== undefined) {
|
|
274
|
+
const read = async (line, requestSignal) => {
|
|
275
|
+
try {
|
|
276
|
+
return await send(parsePacket(line), expect, requestSignal);
|
|
277
|
+
} catch (error) {
|
|
278
|
+
if (!requestSignal.aborted) {
|
|
279
|
+
writeLog('error', `Socket request: ${error.message}`);
|
|
280
|
+
}
|
|
281
|
+
return null;
|
|
282
|
+
}
|
|
283
|
+
};
|
|
284
|
+
closeSocket = await openRequestSocket(options.socket, read, signal, error => stop.abort(error));
|
|
285
|
+
}
|
|
286
|
+
await readWrites(send, signal);
|
|
171
287
|
if (!options.exitAfterWrite && !signal.aborted) {
|
|
172
288
|
await once(signal, 'abort');
|
|
173
289
|
}
|
|
@@ -177,12 +293,18 @@ async function run(options, mode, packet) {
|
|
|
177
293
|
throw error;
|
|
178
294
|
}
|
|
179
295
|
} finally {
|
|
296
|
+
stop.abort();
|
|
180
297
|
try {
|
|
181
|
-
await
|
|
298
|
+
await closeSocket?.();
|
|
182
299
|
} finally {
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
300
|
+
try {
|
|
301
|
+
await monitor;
|
|
302
|
+
await session?.close();
|
|
303
|
+
} finally {
|
|
304
|
+
process.off('SIGINT', interrupt);
|
|
305
|
+
process.off('SIGTERM', interrupt);
|
|
306
|
+
process.stdout.off('error', brokenPipe);
|
|
307
|
+
}
|
|
186
308
|
}
|
|
187
309
|
}
|
|
188
310
|
}
|
|
@@ -218,14 +340,23 @@ function readOptions(command) {
|
|
|
218
340
|
.option('--expect <commandId>', 'Expected ZCL reply command ID (inferred for attribute reads and writes)', integer(0, 255));
|
|
219
341
|
}
|
|
220
342
|
|
|
221
|
-
|
|
343
|
+
function gracefulOption() {
|
|
344
|
+
return new Option('-g, --graceful', 'Reconnect after adapter loss (-g once, -gg repeatedly)')
|
|
345
|
+
.argParser((_, count) => count + 1)
|
|
346
|
+
.default(0);
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
readOptions(program.command('run', { isDefault: true }))
|
|
350
|
+
.addOption(gracefulOption())
|
|
222
351
|
.description('Resume, stream received packets, and accept writes on stdin')
|
|
352
|
+
.option('--socket <path>', 'Listen for requests on a local IPC socket')
|
|
223
353
|
.action((_options, command) => {
|
|
224
354
|
const options = command.optsWithGlobals();
|
|
225
355
|
return run(options, 'run');
|
|
226
356
|
});
|
|
227
357
|
|
|
228
358
|
packetOptions(program.command('write'))
|
|
359
|
+
.addOption(gracefulOption())
|
|
229
360
|
.description('Resume and send packets from stdin, then exit at EOF')
|
|
230
361
|
.action((_options, command) => {
|
|
231
362
|
const options = command.optsWithGlobals();
|
package/package.json
CHANGED
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
import { once } from 'node:events';
|
|
2
|
+
import { createServer } from 'node:net';
|
|
3
|
+
|
|
4
|
+
const MAX_CLIENTS = 16;
|
|
5
|
+
const MAX_LINE_BYTES = 8192;
|
|
6
|
+
|
|
7
|
+
function validateSocketPath(path) {
|
|
8
|
+
if (process.platform === 'win32') {
|
|
9
|
+
if (typeof path !== 'string' || !/^\\\\[.?]\\pipe\\[^\\/\0]+$/i.test(path)) {
|
|
10
|
+
throw new Error('Expected a Windows named pipe path (\\\\.\\pipe\\name).');
|
|
11
|
+
}
|
|
12
|
+
} else {
|
|
13
|
+
if (typeof path !== 'string' || !path.startsWith('/') || path.includes('\0')) {
|
|
14
|
+
throw new Error('Expected an absolute Unix socket path.');
|
|
15
|
+
}
|
|
16
|
+
const maxPathBytes = process.platform === 'linux' ? 107 : 103;
|
|
17
|
+
if (Buffer.byteLength(path) > maxPathBytes) {
|
|
18
|
+
throw new Error(`Socket path is longer than ${maxPathBytes} bytes.`);
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
function checkLineLength(line) {
|
|
24
|
+
if (Buffer.byteLength(line) > MAX_LINE_BYTES) {
|
|
25
|
+
throw new Error(`Request line exceeds ${MAX_LINE_BYTES} bytes.`);
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
async function serveClient(socket, handleRequest, signal) {
|
|
30
|
+
const disconnected = new AbortController();
|
|
31
|
+
socket.once('close', () => disconnected.abort());
|
|
32
|
+
const requestSignal = AbortSignal.any([signal, disconnected.signal]);
|
|
33
|
+
|
|
34
|
+
const reply = async line => {
|
|
35
|
+
checkLineLength(line);
|
|
36
|
+
if (!line.trim()) {
|
|
37
|
+
return;
|
|
38
|
+
}
|
|
39
|
+
requestSignal.throwIfAborted();
|
|
40
|
+
const result = await handleRequest(line, requestSignal);
|
|
41
|
+
requestSignal.throwIfAborted();
|
|
42
|
+
await new Promise((resolve, reject) => {
|
|
43
|
+
socket.write(`${JSON.stringify(result)}\n`, error => error ? reject(error) : resolve());
|
|
44
|
+
});
|
|
45
|
+
};
|
|
46
|
+
|
|
47
|
+
let buffer = '';
|
|
48
|
+
// Keep replies writable after a client half-closes.
|
|
49
|
+
for await (const chunk of socket.setEncoding('utf8').iterator({ destroyOnReturn: false })) {
|
|
50
|
+
buffer += chunk;
|
|
51
|
+
let newline;
|
|
52
|
+
while ((newline = buffer.indexOf('\n')) !== -1) {
|
|
53
|
+
const line = buffer.slice(0, newline);
|
|
54
|
+
buffer = buffer.slice(newline + 1);
|
|
55
|
+
await reply(line);
|
|
56
|
+
}
|
|
57
|
+
checkLineLength(buffer);
|
|
58
|
+
}
|
|
59
|
+
await reply(buffer);
|
|
60
|
+
socket.end();
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export async function openRequestSocket(path, handleRequest, signal, onError) {
|
|
64
|
+
validateSocketPath(path);
|
|
65
|
+
signal.throwIfAborted();
|
|
66
|
+
|
|
67
|
+
const clients = new Set();
|
|
68
|
+
const server = createServer({ allowHalfOpen: true }, socket => {
|
|
69
|
+
clients.add(socket);
|
|
70
|
+
socket.on('error', () => socket.destroy());
|
|
71
|
+
socket.once('close', () => clients.delete(socket));
|
|
72
|
+
serveClient(socket, handleRequest, signal).catch(() => socket.destroy());
|
|
73
|
+
});
|
|
74
|
+
server.maxConnections = MAX_CLIENTS;
|
|
75
|
+
|
|
76
|
+
let closing;
|
|
77
|
+
const close = () => {
|
|
78
|
+
if (!closing) {
|
|
79
|
+
signal.removeEventListener('abort', abort);
|
|
80
|
+
closing = new Promise(resolve => server.close(() => resolve()));
|
|
81
|
+
for (const socket of clients) {
|
|
82
|
+
socket.destroy();
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
return closing;
|
|
86
|
+
};
|
|
87
|
+
const abort = () => {
|
|
88
|
+
void close();
|
|
89
|
+
};
|
|
90
|
+
|
|
91
|
+
await once(server.listen(path), 'listening');
|
|
92
|
+
if (signal.aborted) {
|
|
93
|
+
await close();
|
|
94
|
+
signal.throwIfAborted();
|
|
95
|
+
}
|
|
96
|
+
server.on('error', error => {
|
|
97
|
+
void close();
|
|
98
|
+
onError?.(error);
|
|
99
|
+
});
|
|
100
|
+
signal.addEventListener('abort', abort, { once: true });
|
|
101
|
+
return close;
|
|
102
|
+
}
|
package/router.js
CHANGED
|
@@ -22,6 +22,7 @@ const {
|
|
|
22
22
|
EmberNodeType,
|
|
23
23
|
EmberOutgoingMessageType,
|
|
24
24
|
EzspNetworkScanType,
|
|
25
|
+
EzspStatus,
|
|
25
26
|
SLStatus,
|
|
26
27
|
} = requireEmber('zigbee-herdsman/dist/adapter/ember/enums.js');
|
|
27
28
|
const { AdapterTransport } = requireEmber('zigbee-herdsman/dist/adapter/transport.js');
|
|
@@ -40,7 +41,7 @@ function check(status, operation, code) {
|
|
|
40
41
|
}
|
|
41
42
|
}
|
|
42
43
|
|
|
43
|
-
export async function openRouter(options, log) {
|
|
44
|
+
export async function openRouter(options, log, onDisconnect, signal) {
|
|
44
45
|
setLogger(Object.fromEntries(['debug', 'info', 'warning', 'error'].map(level => [
|
|
45
46
|
level,
|
|
46
47
|
(message, namespace) => log(level, message, namespace),
|
|
@@ -53,15 +54,61 @@ export async function openRouter(options, log) {
|
|
|
53
54
|
xon: !options.rtscts,
|
|
54
55
|
xoff: !options.rtscts,
|
|
55
56
|
});
|
|
56
|
-
|
|
57
|
+
let ezsp;
|
|
58
|
+
let disconnected;
|
|
59
|
+
let closing;
|
|
60
|
+
const adapterLost = message => {
|
|
61
|
+
if (!disconnected) {
|
|
62
|
+
disconnected = routerError(message, 'ADAPTER_DISCONNECTED');
|
|
63
|
+
onDisconnect?.(disconnected);
|
|
64
|
+
}
|
|
65
|
+
};
|
|
66
|
+
const onClose = error => adapterLost(error instanceof Error
|
|
67
|
+
? `Adapter transport closed: ${error.message}`
|
|
68
|
+
: 'Adapter transport closed.');
|
|
69
|
+
const onReset = status => adapterLost(`Adapter needs a reset: ${EzspStatus[status] ?? status}.`);
|
|
70
|
+
|
|
71
|
+
const close = () => closing ??= (async () => {
|
|
72
|
+
transport.off('close', onClose);
|
|
73
|
+
ezsp?.off('ncpNeedsResetAndInit', onReset);
|
|
74
|
+
if (!ezsp) {
|
|
75
|
+
await transport.close();
|
|
76
|
+
return;
|
|
77
|
+
}
|
|
78
|
+
try {
|
|
79
|
+
await emberStop(ezsp);
|
|
80
|
+
} catch (error) {
|
|
81
|
+
await transport.close().catch(closeError =>
|
|
82
|
+
log('warning', `Failed to close adapter transport: ${closeError.message}`));
|
|
83
|
+
throw error;
|
|
84
|
+
}
|
|
85
|
+
})();
|
|
57
86
|
|
|
87
|
+
const abortConnect = () => {
|
|
88
|
+
const socket = transport.socketInstance;
|
|
89
|
+
if (socket?.connecting) {
|
|
90
|
+
socket.destroy(signal.reason);
|
|
91
|
+
}
|
|
92
|
+
};
|
|
93
|
+
transport.once('close', onClose);
|
|
94
|
+
signal?.addEventListener('abort', abortConnect, { once: true });
|
|
58
95
|
try {
|
|
96
|
+
signal?.throwIfAborted();
|
|
97
|
+
ezsp = await emberStart(transport);
|
|
98
|
+
signal?.throwIfAborted();
|
|
99
|
+
ezsp.once('ncpNeedsResetAndInit', onReset);
|
|
59
100
|
await emberNetworkConfig(ezsp, DEFAULT_STACK_CONFIG, options.manufacturerCode);
|
|
60
101
|
await emberRegisterFixedEndpoints(ezsp, [], true);
|
|
61
|
-
|
|
102
|
+
signal?.throwIfAborted();
|
|
103
|
+
if (disconnected || !transport.isOpen) {
|
|
104
|
+
throw disconnected ?? routerError('Adapter connection closed during initialization.', 'ADAPTER_DISCONNECTED');
|
|
105
|
+
}
|
|
106
|
+
return { ezsp, close };
|
|
62
107
|
} catch (error) {
|
|
63
|
-
await
|
|
108
|
+
await close().catch(closeError => log('warning', `Failed to stop adapter: ${closeError.message}`));
|
|
64
109
|
throw error;
|
|
110
|
+
} finally {
|
|
111
|
+
signal?.removeEventListener('abort', abortConnect);
|
|
65
112
|
}
|
|
66
113
|
}
|
|
67
114
|
|
|
@@ -274,7 +321,7 @@ export async function attachNetwork(ezsp, options, join, signal) {
|
|
|
274
321
|
throw new Error('The adapter already has a saved network. Run without join to resume it.');
|
|
275
322
|
}
|
|
276
323
|
} else if (!join) {
|
|
277
|
-
throw
|
|
324
|
+
throw routerError('No saved network. Run ember-router join first.', 'NO_SAVED_NETWORK');
|
|
278
325
|
}
|
|
279
326
|
|
|
280
327
|
const stop = new AbortController();
|
|
@@ -311,7 +358,7 @@ async function verifyNetwork(ezsp, selected) {
|
|
|
311
358
|
const [parameterStatus, role, network] = await ezsp.ezspGetNetworkParameters();
|
|
312
359
|
check(parameterStatus, 'Read network parameters');
|
|
313
360
|
if (role !== EmberNodeType.ROUTER) {
|
|
314
|
-
throw
|
|
361
|
+
throw routerError('Saved network is not configured for a router.', 'WRONG_NODE_TYPE');
|
|
315
362
|
}
|
|
316
363
|
if (selected && (
|
|
317
364
|
network.panId !== selected.panId ||
|