ember-router 1.2.0 → 2.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/README.md +30 -35
- package/index.js +153 -74
- package/package.json +1 -1
- package/packet-wire.js +88 -0
- package/request-socket.js +4 -28
- package/router.js +75 -23
package/README.md
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
A command-line utility for using an EmberZNet adapter as a router on an existing Zigbee network. Ember Router connects over serial or TCP to an adapter running EmberZNet coordinator (NCP) firmware, following the approach described in the [ember-zli Router wiki](https://github.com/Nerivec/ember-zli/wiki/Router). It can join an open network or resume the network saved on the adapter.
|
|
4
4
|
|
|
5
|
-
The utility
|
|
5
|
+
The utility exchanges binary packets over stdin, stdout, or a local socket. It can send a finite batch or stay connected to receive packets and accept writes in the same session. The adapter can remain a router while powered after the CLI exits. Keep a session running to stream packets to the host.
|
|
6
6
|
|
|
7
7
|
## Installation
|
|
8
8
|
|
|
@@ -22,7 +22,7 @@ ember-router reset -p <path> --yes [options]
|
|
|
22
22
|
|
|
23
23
|
`run` is the default command (and can be omitted). It resumes the saved network, streams received packets to stdout, and accepts outgoing packets on stdin. With empty or closed stdin, it continues receiving.
|
|
24
24
|
|
|
25
|
-
`read` sends one
|
|
25
|
+
`read` sends one packet from stdin and writes the matching ZCL reply to stdout.
|
|
26
26
|
|
|
27
27
|
`write` resumes the saved network and sends a single packet or a batch from stdin. It exits after stdin closes and all submitted packets have been processed.
|
|
28
28
|
|
|
@@ -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 a zero-length record 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
|
|
|
@@ -57,7 +64,7 @@ ember-router reset -p <path> --yes [options]
|
|
|
57
64
|
|
|
58
65
|
`ember-router reset -p <path> --yes` leaves the saved Zigbee network, then resets the adapter's NVM3 tokens. If there is no saved network, it resets the tokens directly. This erases persisted adapter state. Back up tokens with ember-zli first if you need to restore that state.
|
|
59
66
|
|
|
60
|
-
After a successful reset,
|
|
67
|
+
After a successful reset, the adapter's EUI64, also called EUID, is reported on stderr.
|
|
61
68
|
|
|
62
69
|
- `--yes` confirms the reset (required).
|
|
63
70
|
- `--preserve-frame-counters` keeps the outgoing network and APS frame counter tokens.
|
|
@@ -73,60 +80,48 @@ ember-router join -p tcp://192.168.1.42:6638 -c 19 --pan-id 0x8cde
|
|
|
73
80
|
ember-router join -p tcp://192.168.1.42:6638 -c 19 -l 00112233445566778899aabbccddeeff
|
|
74
81
|
|
|
75
82
|
# Resume the saved network and receive packets
|
|
76
|
-
ember-router -p tcp://192.168.1.42:6638
|
|
83
|
+
ember-router -p tcp://192.168.1.42:6638 > capture.bin
|
|
77
84
|
|
|
78
85
|
# Send packets from stdin and keep receiving after stdin closes
|
|
79
|
-
|
|
86
|
+
ember-router run -p tcp://192.168.1.42:6638 < requests.bin > capture.bin
|
|
80
87
|
|
|
81
88
|
# Send a finite batch and exit
|
|
82
|
-
|
|
89
|
+
ember-router write -p tcp://192.168.1.42:6638 < requests.bin > capture.bin
|
|
83
90
|
|
|
84
91
|
# Leave network, reset the adapter and print the EUI64
|
|
85
92
|
ember-router reset -p tcp://192.168.1.42:6638 --yes
|
|
86
93
|
```
|
|
87
94
|
|
|
88
|
-
##
|
|
95
|
+
## Binary packet format
|
|
89
96
|
|
|
90
|
-
|
|
97
|
+
Starting with version 2.0, `read`, `write`, `run`, and `run --socket` use the same length-prefixed binary records. The addressing fields follow [Silicon Labs’ EZSP APS metadata](https://docs.silabs.com/zigbee/7.4/zigbee-stack-api/ember-aps-frame). The length prefix and record kind are specific to Ember Router. Payloads are raw Zigbee bytes. Diagnostics go to stderr.
|
|
91
98
|
|
|
92
|
-
|
|
93
|
-
{"type":"aps","source":4660,"sourceEndpoint":1,"destinationEndpoint":1,"profileId":260,"clusterId":513,"lqi":180,"payload":"1842011200299e07"}
|
|
94
|
-
```
|
|
95
|
-
|
|
96
|
-
`zdo` packets use the same frame fields. `touchlink` packets carry `panId`, `source`, `groupId`, `lqi`, and `payload`.
|
|
99
|
+
Each record starts with a two-byte unsigned little-endian body length. It excludes the length field itself. The first byte of the body is the record kind. All multi-byte values below are little-endian.
|
|
97
100
|
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
```
|
|
101
|
+
| Kind | Body fields after the kind byte, in order |
|
|
102
|
+
| --- | --- |
|
|
103
|
+
| `0x00` APS or ZDO | Short address (2), profile ID (2), cluster ID (2), source endpoint (1), destination endpoint (1), LQI (1), raw payload |
|
|
104
|
+
| `0x01` Touchlink | PAN ID (2), source EUI64 (8), group ID (2), LQI (1), raw payload |
|
|
103
105
|
|
|
104
|
-
For
|
|
106
|
+
Field sizes are in bytes. For APS sends, the short address is the destination and the LQI byte can be zero. The short address and LQI are the sender’s values on receive. Profile `0x0000` identifies a ZDO record. Stdin and socket clients send APS application unicasts. ZDO and Touchlink records are receive-only.
|
|
105
107
|
|
|
106
|
-
|
|
108
|
+
### Read an attribute
|
|
107
109
|
|
|
108
|
-
Read the occupied heating setpoint (`0x0012`) from
|
|
110
|
+
Read the occupied heating setpoint (`0x0012`) from short address `0x1234`, endpoint `1`, profile `0x0104`, and cluster `0x0201`. `xxd` converts the example hex to bytes and displays the binary reply.
|
|
109
111
|
|
|
110
112
|
```sh
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
EOF
|
|
113
|
+
printf '%s' 0f00003412040101020101001001001200 | xxd -r -p |
|
|
114
|
+
ember-router read -p tcp://192.168.1.42:6638 | xxd -g 1
|
|
114
115
|
```
|
|
115
116
|
|
|
116
|
-
The router
|
|
117
|
-
|
|
118
|
-
`read` prints the received packet, including matching ZCL Default Responses with an error status. A send failure or timeout reports an error on stderr and exits with status `1`.
|
|
119
|
-
|
|
120
|
-
```json
|
|
121
|
-
{"type":"aps","source":4660,"sourceEndpoint":1,"destinationEndpoint":1,"profileId":260,"clusterId":513,"lqi":180,"payload":"180101120000299e07"}
|
|
122
|
-
```
|
|
117
|
+
The request body is 15 bytes and ends with ZCL payload `10 01 00 12 00`. The router infers Read Attributes Response (`0x01`) or Write Attributes Response (`0x04`) for those requests. Use `--expect` to select a different ZCL reply command. `read` writes one matching record, including a matching ZCL Default Response with an error status. A send failure or timeout reports an error on stderr and exits with status `1`.
|
|
123
118
|
|
|
124
119
|
### Local socket
|
|
125
120
|
|
|
126
121
|
```sh
|
|
127
|
-
ember-router run -p tcp://192.168.1.42:6638 --socket /path/to/private/ember-router.sock
|
|
122
|
+
ember-router run -p tcp://192.168.1.42:6638 --socket /path/to/private/ember-router.sock > capture.bin
|
|
128
123
|
```
|
|
129
124
|
|
|
130
|
-
Send one
|
|
125
|
+
Send one record and receive one record in the same order on the same connection. A failed exchange returns `00 00` (a zero-length body) and logs the error on stderr. Keep the connection open until the replies arrive. The socket supports up to 16 clients and one active send on the adapter at a time.
|
|
131
126
|
|
|
132
127
|
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,9 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import { once } from 'node:events';
|
|
3
|
-
import {
|
|
2
|
+
import { addAbortListener, once } from 'node:events';
|
|
3
|
+
import { setTimeout as delay } from 'node:timers/promises';
|
|
4
4
|
import { Command, InvalidArgumentError, Option } from 'commander';
|
|
5
5
|
import packageJson from './package.json' with { type: 'json' };
|
|
6
|
+
import { decodeOutgoing, encodePacket, readRecords } from './packet-wire.js';
|
|
6
7
|
import { openRequestSocket } from './request-socket.js';
|
|
7
8
|
import { attachNetwork, capture, openRouter, resetRouter, sendPacket, SLStatus, Zcl } from './router.js';
|
|
8
9
|
|
|
@@ -36,25 +37,22 @@ function writeLog(level, message, namespace) {
|
|
|
36
37
|
process.stderr.write(`${prefix}: ${text}\n`);
|
|
37
38
|
}
|
|
38
39
|
|
|
39
|
-
function parsePacket(line) {
|
|
40
|
-
const packet = JSON.parse(line);
|
|
41
|
-
if (packet === null || typeof packet !== 'object' || Array.isArray(packet)) {
|
|
42
|
-
throw new Error('Expected a packet object.');
|
|
43
|
-
}
|
|
44
|
-
return packet;
|
|
45
|
-
}
|
|
46
|
-
|
|
47
40
|
function createSender(ezsp, timeout, signal) {
|
|
48
41
|
let tag = 0;
|
|
49
42
|
let pending = Promise.resolve();
|
|
50
|
-
return (packet, expect,
|
|
43
|
+
return (packet, expect, clientSignal) => {
|
|
44
|
+
const requestSignal = clientSignal ? AbortSignal.any([signal, clientSignal]) : signal;
|
|
51
45
|
const operation = pending.then(() => {
|
|
52
46
|
requestSignal.throwIfAborted();
|
|
53
47
|
tag = (tag + 1) & 0x7f;
|
|
54
48
|
return sendPacket(ezsp, packet, tag, timeout, requestSignal, expect);
|
|
55
49
|
});
|
|
56
50
|
pending = operation.catch(() => {});
|
|
57
|
-
|
|
51
|
+
// Release the caller on abort while the adapter queue drains.
|
|
52
|
+
return new Promise((resolve, reject) => {
|
|
53
|
+
const abort = addAbortListener(requestSignal, () => reject(requestSignal.reason));
|
|
54
|
+
operation.then(resolve, reject).finally(() => abort[Symbol.dispose]());
|
|
55
|
+
});
|
|
58
56
|
};
|
|
59
57
|
}
|
|
60
58
|
|
|
@@ -64,63 +62,79 @@ async function readWrites(send, signal) {
|
|
|
64
62
|
return;
|
|
65
63
|
}
|
|
66
64
|
|
|
67
|
-
const
|
|
68
|
-
|
|
69
|
-
signal.addEventListener('abort', closeInput, { once: true });
|
|
70
|
-
|
|
71
|
-
let lineNumber = 0;
|
|
65
|
+
const abort = addAbortListener(signal, () => stdin.destroy());
|
|
66
|
+
let recordNumber = 0;
|
|
72
67
|
try {
|
|
73
|
-
for await (const
|
|
68
|
+
for await (const body of readRecords(stdin)) {
|
|
74
69
|
if (signal.aborted) {
|
|
75
70
|
break;
|
|
76
71
|
}
|
|
77
72
|
|
|
78
|
-
|
|
79
|
-
if (!line.trim()) {
|
|
80
|
-
continue;
|
|
81
|
-
}
|
|
82
|
-
|
|
73
|
+
recordNumber++;
|
|
83
74
|
try {
|
|
84
|
-
await send(
|
|
75
|
+
await send(decodeOutgoing(body));
|
|
85
76
|
} catch (error) {
|
|
86
77
|
if (signal.aborted) {
|
|
87
78
|
break;
|
|
88
79
|
}
|
|
89
80
|
process.exitCode = 1;
|
|
90
|
-
writeLog('error', `Write
|
|
81
|
+
writeLog('error', `Write record ${recordNumber}: ${error.message}`);
|
|
91
82
|
}
|
|
92
83
|
}
|
|
84
|
+
} catch (error) {
|
|
85
|
+
signal.throwIfAborted();
|
|
86
|
+
throw error;
|
|
93
87
|
} finally {
|
|
94
|
-
|
|
95
|
-
input.close();
|
|
88
|
+
abort[Symbol.dispose]();
|
|
96
89
|
stdin.pause();
|
|
97
90
|
}
|
|
98
91
|
}
|
|
99
92
|
|
|
100
|
-
async function
|
|
93
|
+
async function readPacket() {
|
|
101
94
|
const { stdin } = process;
|
|
102
|
-
const input = createInterface({ input: stdin, crlfDelay: Infinity, terminal: false });
|
|
103
95
|
try {
|
|
104
|
-
for await (const
|
|
105
|
-
|
|
106
|
-
return line;
|
|
107
|
-
}
|
|
96
|
+
for await (const body of readRecords(stdin)) {
|
|
97
|
+
return decodeOutgoing(body);
|
|
108
98
|
}
|
|
109
99
|
throw new Error('Expected a packet on stdin.');
|
|
110
100
|
} finally {
|
|
111
|
-
input.close();
|
|
112
101
|
stdin.pause();
|
|
113
102
|
}
|
|
114
103
|
}
|
|
115
104
|
|
|
116
105
|
async function readOnce(options) {
|
|
117
|
-
const packet =
|
|
106
|
+
const packet = await readPacket();
|
|
118
107
|
const reply = await run(options, 'read', packet);
|
|
119
|
-
process.stdout.write(
|
|
108
|
+
process.stdout.write(encodePacket(reply));
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
async function closeSession(session) {
|
|
112
|
+
try {
|
|
113
|
+
await session.close();
|
|
114
|
+
} catch (error) {
|
|
115
|
+
writeLog('warning', `Could not close adapter: ${error.message}`);
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
async function reconnect(connect, graceful, signal) {
|
|
120
|
+
for (let backoff = 5000; ; backoff = Math.min(backoff * 2, 120_000)) {
|
|
121
|
+
writeLog('info', `Reconnecting to adapter in ${backoff / 1000} seconds.`);
|
|
122
|
+
await delay(backoff, undefined, { signal });
|
|
123
|
+
try {
|
|
124
|
+
return await connect();
|
|
125
|
+
} catch (error) {
|
|
126
|
+
signal.throwIfAborted();
|
|
127
|
+
if (graceful < 2 || ['NO_SAVED_NETWORK', 'WRONG_NODE_TYPE', 'NETWORK_CHANGED'].includes(error.code)) {
|
|
128
|
+
throw error;
|
|
129
|
+
}
|
|
130
|
+
writeLog('warning', `Could not reconnect to adapter: ${error.message}`);
|
|
131
|
+
}
|
|
132
|
+
}
|
|
120
133
|
}
|
|
121
134
|
|
|
122
135
|
async function run(options, mode, packet) {
|
|
123
136
|
const join = mode === 'join';
|
|
137
|
+
const streaming = mode === 'run' || mode === 'write';
|
|
124
138
|
const stop = new AbortController();
|
|
125
139
|
const { signal } = stop;
|
|
126
140
|
const interrupt = () => stop.abort();
|
|
@@ -137,57 +151,112 @@ async function run(options, mode, packet) {
|
|
|
137
151
|
writeLog(level, message, namespace);
|
|
138
152
|
}
|
|
139
153
|
};
|
|
154
|
+
|
|
155
|
+
let networkId;
|
|
156
|
+
const connect = async () => {
|
|
157
|
+
const disconnected = new AbortController();
|
|
158
|
+
const sessionSignal = AbortSignal.any([signal, disconnected.signal]);
|
|
159
|
+
const adapter = await openRouter(options, log, error => disconnected.abort(error), sessionSignal);
|
|
160
|
+
const { ezsp } = adapter;
|
|
161
|
+
let captureReady = !networkId;
|
|
162
|
+
try {
|
|
163
|
+
sessionSignal.throwIfAborted();
|
|
164
|
+
if (mode !== 'reset') {
|
|
165
|
+
ezsp.on('stackStatus', status => {
|
|
166
|
+
if (status === SLStatus.NETWORK_DOWN) {
|
|
167
|
+
disconnected.abort(new Error('Network went down.'));
|
|
168
|
+
}
|
|
169
|
+
});
|
|
170
|
+
if (streaming) {
|
|
171
|
+
capture(ezsp, record => {
|
|
172
|
+
if (!captureReady || sessionSignal.aborted) {
|
|
173
|
+
return;
|
|
174
|
+
}
|
|
175
|
+
process.stdout.write(encodePacket(record));
|
|
176
|
+
if (process.stdout.writableLength > 1024 * 1024) {
|
|
177
|
+
stop.abort(new Error('Packet output consumer is too slow.'));
|
|
178
|
+
}
|
|
179
|
+
});
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
const network = await attachNetwork(ezsp, options, join, sessionSignal);
|
|
183
|
+
sessionSignal.throwIfAborted();
|
|
184
|
+
if (options.graceful) {
|
|
185
|
+
const id = Buffer.from(network.extendedPanId);
|
|
186
|
+
if (networkId && !networkId.equals(id)) {
|
|
187
|
+
throw Object.assign(new Error('Adapter resumed a different Zigbee network.'), { code: 'NETWORK_CHANGED' });
|
|
188
|
+
}
|
|
189
|
+
networkId = id;
|
|
190
|
+
}
|
|
191
|
+
captureReady = true;
|
|
192
|
+
writeLog('info', `${join ? 'Joined' : 'Resumed'} PAN 0x${network.panId.toString(16)} on channel ${network.radioChannel}.`);
|
|
193
|
+
}
|
|
194
|
+
return {
|
|
195
|
+
...adapter,
|
|
196
|
+
signal: sessionSignal,
|
|
197
|
+
send: streaming ? createSender(ezsp, options.writeTimeout, sessionSignal) : undefined,
|
|
198
|
+
};
|
|
199
|
+
} catch (error) {
|
|
200
|
+
await closeSession(adapter);
|
|
201
|
+
throw error;
|
|
202
|
+
}
|
|
203
|
+
};
|
|
204
|
+
|
|
205
|
+
let session;
|
|
206
|
+
let closeSocket;
|
|
207
|
+
let monitor;
|
|
208
|
+
const watchSession = async () => {
|
|
209
|
+
for (;;) {
|
|
210
|
+
if (!session.signal.aborted) {
|
|
211
|
+
await once(session.signal, 'abort');
|
|
212
|
+
}
|
|
213
|
+
signal.throwIfAborted();
|
|
214
|
+
const error = session.signal.reason;
|
|
215
|
+
if (!options.graceful || error.code !== 'ADAPTER_DISCONNECTED') {
|
|
216
|
+
throw error;
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
const previous = session;
|
|
220
|
+
session = undefined;
|
|
221
|
+
writeLog('warning', error.message);
|
|
222
|
+
await closeSession(previous);
|
|
223
|
+
signal.throwIfAborted();
|
|
224
|
+
session = await reconnect(connect, options.graceful, signal);
|
|
225
|
+
}
|
|
226
|
+
};
|
|
227
|
+
|
|
140
228
|
process.on('SIGINT', interrupt);
|
|
141
229
|
process.on('SIGTERM', interrupt);
|
|
142
230
|
process.stdout.on('error', brokenPipe);
|
|
143
|
-
let session;
|
|
144
|
-
let closeSocket;
|
|
145
231
|
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.')));
|
|
232
|
+
session = await connect();
|
|
233
|
+
session.signal.throwIfAborted();
|
|
150
234
|
if (mode === 'reset') {
|
|
151
|
-
const eui64 = await resetRouter(ezsp, options, signal);
|
|
235
|
+
const eui64 = await resetRouter(session.ezsp, options, session.signal);
|
|
152
236
|
writeLog('info', 'Reset NVM3 tokens.');
|
|
153
237
|
writeLog('info', `Adapter EUI64: ${eui64}`);
|
|
154
238
|
return;
|
|
155
239
|
}
|
|
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
240
|
if (join) {
|
|
177
241
|
return;
|
|
178
242
|
}
|
|
179
243
|
|
|
180
|
-
signal.throwIfAborted();
|
|
181
244
|
const expect = { commandId: options.expect, timeout: options.readTimeout };
|
|
182
245
|
if (mode === 'read') {
|
|
183
|
-
return await sendPacket(ezsp, packet, 1, options.writeTimeout, signal, expect);
|
|
246
|
+
return await sendPacket(session.ezsp, packet, 1, options.writeTimeout, session.signal, expect);
|
|
184
247
|
}
|
|
185
248
|
|
|
186
|
-
|
|
249
|
+
monitor = watchSession().catch(error => stop.abort(error));
|
|
250
|
+
const send = (packet, expect, requestSignal) => {
|
|
251
|
+
if (!session) {
|
|
252
|
+
throw new Error('Adapter is reconnecting.');
|
|
253
|
+
}
|
|
254
|
+
return session.send(packet, expect, requestSignal);
|
|
255
|
+
};
|
|
187
256
|
if (options.socket !== undefined) {
|
|
188
|
-
const read = async (
|
|
257
|
+
const read = async (body, requestSignal) => {
|
|
189
258
|
try {
|
|
190
|
-
return await send(
|
|
259
|
+
return await send(decodeOutgoing(body), expect, requestSignal);
|
|
191
260
|
} catch (error) {
|
|
192
261
|
if (!requestSignal.aborted) {
|
|
193
262
|
writeLog('error', `Socket request: ${error.message}`);
|
|
@@ -207,16 +276,18 @@ async function run(options, mode, packet) {
|
|
|
207
276
|
throw error;
|
|
208
277
|
}
|
|
209
278
|
} finally {
|
|
279
|
+
stop.abort();
|
|
210
280
|
try {
|
|
281
|
+
await closeSocket?.();
|
|
282
|
+
} finally {
|
|
211
283
|
try {
|
|
212
|
-
await
|
|
213
|
-
} finally {
|
|
284
|
+
await monitor;
|
|
214
285
|
await session?.close();
|
|
286
|
+
} finally {
|
|
287
|
+
process.off('SIGINT', interrupt);
|
|
288
|
+
process.off('SIGTERM', interrupt);
|
|
289
|
+
process.stdout.off('error', brokenPipe);
|
|
215
290
|
}
|
|
216
|
-
} finally {
|
|
217
|
-
process.off('SIGINT', interrupt);
|
|
218
|
-
process.off('SIGTERM', interrupt);
|
|
219
|
-
process.stdout.off('error', brokenPipe);
|
|
220
291
|
}
|
|
221
292
|
}
|
|
222
293
|
}
|
|
@@ -252,7 +323,14 @@ function readOptions(command) {
|
|
|
252
323
|
.option('--expect <commandId>', 'Expected ZCL reply command ID (inferred for attribute reads and writes)', integer(0, 255));
|
|
253
324
|
}
|
|
254
325
|
|
|
326
|
+
function gracefulOption() {
|
|
327
|
+
return new Option('-g, --graceful', 'Reconnect after adapter loss (-g once, -gg repeatedly)')
|
|
328
|
+
.argParser((_, count) => count + 1)
|
|
329
|
+
.default(0);
|
|
330
|
+
}
|
|
331
|
+
|
|
255
332
|
readOptions(program.command('run', { isDefault: true }))
|
|
333
|
+
.addOption(gracefulOption())
|
|
256
334
|
.description('Resume, stream received packets, and accept writes on stdin')
|
|
257
335
|
.option('--socket <path>', 'Listen for requests on a local IPC socket')
|
|
258
336
|
.action((_options, command) => {
|
|
@@ -261,6 +339,7 @@ readOptions(program.command('run', { isDefault: true }))
|
|
|
261
339
|
});
|
|
262
340
|
|
|
263
341
|
packetOptions(program.command('write'))
|
|
342
|
+
.addOption(gracefulOption())
|
|
264
343
|
.description('Resume and send packets from stdin, then exit at EOF')
|
|
265
344
|
.action((_options, command) => {
|
|
266
345
|
const options = command.optsWithGlobals();
|
package/package.json
CHANGED
package/packet-wire.js
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
const LENGTH_BYTES = 2;
|
|
2
|
+
const APS_KIND = 0;
|
|
3
|
+
const TOUCHLINK_KIND = 1;
|
|
4
|
+
const APS_HEADER_BYTES = 10;
|
|
5
|
+
const TOUCHLINK_HEADER_BYTES = 14;
|
|
6
|
+
|
|
7
|
+
export function encodePacket(packet) {
|
|
8
|
+
if (packet === null) {
|
|
9
|
+
return Buffer.alloc(LENGTH_BYTES);
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
const touchlink = packet.type === 'touchlink';
|
|
13
|
+
if (!touchlink && packet.type !== 'aps' && packet.type !== 'zdo') {
|
|
14
|
+
throw new TypeError(`Unsupported packet type: ${packet.type}.`);
|
|
15
|
+
}
|
|
16
|
+
const headerBytes = touchlink ? TOUCHLINK_HEADER_BYTES : APS_HEADER_BYTES;
|
|
17
|
+
const length = headerBytes + packet.payload.length;
|
|
18
|
+
if (length > 0xffff) {
|
|
19
|
+
throw new RangeError('Packet exceeds the maximum record length.');
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
const record = Buffer.allocUnsafe(LENGTH_BYTES + length);
|
|
23
|
+
record.writeUInt16LE(length);
|
|
24
|
+
const body = record.subarray(LENGTH_BYTES);
|
|
25
|
+
if (touchlink) {
|
|
26
|
+
body[0] = TOUCHLINK_KIND;
|
|
27
|
+
body.writeUInt16LE(packet.panId, 1);
|
|
28
|
+
body.writeBigUInt64LE(BigInt(packet.source), 3);
|
|
29
|
+
body.writeUInt16LE(packet.groupId, 11);
|
|
30
|
+
body[13] = packet.lqi;
|
|
31
|
+
} else {
|
|
32
|
+
body[0] = APS_KIND;
|
|
33
|
+
body.writeUInt16LE(packet.source, 1);
|
|
34
|
+
body.writeUInt16LE(packet.profileId, 3);
|
|
35
|
+
body.writeUInt16LE(packet.clusterId, 5);
|
|
36
|
+
body[7] = packet.sourceEndpoint;
|
|
37
|
+
body[8] = packet.destinationEndpoint;
|
|
38
|
+
body[9] = packet.lqi;
|
|
39
|
+
}
|
|
40
|
+
packet.payload.copy(body, headerBytes);
|
|
41
|
+
return record;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export function decodeOutgoing(body) {
|
|
45
|
+
if (body.length < APS_HEADER_BYTES || body[0] !== APS_KIND) {
|
|
46
|
+
throw new Error('Expected an APS packet.');
|
|
47
|
+
}
|
|
48
|
+
return {
|
|
49
|
+
destination: body.readUInt16LE(1),
|
|
50
|
+
profileId: body.readUInt16LE(3),
|
|
51
|
+
clusterId: body.readUInt16LE(5),
|
|
52
|
+
sourceEndpoint: body[7],
|
|
53
|
+
destinationEndpoint: body[8],
|
|
54
|
+
payload: body.subarray(APS_HEADER_BYTES),
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export async function* readRecords(stream) {
|
|
59
|
+
const length = Buffer.allocUnsafe(LENGTH_BYTES);
|
|
60
|
+
let buffer = length;
|
|
61
|
+
let written = 0;
|
|
62
|
+
|
|
63
|
+
for await (const chunk of stream.iterator({ destroyOnReturn: false })) {
|
|
64
|
+
for (let offset = 0; offset < chunk.length;) {
|
|
65
|
+
const copied = chunk.copy(buffer, written, offset, offset + buffer.length - written);
|
|
66
|
+
offset += copied;
|
|
67
|
+
written += copied;
|
|
68
|
+
if (written < buffer.length) {
|
|
69
|
+
continue;
|
|
70
|
+
}
|
|
71
|
+
if (buffer === length) {
|
|
72
|
+
buffer = Buffer.allocUnsafe(length.readUInt16LE());
|
|
73
|
+
written = 0;
|
|
74
|
+
if (buffer.length) {
|
|
75
|
+
continue;
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
const body = buffer;
|
|
80
|
+
buffer = length;
|
|
81
|
+
written = 0;
|
|
82
|
+
yield body;
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
if (buffer !== length || written !== 0) {
|
|
86
|
+
throw new Error('Truncated packet record.');
|
|
87
|
+
}
|
|
88
|
+
}
|
package/request-socket.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { once } from 'node:events';
|
|
2
2
|
import { createServer } from 'node:net';
|
|
3
|
+
import { encodePacket, readRecords } from "./packet-wire.js";
|
|
3
4
|
|
|
4
5
|
const MAX_CLIENTS = 16;
|
|
5
|
-
const MAX_LINE_BYTES = 8192;
|
|
6
6
|
|
|
7
7
|
function validateSocketPath(path) {
|
|
8
8
|
if (process.platform === 'win32') {
|
|
@@ -20,43 +20,19 @@ function validateSocketPath(path) {
|
|
|
20
20
|
}
|
|
21
21
|
}
|
|
22
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
23
|
async function serveClient(socket, handleRequest, signal) {
|
|
30
24
|
const disconnected = new AbortController();
|
|
31
25
|
socket.once('close', () => disconnected.abort());
|
|
32
26
|
const requestSignal = AbortSignal.any([signal, disconnected.signal]);
|
|
33
27
|
|
|
34
|
-
|
|
35
|
-
checkLineLength(line);
|
|
36
|
-
if (!line.trim()) {
|
|
37
|
-
return;
|
|
38
|
-
}
|
|
28
|
+
for await (const body of readRecords(socket)) {
|
|
39
29
|
requestSignal.throwIfAborted();
|
|
40
|
-
const result = await handleRequest(
|
|
30
|
+
const result = await handleRequest(body, requestSignal);
|
|
41
31
|
requestSignal.throwIfAborted();
|
|
42
32
|
await new Promise((resolve, reject) => {
|
|
43
|
-
socket.write(
|
|
33
|
+
socket.write(encodePacket(result), error => error ? reject(error) : resolve());
|
|
44
34
|
});
|
|
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
35
|
}
|
|
59
|
-
await reply(buffer);
|
|
60
36
|
socket.end();
|
|
61
37
|
}
|
|
62
38
|
|
package/router.js
CHANGED
|
@@ -22,11 +22,13 @@ 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');
|
|
28
29
|
const { DEFAULT_STACK_CONFIG } = requireEmber('zigbee-herdsman/dist/adapter/ember/adapter/emberAdapter.js');
|
|
29
30
|
const { STACK_PROFILE_ZIGBEE_PRO } = requireEmber('zigbee-herdsman/dist/adapter/ember/consts.js');
|
|
31
|
+
const { EZSP_EXTENDED_PARAMETERS_INDEX, EZSP_MAX_FRAME_LENGTH } = requireEmber('zigbee-herdsman/dist/adapter/ember/ezsp/consts.js');
|
|
30
32
|
|
|
31
33
|
export { SLStatus, Zcl };
|
|
32
34
|
|
|
@@ -40,7 +42,7 @@ function check(status, operation, code) {
|
|
|
40
42
|
}
|
|
41
43
|
}
|
|
42
44
|
|
|
43
|
-
export async function openRouter(options, log) {
|
|
45
|
+
export async function openRouter(options, log, onDisconnect, signal) {
|
|
44
46
|
setLogger(Object.fromEntries(['debug', 'info', 'warning', 'error'].map(level => [
|
|
45
47
|
level,
|
|
46
48
|
(message, namespace) => log(level, message, namespace),
|
|
@@ -53,15 +55,61 @@ export async function openRouter(options, log) {
|
|
|
53
55
|
xon: !options.rtscts,
|
|
54
56
|
xoff: !options.rtscts,
|
|
55
57
|
});
|
|
56
|
-
|
|
58
|
+
let ezsp;
|
|
59
|
+
let disconnected;
|
|
60
|
+
let closing;
|
|
61
|
+
const adapterLost = message => {
|
|
62
|
+
if (!disconnected) {
|
|
63
|
+
disconnected = routerError(message, 'ADAPTER_DISCONNECTED');
|
|
64
|
+
onDisconnect?.(disconnected);
|
|
65
|
+
}
|
|
66
|
+
};
|
|
67
|
+
const onClose = error => adapterLost(error instanceof Error
|
|
68
|
+
? `Adapter transport closed: ${error.message}`
|
|
69
|
+
: 'Adapter transport closed.');
|
|
70
|
+
const onReset = status => adapterLost(`Adapter needs a reset: ${EzspStatus[status] ?? status}.`);
|
|
71
|
+
|
|
72
|
+
const close = () => closing ??= (async () => {
|
|
73
|
+
transport.off('close', onClose);
|
|
74
|
+
ezsp?.off('ncpNeedsResetAndInit', onReset);
|
|
75
|
+
if (!ezsp) {
|
|
76
|
+
await transport.close();
|
|
77
|
+
return;
|
|
78
|
+
}
|
|
79
|
+
try {
|
|
80
|
+
await emberStop(ezsp);
|
|
81
|
+
} catch (error) {
|
|
82
|
+
await transport.close().catch(closeError =>
|
|
83
|
+
log('warning', `Failed to close adapter transport: ${closeError.message}`));
|
|
84
|
+
throw error;
|
|
85
|
+
}
|
|
86
|
+
})();
|
|
57
87
|
|
|
88
|
+
const abortConnect = () => {
|
|
89
|
+
const socket = transport.socketInstance;
|
|
90
|
+
if (socket?.connecting) {
|
|
91
|
+
socket.destroy(signal.reason);
|
|
92
|
+
}
|
|
93
|
+
};
|
|
94
|
+
transport.once('close', onClose);
|
|
95
|
+
signal?.addEventListener('abort', abortConnect, { once: true });
|
|
58
96
|
try {
|
|
97
|
+
signal?.throwIfAborted();
|
|
98
|
+
ezsp = await emberStart(transport);
|
|
99
|
+
signal?.throwIfAborted();
|
|
100
|
+
ezsp.once('ncpNeedsResetAndInit', onReset);
|
|
59
101
|
await emberNetworkConfig(ezsp, DEFAULT_STACK_CONFIG, options.manufacturerCode);
|
|
60
102
|
await emberRegisterFixedEndpoints(ezsp, [], true);
|
|
61
|
-
|
|
103
|
+
signal?.throwIfAborted();
|
|
104
|
+
if (disconnected || !transport.isOpen) {
|
|
105
|
+
throw disconnected ?? routerError('Adapter connection closed during initialization.', 'ADAPTER_DISCONNECTED');
|
|
106
|
+
}
|
|
107
|
+
return { ezsp, close };
|
|
62
108
|
} catch (error) {
|
|
63
|
-
await
|
|
109
|
+
await close().catch(closeError => log('warning', `Failed to stop adapter: ${closeError.message}`));
|
|
64
110
|
throw error;
|
|
111
|
+
} finally {
|
|
112
|
+
signal?.removeEventListener('abort', abortConnect);
|
|
65
113
|
}
|
|
66
114
|
}
|
|
67
115
|
|
|
@@ -69,8 +117,17 @@ function pendingEvent(timeout, signal, subscribe, description = 'adapter callbac
|
|
|
69
117
|
let unsubscribe;
|
|
70
118
|
let timer;
|
|
71
119
|
let abort;
|
|
120
|
+
const close = () => {
|
|
121
|
+
clearTimeout(timer);
|
|
122
|
+
signal.removeEventListener('abort', abort);
|
|
123
|
+
unsubscribe?.();
|
|
124
|
+
unsubscribe = undefined;
|
|
125
|
+
};
|
|
72
126
|
const promise = new Promise((resolve, reject) => {
|
|
73
|
-
abort = () =>
|
|
127
|
+
abort = () => {
|
|
128
|
+
close();
|
|
129
|
+
reject(signal.reason);
|
|
130
|
+
};
|
|
74
131
|
signal.addEventListener('abort', abort, { once: true });
|
|
75
132
|
try {
|
|
76
133
|
signal.throwIfAborted();
|
|
@@ -81,14 +138,7 @@ function pendingEvent(timeout, signal, subscribe, description = 'adapter callbac
|
|
|
81
138
|
}
|
|
82
139
|
});
|
|
83
140
|
promise.catch(() => {});
|
|
84
|
-
return {
|
|
85
|
-
promise,
|
|
86
|
-
close() {
|
|
87
|
-
clearTimeout(timer);
|
|
88
|
-
signal.removeEventListener('abort', abort);
|
|
89
|
-
unsubscribe?.();
|
|
90
|
-
},
|
|
91
|
-
};
|
|
141
|
+
return { promise, close };
|
|
92
142
|
}
|
|
93
143
|
|
|
94
144
|
async function networkCommand(ezsp, command, timeout, signal, expectedStatus = SLStatus.NETWORK_UP) {
|
|
@@ -255,7 +305,7 @@ function listenForInterview(ezsp, timeout, signal) {
|
|
|
255
305
|
destination: sender,
|
|
256
306
|
destinationEndpoint: frame.sourceEndpoint,
|
|
257
307
|
clusterId: frame.clusterId,
|
|
258
|
-
payload: answer.payload
|
|
308
|
+
payload: answer.payload,
|
|
259
309
|
}, tag, timeout, signal);
|
|
260
310
|
if (answer.complete) {
|
|
261
311
|
complete.resolve();
|
|
@@ -274,7 +324,7 @@ export async function attachNetwork(ezsp, options, join, signal) {
|
|
|
274
324
|
throw new Error('The adapter already has a saved network. Run without join to resume it.');
|
|
275
325
|
}
|
|
276
326
|
} else if (!join) {
|
|
277
|
-
throw
|
|
327
|
+
throw routerError('No saved network. Run ember-router join first.', 'NO_SAVED_NETWORK');
|
|
278
328
|
}
|
|
279
329
|
|
|
280
330
|
const stop = new AbortController();
|
|
@@ -311,7 +361,7 @@ async function verifyNetwork(ezsp, selected) {
|
|
|
311
361
|
const [parameterStatus, role, network] = await ezsp.ezspGetNetworkParameters();
|
|
312
362
|
check(parameterStatus, 'Read network parameters');
|
|
313
363
|
if (role !== EmberNodeType.ROUTER) {
|
|
314
|
-
throw
|
|
364
|
+
throw routerError('Saved network is not configured for a router.', 'WRONG_NODE_TYPE');
|
|
315
365
|
}
|
|
316
366
|
if (selected && (
|
|
317
367
|
network.panId !== selected.panId ||
|
|
@@ -385,14 +435,14 @@ function apsPacket(frame, source, lqi, payload) {
|
|
|
385
435
|
profileId: frame.profileId,
|
|
386
436
|
clusterId: frame.clusterId,
|
|
387
437
|
lqi,
|
|
388
|
-
payload
|
|
438
|
+
payload,
|
|
389
439
|
};
|
|
390
440
|
}
|
|
391
441
|
|
|
392
442
|
export function capture(ezsp, emit) {
|
|
393
443
|
observeAps(ezsp, (_type, frame, lqi, source, payload) => emit(apsPacket(frame, source, lqi, payload)));
|
|
394
444
|
ezsp.on('touchlinkMessage', (panId, source, groupId, lqi, payload) =>
|
|
395
|
-
emit({ type: 'touchlink', panId, source, groupId, lqi, payload
|
|
445
|
+
emit({ type: 'touchlink', panId, source, groupId, lqi, payload }));
|
|
396
446
|
}
|
|
397
447
|
|
|
398
448
|
const attributeReplies = new Map([
|
|
@@ -431,12 +481,14 @@ export async function sendPacket(ezsp, packet, tag, timeout, signal, expect) {
|
|
|
431
481
|
throw routerError(`Invalid ${label}.`, 'INVALID_PACKET');
|
|
432
482
|
}
|
|
433
483
|
}
|
|
434
|
-
|
|
435
|
-
|
|
484
|
+
// SEND_UNICAST uses three bytes for mode and destination, eleven for the APS frame, and one for payload length.
|
|
485
|
+
const messageTagLength = ezsp.version < 0x0e ? 1 : 2;
|
|
486
|
+
const maxPayloadLength = EZSP_MAX_FRAME_LENGTH - EZSP_EXTENDED_PARAMETERS_INDEX - 3 - 11 - messageTagLength - 1;
|
|
487
|
+
if (!Buffer.isBuffer(payload) || payload.length === 0 || payload.length > maxPayloadLength) {
|
|
488
|
+
throw routerError(`payload must contain 1 to ${maxPayloadLength} bytes.`, 'INVALID_PACKET');
|
|
436
489
|
}
|
|
437
490
|
|
|
438
|
-
const
|
|
439
|
-
const request = expect && Zcl.Header.fromBuffer(message);
|
|
491
|
+
const request = expect && Zcl.Header.fromBuffer(payload);
|
|
440
492
|
if (expect && (!request || !(request.isGlobal || request.isSpecific) || request.frameControl.reservedBits !== 0)) {
|
|
441
493
|
throw routerError('payload must have a valid ZCL header to match a reply.', 'INVALID_PACKET');
|
|
442
494
|
}
|
|
@@ -474,7 +526,7 @@ export async function sendPacket(ezsp, packet, tag, timeout, signal, expect) {
|
|
|
474
526
|
}), 'ZCL reply', 'REPLY_TIMEOUT');
|
|
475
527
|
try {
|
|
476
528
|
signal.throwIfAborted();
|
|
477
|
-
const [status] = await ezsp.ezspSendUnicast(EmberOutgoingMessageType.DIRECT, destination, aps, tag,
|
|
529
|
+
const [status] = await ezsp.ezspSendUnicast(EmberOutgoingMessageType.DIRECT, destination, aps, tag, payload);
|
|
478
530
|
check(status, 'Queue write', 'QUEUE_FAILED');
|
|
479
531
|
const delivered = delivery.promise.then(result => check(result, 'Deliver write', 'DELIVERY_FAILED'));
|
|
480
532
|
if (!reply) {
|