ember-router 1.3.0 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  A command-line utility for using an EmberZNet adapter as a router on an existing Zigbee network. Ember Router connects over serial or TCP to an adapter running EmberZNet coordinator (NCP) firmware, following the approach described in the [ember-zli Router wiki](https://github.com/Nerivec/ember-zli/wiki/Router). It can join an open network or resume the network saved on the adapter.
4
4
 
5
- The utility 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.
5
+ The utility exchanges binary packets over stdin, stdout, or a local socket. It can send a finite batch or stay connected to receive packets and accept writes in the same session. The adapter can remain a router while powered after the CLI exits. Keep a session running to stream packets to the host.
6
6
 
7
7
  ## Installation
8
8
 
@@ -22,7 +22,7 @@ ember-router reset -p <path> --yes [options]
22
22
 
23
23
  `run` is the default command (and can be omitted). It resumes the saved network, streams received packets to stdout, and accepts outgoing packets on stdin. With empty or closed stdin, it continues receiving.
24
24
 
25
- `read` sends one JSON packet from stdin and prints the matching ZCL reply.
25
+ `read` sends one packet from stdin and writes the matching ZCL reply to stdout.
26
26
 
27
27
  `write` resumes the saved network and sends a single packet or a batch from stdin. It exits after stdin closes and all submitted packets have been processed.
28
28
 
@@ -44,7 +44,7 @@ ember-router reset -p <path> --yes [options]
44
44
 
45
45
  After a session starts, `-g` waits 5 seconds and makes one recovery attempt per adapter loss. `-gg` continues with exponential backoff capped at 120 seconds. Recovery resumes the network saved on the adapter. Initial startup failures still exit with an error.
46
46
 
47
- Stdin, stdout, stderr, and local socket clients stay open during recovery. Interrupted requests and requests submitted while offline fail. Socket requests return `null` and writes report errors on stderr. Once the adapter reconnects, the router can handle new requests. `write` still exits after EOF and reports any failed packets in its exit status.
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.
48
48
 
49
49
  #### Joining networks
50
50
 
@@ -64,7 +64,7 @@ Stdin, stdout, stderr, and local socket clients stay open during recovery. Inter
64
64
 
65
65
  `ember-router reset -p <path> --yes` leaves the saved Zigbee network, then resets the adapter's NVM3 tokens. If there is no saved network, it resets the tokens directly. This erases persisted adapter state. Back up tokens with ember-zli first if you need to restore that state.
66
66
 
67
- After a successful reset, stdout contains the adapter's EUI64, also called EUID. Diagnostics go to stderr.
67
+ After a successful reset, the adapter's EUI64, also called EUID, is reported on stderr.
68
68
 
69
69
  - `--yes` confirms the reset (required).
70
70
  - `--preserve-frame-counters` keeps the outgoing network and APS frame counter tokens.
@@ -80,60 +80,48 @@ ember-router join -p tcp://192.168.1.42:6638 -c 19 --pan-id 0x8cde
80
80
  ember-router join -p tcp://192.168.1.42:6638 -c 19 -l 00112233445566778899aabbccddeeff
81
81
 
82
82
  # Resume the saved network and receive packets
83
- ember-router -p tcp://192.168.1.42:6638
83
+ ember-router -p tcp://192.168.1.42:6638 > capture.bin
84
84
 
85
85
  # Send packets from stdin and keep receiving after stdin closes
86
- cat packets.jsonl | ember-router run -p tcp://192.168.1.42:6638
86
+ ember-router run -p tcp://192.168.1.42:6638 < requests.bin > capture.bin
87
87
 
88
88
  # Send a finite batch and exit
89
- cat packets.jsonl | ember-router write -p tcp://192.168.1.42:6638
89
+ ember-router write -p tcp://192.168.1.42:6638 < requests.bin > capture.bin
90
90
 
91
91
  # Leave network, reset the adapter and print the EUI64
92
92
  ember-router reset -p tcp://192.168.1.42:6638 --yes
93
93
  ```
94
94
 
95
- ## Packet format
95
+ ## Binary packet format
96
96
 
97
- 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.
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.
98
98
 
99
- ```json
100
- {"type":"aps","source":4660,"sourceEndpoint":1,"destinationEndpoint":1,"profileId":260,"clusterId":513,"lqi":180,"payload":"1842011200299e07"}
101
- ```
102
-
103
- `zdo` packets use the same frame fields. `touchlink` packets carry `panId`, `source`, `groupId`, `lqi`, and `payload`.
99
+ Each record starts with a two-byte unsigned little-endian body length. It excludes the length field itself. The first byte of the body is the record kind. All multi-byte values below are little-endian.
104
100
 
105
- 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.
106
-
107
- ```json
108
- {"destination":4660,"destinationEndpoint":1,"clusterId":513,"payload":"1001001200"}
109
- ```
101
+ | Kind | Body fields after the kind byte, in order |
102
+ | --- | --- |
103
+ | `0x00` APS or ZDO | Short address (2), profile ID (2), cluster ID (2), source endpoint (1), destination endpoint (1), LQI (1), raw payload |
104
+ | `0x01` Touchlink | PAN ID (2), source EUI64 (8), group ID (2), LQI (1), raw payload |
110
105
 
111
- 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.
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.
112
107
 
113
- ## Read format
108
+ ### Read an attribute
114
109
 
115
- Read the occupied heating setpoint (`0x0012`) from a thermostat at short address `4660`.
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.
116
111
 
117
112
  ```sh
118
- ember-router read -p tcp://192.168.1.42:6638 <<'EOF'
119
- {"destination":4660,"clusterId":513,"payload":"1001001200"}
120
- EOF
113
+ printf '%s' 0f00003412040101020101001001001200 | xxd -r -p |
114
+ ember-router read -p tcp://192.168.1.42:6638 | xxd -g 1
121
115
  ```
122
116
 
123
- 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.
124
-
125
- `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`.
126
-
127
- ```json
128
- {"type":"aps","source":4660,"sourceEndpoint":1,"destinationEndpoint":1,"profileId":260,"clusterId":513,"lqi":180,"payload":"180101120000299e07"}
129
- ```
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`.
130
118
 
131
119
  ### Local socket
132
120
 
133
121
  ```sh
134
- ember-router run -p tcp://192.168.1.42:6638 --socket /path/to/private/ember-router.sock
122
+ ember-router run -p tcp://192.168.1.42:6638 --socket /path/to/private/ember-router.sock > capture.bin
135
123
  ```
136
124
 
137
- 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.
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.
138
126
 
139
127
  Use a private directory for the Unix socket. If a crash leaves a stale socket, confirm it is unused before removing it. On Windows, use a named pipe such as `\\.\pipe\ember-router`.
package/index.js CHANGED
@@ -1,9 +1,9 @@
1
1
  #!/usr/bin/env node
2
2
  import { addAbortListener, once } from 'node:events';
3
- import { createInterface } from 'node:readline';
4
3
  import { setTimeout as delay } from 'node:timers/promises';
5
4
  import { Command, InvalidArgumentError, Option } from 'commander';
6
5
  import packageJson from './package.json' with { type: 'json' };
6
+ import { decodeOutgoing, encodePacket, readRecords } from './packet-wire.js';
7
7
  import { openRequestSocket } from './request-socket.js';
8
8
  import { attachNetwork, capture, openRouter, resetRouter, sendPacket, SLStatus, Zcl } from './router.js';
9
9
 
@@ -37,14 +37,6 @@ function writeLog(level, message, namespace) {
37
37
  process.stderr.write(`${prefix}: ${text}\n`);
38
38
  }
39
39
 
40
- function parsePacket(line) {
41
- const packet = JSON.parse(line);
42
- if (packet === null || typeof packet !== 'object' || Array.isArray(packet)) {
43
- throw new Error('Expected a packet object.');
44
- }
45
- return packet;
46
- }
47
-
48
40
  function createSender(ezsp, timeout, signal) {
49
41
  let tag = 0;
50
42
  let pending = Promise.resolve();
@@ -70,59 +62,50 @@ async function readWrites(send, signal) {
70
62
  return;
71
63
  }
72
64
 
73
- const input = createInterface({ input: stdin, crlfDelay: Infinity, terminal: false });
74
- const closeInput = () => input.close();
75
- signal.addEventListener('abort', closeInput, { once: true });
76
-
77
- let lineNumber = 0;
65
+ const abort = addAbortListener(signal, () => stdin.destroy());
66
+ let recordNumber = 0;
78
67
  try {
79
- for await (const line of input) {
68
+ for await (const body of readRecords(stdin)) {
80
69
  if (signal.aborted) {
81
70
  break;
82
71
  }
83
72
 
84
- lineNumber++;
85
- if (!line.trim()) {
86
- continue;
87
- }
88
-
73
+ recordNumber++;
89
74
  try {
90
- await send(parsePacket(line));
75
+ await send(decodeOutgoing(body));
91
76
  } catch (error) {
92
77
  if (signal.aborted) {
93
78
  break;
94
79
  }
95
80
  process.exitCode = 1;
96
- writeLog('error', `Write line ${lineNumber}: ${error.message}`);
81
+ writeLog('error', `Write record ${recordNumber}: ${error.message}`);
97
82
  }
98
83
  }
84
+ } catch (error) {
85
+ signal.throwIfAborted();
86
+ throw error;
99
87
  } finally {
100
- signal.removeEventListener('abort', closeInput);
101
- input.close();
88
+ abort[Symbol.dispose]();
102
89
  stdin.pause();
103
90
  }
104
91
  }
105
92
 
106
- async function readPacketLine() {
93
+ async function readPacket() {
107
94
  const { stdin } = process;
108
- const input = createInterface({ input: stdin, crlfDelay: Infinity, terminal: false });
109
95
  try {
110
- for await (const line of input) {
111
- if (line.trim()) {
112
- return line;
113
- }
96
+ for await (const body of readRecords(stdin)) {
97
+ return decodeOutgoing(body);
114
98
  }
115
99
  throw new Error('Expected a packet on stdin.');
116
100
  } finally {
117
- input.close();
118
101
  stdin.pause();
119
102
  }
120
103
  }
121
104
 
122
105
  async function readOnce(options) {
123
- const packet = parsePacket(await readPacketLine());
106
+ const packet = await readPacket();
124
107
  const reply = await run(options, 'read', packet);
125
- process.stdout.write(`${JSON.stringify(reply)}\n`);
108
+ process.stdout.write(encodePacket(reply));
126
109
  }
127
110
 
128
111
  async function closeSession(session) {
@@ -189,9 +172,9 @@ async function run(options, mode, packet) {
189
172
  if (!captureReady || sessionSignal.aborted) {
190
173
  return;
191
174
  }
192
- process.stdout.write(`${JSON.stringify(record)}\n`);
175
+ process.stdout.write(encodePacket(record));
193
176
  if (process.stdout.writableLength > 1024 * 1024) {
194
- stop.abort(new Error('JSON output consumer is too slow.'));
177
+ stop.abort(new Error('Packet output consumer is too slow.'));
195
178
  }
196
179
  });
197
180
  }
@@ -271,9 +254,9 @@ async function run(options, mode, packet) {
271
254
  return session.send(packet, expect, requestSignal);
272
255
  };
273
256
  if (options.socket !== undefined) {
274
- const read = async (line, requestSignal) => {
257
+ const read = async (body, requestSignal) => {
275
258
  try {
276
- return await send(parsePacket(line), expect, requestSignal);
259
+ return await send(decodeOutgoing(body), expect, requestSignal);
277
260
  } catch (error) {
278
261
  if (!requestSignal.aborted) {
279
262
  writeLog('error', `Socket request: ${error.message}`);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ember-router",
3
- "version": "1.3.0",
3
+ "version": "2.0.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",
package/packet-wire.js ADDED
@@ -0,0 +1,88 @@
1
+ const LENGTH_BYTES = 2;
2
+ const APS_KIND = 0;
3
+ const TOUCHLINK_KIND = 1;
4
+ const APS_HEADER_BYTES = 10;
5
+ const TOUCHLINK_HEADER_BYTES = 14;
6
+
7
+ export function encodePacket(packet) {
8
+ if (packet === null) {
9
+ return Buffer.alloc(LENGTH_BYTES);
10
+ }
11
+
12
+ const touchlink = packet.type === 'touchlink';
13
+ if (!touchlink && packet.type !== 'aps' && packet.type !== 'zdo') {
14
+ throw new TypeError(`Unsupported packet type: ${packet.type}.`);
15
+ }
16
+ const headerBytes = touchlink ? TOUCHLINK_HEADER_BYTES : APS_HEADER_BYTES;
17
+ const length = headerBytes + packet.payload.length;
18
+ if (length > 0xffff) {
19
+ throw new RangeError('Packet exceeds the maximum record length.');
20
+ }
21
+
22
+ const record = Buffer.allocUnsafe(LENGTH_BYTES + length);
23
+ record.writeUInt16LE(length);
24
+ const body = record.subarray(LENGTH_BYTES);
25
+ if (touchlink) {
26
+ body[0] = TOUCHLINK_KIND;
27
+ body.writeUInt16LE(packet.panId, 1);
28
+ body.writeBigUInt64LE(BigInt(packet.source), 3);
29
+ body.writeUInt16LE(packet.groupId, 11);
30
+ body[13] = packet.lqi;
31
+ } else {
32
+ body[0] = APS_KIND;
33
+ body.writeUInt16LE(packet.source, 1);
34
+ body.writeUInt16LE(packet.profileId, 3);
35
+ body.writeUInt16LE(packet.clusterId, 5);
36
+ body[7] = packet.sourceEndpoint;
37
+ body[8] = packet.destinationEndpoint;
38
+ body[9] = packet.lqi;
39
+ }
40
+ packet.payload.copy(body, headerBytes);
41
+ return record;
42
+ }
43
+
44
+ export function decodeOutgoing(body) {
45
+ if (body.length < APS_HEADER_BYTES || body[0] !== APS_KIND) {
46
+ throw new Error('Expected an APS packet.');
47
+ }
48
+ return {
49
+ destination: body.readUInt16LE(1),
50
+ profileId: body.readUInt16LE(3),
51
+ clusterId: body.readUInt16LE(5),
52
+ sourceEndpoint: body[7],
53
+ destinationEndpoint: body[8],
54
+ payload: body.subarray(APS_HEADER_BYTES),
55
+ };
56
+ }
57
+
58
+ export async function* readRecords(stream) {
59
+ const length = Buffer.allocUnsafe(LENGTH_BYTES);
60
+ let buffer = length;
61
+ let written = 0;
62
+
63
+ for await (const chunk of stream.iterator({ destroyOnReturn: false })) {
64
+ for (let offset = 0; offset < chunk.length;) {
65
+ const copied = chunk.copy(buffer, written, offset, offset + buffer.length - written);
66
+ offset += copied;
67
+ written += copied;
68
+ if (written < buffer.length) {
69
+ continue;
70
+ }
71
+ if (buffer === length) {
72
+ buffer = Buffer.allocUnsafe(length.readUInt16LE());
73
+ written = 0;
74
+ if (buffer.length) {
75
+ continue;
76
+ }
77
+ }
78
+
79
+ const body = buffer;
80
+ buffer = length;
81
+ written = 0;
82
+ yield body;
83
+ }
84
+ }
85
+ if (buffer !== length || written !== 0) {
86
+ throw new Error('Truncated packet record.');
87
+ }
88
+ }
package/request-socket.js CHANGED
@@ -1,8 +1,8 @@
1
1
  import { once } from 'node:events';
2
2
  import { createServer } from 'node:net';
3
+ import { encodePacket, readRecords } from "./packet-wire.js";
3
4
 
4
5
  const MAX_CLIENTS = 16;
5
- const MAX_LINE_BYTES = 8192;
6
6
 
7
7
  function validateSocketPath(path) {
8
8
  if (process.platform === 'win32') {
@@ -20,43 +20,19 @@ function validateSocketPath(path) {
20
20
  }
21
21
  }
22
22
 
23
- function checkLineLength(line) {
24
- if (Buffer.byteLength(line) > MAX_LINE_BYTES) {
25
- throw new Error(`Request line exceeds ${MAX_LINE_BYTES} bytes.`);
26
- }
27
- }
28
-
29
23
  async function serveClient(socket, handleRequest, signal) {
30
24
  const disconnected = new AbortController();
31
25
  socket.once('close', () => disconnected.abort());
32
26
  const requestSignal = AbortSignal.any([signal, disconnected.signal]);
33
27
 
34
- const reply = async line => {
35
- checkLineLength(line);
36
- if (!line.trim()) {
37
- return;
38
- }
28
+ for await (const body of readRecords(socket)) {
39
29
  requestSignal.throwIfAborted();
40
- const result = await handleRequest(line, requestSignal);
30
+ const result = await handleRequest(body, requestSignal);
41
31
  requestSignal.throwIfAborted();
42
32
  await new Promise((resolve, reject) => {
43
- socket.write(`${JSON.stringify(result)}\n`, error => error ? reject(error) : resolve());
33
+ socket.write(encodePacket(result), error => error ? reject(error) : resolve());
44
34
  });
45
- };
46
-
47
- let buffer = '';
48
- // Keep replies writable after a client half-closes.
49
- for await (const chunk of socket.setEncoding('utf8').iterator({ destroyOnReturn: false })) {
50
- buffer += chunk;
51
- let newline;
52
- while ((newline = buffer.indexOf('\n')) !== -1) {
53
- const line = buffer.slice(0, newline);
54
- buffer = buffer.slice(newline + 1);
55
- await reply(line);
56
- }
57
- checkLineLength(buffer);
58
35
  }
59
- await reply(buffer);
60
36
  socket.end();
61
37
  }
62
38
 
package/router.js CHANGED
@@ -28,6 +28,7 @@ const {
28
28
  const { AdapterTransport } = requireEmber('zigbee-herdsman/dist/adapter/transport.js');
29
29
  const { DEFAULT_STACK_CONFIG } = requireEmber('zigbee-herdsman/dist/adapter/ember/adapter/emberAdapter.js');
30
30
  const { STACK_PROFILE_ZIGBEE_PRO } = requireEmber('zigbee-herdsman/dist/adapter/ember/consts.js');
31
+ const { EZSP_EXTENDED_PARAMETERS_INDEX, EZSP_MAX_FRAME_LENGTH } = requireEmber('zigbee-herdsman/dist/adapter/ember/ezsp/consts.js');
31
32
 
32
33
  export { SLStatus, Zcl };
33
34
 
@@ -116,8 +117,17 @@ function pendingEvent(timeout, signal, subscribe, description = 'adapter callbac
116
117
  let unsubscribe;
117
118
  let timer;
118
119
  let abort;
120
+ const close = () => {
121
+ clearTimeout(timer);
122
+ signal.removeEventListener('abort', abort);
123
+ unsubscribe?.();
124
+ unsubscribe = undefined;
125
+ };
119
126
  const promise = new Promise((resolve, reject) => {
120
- abort = () => reject(signal.reason);
127
+ abort = () => {
128
+ close();
129
+ reject(signal.reason);
130
+ };
121
131
  signal.addEventListener('abort', abort, { once: true });
122
132
  try {
123
133
  signal.throwIfAborted();
@@ -128,14 +138,7 @@ function pendingEvent(timeout, signal, subscribe, description = 'adapter callbac
128
138
  }
129
139
  });
130
140
  promise.catch(() => {});
131
- return {
132
- promise,
133
- close() {
134
- clearTimeout(timer);
135
- signal.removeEventListener('abort', abort);
136
- unsubscribe?.();
137
- },
138
- };
141
+ return { promise, close };
139
142
  }
140
143
 
141
144
  async function networkCommand(ezsp, command, timeout, signal, expectedStatus = SLStatus.NETWORK_UP) {
@@ -302,7 +305,7 @@ function listenForInterview(ezsp, timeout, signal) {
302
305
  destination: sender,
303
306
  destinationEndpoint: frame.sourceEndpoint,
304
307
  clusterId: frame.clusterId,
305
- payload: answer.payload.toString('hex'),
308
+ payload: answer.payload,
306
309
  }, tag, timeout, signal);
307
310
  if (answer.complete) {
308
311
  complete.resolve();
@@ -432,14 +435,14 @@ function apsPacket(frame, source, lqi, payload) {
432
435
  profileId: frame.profileId,
433
436
  clusterId: frame.clusterId,
434
437
  lqi,
435
- payload: payload.toString('hex'),
438
+ payload,
436
439
  };
437
440
  }
438
441
 
439
442
  export function capture(ezsp, emit) {
440
443
  observeAps(ezsp, (_type, frame, lqi, source, payload) => emit(apsPacket(frame, source, lqi, payload)));
441
444
  ezsp.on('touchlinkMessage', (panId, source, groupId, lqi, payload) =>
442
- emit({ type: 'touchlink', panId, source, groupId, lqi, payload: payload.toString('hex') }));
445
+ emit({ type: 'touchlink', panId, source, groupId, lqi, payload }));
443
446
  }
444
447
 
445
448
  const attributeReplies = new Map([
@@ -478,12 +481,14 @@ export async function sendPacket(ezsp, packet, tag, timeout, signal, expect) {
478
481
  throw routerError(`Invalid ${label}.`, 'INVALID_PACKET');
479
482
  }
480
483
  }
481
- if (typeof payload !== 'string' || !/^(?:[\da-f]{2})+$/i.test(payload)) {
482
- throw routerError('payload must be nonempty, even-length hex.', 'INVALID_PACKET');
484
+ // SEND_UNICAST uses three bytes for mode and destination, eleven for the APS frame, and one for payload length.
485
+ const messageTagLength = ezsp.version < 0x0e ? 1 : 2;
486
+ const maxPayloadLength = EZSP_MAX_FRAME_LENGTH - EZSP_EXTENDED_PARAMETERS_INDEX - 3 - 11 - messageTagLength - 1;
487
+ if (!Buffer.isBuffer(payload) || payload.length === 0 || payload.length > maxPayloadLength) {
488
+ throw routerError(`payload must contain 1 to ${maxPayloadLength} bytes.`, 'INVALID_PACKET');
483
489
  }
484
490
 
485
- const message = Buffer.from(payload, 'hex');
486
- const request = expect && Zcl.Header.fromBuffer(message);
491
+ const request = expect && Zcl.Header.fromBuffer(payload);
487
492
  if (expect && (!request || !(request.isGlobal || request.isSpecific) || request.frameControl.reservedBits !== 0)) {
488
493
  throw routerError('payload must have a valid ZCL header to match a reply.', 'INVALID_PACKET');
489
494
  }
@@ -521,7 +526,7 @@ export async function sendPacket(ezsp, packet, tag, timeout, signal, expect) {
521
526
  }), 'ZCL reply', 'REPLY_TIMEOUT');
522
527
  try {
523
528
  signal.throwIfAborted();
524
- const [status] = await ezsp.ezspSendUnicast(EmberOutgoingMessageType.DIRECT, destination, aps, tag, message);
529
+ const [status] = await ezsp.ezspSendUnicast(EmberOutgoingMessageType.DIRECT, destination, aps, tag, payload);
525
530
  check(status, 'Queue write', 'QUEUE_FAILED');
526
531
  const delivered = delivery.promise.then(result => check(result, 'Deliver write', 'DELIVERY_FAILED'));
527
532
  if (!reply) {