ember-router 1.0.0 → 1.2.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 +36 -3
- package/index.js +90 -13
- package/package.json +1 -1
- package/request-socket.js +102 -0
- package/router.js +111 -29
package/README.md
CHANGED
|
@@ -15,12 +15,15 @@ npm install -g ember-router
|
|
|
15
15
|
```sh
|
|
16
16
|
ember-router join -p <path> [options]
|
|
17
17
|
ember-router run -p <path> [options]
|
|
18
|
+
ember-router read -p <path> [options]
|
|
18
19
|
ember-router write -p <path> [options]
|
|
19
20
|
ember-router reset -p <path> --yes [options]
|
|
20
21
|
```
|
|
21
22
|
|
|
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.
|
|
23
24
|
|
|
25
|
+
`read` sends one JSON packet from stdin and prints the matching ZCL reply.
|
|
26
|
+
|
|
24
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.
|
|
25
28
|
|
|
26
29
|
### Options
|
|
@@ -31,7 +34,10 @@ ember-router reset -p <path> --yes [options]
|
|
|
31
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.
|
|
32
35
|
- `--timeout <ms>` for scan and network callbacks (default `45000`).
|
|
33
36
|
- `-v, --verbose` for more diagnostics on stderr. Repeat for debug output during `run`.
|
|
34
|
-
- `--write-timeout <ms>` for `run` and `
|
|
37
|
+
- `--write-timeout <ms>` for `run`, `write`, and `read` to set the APS delivery timeout (default `15000`).
|
|
38
|
+
- `--read-timeout <ms>` for `read` and `run --socket` to set the ZCL reply timeout (default `5000`, range `100`–`300000`).
|
|
39
|
+
- `--expect <commandId>` for `read` and `run --socket` to select the ZCL reply command by decimal or `0x` value.
|
|
40
|
+
- `--socket <path>` for `run` to accept requests over a local Unix domain socket or a Windows named pipe.
|
|
35
41
|
|
|
36
42
|
#### Joining networks
|
|
37
43
|
|
|
@@ -81,7 +87,7 @@ ember-router reset -p tcp://192.168.1.42:6638 --yes
|
|
|
81
87
|
|
|
82
88
|
## Packet format
|
|
83
89
|
|
|
84
|
-
|
|
90
|
+
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.
|
|
85
91
|
|
|
86
92
|
```json
|
|
87
93
|
{"type":"aps","source":4660,"sourceEndpoint":1,"destinationEndpoint":1,"profileId":260,"clusterId":513,"lqi":180,"payload":"1842011200299e07"}
|
|
@@ -89,7 +95,7 @@ Stdout contains one JSON object per received packet. Diagnostics go to stderr. T
|
|
|
89
95
|
|
|
90
96
|
`zdo` packets use the same frame fields. `touchlink` packets carry `panId`, `source`, `groupId`, `lqi`, and `payload`.
|
|
91
97
|
|
|
92
|
-
Send one JSON object per line on stdin. The following example
|
|
98
|
+
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.
|
|
93
99
|
|
|
94
100
|
```json
|
|
95
101
|
{"destination":4660,"destinationEndpoint":1,"clusterId":513,"payload":"1001001200"}
|
|
@@ -97,3 +103,30 @@ Send one JSON object per line on stdin. The following example reads an attribute
|
|
|
97
103
|
|
|
98
104
|
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.
|
|
99
105
|
|
|
106
|
+
## Read format
|
|
107
|
+
|
|
108
|
+
Read the occupied heating setpoint (`0x0012`) from a thermostat at short address `4660`.
|
|
109
|
+
|
|
110
|
+
```sh
|
|
111
|
+
ember-router read -p tcp://192.168.1.42:6638 <<'EOF'
|
|
112
|
+
{"destination":4660,"clusterId":513,"payload":"1001001200"}
|
|
113
|
+
EOF
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
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.
|
|
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
|
+
```
|
|
123
|
+
|
|
124
|
+
### Local socket
|
|
125
|
+
|
|
126
|
+
```sh
|
|
127
|
+
ember-router run -p tcp://192.168.1.42:6638 --socket /path/to/private/ember-router.sock
|
|
128
|
+
```
|
|
129
|
+
|
|
130
|
+
Send one packet per JSON line and receive one reply per line in the same order. A failed request returns `null` and logs the error on stderr. Keep the connection open until replies arrive. The socket supports 16 clients and 8192 bytes per line, with one request active on the adapter at a time.
|
|
131
|
+
|
|
132
|
+
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
|
@@ -2,6 +2,8 @@
|
|
|
2
2
|
import { once } from 'node:events';
|
|
3
3
|
import { createInterface } from 'node:readline';
|
|
4
4
|
import { Command, InvalidArgumentError, Option } from 'commander';
|
|
5
|
+
import packageJson from './package.json' with { type: 'json' };
|
|
6
|
+
import { openRequestSocket } from './request-socket.js';
|
|
5
7
|
import { attachNetwork, capture, openRouter, resetRouter, sendPacket, SLStatus, Zcl } from './router.js';
|
|
6
8
|
|
|
7
9
|
function integer(min, max) {
|
|
@@ -34,7 +36,29 @@ function writeLog(level, message, namespace) {
|
|
|
34
36
|
process.stderr.write(`${prefix}: ${text}\n`);
|
|
35
37
|
}
|
|
36
38
|
|
|
37
|
-
|
|
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
|
+
function createSender(ezsp, timeout, signal) {
|
|
48
|
+
let tag = 0;
|
|
49
|
+
let pending = Promise.resolve();
|
|
50
|
+
return (packet, expect, requestSignal = signal) => {
|
|
51
|
+
const operation = pending.then(() => {
|
|
52
|
+
requestSignal.throwIfAborted();
|
|
53
|
+
tag = (tag + 1) & 0x7f;
|
|
54
|
+
return sendPacket(ezsp, packet, tag, timeout, requestSignal, expect);
|
|
55
|
+
});
|
|
56
|
+
pending = operation.catch(() => {});
|
|
57
|
+
return operation;
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
async function readWrites(send, signal) {
|
|
38
62
|
const { stdin } = process;
|
|
39
63
|
if (stdin.readableEnded || stdin.destroyed) {
|
|
40
64
|
return;
|
|
@@ -57,11 +81,7 @@ async function readWrites(ezsp, timeout, signal) {
|
|
|
57
81
|
}
|
|
58
82
|
|
|
59
83
|
try {
|
|
60
|
-
|
|
61
|
-
if (!packet || typeof packet !== 'object' || Array.isArray(packet)) {
|
|
62
|
-
throw new Error('Expected a packet object.');
|
|
63
|
-
}
|
|
64
|
-
await sendPacket(ezsp, packet, lineNumber & 0x7f, timeout, signal);
|
|
84
|
+
await send(parsePacket(line));
|
|
65
85
|
} catch (error) {
|
|
66
86
|
if (signal.aborted) {
|
|
67
87
|
break;
|
|
@@ -77,7 +97,29 @@ async function readWrites(ezsp, timeout, signal) {
|
|
|
77
97
|
}
|
|
78
98
|
}
|
|
79
99
|
|
|
80
|
-
async function
|
|
100
|
+
async function readPacketLine() {
|
|
101
|
+
const { stdin } = process;
|
|
102
|
+
const input = createInterface({ input: stdin, crlfDelay: Infinity, terminal: false });
|
|
103
|
+
try {
|
|
104
|
+
for await (const line of input) {
|
|
105
|
+
if (line.trim()) {
|
|
106
|
+
return line;
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
throw new Error('Expected a packet on stdin.');
|
|
110
|
+
} finally {
|
|
111
|
+
input.close();
|
|
112
|
+
stdin.pause();
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
async function readOnce(options) {
|
|
117
|
+
const packet = parsePacket(await readPacketLine());
|
|
118
|
+
const reply = await run(options, 'read', packet);
|
|
119
|
+
process.stdout.write(`${JSON.stringify(reply)}\n`);
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
async function run(options, mode, packet) {
|
|
81
123
|
const join = mode === 'join';
|
|
82
124
|
const stop = new AbortController();
|
|
83
125
|
const { signal } = stop;
|
|
@@ -99,6 +141,7 @@ async function run(options, mode) {
|
|
|
99
141
|
process.on('SIGTERM', interrupt);
|
|
100
142
|
process.stdout.on('error', brokenPipe);
|
|
101
143
|
let session;
|
|
144
|
+
let closeSocket;
|
|
102
145
|
try {
|
|
103
146
|
session = await openRouter(options, log);
|
|
104
147
|
signal.throwIfAborted();
|
|
@@ -116,7 +159,7 @@ async function run(options, mode) {
|
|
|
116
159
|
stop.abort(new Error('Network went down.'));
|
|
117
160
|
}
|
|
118
161
|
});
|
|
119
|
-
if (
|
|
162
|
+
if (mode === 'run' || mode === 'write') {
|
|
120
163
|
capture(ezsp, record => {
|
|
121
164
|
if (signal.aborted) {
|
|
122
165
|
return;
|
|
@@ -135,18 +178,41 @@ async function run(options, mode) {
|
|
|
135
178
|
}
|
|
136
179
|
|
|
137
180
|
signal.throwIfAborted();
|
|
138
|
-
|
|
181
|
+
const expect = { commandId: options.expect, timeout: options.readTimeout };
|
|
182
|
+
if (mode === 'read') {
|
|
183
|
+
return await sendPacket(ezsp, packet, 1, options.writeTimeout, signal, expect);
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
const send = createSender(ezsp, options.writeTimeout, signal);
|
|
187
|
+
if (options.socket !== undefined) {
|
|
188
|
+
const read = async (line, requestSignal) => {
|
|
189
|
+
try {
|
|
190
|
+
return await send(parsePacket(line), expect, requestSignal);
|
|
191
|
+
} catch (error) {
|
|
192
|
+
if (!requestSignal.aborted) {
|
|
193
|
+
writeLog('error', `Socket request: ${error.message}`);
|
|
194
|
+
}
|
|
195
|
+
return null;
|
|
196
|
+
}
|
|
197
|
+
};
|
|
198
|
+
closeSocket = await openRequestSocket(options.socket, read, signal, error => stop.abort(error));
|
|
199
|
+
}
|
|
200
|
+
await readWrites(send, signal);
|
|
139
201
|
if (!options.exitAfterWrite && !signal.aborted) {
|
|
140
202
|
await once(signal, 'abort');
|
|
141
203
|
}
|
|
142
204
|
signal.throwIfAborted();
|
|
143
205
|
} catch (error) {
|
|
144
|
-
if (error?.name !== 'AbortError' && error?.code !== 'EPIPE') {
|
|
206
|
+
if (mode === 'read' || (error?.name !== 'AbortError' && error?.code !== 'EPIPE')) {
|
|
145
207
|
throw error;
|
|
146
208
|
}
|
|
147
209
|
} finally {
|
|
148
210
|
try {
|
|
149
|
-
|
|
211
|
+
try {
|
|
212
|
+
await closeSocket?.();
|
|
213
|
+
} finally {
|
|
214
|
+
await session?.close();
|
|
215
|
+
}
|
|
150
216
|
} finally {
|
|
151
217
|
process.off('SIGINT', interrupt);
|
|
152
218
|
process.off('SIGTERM', interrupt);
|
|
@@ -155,7 +221,7 @@ async function run(options, mode) {
|
|
|
155
221
|
}
|
|
156
222
|
}
|
|
157
223
|
|
|
158
|
-
const program = new Command().name('ember-router')
|
|
224
|
+
const program = new Command().name('ember-router').version(packageJson.version)
|
|
159
225
|
.description('Resume a saved Zigbee router network and stream packets, or join an open network')
|
|
160
226
|
.requiredOption('-p, --path <path>', 'Serial port or tcp://host:port')
|
|
161
227
|
.option('-b, --baud-rate <rate>', 'Serial baud rate', integer(1, 4_000_000), 115200)
|
|
@@ -180,8 +246,15 @@ function packetOptions(command) {
|
|
|
180
246
|
.option('--write-timeout <ms>', 'Wait for each APS delivery status', integer(100, 300_000), 15000);
|
|
181
247
|
}
|
|
182
248
|
|
|
183
|
-
|
|
249
|
+
function readOptions(command) {
|
|
250
|
+
return packetOptions(command)
|
|
251
|
+
.option('--read-timeout <ms>', 'Wait for a matching ZCL reply', integer(100, 300_000), 5000)
|
|
252
|
+
.option('--expect <commandId>', 'Expected ZCL reply command ID (inferred for attribute reads and writes)', integer(0, 255));
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
readOptions(program.command('run', { isDefault: true }))
|
|
184
256
|
.description('Resume, stream received packets, and accept writes on stdin')
|
|
257
|
+
.option('--socket <path>', 'Listen for requests on a local IPC socket')
|
|
185
258
|
.action((_options, command) => {
|
|
186
259
|
const options = command.optsWithGlobals();
|
|
187
260
|
return run(options, 'run');
|
|
@@ -194,6 +267,10 @@ packetOptions(program.command('write'))
|
|
|
194
267
|
return run({ ...options, exitAfterWrite: true }, 'write');
|
|
195
268
|
});
|
|
196
269
|
|
|
270
|
+
readOptions(program.command('read'))
|
|
271
|
+
.description('Send one packet from stdin and print the matching reply')
|
|
272
|
+
.action((_options, command) => readOnce(command.optsWithGlobals()));
|
|
273
|
+
|
|
197
274
|
program.command('reset').description('Leave the saved network and reset NVM3 tokens')
|
|
198
275
|
.option('--yes', 'Confirm deletion of saved adapter state')
|
|
199
276
|
.option('--preserve-frame-counters', 'Keep outgoing network and APS frame counter tokens', false)
|
package/package.json
CHANGED
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
import { once } from 'node:events';
|
|
2
|
+
import { createServer } from 'node:net';
|
|
3
|
+
|
|
4
|
+
const MAX_CLIENTS = 16;
|
|
5
|
+
const MAX_LINE_BYTES = 8192;
|
|
6
|
+
|
|
7
|
+
function validateSocketPath(path) {
|
|
8
|
+
if (process.platform === 'win32') {
|
|
9
|
+
if (typeof path !== 'string' || !/^\\\\[.?]\\pipe\\[^\\/\0]+$/i.test(path)) {
|
|
10
|
+
throw new Error('Expected a Windows named pipe path (\\\\.\\pipe\\name).');
|
|
11
|
+
}
|
|
12
|
+
} else {
|
|
13
|
+
if (typeof path !== 'string' || !path.startsWith('/') || path.includes('\0')) {
|
|
14
|
+
throw new Error('Expected an absolute Unix socket path.');
|
|
15
|
+
}
|
|
16
|
+
const maxPathBytes = process.platform === 'linux' ? 107 : 103;
|
|
17
|
+
if (Buffer.byteLength(path) > maxPathBytes) {
|
|
18
|
+
throw new Error(`Socket path is longer than ${maxPathBytes} bytes.`);
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
function checkLineLength(line) {
|
|
24
|
+
if (Buffer.byteLength(line) > MAX_LINE_BYTES) {
|
|
25
|
+
throw new Error(`Request line exceeds ${MAX_LINE_BYTES} bytes.`);
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
async function serveClient(socket, handleRequest, signal) {
|
|
30
|
+
const disconnected = new AbortController();
|
|
31
|
+
socket.once('close', () => disconnected.abort());
|
|
32
|
+
const requestSignal = AbortSignal.any([signal, disconnected.signal]);
|
|
33
|
+
|
|
34
|
+
const reply = async line => {
|
|
35
|
+
checkLineLength(line);
|
|
36
|
+
if (!line.trim()) {
|
|
37
|
+
return;
|
|
38
|
+
}
|
|
39
|
+
requestSignal.throwIfAborted();
|
|
40
|
+
const result = await handleRequest(line, requestSignal);
|
|
41
|
+
requestSignal.throwIfAborted();
|
|
42
|
+
await new Promise((resolve, reject) => {
|
|
43
|
+
socket.write(`${JSON.stringify(result)}\n`, error => error ? reject(error) : resolve());
|
|
44
|
+
});
|
|
45
|
+
};
|
|
46
|
+
|
|
47
|
+
let buffer = '';
|
|
48
|
+
// Keep replies writable after a client half-closes.
|
|
49
|
+
for await (const chunk of socket.setEncoding('utf8').iterator({ destroyOnReturn: false })) {
|
|
50
|
+
buffer += chunk;
|
|
51
|
+
let newline;
|
|
52
|
+
while ((newline = buffer.indexOf('\n')) !== -1) {
|
|
53
|
+
const line = buffer.slice(0, newline);
|
|
54
|
+
buffer = buffer.slice(newline + 1);
|
|
55
|
+
await reply(line);
|
|
56
|
+
}
|
|
57
|
+
checkLineLength(buffer);
|
|
58
|
+
}
|
|
59
|
+
await reply(buffer);
|
|
60
|
+
socket.end();
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export async function openRequestSocket(path, handleRequest, signal, onError) {
|
|
64
|
+
validateSocketPath(path);
|
|
65
|
+
signal.throwIfAborted();
|
|
66
|
+
|
|
67
|
+
const clients = new Set();
|
|
68
|
+
const server = createServer({ allowHalfOpen: true }, socket => {
|
|
69
|
+
clients.add(socket);
|
|
70
|
+
socket.on('error', () => socket.destroy());
|
|
71
|
+
socket.once('close', () => clients.delete(socket));
|
|
72
|
+
serveClient(socket, handleRequest, signal).catch(() => socket.destroy());
|
|
73
|
+
});
|
|
74
|
+
server.maxConnections = MAX_CLIENTS;
|
|
75
|
+
|
|
76
|
+
let closing;
|
|
77
|
+
const close = () => {
|
|
78
|
+
if (!closing) {
|
|
79
|
+
signal.removeEventListener('abort', abort);
|
|
80
|
+
closing = new Promise(resolve => server.close(() => resolve()));
|
|
81
|
+
for (const socket of clients) {
|
|
82
|
+
socket.destroy();
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
return closing;
|
|
86
|
+
};
|
|
87
|
+
const abort = () => {
|
|
88
|
+
void close();
|
|
89
|
+
};
|
|
90
|
+
|
|
91
|
+
await once(server.listen(path), 'listening');
|
|
92
|
+
if (signal.aborted) {
|
|
93
|
+
await close();
|
|
94
|
+
signal.throwIfAborted();
|
|
95
|
+
}
|
|
96
|
+
server.on('error', error => {
|
|
97
|
+
void close();
|
|
98
|
+
onError?.(error);
|
|
99
|
+
});
|
|
100
|
+
signal.addEventListener('abort', abort, { once: true });
|
|
101
|
+
return close;
|
|
102
|
+
}
|
package/router.js
CHANGED
|
@@ -15,6 +15,7 @@ const { Zcl, ZSpec, setLogger } = requireEmber('zigbee-herdsman');
|
|
|
15
15
|
const {
|
|
16
16
|
EmberApsOption,
|
|
17
17
|
EmberExtendedSecurityBitmask,
|
|
18
|
+
EmberIncomingMessageType,
|
|
18
19
|
EmberInitialSecurityBitmask,
|
|
19
20
|
EmberJoinMethod,
|
|
20
21
|
EmberKeyStatus,
|
|
@@ -29,9 +30,13 @@ const { STACK_PROFILE_ZIGBEE_PRO } = requireEmber('zigbee-herdsman/dist/adapter/
|
|
|
29
30
|
|
|
30
31
|
export { SLStatus, Zcl };
|
|
31
32
|
|
|
32
|
-
function
|
|
33
|
+
function routerError(message, code) {
|
|
34
|
+
return Object.assign(new Error(message), code ? { code } : {});
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function check(status, operation, code) {
|
|
33
38
|
if (status !== SLStatus.OK) {
|
|
34
|
-
throw
|
|
39
|
+
throw routerError(`${operation}: ${SLStatus[status] ?? status}`, code);
|
|
35
40
|
}
|
|
36
41
|
}
|
|
37
42
|
|
|
@@ -60,7 +65,7 @@ export async function openRouter(options, log) {
|
|
|
60
65
|
}
|
|
61
66
|
}
|
|
62
67
|
|
|
63
|
-
function pendingEvent(timeout, signal, subscribe, description = 'adapter callback') {
|
|
68
|
+
function pendingEvent(timeout, signal, subscribe, description = 'adapter callback', timeoutCode) {
|
|
64
69
|
let unsubscribe;
|
|
65
70
|
let timer;
|
|
66
71
|
let abort;
|
|
@@ -70,7 +75,7 @@ function pendingEvent(timeout, signal, subscribe, description = 'adapter callbac
|
|
|
70
75
|
try {
|
|
71
76
|
signal.throwIfAborted();
|
|
72
77
|
unsubscribe = subscribe(resolve, reject);
|
|
73
|
-
timer = setTimeout(() => reject(
|
|
78
|
+
timer = setTimeout(() => reject(routerError(`Timed out waiting for ${description}.`, timeoutCode)), timeout);
|
|
74
79
|
} catch (error) {
|
|
75
80
|
reject(error);
|
|
76
81
|
}
|
|
@@ -336,10 +341,43 @@ export async function resetRouter(ezsp, options, signal) {
|
|
|
336
341
|
return eui64.replace(/^0x/i, '');
|
|
337
342
|
}
|
|
338
343
|
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
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 {
|
|
343
381
|
type: frame.profileId === 0 ? 'zdo' : 'aps',
|
|
344
382
|
source,
|
|
345
383
|
sourceEndpoint: frame.sourceEndpoint,
|
|
@@ -348,27 +386,38 @@ export function capture(ezsp, emit) {
|
|
|
348
386
|
clusterId: frame.clusterId,
|
|
349
387
|
lqi,
|
|
350
388
|
payload: payload.toString('hex'),
|
|
351
|
-
});
|
|
352
|
-
|
|
353
|
-
ezsp.ezspIncomingMessageHandler = (type, frame, info, payload) => {
|
|
354
|
-
packet(frame, info.senderShortId, info.lastHopLqi, payload);
|
|
355
|
-
dispatching = true;
|
|
356
|
-
try {
|
|
357
|
-
original(type, frame, info, payload);
|
|
358
|
-
} finally {
|
|
359
|
-
dispatching = false;
|
|
360
|
-
}
|
|
361
389
|
};
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
});
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
export function capture(ezsp, emit) {
|
|
393
|
+
observeAps(ezsp, (_type, frame, lqi, source, payload) => emit(apsPacket(frame, source, lqi, payload)));
|
|
367
394
|
ezsp.on('touchlinkMessage', (panId, source, groupId, lqi, payload) =>
|
|
368
395
|
emit({ type: 'touchlink', panId, source, groupId, lqi, payload: payload.toString('hex') }));
|
|
369
396
|
}
|
|
370
397
|
|
|
371
|
-
|
|
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) {
|
|
372
421
|
const { destination, destinationEndpoint = 1, sourceEndpoint = 1, profileId = ZSpec.HA_PROFILE_ID, clusterId, payload } = packet;
|
|
373
422
|
const fields = [
|
|
374
423
|
['destination', destination, 0, 0xfff7],
|
|
@@ -379,14 +428,23 @@ export async function sendPacket(ezsp, packet, tag, timeout, signal) {
|
|
|
379
428
|
];
|
|
380
429
|
for (const [label, value, min, max] of fields) {
|
|
381
430
|
if (!Number.isInteger(value) || value < min || value > max) {
|
|
382
|
-
throw
|
|
431
|
+
throw routerError(`Invalid ${label}.`, 'INVALID_PACKET');
|
|
383
432
|
}
|
|
384
433
|
}
|
|
385
434
|
if (typeof payload !== 'string' || !/^(?:[\da-f]{2})+$/i.test(payload)) {
|
|
386
|
-
throw
|
|
435
|
+
throw routerError('payload must be nonempty, even-length hex.', 'INVALID_PACKET');
|
|
387
436
|
}
|
|
388
437
|
|
|
389
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
|
+
|
|
390
448
|
const aps = {
|
|
391
449
|
profileId,
|
|
392
450
|
clusterId,
|
|
@@ -404,13 +462,37 @@ export async function sendPacket(ezsp, packet, tag, timeout, signal) {
|
|
|
404
462
|
};
|
|
405
463
|
ezsp.on('messageSent', listener);
|
|
406
464
|
return () => ezsp.off('messageSent', listener);
|
|
407
|
-
});
|
|
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');
|
|
408
475
|
try {
|
|
409
476
|
signal.throwIfAborted();
|
|
410
477
|
const [status] = await ezsp.ezspSendUnicast(EmberOutgoingMessageType.DIRECT, destination, aps, tag, message);
|
|
411
|
-
check(status, 'Queue write');
|
|
412
|
-
|
|
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
|
+
}
|
|
413
494
|
} finally {
|
|
495
|
+
reply?.close();
|
|
414
496
|
delivery.close();
|
|
415
497
|
}
|
|
416
498
|
}
|