ember-router 1.2.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 +9 -2
- package/index.js +135 -39
- package/package.json +1 -1
- package/router.js +53 -6
package/README.md
CHANGED
|
@@ -33,11 +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
|
-
- `-v, --verbose` for more diagnostics on stderr. Repeat for debug output during `run`.
|
|
37
|
-
- `--write-timeout <ms>` for `run`, `write`, and `read` to set the APS delivery timeout (default `15000`).
|
|
38
36
|
- `--read-timeout <ms>` for `read` and `run --socket` to set the ZCL reply timeout (default `5000`, range `100`–`300000`).
|
|
37
|
+
- `--write-timeout <ms>` for `run`, `write`, and `read` to set the APS delivery timeout (default `15000`).
|
|
39
38
|
- `--expect <commandId>` for `read` and `run --socket` to select the ZCL reply command by decimal or `0x` value.
|
|
40
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.
|
|
41
48
|
|
|
42
49
|
#### Joining networks
|
|
43
50
|
|
package/index.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
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' };
|
|
6
7
|
import { openRequestSocket } from './request-socket.js';
|
|
@@ -47,14 +48,19 @@ function parsePacket(line) {
|
|
|
47
48
|
function createSender(ezsp, timeout, signal) {
|
|
48
49
|
let tag = 0;
|
|
49
50
|
let pending = Promise.resolve();
|
|
50
|
-
return (packet, expect,
|
|
51
|
+
return (packet, expect, clientSignal) => {
|
|
52
|
+
const requestSignal = clientSignal ? AbortSignal.any([signal, clientSignal]) : signal;
|
|
51
53
|
const operation = pending.then(() => {
|
|
52
54
|
requestSignal.throwIfAborted();
|
|
53
55
|
tag = (tag + 1) & 0x7f;
|
|
54
56
|
return sendPacket(ezsp, packet, tag, timeout, requestSignal, expect);
|
|
55
57
|
});
|
|
56
58
|
pending = operation.catch(() => {});
|
|
57
|
-
|
|
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
|
+
});
|
|
58
64
|
};
|
|
59
65
|
}
|
|
60
66
|
|
|
@@ -119,8 +125,33 @@ async function readOnce(options) {
|
|
|
119
125
|
process.stdout.write(`${JSON.stringify(reply)}\n`);
|
|
120
126
|
}
|
|
121
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
|
+
|
|
122
152
|
async function run(options, mode, packet) {
|
|
123
153
|
const join = mode === 'join';
|
|
154
|
+
const streaming = mode === 'run' || mode === 'write';
|
|
124
155
|
const stop = new AbortController();
|
|
125
156
|
const { signal } = stop;
|
|
126
157
|
const interrupt = () => stop.abort();
|
|
@@ -137,53 +168,108 @@ async function run(options, mode, packet) {
|
|
|
137
168
|
writeLog(level, message, namespace);
|
|
138
169
|
}
|
|
139
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
|
+
|
|
140
245
|
process.on('SIGINT', interrupt);
|
|
141
246
|
process.on('SIGTERM', interrupt);
|
|
142
247
|
process.stdout.on('error', brokenPipe);
|
|
143
|
-
let session;
|
|
144
|
-
let closeSocket;
|
|
145
248
|
try {
|
|
146
|
-
session = await
|
|
147
|
-
signal.throwIfAborted();
|
|
148
|
-
const { ezsp } = session;
|
|
149
|
-
ezsp.on('ncpNeedsResetAndInit', () => stop.abort(new Error('Adapter needs a reset. Restart ember-router to resume.')));
|
|
249
|
+
session = await connect();
|
|
250
|
+
session.signal.throwIfAborted();
|
|
150
251
|
if (mode === 'reset') {
|
|
151
|
-
const eui64 = await resetRouter(ezsp, options, signal);
|
|
252
|
+
const eui64 = await resetRouter(session.ezsp, options, session.signal);
|
|
152
253
|
writeLog('info', 'Reset NVM3 tokens.');
|
|
153
254
|
writeLog('info', `Adapter EUI64: ${eui64}`);
|
|
154
255
|
return;
|
|
155
256
|
}
|
|
156
|
-
|
|
157
|
-
ezsp.on('stackStatus', status => {
|
|
158
|
-
if (status === SLStatus.NETWORK_DOWN && !signal.aborted) {
|
|
159
|
-
stop.abort(new Error('Network went down.'));
|
|
160
|
-
}
|
|
161
|
-
});
|
|
162
|
-
if (mode === 'run' || mode === 'write') {
|
|
163
|
-
capture(ezsp, record => {
|
|
164
|
-
if (signal.aborted) {
|
|
165
|
-
return;
|
|
166
|
-
}
|
|
167
|
-
process.stdout.write(`${JSON.stringify(record)}\n`);
|
|
168
|
-
if (process.stdout.writableLength > 1024 * 1024) {
|
|
169
|
-
stop.abort(new Error('JSON output consumer is too slow.'));
|
|
170
|
-
}
|
|
171
|
-
});
|
|
172
|
-
}
|
|
173
|
-
|
|
174
|
-
const network = await attachNetwork(ezsp, options, join, signal);
|
|
175
|
-
writeLog('info', `${join ? 'Joined' : 'Resumed'} PAN 0x${network.panId.toString(16)} on channel ${network.radioChannel}.`);
|
|
176
257
|
if (join) {
|
|
177
258
|
return;
|
|
178
259
|
}
|
|
179
260
|
|
|
180
|
-
signal.throwIfAborted();
|
|
181
261
|
const expect = { commandId: options.expect, timeout: options.readTimeout };
|
|
182
262
|
if (mode === 'read') {
|
|
183
|
-
return await sendPacket(ezsp, packet, 1, options.writeTimeout, signal, expect);
|
|
263
|
+
return await sendPacket(session.ezsp, packet, 1, options.writeTimeout, session.signal, expect);
|
|
184
264
|
}
|
|
185
265
|
|
|
186
|
-
|
|
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
|
+
};
|
|
187
273
|
if (options.socket !== undefined) {
|
|
188
274
|
const read = async (line, requestSignal) => {
|
|
189
275
|
try {
|
|
@@ -207,16 +293,18 @@ async function run(options, mode, packet) {
|
|
|
207
293
|
throw error;
|
|
208
294
|
}
|
|
209
295
|
} finally {
|
|
296
|
+
stop.abort();
|
|
210
297
|
try {
|
|
298
|
+
await closeSocket?.();
|
|
299
|
+
} finally {
|
|
211
300
|
try {
|
|
212
|
-
await
|
|
213
|
-
} finally {
|
|
301
|
+
await monitor;
|
|
214
302
|
await session?.close();
|
|
303
|
+
} finally {
|
|
304
|
+
process.off('SIGINT', interrupt);
|
|
305
|
+
process.off('SIGTERM', interrupt);
|
|
306
|
+
process.stdout.off('error', brokenPipe);
|
|
215
307
|
}
|
|
216
|
-
} finally {
|
|
217
|
-
process.off('SIGINT', interrupt);
|
|
218
|
-
process.off('SIGTERM', interrupt);
|
|
219
|
-
process.stdout.off('error', brokenPipe);
|
|
220
308
|
}
|
|
221
309
|
}
|
|
222
310
|
}
|
|
@@ -252,7 +340,14 @@ function readOptions(command) {
|
|
|
252
340
|
.option('--expect <commandId>', 'Expected ZCL reply command ID (inferred for attribute reads and writes)', integer(0, 255));
|
|
253
341
|
}
|
|
254
342
|
|
|
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
|
+
|
|
255
349
|
readOptions(program.command('run', { isDefault: true }))
|
|
350
|
+
.addOption(gracefulOption())
|
|
256
351
|
.description('Resume, stream received packets, and accept writes on stdin')
|
|
257
352
|
.option('--socket <path>', 'Listen for requests on a local IPC socket')
|
|
258
353
|
.action((_options, command) => {
|
|
@@ -261,6 +356,7 @@ readOptions(program.command('run', { isDefault: true }))
|
|
|
261
356
|
});
|
|
262
357
|
|
|
263
358
|
packetOptions(program.command('write'))
|
|
359
|
+
.addOption(gracefulOption())
|
|
264
360
|
.description('Resume and send packets from stdin, then exit at EOF')
|
|
265
361
|
.action((_options, command) => {
|
|
266
362
|
const options = command.optsWithGlobals();
|
package/package.json
CHANGED
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 ||
|