ember-router 0.0.0-stage → 1.1.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 +120 -2
- package/index.js +256 -0
- package/interview.js +109 -0
- package/package.json +30 -3
- package/router.js +498 -0
- package/silence-ember-zli.js +35 -0
package/README.md
CHANGED
|
@@ -1,3 +1,121 @@
|
|
|
1
|
-
#
|
|
1
|
+
# Ember Router
|
|
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
|
+
|
|
5
|
+
The utility writes packets delivered to the router as JSON Lines on standard output and accepts outgoing Zigbee packets in the same format on standard input. 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
|
+
|
|
7
|
+
## Installation
|
|
8
|
+
|
|
9
|
+
```sh
|
|
10
|
+
npm install -g ember-router
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
## Usage
|
|
14
|
+
|
|
15
|
+
```sh
|
|
16
|
+
ember-router join -p <path> [options]
|
|
17
|
+
ember-router run -p <path> [options]
|
|
18
|
+
ember-router read -p <path> [options]
|
|
19
|
+
ember-router write -p <path> [options]
|
|
20
|
+
ember-router reset -p <path> --yes [options]
|
|
21
|
+
```
|
|
22
|
+
|
|
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
|
+
|
|
25
|
+
`read` sends one JSON packet from stdin and prints the matching ZCL reply.
|
|
26
|
+
|
|
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
|
+
|
|
29
|
+
### Options
|
|
30
|
+
|
|
31
|
+
- `-p, --path <path>` for the serial port or TCP address (required).
|
|
32
|
+
- `-b, --baud-rate <rate>` for the serial baud rate (default `115200`).
|
|
33
|
+
- `-r, --rtscts` to enable hardware flow control.
|
|
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
|
+
- `--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
|
+
- `--read-timeout <ms>` for `read` to set the ZCL reply timeout (default `5000`, range `100`–`300000`).
|
|
39
|
+
- `--expect <commandId>` for `read` to select the ZCL reply command by decimal or `0x` value.
|
|
40
|
+
|
|
41
|
+
#### Joining networks
|
|
42
|
+
|
|
43
|
+
`join` also accepts the shared adapter and logging options above. Open permit joining on the target network before running the command. Exactly one open network must match, and the adapter must have no saved network.
|
|
44
|
+
|
|
45
|
+
- `-c, --channel <channel>` to scan a single channel from 11 to 26 (default scans all channels).
|
|
46
|
+
- `--pan-id <pan>` to filter by decimal or `0x`-prefixed PAN ID.
|
|
47
|
+
- `--extended-pan-id <hex>` to filter by 16 hex digits in EZSP byte order.
|
|
48
|
+
- `-l, --link-key <hex>` to use a derived 16-byte link key as 32 hex digits (default uses the global Zigbee link key). You can also set `EMBER_ROUTER_LINK_KEY`.
|
|
49
|
+
- `-P, --radio-power <dbm>` to set transmit power in dBm (default `5`).
|
|
50
|
+
- `--scan-duration <exponent>` to set the EZSP active scan duration exponent from 0 to 14 (default `4`).
|
|
51
|
+
- `--answer-interview` to answer coordinator interview requests and wait for delivery of the Basic Power Source Configure Reporting response.
|
|
52
|
+
- `--skip-post-join-security` to skip closing local permit-join and requesting and verifying the trust-center link-key update.
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
#### Reset an adapter
|
|
56
|
+
|
|
57
|
+
`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.
|
|
58
|
+
|
|
59
|
+
After a successful reset, stdout contains the adapter's EUI64, also called EUID. Diagnostics go to stderr.
|
|
60
|
+
|
|
61
|
+
- `--yes` confirms the reset (required).
|
|
62
|
+
- `--preserve-frame-counters` keeps the outgoing network and APS frame counter tokens.
|
|
63
|
+
- `--preserve-boot-counter` keeps the stack boot counter token.
|
|
64
|
+
|
|
65
|
+
### Examples
|
|
66
|
+
|
|
67
|
+
```sh
|
|
68
|
+
# Join a specific open network on channel 19
|
|
69
|
+
ember-router join -p tcp://192.168.1.42:6638 -c 19 --pan-id 0x8cde
|
|
70
|
+
|
|
71
|
+
# Join a network with a link key on channel 19
|
|
72
|
+
ember-router join -p tcp://192.168.1.42:6638 -c 19 -l 00112233445566778899aabbccddeeff
|
|
73
|
+
|
|
74
|
+
# Resume the saved network and receive packets
|
|
75
|
+
ember-router -p tcp://192.168.1.42:6638
|
|
76
|
+
|
|
77
|
+
# Send packets from stdin and keep receiving after stdin closes
|
|
78
|
+
cat packets.jsonl | ember-router run -p tcp://192.168.1.42:6638
|
|
79
|
+
|
|
80
|
+
# Send a finite batch and exit
|
|
81
|
+
cat packets.jsonl | ember-router write -p tcp://192.168.1.42:6638
|
|
82
|
+
|
|
83
|
+
# Leave network, reset the adapter and print the EUI64
|
|
84
|
+
ember-router reset -p tcp://192.168.1.42:6638 --yes
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
## Packet format
|
|
88
|
+
|
|
89
|
+
With `run` and `write`, stdout contains one JSON object per received packet. Diagnostics go to stderr. The router sees packets delivered to its host by EZSP. Retain the sniffer for passive observation of exchanges between other devices.
|
|
90
|
+
|
|
91
|
+
```json
|
|
92
|
+
{"type":"aps","source":4660,"sourceEndpoint":1,"destinationEndpoint":1,"profileId":260,"clusterId":513,"lqi":180,"payload":"1842011200299e07"}
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
`zdo` packets use the same frame fields. `touchlink` packets carry `panId`, `source`, `groupId`, `lqi`, and `payload`.
|
|
96
|
+
|
|
97
|
+
Send one JSON object per line on stdin. The following example sends an already encoded ZCL Read Attributes frame. Use `read` to wait for a matching reply.
|
|
98
|
+
|
|
99
|
+
```json
|
|
100
|
+
{"destination":4660,"destinationEndpoint":1,"clusterId":513,"payload":"1001001200"}
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
For attribute writes, supply the encoded ZCL Write Attributes frame in `payload`. The CLI sends raw APS unicasts and leaves encoding and device identity resolution to the caller. Addresses and IDs are numeric. Endpoints default to `1` and `profileId` to `260`. The CLI waits for each delivery result before proceeding.
|
|
104
|
+
|
|
105
|
+
## Read format
|
|
106
|
+
|
|
107
|
+
Read the occupied heating setpoint (`0x0012`) from a thermostat at short address `4660`.
|
|
108
|
+
|
|
109
|
+
```sh
|
|
110
|
+
ember-router read -p tcp://192.168.1.42:6638 <<'EOF'
|
|
111
|
+
{"destination":4660,"clusterId":513,"payload":"1001001200"}
|
|
112
|
+
EOF
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
The router automatically expects Read Attributes Response (`0x01`) or Write Attributes Response (`0x04`) for the corresponding request. Use `--expect` to override that choice or match a reply to another ZCL command.
|
|
116
|
+
|
|
117
|
+
`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`.
|
|
118
|
+
|
|
119
|
+
```json
|
|
120
|
+
{"type":"aps","source":4660,"sourceEndpoint":1,"destinationEndpoint":1,"profileId":260,"clusterId":513,"lqi":180,"payload":"180101120000299e07"}
|
|
121
|
+
```
|
package/index.js
ADDED
|
@@ -0,0 +1,256 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { once } from 'node:events';
|
|
3
|
+
import { createInterface } from 'node:readline';
|
|
4
|
+
import { Command, InvalidArgumentError, Option } from 'commander';
|
|
5
|
+
import packageJson from './package.json' with { type: 'json' };
|
|
6
|
+
import { attachNetwork, capture, openRouter, resetRouter, sendPacket, SLStatus, Zcl } from './router.js';
|
|
7
|
+
|
|
8
|
+
function integer(min, max) {
|
|
9
|
+
return value => {
|
|
10
|
+
const number = Number(value);
|
|
11
|
+
if (!/^(?:-?\d+|0x[\da-f]+)$/i.test(value) || !Number.isInteger(number) || number < min || number > max) {
|
|
12
|
+
throw new InvalidArgumentError(`Expected an integer from ${min} to ${max}.`);
|
|
13
|
+
}
|
|
14
|
+
return number;
|
|
15
|
+
};
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
function hex(length) {
|
|
19
|
+
return value => {
|
|
20
|
+
if (value.length !== length || !/^[a-f\d]+$/i.test(value)) {
|
|
21
|
+
throw new InvalidArgumentError(`Expected ${length} hex digits.`);
|
|
22
|
+
}
|
|
23
|
+
return value.toLowerCase();
|
|
24
|
+
};
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function manufacturer(value) {
|
|
28
|
+
const code = Zcl.ManufacturerCode[value.toUpperCase()];
|
|
29
|
+
return typeof code === 'number' ? code : integer(0, 0xffff)(value);
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function writeLog(level, message, namespace) {
|
|
33
|
+
const text = typeof message === 'function' ? message() : message;
|
|
34
|
+
const prefix = typeof namespace === 'string' ? `${level} ${namespace}` : level;
|
|
35
|
+
process.stderr.write(`${prefix}: ${text}\n`);
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function parsePacket(line) {
|
|
39
|
+
const packet = JSON.parse(line);
|
|
40
|
+
if (packet === null || typeof packet !== 'object' || Array.isArray(packet)) {
|
|
41
|
+
throw new Error('Expected a packet object.');
|
|
42
|
+
}
|
|
43
|
+
return packet;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
async function readWrites(ezsp, timeout, signal) {
|
|
47
|
+
const { stdin } = process;
|
|
48
|
+
if (stdin.readableEnded || stdin.destroyed) {
|
|
49
|
+
return;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
const input = createInterface({ input: stdin, crlfDelay: Infinity, terminal: false });
|
|
53
|
+
const closeInput = () => input.close();
|
|
54
|
+
signal.addEventListener('abort', closeInput, { once: true });
|
|
55
|
+
|
|
56
|
+
let lineNumber = 0;
|
|
57
|
+
try {
|
|
58
|
+
for await (const line of input) {
|
|
59
|
+
if (signal.aborted) {
|
|
60
|
+
break;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
lineNumber++;
|
|
64
|
+
if (!line.trim()) {
|
|
65
|
+
continue;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
try {
|
|
69
|
+
await sendPacket(ezsp, parsePacket(line), lineNumber & 0x7f, timeout, signal);
|
|
70
|
+
} catch (error) {
|
|
71
|
+
if (signal.aborted) {
|
|
72
|
+
break;
|
|
73
|
+
}
|
|
74
|
+
process.exitCode = 1;
|
|
75
|
+
writeLog('error', `Write line ${lineNumber}: ${error.message}`);
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
} finally {
|
|
79
|
+
signal.removeEventListener('abort', closeInput);
|
|
80
|
+
input.close();
|
|
81
|
+
stdin.pause();
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
async function readPacketLine() {
|
|
86
|
+
const { stdin } = process;
|
|
87
|
+
const input = createInterface({ input: stdin, crlfDelay: Infinity, terminal: false });
|
|
88
|
+
try {
|
|
89
|
+
for await (const line of input) {
|
|
90
|
+
if (line.trim()) {
|
|
91
|
+
return line;
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
throw new Error('Expected a packet on stdin.');
|
|
95
|
+
} finally {
|
|
96
|
+
input.close();
|
|
97
|
+
stdin.pause();
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
async function readOnce(options) {
|
|
102
|
+
const packet = parsePacket(await readPacketLine());
|
|
103
|
+
const reply = await run(options, 'read', packet);
|
|
104
|
+
process.stdout.write(`${JSON.stringify(reply)}\n`);
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
async function run(options, mode, packet) {
|
|
108
|
+
const join = mode === 'join';
|
|
109
|
+
const stop = new AbortController();
|
|
110
|
+
const { signal } = stop;
|
|
111
|
+
const interrupt = () => stop.abort();
|
|
112
|
+
const brokenPipe = error => stop.abort(error);
|
|
113
|
+
const log = (level, message, namespace) => {
|
|
114
|
+
// EZSP debug traces may contain the join key in raw command bytes.
|
|
115
|
+
if (join && level === 'debug') {
|
|
116
|
+
return;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
const alwaysLog = level === 'error' || level === 'warning' || level === 'warn';
|
|
120
|
+
const minimumVerbosity = level === 'debug' ? 2 : 1;
|
|
121
|
+
if (alwaysLog || options.verbose >= minimumVerbosity) {
|
|
122
|
+
writeLog(level, message, namespace);
|
|
123
|
+
}
|
|
124
|
+
};
|
|
125
|
+
process.on('SIGINT', interrupt);
|
|
126
|
+
process.on('SIGTERM', interrupt);
|
|
127
|
+
process.stdout.on('error', brokenPipe);
|
|
128
|
+
let session;
|
|
129
|
+
try {
|
|
130
|
+
session = await openRouter(options, log);
|
|
131
|
+
signal.throwIfAborted();
|
|
132
|
+
const { ezsp } = session;
|
|
133
|
+
ezsp.on('ncpNeedsResetAndInit', () => stop.abort(new Error('Adapter needs a reset. Restart ember-router to resume.')));
|
|
134
|
+
if (mode === 'reset') {
|
|
135
|
+
const eui64 = await resetRouter(ezsp, options, signal);
|
|
136
|
+
writeLog('info', 'Reset NVM3 tokens.');
|
|
137
|
+
writeLog('info', `Adapter EUI64: ${eui64}`);
|
|
138
|
+
return;
|
|
139
|
+
}
|
|
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
|
+
if (join) {
|
|
161
|
+
return;
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
signal.throwIfAborted();
|
|
165
|
+
if (mode === 'read') {
|
|
166
|
+
const expect = { commandId: options.expect, timeout: options.readTimeout };
|
|
167
|
+
return await sendPacket(ezsp, packet, 1, options.writeTimeout, signal, expect);
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
await readWrites(ezsp, options.writeTimeout, signal);
|
|
171
|
+
if (!options.exitAfterWrite && !signal.aborted) {
|
|
172
|
+
await once(signal, 'abort');
|
|
173
|
+
}
|
|
174
|
+
signal.throwIfAborted();
|
|
175
|
+
} catch (error) {
|
|
176
|
+
if (mode === 'read' || (error?.name !== 'AbortError' && error?.code !== 'EPIPE')) {
|
|
177
|
+
throw error;
|
|
178
|
+
}
|
|
179
|
+
} finally {
|
|
180
|
+
try {
|
|
181
|
+
await session?.close();
|
|
182
|
+
} finally {
|
|
183
|
+
process.off('SIGINT', interrupt);
|
|
184
|
+
process.off('SIGTERM', interrupt);
|
|
185
|
+
process.stdout.off('error', brokenPipe);
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
const program = new Command().name('ember-router').version(packageJson.version)
|
|
191
|
+
.description('Resume a saved Zigbee router network and stream packets, or join an open network')
|
|
192
|
+
.requiredOption('-p, --path <path>', 'Serial port or tcp://host:port')
|
|
193
|
+
.option('-b, --baud-rate <rate>', 'Serial baud rate', integer(1, 4_000_000), 115200)
|
|
194
|
+
.option('-r, --rtscts', 'Use RTS/CTS flow control', false)
|
|
195
|
+
.option('-m, --manufacturer-code <code>', 'ZCL manufacturer enum name, decimal or hex', manufacturer, Zcl.ManufacturerCode.SILICON_LABORATORIES)
|
|
196
|
+
.option('--timeout <ms>', 'Network and scan callback timeout', integer(100, 300_000), 45000)
|
|
197
|
+
.option('-v, --verbose', 'Increase diagnostic verbosity', (_, count) => count + 1, 0);
|
|
198
|
+
|
|
199
|
+
program.command('join').description('Join one matching open network and save membership on the adapter')
|
|
200
|
+
.option('-c, --channel <channel>', 'Scan only this Zigbee channel', integer(11, 26))
|
|
201
|
+
.option('--pan-id <pan>', 'Filter by decimal or 0x-prefixed PAN ID', integer(0, 0xfffe))
|
|
202
|
+
.option('--extended-pan-id <hex>', 'Filter by the 16 hex digits in EZSP byte order', hex(16))
|
|
203
|
+
.addOption(new Option('-l, --link-key <hex>', 'Use a private 16-byte link key instead of the global link key').env('EMBER_ROUTER_LINK_KEY').argParser(hex(32)))
|
|
204
|
+
.option('-P, --radio-power <dbm>', 'Radio transmit power', integer(-128, 127), 5)
|
|
205
|
+
.option('--scan-duration <exponent>', 'EZSP active scan duration', integer(0, 14), 4)
|
|
206
|
+
.option('--answer-interview', 'Answer the coordinator interview and wait for its reporting exchange')
|
|
207
|
+
.option('--skip-post-join-security', 'Skip closing local permit-join and updating the trust-center link key')
|
|
208
|
+
.action((_options, command) => run(command.optsWithGlobals(), 'join'));
|
|
209
|
+
|
|
210
|
+
function packetOptions(command) {
|
|
211
|
+
return command
|
|
212
|
+
.option('--write-timeout <ms>', 'Wait for each APS delivery status', integer(100, 300_000), 15000);
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
function readOptions(command) {
|
|
216
|
+
return packetOptions(command)
|
|
217
|
+
.option('--read-timeout <ms>', 'Wait for a matching ZCL reply', integer(100, 300_000), 5000)
|
|
218
|
+
.option('--expect <commandId>', 'Expected ZCL reply command ID (inferred for attribute reads and writes)', integer(0, 255));
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
packetOptions(program.command('run', { isDefault: true }))
|
|
222
|
+
.description('Resume, stream received packets, and accept writes on stdin')
|
|
223
|
+
.action((_options, command) => {
|
|
224
|
+
const options = command.optsWithGlobals();
|
|
225
|
+
return run(options, 'run');
|
|
226
|
+
});
|
|
227
|
+
|
|
228
|
+
packetOptions(program.command('write'))
|
|
229
|
+
.description('Resume and send packets from stdin, then exit at EOF')
|
|
230
|
+
.action((_options, command) => {
|
|
231
|
+
const options = command.optsWithGlobals();
|
|
232
|
+
return run({ ...options, exitAfterWrite: true }, 'write');
|
|
233
|
+
});
|
|
234
|
+
|
|
235
|
+
readOptions(program.command('read'))
|
|
236
|
+
.description('Send one packet from stdin and print the matching reply')
|
|
237
|
+
.action((_options, command) => readOnce(command.optsWithGlobals()));
|
|
238
|
+
|
|
239
|
+
program.command('reset').description('Leave the saved network and reset NVM3 tokens')
|
|
240
|
+
.option('--yes', 'Confirm deletion of saved adapter state')
|
|
241
|
+
.option('--preserve-frame-counters', 'Keep outgoing network and APS frame counter tokens', false)
|
|
242
|
+
.option('--preserve-boot-counter', 'Keep the stack boot counter token', false)
|
|
243
|
+
.action((_options, command) => {
|
|
244
|
+
const options = command.optsWithGlobals();
|
|
245
|
+
if (!options.yes) {
|
|
246
|
+
command.error('Reset erases saved network state and NVM3 tokens. Pass --yes to confirm.');
|
|
247
|
+
}
|
|
248
|
+
return run(options, 'reset');
|
|
249
|
+
});
|
|
250
|
+
|
|
251
|
+
try {
|
|
252
|
+
await program.parseAsync();
|
|
253
|
+
} catch (error) {
|
|
254
|
+
writeLog('error', error.message);
|
|
255
|
+
process.exitCode = 1;
|
|
256
|
+
}
|
package/interview.js
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
const BASIC = 0x0000;
|
|
2
|
+
const IDENTIFY = 0x0003;
|
|
3
|
+
const THERMOSTAT = 0x0201;
|
|
4
|
+
|
|
5
|
+
function word(value) {
|
|
6
|
+
const bytes = Buffer.alloc(2);
|
|
7
|
+
bytes.writeUInt16LE(value);
|
|
8
|
+
return bytes;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
function string(value) {
|
|
12
|
+
return Buffer.concat([Buffer.from([0x42, Buffer.byteLength(value)]), Buffer.from(value)]);
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
const basicAttributes = new Map([
|
|
16
|
+
[0x0000, Buffer.from([0x20, 8])], // ZCLVersion: ZCL revision 8.
|
|
17
|
+
[0x0001, Buffer.from([0x20, 1])], // ApplicationVersion: version 1.
|
|
18
|
+
[0x0004, string('Generic')], // ManufacturerName: generic manufacturer label.
|
|
19
|
+
[0x0005, string('Zigbee Router')], // ModelIdentifier: generic router name.
|
|
20
|
+
[0x0007, Buffer.from([0x30, 4])], // PowerSource: DC source.
|
|
21
|
+
[0xfffd, Buffer.from([0x21, 2, 0])], // ClusterRevision: Basic cluster revision 2.
|
|
22
|
+
]);
|
|
23
|
+
|
|
24
|
+
export function createInterview() {
|
|
25
|
+
let identifyUntil = 0;
|
|
26
|
+
const identifySeconds = () => Math.max(0, Math.ceil((identifyUntil - Date.now()) / 1000));
|
|
27
|
+
|
|
28
|
+
return (cluster, payload) => {
|
|
29
|
+
const manufacturerSpecific = Boolean(payload[0] & 4);
|
|
30
|
+
const serverToClient = Boolean(payload[0] & 8);
|
|
31
|
+
const disableDefault = Boolean(payload[0] & 16);
|
|
32
|
+
const frameType = payload[0] & 3;
|
|
33
|
+
const offset = manufacturerSpecific ? 3 : 1;
|
|
34
|
+
if (payload.length < offset + 2) {
|
|
35
|
+
return;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
const sequence = payload[offset];
|
|
39
|
+
const command = payload[offset + 1];
|
|
40
|
+
const body = payload.subarray(offset + 2);
|
|
41
|
+
const attributes = new Map();
|
|
42
|
+
if (manufacturerSpecific) {
|
|
43
|
+
if (!serverToClient && cluster === IDENTIFY && payload.readUInt16LE(1) === 0x1221) {
|
|
44
|
+
attributes.set(0x4000, Buffer.from([0x10, 0]));
|
|
45
|
+
}
|
|
46
|
+
} else if (!serverToClient && cluster === BASIC) {
|
|
47
|
+
for (const [id, value] of basicAttributes) {
|
|
48
|
+
attributes.set(id, value);
|
|
49
|
+
}
|
|
50
|
+
} else if (!serverToClient && cluster === IDENTIFY) {
|
|
51
|
+
attributes.set(0, Buffer.concat([Buffer.from([0x21]), word(identifySeconds())]));
|
|
52
|
+
attributes.set(0xfffd, Buffer.from([0x21, 1, 0]));
|
|
53
|
+
} else if (serverToClient && (cluster === BASIC || cluster === THERMOSTAT)) {
|
|
54
|
+
attributes.set(0xfffd, Buffer.from([0x21, 1, 0]));
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
function response(id, data, kind = 0, complete = false) {
|
|
58
|
+
const control = 0x10 | (serverToClient ? 0 : 8) | (manufacturerSpecific ? 4 : 0) | kind;
|
|
59
|
+
const manufacturer = manufacturerSpecific ? payload.subarray(1, 3) : Buffer.alloc(0);
|
|
60
|
+
return {
|
|
61
|
+
payload: Buffer.concat([Buffer.from([control]), manufacturer, Buffer.from([sequence, id]), data]),
|
|
62
|
+
complete,
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
if (frameType === 0 && command === 0x0c && body.length === 3) {
|
|
67
|
+
if (body[2] === 0) {
|
|
68
|
+
return response(0x0b, Buffer.from([command, 0x80]));
|
|
69
|
+
}
|
|
70
|
+
const start = body.readUInt16LE(0);
|
|
71
|
+
const remaining = [...attributes].filter(([id]) => id >= start).sort(([a], [b]) => a - b);
|
|
72
|
+
const page = remaining.slice(0, Math.min(body[2], 16));
|
|
73
|
+
const records = page.map(([id, value]) => Buffer.concat([word(id), value.subarray(0, 1)]));
|
|
74
|
+
return response(0x0d, Buffer.concat([Buffer.from([Number(page.length === remaining.length)]), ...records]));
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
if (frameType === 0 && command === 0 && body.length > 0 && body.length % 2 === 0 && body.length <= 48) {
|
|
78
|
+
const records = [];
|
|
79
|
+
for (let offset = 0; offset < body.length; offset += 2) {
|
|
80
|
+
const id = body.readUInt16LE(offset);
|
|
81
|
+
const value = attributes.get(id);
|
|
82
|
+
records.push(Buffer.concat([word(id), Buffer.from([value ? 0 : 0x86]), value ?? Buffer.alloc(0)]));
|
|
83
|
+
}
|
|
84
|
+
return response(1, Buffer.concat(records));
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
if (frameType === 0 && command === 6 && !manufacturerSpecific && !serverToClient && cluster === BASIC &&
|
|
88
|
+
body.length === 8 && body[0] === 0 && body.readUInt16LE(1) === 7 && body[3] === 0x30 && body.readUInt16LE(6) >= 0xfffe) {
|
|
89
|
+
// Use successful Power Source reporting configuration as the interview completion checkpoint.
|
|
90
|
+
return response(7, Buffer.from([0]), 0, true);
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
if (frameType === 1 && !manufacturerSpecific && !serverToClient && cluster === IDENTIFY) {
|
|
94
|
+
if (command === 0 && body.length === 2) {
|
|
95
|
+
identifyUntil = Date.now() + body.readUInt16LE(0) * 1000;
|
|
96
|
+
return disableDefault ? undefined : response(0x0b, Buffer.from([command, 0]));
|
|
97
|
+
}
|
|
98
|
+
if (command === 1 && body.length === 0) {
|
|
99
|
+
const seconds = identifySeconds();
|
|
100
|
+
return seconds ? response(0, word(seconds), 1) : undefined;
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
if (disableDefault || (frameType === 0 && [1, 4, 7, 9, 0x0a, 0x0b, 0x0d, 0x12, 0x14, 0x16].includes(command))) {
|
|
105
|
+
return;
|
|
106
|
+
}
|
|
107
|
+
return response(0x0b, Buffer.from([command, frameType === 0 ? 0x82 : 0x81]));
|
|
108
|
+
};
|
|
109
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,33 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "ember-router",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "1.1.0",
|
|
4
|
+
"description": "ZigBee router CLI for EmberZNet-based adapters using ember-zli and zigbee-herdsman",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"bin": "./index.js",
|
|
7
|
+
"files": [
|
|
8
|
+
"*.js",
|
|
9
|
+
"!.yarn/**"
|
|
10
|
+
],
|
|
11
|
+
"engines": {
|
|
12
|
+
"node": ">=22"
|
|
13
|
+
},
|
|
14
|
+
"author": {
|
|
15
|
+
"name": "Kristian Kraljic",
|
|
16
|
+
"email": "kris@kra.lc",
|
|
17
|
+
"url": "https://kra.lc/"
|
|
18
|
+
},
|
|
19
|
+
"repository": {
|
|
20
|
+
"type": "git",
|
|
21
|
+
"url": "https://github.com/kristian/ember-router.git"
|
|
22
|
+
},
|
|
23
|
+
"homepage": "https://github.com/kristian/ember-router",
|
|
24
|
+
"bugs": {
|
|
25
|
+
"url": "https://github.com/kristian/ember-router/issues"
|
|
26
|
+
},
|
|
27
|
+
"license": "Apache-2.0",
|
|
28
|
+
"dependencies": {
|
|
29
|
+
"commander": "^14.0.0",
|
|
30
|
+
"ember-zli": "6.1.0"
|
|
31
|
+
},
|
|
32
|
+
"packageManager": "yarn@4.18.1"
|
|
6
33
|
}
|
package/router.js
ADDED
|
@@ -0,0 +1,498 @@
|
|
|
1
|
+
import './silence-ember-zli.js';
|
|
2
|
+
import { createRequire } from 'node:module';
|
|
3
|
+
import { createInterview } from './interview.js';
|
|
4
|
+
import {
|
|
5
|
+
emberNetworkConfig,
|
|
6
|
+
emberNetworkInit,
|
|
7
|
+
emberRegisterFixedEndpoints,
|
|
8
|
+
emberStart,
|
|
9
|
+
emberStop,
|
|
10
|
+
} from 'ember-zli/dist/utils/ember.js';
|
|
11
|
+
|
|
12
|
+
const requireHere = createRequire(import.meta.url);
|
|
13
|
+
const requireEmber = createRequire(requireHere.resolve('ember-zli'));
|
|
14
|
+
const { Zcl, ZSpec, setLogger } = requireEmber('zigbee-herdsman');
|
|
15
|
+
const {
|
|
16
|
+
EmberApsOption,
|
|
17
|
+
EmberExtendedSecurityBitmask,
|
|
18
|
+
EmberIncomingMessageType,
|
|
19
|
+
EmberInitialSecurityBitmask,
|
|
20
|
+
EmberJoinMethod,
|
|
21
|
+
EmberKeyStatus,
|
|
22
|
+
EmberNodeType,
|
|
23
|
+
EmberOutgoingMessageType,
|
|
24
|
+
EzspNetworkScanType,
|
|
25
|
+
SLStatus,
|
|
26
|
+
} = requireEmber('zigbee-herdsman/dist/adapter/ember/enums.js');
|
|
27
|
+
const { AdapterTransport } = requireEmber('zigbee-herdsman/dist/adapter/transport.js');
|
|
28
|
+
const { DEFAULT_STACK_CONFIG } = requireEmber('zigbee-herdsman/dist/adapter/ember/adapter/emberAdapter.js');
|
|
29
|
+
const { STACK_PROFILE_ZIGBEE_PRO } = requireEmber('zigbee-herdsman/dist/adapter/ember/consts.js');
|
|
30
|
+
|
|
31
|
+
export { SLStatus, Zcl };
|
|
32
|
+
|
|
33
|
+
function routerError(message, code) {
|
|
34
|
+
return Object.assign(new Error(message), code ? { code } : {});
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function check(status, operation, code) {
|
|
38
|
+
if (status !== SLStatus.OK) {
|
|
39
|
+
throw routerError(`${operation}: ${SLStatus[status] ?? status}`, code);
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export async function openRouter(options, log) {
|
|
44
|
+
setLogger(Object.fromEntries(['debug', 'info', 'warning', 'error'].map(level => [
|
|
45
|
+
level,
|
|
46
|
+
(message, namespace) => log(level, message, namespace),
|
|
47
|
+
])));
|
|
48
|
+
|
|
49
|
+
const transport = new AdapterTransport({
|
|
50
|
+
path: options.path,
|
|
51
|
+
baudRate: options.baudRate,
|
|
52
|
+
rtscts: options.rtscts,
|
|
53
|
+
xon: !options.rtscts,
|
|
54
|
+
xoff: !options.rtscts,
|
|
55
|
+
});
|
|
56
|
+
const ezsp = await emberStart(transport);
|
|
57
|
+
|
|
58
|
+
try {
|
|
59
|
+
await emberNetworkConfig(ezsp, DEFAULT_STACK_CONFIG, options.manufacturerCode);
|
|
60
|
+
await emberRegisterFixedEndpoints(ezsp, [], true);
|
|
61
|
+
return { ezsp, close: () => emberStop(ezsp) };
|
|
62
|
+
} catch (error) {
|
|
63
|
+
await emberStop(ezsp);
|
|
64
|
+
throw error;
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
function pendingEvent(timeout, signal, subscribe, description = 'adapter callback', timeoutCode) {
|
|
69
|
+
let unsubscribe;
|
|
70
|
+
let timer;
|
|
71
|
+
let abort;
|
|
72
|
+
const promise = new Promise((resolve, reject) => {
|
|
73
|
+
abort = () => reject(signal.reason);
|
|
74
|
+
signal.addEventListener('abort', abort, { once: true });
|
|
75
|
+
try {
|
|
76
|
+
signal.throwIfAborted();
|
|
77
|
+
unsubscribe = subscribe(resolve, reject);
|
|
78
|
+
timer = setTimeout(() => reject(routerError(`Timed out waiting for ${description}.`, timeoutCode)), timeout);
|
|
79
|
+
} catch (error) {
|
|
80
|
+
reject(error);
|
|
81
|
+
}
|
|
82
|
+
});
|
|
83
|
+
promise.catch(() => {});
|
|
84
|
+
return {
|
|
85
|
+
promise,
|
|
86
|
+
close() {
|
|
87
|
+
clearTimeout(timer);
|
|
88
|
+
signal.removeEventListener('abort', abort);
|
|
89
|
+
unsubscribe?.();
|
|
90
|
+
},
|
|
91
|
+
};
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
async function networkCommand(ezsp, command, timeout, signal, expectedStatus = SLStatus.NETWORK_UP) {
|
|
95
|
+
// ember-zli's stack waiter cannot be cancelled when a command returns NOT_JOINED.
|
|
96
|
+
const transition = pendingEvent(timeout, signal, (resolve, reject) => {
|
|
97
|
+
const listener = status => {
|
|
98
|
+
if (status === expectedStatus) {
|
|
99
|
+
resolve();
|
|
100
|
+
} else if (status === SLStatus.NETWORK_DOWN) {
|
|
101
|
+
reject(new Error('Network went down.'));
|
|
102
|
+
}
|
|
103
|
+
};
|
|
104
|
+
ezsp.on('stackStatus', listener);
|
|
105
|
+
return () => ezsp.off('stackStatus', listener);
|
|
106
|
+
});
|
|
107
|
+
try {
|
|
108
|
+
signal.throwIfAborted();
|
|
109
|
+
const status = await command();
|
|
110
|
+
if (status === SLStatus.OK) {
|
|
111
|
+
await transition.promise;
|
|
112
|
+
}
|
|
113
|
+
return status;
|
|
114
|
+
} finally {
|
|
115
|
+
transition.close();
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
async function scan(ezsp, options, signal) {
|
|
120
|
+
const networks = new Map();
|
|
121
|
+
const found = ezsp.ezspNetworkFoundHandler;
|
|
122
|
+
const complete = ezsp.ezspScanCompleteHandler;
|
|
123
|
+
const scanDone = pendingEvent(options.timeout, signal, resolve => {
|
|
124
|
+
ezsp.ezspNetworkFoundHandler = network => {
|
|
125
|
+
const extendedPanId = Buffer.from(network.extendedPanId).toString('hex');
|
|
126
|
+
const matchesPan = options.panId === undefined || options.panId === network.panId;
|
|
127
|
+
const matchesExtendedPan = !options.extendedPanId || options.extendedPanId === extendedPanId;
|
|
128
|
+
|
|
129
|
+
if (network.allowingJoin && network.stackProfile === STACK_PROFILE_ZIGBEE_PRO && matchesPan && matchesExtendedPan) {
|
|
130
|
+
networks.set(`${network.panId}:${extendedPanId}:${network.channel}`, network);
|
|
131
|
+
}
|
|
132
|
+
};
|
|
133
|
+
ezsp.ezspScanCompleteHandler = (_channel, status) => resolve(status);
|
|
134
|
+
return () => {
|
|
135
|
+
ezsp.ezspNetworkFoundHandler = found;
|
|
136
|
+
ezsp.ezspScanCompleteHandler = complete;
|
|
137
|
+
};
|
|
138
|
+
});
|
|
139
|
+
try {
|
|
140
|
+
signal.throwIfAborted();
|
|
141
|
+
const channels = options.channel ? 1 << options.channel : ZSpec.ALL_802_15_4_CHANNELS_MASK;
|
|
142
|
+
check(await ezsp.ezspStartScan(EzspNetworkScanType.ACTIVE_SCAN, channels, options.scanDuration), 'Start scan');
|
|
143
|
+
check(await scanDone.promise, 'Complete scan');
|
|
144
|
+
if (networks.size > 1) {
|
|
145
|
+
throw new Error('Multiple open networks match. Specify --pan-id, --extended-pan-id or --channel.');
|
|
146
|
+
}
|
|
147
|
+
return networks.values().next().value;
|
|
148
|
+
} finally {
|
|
149
|
+
scanDone.close();
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
async function configureJoinSecurity(ezsp, linkKey) {
|
|
154
|
+
const useGlobalKey = linkKey === undefined;
|
|
155
|
+
const preconfiguredKey = {
|
|
156
|
+
contents: useGlobalKey ? Buffer.from(ZSpec.INTEROPERABILITY_LINK_KEY) : Buffer.from(linkKey, 'hex'),
|
|
157
|
+
};
|
|
158
|
+
const initial = EmberInitialSecurityBitmask;
|
|
159
|
+
const extended = EmberExtendedSecurityBitmask;
|
|
160
|
+
let initialFlags = initial.HAVE_PRECONFIGURED_KEY | initial.REQUIRE_ENCRYPTED_KEY | initial.NO_FRAME_COUNTER_RESET;
|
|
161
|
+
let extendedFlags = extended.EXT_NO_FRAME_COUNTER_RESET;
|
|
162
|
+
|
|
163
|
+
if (useGlobalKey) {
|
|
164
|
+
initialFlags |= initial.TRUST_CENTER_GLOBAL_LINK_KEY;
|
|
165
|
+
extendedFlags |= extended.JOINER_GLOBAL_LINK_KEY;
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
check(await ezsp.ezspSetInitialSecurityState({
|
|
169
|
+
bitmask: initialFlags,
|
|
170
|
+
preconfiguredKey,
|
|
171
|
+
networkKey: { contents: Buffer.alloc(16) },
|
|
172
|
+
networkKeySequenceNumber: 0,
|
|
173
|
+
preconfiguredTrustCenterEui64: ZSpec.BLANK_EUI64,
|
|
174
|
+
}), 'Configure join security');
|
|
175
|
+
check(await ezsp.ezspSetExtendedSecurityBitmask(extendedFlags), 'Configure extended security');
|
|
176
|
+
|
|
177
|
+
if (useGlobalKey) {
|
|
178
|
+
check(await ezsp.ezspImportTransientKey(ZSpec.BLANK_EUI64, preconfiguredKey), 'Import global transient key');
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
async function joinNetwork(ezsp, options, signal) {
|
|
183
|
+
check(await ezsp.ezspSetRadioPower(options.radioPower), 'Set radio power');
|
|
184
|
+
const selected = await scan(ezsp, options, signal);
|
|
185
|
+
if (!selected) {
|
|
186
|
+
throw new Error('No matching open network found. Open permit joining and retry.');
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
await configureJoinSecurity(ezsp, options.linkKey);
|
|
190
|
+
const parameters = {
|
|
191
|
+
extendedPanId: selected.extendedPanId,
|
|
192
|
+
panId: selected.panId,
|
|
193
|
+
radioChannel: selected.channel,
|
|
194
|
+
radioTxPower: options.radioPower,
|
|
195
|
+
joinMethod: EmberJoinMethod.MAC_ASSOCIATION,
|
|
196
|
+
nwkManagerId: 0,
|
|
197
|
+
nwkUpdateId: selected.nwkUpdateId,
|
|
198
|
+
channels: 1 << selected.channel,
|
|
199
|
+
};
|
|
200
|
+
const status = await networkCommand(ezsp, () => ezsp.ezspJoinNetwork(EmberNodeType.ROUTER, parameters), options.timeout, signal);
|
|
201
|
+
check(status, 'Join network');
|
|
202
|
+
return selected;
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
async function updateTrustCenterKey(ezsp, timeout, signal) {
|
|
206
|
+
const original = ezsp.ezspZigbeeKeyEstablishmentHandler;
|
|
207
|
+
const verified = pendingEvent(timeout, signal, (resolve, reject) => {
|
|
208
|
+
ezsp.ezspZigbeeKeyEstablishmentHandler = (partner, status) => {
|
|
209
|
+
original.call(ezsp, partner, status);
|
|
210
|
+
switch (status) {
|
|
211
|
+
case EmberKeyStatus.VERIFY_LINK_KEY_SUCCESS:
|
|
212
|
+
resolve();
|
|
213
|
+
break;
|
|
214
|
+
case EmberKeyStatus.VERIFY_LINK_KEY_FAILURE:
|
|
215
|
+
case EmberKeyStatus.ESTABLISHMENT_TIMEOUT:
|
|
216
|
+
case EmberKeyStatus.TABLE_FULL:
|
|
217
|
+
case EmberKeyStatus.TRUST_CENTER_IS_PRE_R21:
|
|
218
|
+
reject(new Error(`Trust-center link key update: ${EmberKeyStatus[status]}.`));
|
|
219
|
+
break;
|
|
220
|
+
}
|
|
221
|
+
};
|
|
222
|
+
return () => { ezsp.ezspZigbeeKeyEstablishmentHandler = original; };
|
|
223
|
+
}, 'trust-center link key verification');
|
|
224
|
+
|
|
225
|
+
try {
|
|
226
|
+
signal.throwIfAborted();
|
|
227
|
+
check(await ezsp.ezspUpdateTcLinkKey(2), 'Request trust-center link key update');
|
|
228
|
+
await verified.promise;
|
|
229
|
+
} finally {
|
|
230
|
+
verified.close();
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
function listenForInterview(ezsp, timeout, signal) {
|
|
235
|
+
const reply = createInterview();
|
|
236
|
+
const complete = Promise.withResolvers();
|
|
237
|
+
complete.promise.catch(() => {});
|
|
238
|
+
let queue = Promise.resolve();
|
|
239
|
+
let tag = 0;
|
|
240
|
+
|
|
241
|
+
const listener = (type, frame, _lqi, sender, payload) => {
|
|
242
|
+
if (type > 1 || sender !== ZSpec.COORDINATOR_ADDRESS ||
|
|
243
|
+
frame.profileId !== ZSpec.HA_PROFILE_ID || frame.destinationEndpoint !== 1) {
|
|
244
|
+
return;
|
|
245
|
+
}
|
|
246
|
+
queue = queue.then(async () => {
|
|
247
|
+
signal.throwIfAborted();
|
|
248
|
+
const answer = reply(frame.clusterId, payload);
|
|
249
|
+
if (!answer) {
|
|
250
|
+
return;
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
tag = (tag + 1) & 0x7f;
|
|
254
|
+
await sendPacket(ezsp, {
|
|
255
|
+
destination: sender,
|
|
256
|
+
destinationEndpoint: frame.sourceEndpoint,
|
|
257
|
+
clusterId: frame.clusterId,
|
|
258
|
+
payload: answer.payload.toString('hex'),
|
|
259
|
+
}, tag, timeout, signal);
|
|
260
|
+
if (answer.complete) {
|
|
261
|
+
complete.resolve();
|
|
262
|
+
}
|
|
263
|
+
}).catch(complete.reject);
|
|
264
|
+
};
|
|
265
|
+
ezsp.on('incomingMessage', listener);
|
|
266
|
+
return { complete: complete.promise, close: () => ezsp.off('incomingMessage', listener) };
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
export async function attachNetwork(ezsp, options, join, signal) {
|
|
270
|
+
const status = await networkCommand(ezsp, () => emberNetworkInit(ezsp, true), options.timeout, signal);
|
|
271
|
+
if (status !== SLStatus.NOT_JOINED) {
|
|
272
|
+
check(status, 'Restore network');
|
|
273
|
+
if (join) {
|
|
274
|
+
throw new Error('The adapter already has a saved network. Run without join to resume it.');
|
|
275
|
+
}
|
|
276
|
+
} else if (!join) {
|
|
277
|
+
throw new Error('No saved network. Run ember-router join first.');
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
const stop = new AbortController();
|
|
281
|
+
const joinSignal = AbortSignal.any([signal, stop.signal]);
|
|
282
|
+
const interview = join && options.answerInterview ? listenForInterview(ezsp, options.timeout, joinSignal) : undefined;
|
|
283
|
+
try {
|
|
284
|
+
const selected = join ? await joinNetwork(ezsp, options, joinSignal) : undefined;
|
|
285
|
+
const network = await verifyNetwork(ezsp, selected);
|
|
286
|
+
if (!join || !options.skipPostJoinSecurity) {
|
|
287
|
+
check(await ezsp.ezspPermitJoining(0), 'Close local permit joining');
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
if (join) {
|
|
291
|
+
const interviewDone = interview && pendingEvent(options.timeout, joinSignal, (resolve, reject) => {
|
|
292
|
+
interview.complete.then(resolve, reject);
|
|
293
|
+
}, 'the interview reporting response');
|
|
294
|
+
try {
|
|
295
|
+
const keyUpdate = options.skipPostJoinSecurity
|
|
296
|
+
? undefined
|
|
297
|
+
: updateTrustCenterKey(ezsp, options.timeout, joinSignal);
|
|
298
|
+
await Promise.all([keyUpdate, interviewDone?.promise]);
|
|
299
|
+
} finally {
|
|
300
|
+
interviewDone?.close();
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
return network;
|
|
304
|
+
} finally {
|
|
305
|
+
interview?.close();
|
|
306
|
+
stop.abort();
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
async function verifyNetwork(ezsp, selected) {
|
|
311
|
+
const [parameterStatus, role, network] = await ezsp.ezspGetNetworkParameters();
|
|
312
|
+
check(parameterStatus, 'Read network parameters');
|
|
313
|
+
if (role !== EmberNodeType.ROUTER) {
|
|
314
|
+
throw new Error('Saved network is not configured for a router.');
|
|
315
|
+
}
|
|
316
|
+
if (selected && (
|
|
317
|
+
network.panId !== selected.panId ||
|
|
318
|
+
network.radioChannel !== selected.channel ||
|
|
319
|
+
!Buffer.from(network.extendedPanId).equals(Buffer.from(selected.extendedPanId))
|
|
320
|
+
)) {
|
|
321
|
+
throw new Error('Joined network did not match the scan result.');
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
return network;
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
export async function resetRouter(ezsp, options, signal) {
|
|
328
|
+
signal.throwIfAborted();
|
|
329
|
+
const eui64 = await ezsp.ezspGetEui64();
|
|
330
|
+
const initialize = () => emberNetworkInit(ezsp, true);
|
|
331
|
+
const status = await networkCommand(ezsp, initialize, options.timeout, signal);
|
|
332
|
+
if (status !== SLStatus.NOT_JOINED) {
|
|
333
|
+
check(status, 'Restore network before reset');
|
|
334
|
+
const leave = () => ezsp.ezspLeaveNetwork();
|
|
335
|
+
const leaveStatus = await networkCommand(ezsp, leave, options.timeout, signal, SLStatus.NETWORK_DOWN);
|
|
336
|
+
check(leaveStatus, 'Leave network');
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
signal.throwIfAborted();
|
|
340
|
+
await ezsp.ezspTokenFactoryReset(options.preserveFrameCounters, options.preserveBootCounter);
|
|
341
|
+
return eui64.replace(/^0x/i, '');
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
const apsObservers = new WeakMap();
|
|
345
|
+
|
|
346
|
+
function observeAps(ezsp, observe) {
|
|
347
|
+
let observers = apsObservers.get(ezsp);
|
|
348
|
+
if (!observers) {
|
|
349
|
+
observers = new Set();
|
|
350
|
+
apsObservers.set(ezsp, observers);
|
|
351
|
+
const original = ezsp.ezspIncomingMessageHandler.bind(ezsp);
|
|
352
|
+
let dispatching = false;
|
|
353
|
+
const dispatch = (type, frame, lqi, source, payload) => {
|
|
354
|
+
for (const listener of observers) {
|
|
355
|
+
listener(type, frame, lqi, source, payload);
|
|
356
|
+
}
|
|
357
|
+
};
|
|
358
|
+
|
|
359
|
+
// The driver emits incomingMessage for selected profiles only.
|
|
360
|
+
ezsp.ezspIncomingMessageHandler = (type, frame, info, payload) => {
|
|
361
|
+
dispatch(type, frame, info.lastHopLqi, info.senderShortId, payload);
|
|
362
|
+
dispatching = true;
|
|
363
|
+
try {
|
|
364
|
+
original(type, frame, info, payload);
|
|
365
|
+
} finally {
|
|
366
|
+
dispatching = false;
|
|
367
|
+
}
|
|
368
|
+
};
|
|
369
|
+
ezsp.on('incomingMessage', (...args) => {
|
|
370
|
+
if (!dispatching) {
|
|
371
|
+
dispatch(...args);
|
|
372
|
+
}
|
|
373
|
+
});
|
|
374
|
+
}
|
|
375
|
+
observers.add(observe);
|
|
376
|
+
return () => observers.delete(observe);
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
function apsPacket(frame, source, lqi, payload) {
|
|
380
|
+
return {
|
|
381
|
+
type: frame.profileId === 0 ? 'zdo' : 'aps',
|
|
382
|
+
source,
|
|
383
|
+
sourceEndpoint: frame.sourceEndpoint,
|
|
384
|
+
destinationEndpoint: frame.destinationEndpoint,
|
|
385
|
+
profileId: frame.profileId,
|
|
386
|
+
clusterId: frame.clusterId,
|
|
387
|
+
lqi,
|
|
388
|
+
payload: payload.toString('hex'),
|
|
389
|
+
};
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
export function capture(ezsp, emit) {
|
|
393
|
+
observeAps(ezsp, (_type, frame, lqi, source, payload) => emit(apsPacket(frame, source, lqi, payload)));
|
|
394
|
+
ezsp.on('touchlinkMessage', (panId, source, groupId, lqi, payload) =>
|
|
395
|
+
emit({ type: 'touchlink', panId, source, groupId, lqi, payload: payload.toString('hex') }));
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
const attributeReplies = new Map([
|
|
399
|
+
[Zcl.Foundation.read.ID, Zcl.Foundation.readRsp.ID],
|
|
400
|
+
[Zcl.Foundation.write.ID, Zcl.Foundation.writeRsp.ID],
|
|
401
|
+
]);
|
|
402
|
+
|
|
403
|
+
function matchesReply(request, commandId, payload) {
|
|
404
|
+
const header = Zcl.Header.fromBuffer(payload);
|
|
405
|
+
if (!header ||
|
|
406
|
+
header.transactionSequenceNumber !== request.transactionSequenceNumber ||
|
|
407
|
+
header.manufacturerCode !== request.manufacturerCode ||
|
|
408
|
+
header.frameControl.direction === request.frameControl.direction) {
|
|
409
|
+
return false;
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
const defaultResponse = Zcl.Foundation.defaultRsp.ID;
|
|
413
|
+
if (header.isGlobal && header.commandIdentifier === defaultResponse) {
|
|
414
|
+
return payload.length >= header.length + 2 && payload[header.length] === request.commandIdentifier &&
|
|
415
|
+
(commandId === defaultResponse || payload[header.length + 1] !== Zcl.Status.SUCCESS);
|
|
416
|
+
}
|
|
417
|
+
return header.frameControl.frameType === request.frameControl.frameType && header.commandIdentifier === commandId;
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
export async function sendPacket(ezsp, packet, tag, timeout, signal, expect) {
|
|
421
|
+
const { destination, destinationEndpoint = 1, sourceEndpoint = 1, profileId = ZSpec.HA_PROFILE_ID, clusterId, payload } = packet;
|
|
422
|
+
const fields = [
|
|
423
|
+
['destination', destination, 0, 0xfff7],
|
|
424
|
+
['sourceEndpoint', sourceEndpoint, 1, 254],
|
|
425
|
+
['destinationEndpoint', destinationEndpoint, 1, 240],
|
|
426
|
+
['clusterId', clusterId, 0, 0xffff],
|
|
427
|
+
['profileId', profileId, 1, 0xffff],
|
|
428
|
+
];
|
|
429
|
+
for (const [label, value, min, max] of fields) {
|
|
430
|
+
if (!Number.isInteger(value) || value < min || value > max) {
|
|
431
|
+
throw routerError(`Invalid ${label}.`, 'INVALID_PACKET');
|
|
432
|
+
}
|
|
433
|
+
}
|
|
434
|
+
if (typeof payload !== 'string' || !/^(?:[\da-f]{2})+$/i.test(payload)) {
|
|
435
|
+
throw routerError('payload must be nonempty, even-length hex.', 'INVALID_PACKET');
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
const message = Buffer.from(payload, 'hex');
|
|
439
|
+
const request = expect && Zcl.Header.fromBuffer(message);
|
|
440
|
+
if (expect && (!request || !(request.isGlobal || request.isSpecific) || request.frameControl.reservedBits !== 0)) {
|
|
441
|
+
throw routerError('payload must have a valid ZCL header to match a reply.', 'INVALID_PACKET');
|
|
442
|
+
}
|
|
443
|
+
const responseCommand = expect?.commandId ?? (request?.isGlobal ? attributeReplies.get(request.commandIdentifier) : undefined);
|
|
444
|
+
if (expect && responseCommand === undefined) {
|
|
445
|
+
throw routerError('Use --expect to select a reply for this ZCL command.', 'EXPECT_REQUIRED');
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
const aps = {
|
|
449
|
+
profileId,
|
|
450
|
+
clusterId,
|
|
451
|
+
sourceEndpoint,
|
|
452
|
+
destinationEndpoint,
|
|
453
|
+
groupId: 0,
|
|
454
|
+
sequence: 0,
|
|
455
|
+
options: EmberApsOption.RETRY | EmberApsOption.ENABLE_ROUTE_DISCOVERY,
|
|
456
|
+
};
|
|
457
|
+
const delivery = pendingEvent(timeout, signal, resolve => {
|
|
458
|
+
const listener = (status, type, target, _frame, messageTag) => {
|
|
459
|
+
if (type === EmberOutgoingMessageType.DIRECT && target === destination && messageTag === tag) {
|
|
460
|
+
resolve(status);
|
|
461
|
+
}
|
|
462
|
+
};
|
|
463
|
+
ezsp.on('messageSent', listener);
|
|
464
|
+
return () => ezsp.off('messageSent', listener);
|
|
465
|
+
}, 'adapter callback', 'DELIVERY_TIMEOUT');
|
|
466
|
+
const reply = expect && pendingEvent(expect.timeout, signal, resolve =>
|
|
467
|
+
observeAps(ezsp, (type, frame, lqi, source, payload) => {
|
|
468
|
+
if ((type === EmberIncomingMessageType.UNICAST || type === EmberIncomingMessageType.UNICAST_REPLY) &&
|
|
469
|
+
source === destination && frame.profileId === profileId && frame.clusterId === clusterId &&
|
|
470
|
+
frame.sourceEndpoint === destinationEndpoint && frame.destinationEndpoint === sourceEndpoint &&
|
|
471
|
+
matchesReply(request, responseCommand, payload)) {
|
|
472
|
+
resolve(apsPacket(frame, source, lqi, payload));
|
|
473
|
+
}
|
|
474
|
+
}), 'ZCL reply', 'REPLY_TIMEOUT');
|
|
475
|
+
try {
|
|
476
|
+
signal.throwIfAborted();
|
|
477
|
+
const [status] = await ezsp.ezspSendUnicast(EmberOutgoingMessageType.DIRECT, destination, aps, tag, message);
|
|
478
|
+
check(status, 'Queue write', 'QUEUE_FAILED');
|
|
479
|
+
const delivered = delivery.promise.then(result => check(result, 'Deliver write', 'DELIVERY_FAILED'));
|
|
480
|
+
if (!reply) {
|
|
481
|
+
await delivered;
|
|
482
|
+
return;
|
|
483
|
+
}
|
|
484
|
+
|
|
485
|
+
// A matching device response can arrive before the APS delivery callback, even if its ACK is lost.
|
|
486
|
+
let deliveryError;
|
|
487
|
+
delivered.catch(error => { deliveryError = error; });
|
|
488
|
+
try {
|
|
489
|
+
return await reply.promise;
|
|
490
|
+
} catch (error) {
|
|
491
|
+
signal.throwIfAborted();
|
|
492
|
+
throw deliveryError ?? error;
|
|
493
|
+
}
|
|
494
|
+
} finally {
|
|
495
|
+
reply?.close();
|
|
496
|
+
delivery.close();
|
|
497
|
+
}
|
|
498
|
+
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
// our tool writes a clean JSON stream to stdout, however ember-zli
|
|
2
|
+
// uses winston for logging, which pollutes stdout with log messages.
|
|
3
|
+
// to avoid that, we patch winston used by ember-zli to either use a
|
|
4
|
+
// null transport / logger or write to stderr for verbose logging.
|
|
5
|
+
import { createRequire } from 'node:module';
|
|
6
|
+
|
|
7
|
+
// resolve ember-zli's main file from *this* module
|
|
8
|
+
const requireHere = createRequire(import.meta.url);
|
|
9
|
+
const emberZliPath = requireHere.resolve('ember-zli');
|
|
10
|
+
|
|
11
|
+
// require from ember-zli's location
|
|
12
|
+
const requireFromEmberZli = createRequire(emberZliPath);
|
|
13
|
+
const winston = requireFromEmberZli('winston');
|
|
14
|
+
|
|
15
|
+
const debugLog = process.argv.findIndex(arg => arg.startsWith('-v')) >= 0;
|
|
16
|
+
|
|
17
|
+
// patch winston used by ember-zli
|
|
18
|
+
if (winston.transports.Console) {
|
|
19
|
+
const ConsoleTransport = winston.transports.Console,
|
|
20
|
+
originalLog = ConsoleTransport.prototype.log;
|
|
21
|
+
ConsoleTransport.prototype.log = !debugLog ? function(info, cb) {
|
|
22
|
+
typeof cb === 'function' && cb();
|
|
23
|
+
} : function(...args) {
|
|
24
|
+
this.forceConsole = true; // force to use _consoleLog instead of console._stdout
|
|
25
|
+
this._consoleLog = this._consoleError; // redirect to stderr
|
|
26
|
+
originalLog.apply(this, args);
|
|
27
|
+
};
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
if (winston.transports.File) {
|
|
31
|
+
const FileTransport = winston.transports.File;
|
|
32
|
+
FileTransport.prototype.log = function(info, cb) {
|
|
33
|
+
typeof cb === 'function' && cb();
|
|
34
|
+
};
|
|
35
|
+
}
|