ember-router 2.0.0 → 2.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 CHANGED
@@ -18,9 +18,11 @@ ember-router run -p <path> [options]
18
18
  ember-router read -p <path> [options]
19
19
  ember-router write -p <path> [options]
20
20
  ember-router reset -p <path> --yes [options]
21
+ ember-router encode
22
+ ember-router decode
21
23
  ```
22
24
 
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.
25
+ `run` is the default command (and can be omitted). It resumes the saved network, streams received packets to stdout, and reads packets to send from stdin. With empty or closed stdin, it continues receiving.
24
26
 
25
27
  `read` sends one packet from stdin and writes the matching ZCL reply to stdout.
26
28
 
@@ -28,7 +30,7 @@ ember-router reset -p <path> --yes [options]
28
30
 
29
31
  ### Options
30
32
 
31
- - `-p, --path <path>` for the serial port or TCP address (required).
33
+ - `-p, --path <path>` for the serial port or TCP address (required for adapter commands).
32
34
  - `-b, --baud-rate <rate>` for the serial baud rate (default `115200`).
33
35
  - `-r, --rtscts` to enable hardware flow control.
34
36
  - `-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.
@@ -44,7 +46,7 @@ ember-router reset -p <path> --yes [options]
44
46
 
45
47
  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
48
 
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.
49
+ Stdin, stdout, stderr, and local socket clients stay open during recovery. Interrupted requests and requests submitted while offline fail. Socket responses use the `00 00` failure marker 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.
48
50
 
49
51
  #### Joining networks
50
52
 
@@ -94,27 +96,64 @@ ember-router reset -p tcp://192.168.1.42:6638 --yes
94
96
 
95
97
  ## Binary packet format
96
98
 
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.
99
+ Starting with version 2.0, `read`, `write`, `run`, and `run --socket` use the same length-prefixed binary packets. 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 packet kind are specific to Ember Router. Payloads are raw Zigbee bytes. Diagnostics go to stderr.
98
100
 
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.
101
+ Each binary packet starts with a two-byte unsigned little-endian body length. It excludes the length field itself. The first byte of the body is the packet kind. All multi-byte values below are little-endian.
100
102
 
101
103
  | Kind | Body fields after the kind byte, in order |
102
104
  | --- | --- |
103
105
  | `0x00` APS or ZDO | Short address (2), profile ID (2), cluster ID (2), source endpoint (1), destination endpoint (1), LQI (1), raw payload |
104
106
  | `0x01` Touchlink | PAN ID (2), source EUI64 (8), group ID (2), LQI (1), raw payload |
105
107
 
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.
108
+ 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 packet. Stdin and socket clients send APS application unicasts. ZDO and Touchlink records are receive-only.
109
+
110
+ ### Encode and decode JSON Lines
111
+
112
+ `encode` converts JSON Lines requests to binary. It takes `destination`, `clusterId`, and a hex `payload`. Endpoints default to `1` and `profileId` to `260`.
113
+
114
+ `decode` converts received binary packets to JSON Lines. A socket failure decodes to `null`. Both commands work without an adapter.
115
+
116
+ ```sh
117
+ ember-router decode < capture.bin
118
+ ```
119
+
120
+ ### Node.js socket client
121
+
122
+ Connect to a running `ember-router run --socket` instance from Node.js:
123
+
124
+ ```js
125
+ import { createRouterClient } from 'ember-router/client';
126
+
127
+ const router = createRouterClient('/path/to/private/ember-router.sock', { timeout: 30_000 });
128
+ try {
129
+ const reply = await router.request({ destination: 4660, clusterId: 513, payload: '1001001200' });
130
+ console.log(reply);
131
+ } finally {
132
+ router.close();
133
+ }
134
+ ```
135
+
136
+ Requests share a connection and run one at a time. The timeout is in milliseconds and defaults to 30 seconds per exchange, starting when the request reaches the front of the queue. A router failure, timeout, or disconnect rejects the request. After a lost connection, the next request reconnects. A Zigbee error response is returned as a packet, so inspect its ZCL status when needed.
137
+
138
+ The package root exports the packet helpers. `encodePacket(packet)` produces request bytes, `decodePacket(bytes)` decodes one received packet, and `decodePackets(stream)` decodes a stream of packets.
107
139
 
108
140
  ### Read an attribute
109
141
 
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.
142
+ Read the occupied heating setpoint (`0x0012`) from short address `0x1234`, endpoint `1`, profile `0x0104`, and cluster `0x0201`.
143
+
144
+ ```sh
145
+ printf '%s\n' '{"destination":4660,"clusterId":513,"payload":"1001001200"}' |
146
+ ember-router encode | ember-router read -p tcp://192.168.1.42:6638 | ember-router decode
147
+ ```
148
+
149
+ The same request in binary can be sent and inspected with `xxd`.
111
150
 
112
151
  ```sh
113
152
  printf '%s' 0f00003412040101020101001001001200 | xxd -r -p |
114
153
  ember-router read -p tcp://192.168.1.42:6638 | xxd -g 1
115
154
  ```
116
155
 
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`.
156
+ 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 packet, 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`.
118
157
 
119
158
  ### Local socket
120
159
 
@@ -122,6 +161,6 @@ The request body is 15 bytes and ends with ZCL payload `10 01 00 12 00`. The rou
122
161
  ember-router run -p tcp://192.168.1.42:6638 --socket /path/to/private/ember-router.sock > capture.bin
123
162
  ```
124
163
 
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.
164
+ Send packets and receive their replies 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.
126
165
 
127
166
  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,9 +1,12 @@
1
1
  #!/usr/bin/env node
2
2
  import { addAbortListener, once } from 'node:events';
3
+ import { createInterface } from 'node:readline';
4
+ import { pipeline } from 'node:stream/promises';
3
5
  import { setTimeout as delay } from 'node:timers/promises';
4
6
  import { Command, InvalidArgumentError, Option } from 'commander';
5
7
  import packageJson from './package.json' with { type: 'json' };
6
- import { decodeOutgoing, encodePacket, readRecords } from './packet-wire.js';
8
+ import { decodePackets, encodePacket } from './packet.js';
9
+ import { decodeSendPacket, encodePacketBytes, readPacketBytes } from './packet-codec.js';
7
10
  import { openRequestSocket } from './request-socket.js';
8
11
  import { attachNetwork, capture, openRouter, resetRouter, sendPacket, SLStatus, Zcl } from './router.js';
9
12
 
@@ -63,22 +66,22 @@ async function readWrites(send, signal) {
63
66
  }
64
67
 
65
68
  const abort = addAbortListener(signal, () => stdin.destroy());
66
- let recordNumber = 0;
69
+ let packetNumber = 0;
67
70
  try {
68
- for await (const body of readRecords(stdin)) {
71
+ for await (const bytes of readPacketBytes(stdin)) {
69
72
  if (signal.aborted) {
70
73
  break;
71
74
  }
72
75
 
73
- recordNumber++;
76
+ packetNumber++;
74
77
  try {
75
- await send(decodeOutgoing(body));
78
+ await send(decodeSendPacket(bytes));
76
79
  } catch (error) {
77
80
  if (signal.aborted) {
78
81
  break;
79
82
  }
80
83
  process.exitCode = 1;
81
- writeLog('error', `Write record ${recordNumber}: ${error.message}`);
84
+ writeLog('error', `Write packet ${packetNumber}: ${error.message}`);
82
85
  }
83
86
  }
84
87
  } catch (error) {
@@ -93,8 +96,8 @@ async function readWrites(send, signal) {
93
96
  async function readPacket() {
94
97
  const { stdin } = process;
95
98
  try {
96
- for await (const body of readRecords(stdin)) {
97
- return decodeOutgoing(body);
99
+ for await (const bytes of readPacketBytes(stdin)) {
100
+ return decodeSendPacket(bytes);
98
101
  }
99
102
  throw new Error('Expected a packet on stdin.');
100
103
  } finally {
@@ -105,7 +108,43 @@ async function readPacket() {
105
108
  async function readOnce(options) {
106
109
  const packet = await readPacket();
107
110
  const reply = await run(options, 'read', packet);
108
- process.stdout.write(encodePacket(reply));
111
+ process.stdout.write(encodePacketBytes(reply));
112
+ }
113
+
114
+ async function* encodePackets(input) {
115
+ const lines = createInterface({ input, crlfDelay: Infinity, terminal: false });
116
+ let lineNumber = 0;
117
+ try {
118
+ for await (const line of lines) {
119
+ lineNumber++;
120
+ if (!line.trim()) {
121
+ continue;
122
+ }
123
+ try {
124
+ yield encodePacket(JSON.parse(line));
125
+ } catch (error) {
126
+ throw new Error(`Encode line ${lineNumber}: ${error.message}`);
127
+ }
128
+ }
129
+ } finally {
130
+ lines.close();
131
+ }
132
+ }
133
+
134
+ async function* decodeJsonLines(input) {
135
+ for await (const packet of decodePackets(input)) {
136
+ yield `${JSON.stringify(packet)}\n`;
137
+ }
138
+ }
139
+
140
+ async function convertPackets(packets) {
141
+ try {
142
+ await pipeline(process.stdin, packets, process.stdout);
143
+ } catch (error) {
144
+ if (error.code !== 'EPIPE') {
145
+ throw error;
146
+ }
147
+ }
109
148
  }
110
149
 
111
150
  async function closeSession(session) {
@@ -168,11 +207,11 @@ async function run(options, mode, packet) {
168
207
  }
169
208
  });
170
209
  if (streaming) {
171
- capture(ezsp, record => {
210
+ capture(ezsp, packet => {
172
211
  if (!captureReady || sessionSignal.aborted) {
173
212
  return;
174
213
  }
175
- process.stdout.write(encodePacket(record));
214
+ process.stdout.write(encodePacketBytes(packet));
176
215
  if (process.stdout.writableLength > 1024 * 1024) {
177
216
  stop.abort(new Error('Packet output consumer is too slow.'));
178
217
  }
@@ -254,9 +293,9 @@ async function run(options, mode, packet) {
254
293
  return session.send(packet, expect, requestSignal);
255
294
  };
256
295
  if (options.socket !== undefined) {
257
- const read = async (body, requestSignal) => {
296
+ const read = async (bytes, requestSignal) => {
258
297
  try {
259
- return await send(decodeOutgoing(body), expect, requestSignal);
298
+ return await send(decodeSendPacket(bytes), expect, requestSignal);
260
299
  } catch (error) {
261
300
  if (!requestSignal.aborted) {
262
301
  writeLog('error', `Socket request: ${error.message}`);
@@ -293,14 +332,20 @@ async function run(options, mode, packet) {
293
332
  }
294
333
 
295
334
  const program = new Command().name('ember-router').version(packageJson.version)
296
- .description('Resume a saved Zigbee router network and stream packets, or join an open network')
297
- .requiredOption('-p, --path <path>', 'Serial port or tcp://host:port')
335
+ .description('Run a Zigbee router, join a network, or convert packet formats')
336
+ .option('-p, --path <path>', 'Serial port or tcp://host:port (required for adapter commands)')
298
337
  .option('-b, --baud-rate <rate>', 'Serial baud rate', integer(1, 4_000_000), 115200)
299
338
  .option('-r, --rtscts', 'Use RTS/CTS flow control', false)
300
339
  .option('-m, --manufacturer-code <code>', 'ZCL manufacturer enum name, decimal or hex', manufacturer, Zcl.ManufacturerCode.SILICON_LABORATORIES)
301
340
  .option('--timeout <ms>', 'Network and scan callback timeout', integer(100, 300_000), 45000)
302
341
  .option('-v, --verbose', 'Increase diagnostic verbosity', (_, count) => count + 1, 0);
303
342
 
343
+ program.hook('preAction', (_program, command) => {
344
+ if (!['encode', 'decode'].includes(command.name()) && !command.optsWithGlobals().path) {
345
+ command.error("error: required option '-p, --path <path>' not specified");
346
+ }
347
+ });
348
+
304
349
  program.command('join').description('Join one matching open network and save membership on the adapter')
305
350
  .option('-c, --channel <channel>', 'Scan only this Zigbee channel', integer(11, 26))
306
351
  .option('--pan-id <pan>', 'Filter by decimal or 0x-prefixed PAN ID', integer(0, 0xfffe))
@@ -350,6 +395,14 @@ readOptions(program.command('read'))
350
395
  .description('Send one packet from stdin and print the matching reply')
351
396
  .action((_options, command) => readOnce(command.optsWithGlobals()));
352
397
 
398
+ program.command('encode')
399
+ .description('Encode packets to send from JSON Lines to binary')
400
+ .action(() => convertPackets(encodePackets));
401
+
402
+ program.command('decode')
403
+ .description('Decode received binary packets to JSON Lines')
404
+ .action(() => convertPackets(decodeJsonLines));
405
+
353
406
  program.command('reset').description('Leave the saved network and reset NVM3 tokens')
354
407
  .option('--yes', 'Confirm deletion of saved adapter state')
355
408
  .option('--preserve-frame-counters', 'Keep outgoing network and APS frame counter tokens', false)
package/package.json CHANGED
@@ -1,9 +1,13 @@
1
1
  {
2
2
  "name": "ember-router",
3
- "version": "2.0.0",
3
+ "version": "2.2.0",
4
4
  "description": "ZigBee router CLI for EmberZNet-based adapters using ember-zli and zigbee-herdsman",
5
5
  "type": "module",
6
6
  "bin": "./index.js",
7
+ "exports": {
8
+ ".": "./packet.js",
9
+ "./client": "./router-client.js"
10
+ },
7
11
  "files": [
8
12
  "*.js",
9
13
  "!.yarn/**"
@@ -0,0 +1,167 @@
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 || typeof packet !== 'object' || Array.isArray(packet)) {
9
+ throw new Error('Expected a packet to send.');
10
+ }
11
+ const { destination, profileId = 260, clusterId, sourceEndpoint = 1, destinationEndpoint = 1, payload } = packet;
12
+ validateSendPacket({ destination, profileId, clusterId, sourceEndpoint, destinationEndpoint });
13
+ if (typeof payload !== 'string' || !payload.length || payload.length % 2 || /[^0-9a-f]/i.test(payload)) {
14
+ throw new Error('payload must be nonempty, even-length hex.');
15
+ }
16
+ return encodePacketBytes({
17
+ type: 'aps', destination, profileId, clusterId, sourceEndpoint, destinationEndpoint,
18
+ lqi: 0, payload: Buffer.from(payload, 'hex'),
19
+ });
20
+ }
21
+
22
+ export function decodePacket(bytes) {
23
+ const body = packetBody(bytes);
24
+ if (!body.length) {
25
+ return null;
26
+ }
27
+ if (body[0] === TOUCHLINK_KIND) {
28
+ if (body.length < TOUCHLINK_HEADER_BYTES) {
29
+ throw new Error('Truncated Touchlink packet.');
30
+ }
31
+ return {
32
+ type: 'touchlink',
33
+ panId: body.readUInt16LE(1),
34
+ source: `0x${body.readBigUInt64LE(3).toString(16).padStart(16, '0')}`,
35
+ groupId: body.readUInt16LE(11),
36
+ lqi: body[13],
37
+ payload: body.subarray(TOUCHLINK_HEADER_BYTES).toString('hex'),
38
+ };
39
+ }
40
+
41
+ const { address, payload, ...fields } = decodeApsFields(body);
42
+ return {
43
+ type: fields.profileId === 0 ? 'zdo' : 'aps',
44
+ source: address,
45
+ ...fields,
46
+ lqi: body[9],
47
+ payload: payload.toString('hex'),
48
+ };
49
+ }
50
+
51
+ export async function* decodePackets(stream) {
52
+ for await (const bytes of readPacketBytes(stream)) {
53
+ yield decodePacket(bytes);
54
+ }
55
+ }
56
+
57
+ // Binary packet I/O for the router.
58
+ export function decodeSendPacket(bytes) {
59
+ const { address, ...fields } = decodeApsFields(packetBody(bytes));
60
+ return { destination: address, ...fields };
61
+ }
62
+
63
+ export function validateSendPacket({ destination, profileId, clusterId, sourceEndpoint, destinationEndpoint }) {
64
+ const fields = [
65
+ ['destination', destination, 0, 0xfff7],
66
+ ['profileId', profileId, 1, 0xffff],
67
+ ['clusterId', clusterId, 0, 0xffff],
68
+ ['sourceEndpoint', sourceEndpoint, 1, 254],
69
+ ['destinationEndpoint', destinationEndpoint, 1, 240],
70
+ ];
71
+ for (const [name, value, min, max] of fields) {
72
+ if (!Number.isInteger(value) || value < min || value > max) {
73
+ throw Object.assign(new Error(`Invalid ${name}.`), { code: 'INVALID_PACKET' });
74
+ }
75
+ }
76
+ }
77
+
78
+ export function encodePacketBytes(packet) {
79
+ if (packet === null) {
80
+ return Buffer.alloc(LENGTH_BYTES);
81
+ }
82
+
83
+ const touchlink = packet.type === 'touchlink';
84
+ if (!touchlink && packet.type !== 'aps' && packet.type !== 'zdo') {
85
+ throw new TypeError(`Unsupported packet type: ${packet.type}.`);
86
+ }
87
+ const headerBytes = touchlink ? TOUCHLINK_HEADER_BYTES : APS_HEADER_BYTES;
88
+ const length = headerBytes + packet.payload.length;
89
+ if (length > 0xffff) {
90
+ throw new RangeError('Packet body exceeds 65535 bytes.');
91
+ }
92
+
93
+ const bytes = Buffer.allocUnsafe(LENGTH_BYTES + length);
94
+ bytes.writeUInt16LE(length);
95
+ const body = bytes.subarray(LENGTH_BYTES);
96
+ if (touchlink) {
97
+ body[0] = TOUCHLINK_KIND;
98
+ body.writeUInt16LE(packet.panId, 1);
99
+ body.writeBigUInt64LE(packet.source, 3);
100
+ body.writeUInt16LE(packet.groupId, 11);
101
+ body[13] = packet.lqi;
102
+ } else {
103
+ body[0] = APS_KIND;
104
+ body.writeUInt16LE(packet.destination ?? packet.source, 1);
105
+ body.writeUInt16LE(packet.profileId, 3);
106
+ body.writeUInt16LE(packet.clusterId, 5);
107
+ body[7] = packet.sourceEndpoint;
108
+ body[8] = packet.destinationEndpoint;
109
+ body[9] = packet.lqi;
110
+ }
111
+ packet.payload.copy(body, headerBytes);
112
+ return bytes;
113
+ }
114
+
115
+ export async function* readPacketBytes(stream) {
116
+ const prefix = Buffer.allocUnsafe(LENGTH_BYTES);
117
+ let bytes = prefix;
118
+ let written = 0;
119
+
120
+ for await (const chunk of stream.iterator({ destroyOnReturn: false })) {
121
+ for (let offset = 0; offset < chunk.length;) {
122
+ const copied = chunk.copy(bytes, written, offset, offset + bytes.length - written);
123
+ offset += copied;
124
+ written += copied;
125
+ if (written < bytes.length) {
126
+ continue;
127
+ }
128
+ if (bytes === prefix) {
129
+ bytes = Buffer.allocUnsafe(LENGTH_BYTES + prefix.readUInt16LE(0));
130
+ prefix.copy(bytes);
131
+ if (written < bytes.length) {
132
+ continue;
133
+ }
134
+ }
135
+
136
+ const packet = bytes;
137
+ bytes = prefix;
138
+ written = 0;
139
+ yield packet;
140
+ }
141
+ }
142
+ if (bytes !== prefix || written !== 0) {
143
+ throw new Error('Truncated binary packet.');
144
+ }
145
+ }
146
+
147
+ function packetBody(bytes) {
148
+ if (!Buffer.isBuffer(bytes) || bytes.length < LENGTH_BYTES ||
149
+ bytes.readUInt16LE(0) !== bytes.length - LENGTH_BYTES) {
150
+ throw new Error('Expected one complete binary packet.');
151
+ }
152
+ return bytes.subarray(LENGTH_BYTES);
153
+ }
154
+
155
+ function decodeApsFields(body) {
156
+ if (body.length < APS_HEADER_BYTES || body[0] !== APS_KIND) {
157
+ throw new Error('Expected an APS packet.');
158
+ }
159
+ return {
160
+ address: body.readUInt16LE(1),
161
+ profileId: body.readUInt16LE(3),
162
+ clusterId: body.readUInt16LE(5),
163
+ sourceEndpoint: body[7],
164
+ destinationEndpoint: body[8],
165
+ payload: body.subarray(APS_HEADER_BYTES),
166
+ };
167
+ }
package/packet.js ADDED
@@ -0,0 +1 @@
1
+ export { decodePacket, decodePackets, encodePacket } from './packet-codec.js';
package/request-socket.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { once } from 'node:events';
2
2
  import { createServer } from 'node:net';
3
- import { encodePacket, readRecords } from "./packet-wire.js";
3
+ import { encodePacketBytes, readPacketBytes } from "./packet-codec.js";
4
4
 
5
5
  const MAX_CLIENTS = 16;
6
6
 
@@ -25,12 +25,12 @@ async function serveClient(socket, handleRequest, signal) {
25
25
  socket.once('close', () => disconnected.abort());
26
26
  const requestSignal = AbortSignal.any([signal, disconnected.signal]);
27
27
 
28
- for await (const body of readRecords(socket)) {
28
+ for await (const bytes of readPacketBytes(socket)) {
29
29
  requestSignal.throwIfAborted();
30
- const result = await handleRequest(body, requestSignal);
30
+ const result = await handleRequest(bytes, requestSignal);
31
31
  requestSignal.throwIfAborted();
32
32
  await new Promise((resolve, reject) => {
33
- socket.write(encodePacket(result), error => error ? reject(error) : resolve());
33
+ socket.write(encodePacketBytes(result), error => error ? reject(error) : resolve());
34
34
  });
35
35
  }
36
36
  socket.end();
@@ -0,0 +1,61 @@
1
+ import { createConnection } from "node:net";
2
+ import { decodePackets, encodePacket } from "./packet.js";
3
+
4
+ export function createRouterClient(path, { timeout = 30_000 } = {}) {
5
+ if (typeof path !== "string" || !path || path.includes("\0")) {
6
+ throw new TypeError("Expected a local socket or named pipe path.");
7
+ }
8
+ if (!Number.isInteger(timeout) || timeout < 0) {
9
+ throw new RangeError("timeout must be a positive integer.");
10
+ }
11
+
12
+ let connection;
13
+ let closed = false;
14
+ let pending = Promise.resolve();
15
+
16
+ async function exchange(bytes) {
17
+ if (closed) {
18
+ throw new Error("Router client is closed.");
19
+ }
20
+ if (!connection || connection.socket.destroyed || connection.socket.readableEnded) {
21
+ const socket = createConnection({ path });
22
+ // the decoder observes errors during exchanges. handle idle socket errors too
23
+ socket.on("error", () => {});
24
+ connection = { socket, replies: decodePackets(socket) };
25
+ }
26
+
27
+ const { socket, replies } = connection;
28
+ const deadline = setTimeout(() => socket.destroy(new Error("Timed out waiting for the router reply.")), timeout);
29
+ try {
30
+ socket.write(bytes);
31
+ const { done, value } = await replies.next();
32
+ if (done) {
33
+ throw new Error("Router disconnected before replying.");
34
+ }
35
+ return value;
36
+ } catch (error) {
37
+ socket.destroy();
38
+ throw error;
39
+ } finally {
40
+ clearTimeout(deadline);
41
+ }
42
+ }
43
+
44
+ return {
45
+ async request(packet) {
46
+ const bytes = encodePacket(packet);
47
+ // the socket protocol matches replies to requests by order
48
+ const result = pending.then(() => exchange(bytes));
49
+ pending = result.catch(() => {});
50
+ const reply = await result;
51
+ if (reply === null) {
52
+ throw new Error("Router could not complete the Zigbee request.");
53
+ }
54
+ return reply;
55
+ },
56
+ close() {
57
+ closed = true;
58
+ connection?.socket.destroy();
59
+ },
60
+ };
61
+ }
package/router.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import './silence-ember-zli.js';
2
2
  import { createRequire } from 'node:module';
3
3
  import { createInterview } from './interview.js';
4
+ import { validateSendPacket } from './packet-codec.js';
4
5
  import {
5
6
  emberNetworkConfig,
6
7
  emberNetworkInit,
@@ -442,7 +443,7 @@ function apsPacket(frame, source, lqi, payload) {
442
443
  export function capture(ezsp, emit) {
443
444
  observeAps(ezsp, (_type, frame, lqi, source, payload) => emit(apsPacket(frame, source, lqi, payload)));
444
445
  ezsp.on('touchlinkMessage', (panId, source, groupId, lqi, payload) =>
445
- emit({ type: 'touchlink', panId, source, groupId, lqi, payload }));
446
+ emit({ type: 'touchlink', panId, source: BigInt(source), groupId, lqi, payload }));
446
447
  }
447
448
 
448
449
  const attributeReplies = new Map([
@@ -469,18 +470,7 @@ function matchesReply(request, commandId, payload) {
469
470
 
470
471
  export async function sendPacket(ezsp, packet, tag, timeout, signal, expect) {
471
472
  const { destination, destinationEndpoint = 1, sourceEndpoint = 1, profileId = ZSpec.HA_PROFILE_ID, clusterId, payload } = packet;
472
- const fields = [
473
- ['destination', destination, 0, 0xfff7],
474
- ['sourceEndpoint', sourceEndpoint, 1, 254],
475
- ['destinationEndpoint', destinationEndpoint, 1, 240],
476
- ['clusterId', clusterId, 0, 0xffff],
477
- ['profileId', profileId, 1, 0xffff],
478
- ];
479
- for (const [label, value, min, max] of fields) {
480
- if (!Number.isInteger(value) || value < min || value > max) {
481
- throw routerError(`Invalid ${label}.`, 'INVALID_PACKET');
482
- }
483
- }
473
+ validateSendPacket({ destination, profileId, clusterId, sourceEndpoint, destinationEndpoint });
484
474
  // SEND_UNICAST uses three bytes for mode and destination, eleven for the APS frame, and one for payload length.
485
475
  const messageTagLength = ezsp.version < 0x0e ? 1 : 2;
486
476
  const maxPayloadLength = EZSP_MAX_FRAME_LENGTH - EZSP_EXTENDED_PARAMETERS_INDEX - 3 - 11 - messageTagLength - 1;
package/packet-wire.js DELETED
@@ -1,88 +0,0 @@
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
- }