ember-router 1.0.0 → 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.
Files changed (4) hide show
  1. package/README.md +25 -3
  2. package/index.js +51 -9
  3. package/package.json +1 -1
  4. 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,9 @@ 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 `write` to set the delivery timeout per packet (default `15000`).
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.
35
40
 
36
41
  #### Joining networks
37
42
 
@@ -81,7 +86,7 @@ ember-router reset -p tcp://192.168.1.42:6638 --yes
81
86
 
82
87
  ## Packet format
83
88
 
84
- 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.
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.
85
90
 
86
91
  ```json
87
92
  {"type":"aps","source":4660,"sourceEndpoint":1,"destinationEndpoint":1,"profileId":260,"clusterId":513,"lqi":180,"payload":"1842011200299e07"}
@@ -89,7 +94,7 @@ Stdout contains one JSON object per received packet. Diagnostics go to stderr. T
89
94
 
90
95
  `zdo` packets use the same frame fields. `touchlink` packets carry `panId`, `source`, `groupId`, `lqi`, and `payload`.
91
96
 
92
- Send one JSON object per line on stdin. The following example reads an attribute on a known destination using an already encoded ZCL payload:
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.
93
98
 
94
99
  ```json
95
100
  {"destination":4660,"destinationEndpoint":1,"clusterId":513,"payload":"1001001200"}
@@ -97,3 +102,20 @@ Send one JSON object per line on stdin. The following example reads an attribute
97
102
 
98
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.
99
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 CHANGED
@@ -2,6 +2,7 @@
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' };
5
6
  import { attachNetwork, capture, openRouter, resetRouter, sendPacket, SLStatus, Zcl } from './router.js';
6
7
 
7
8
  function integer(min, max) {
@@ -34,6 +35,14 @@ function writeLog(level, message, namespace) {
34
35
  process.stderr.write(`${prefix}: ${text}\n`);
35
36
  }
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
+
37
46
  async function readWrites(ezsp, timeout, signal) {
38
47
  const { stdin } = process;
39
48
  if (stdin.readableEnded || stdin.destroyed) {
@@ -57,11 +66,7 @@ async function readWrites(ezsp, timeout, signal) {
57
66
  }
58
67
 
59
68
  try {
60
- const packet = JSON.parse(line);
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);
69
+ await sendPacket(ezsp, parsePacket(line), lineNumber & 0x7f, timeout, signal);
65
70
  } catch (error) {
66
71
  if (signal.aborted) {
67
72
  break;
@@ -77,7 +82,29 @@ async function readWrites(ezsp, timeout, signal) {
77
82
  }
78
83
  }
79
84
 
80
- async function run(options, mode) {
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) {
81
108
  const join = mode === 'join';
82
109
  const stop = new AbortController();
83
110
  const { signal } = stop;
@@ -116,7 +143,7 @@ async function run(options, mode) {
116
143
  stop.abort(new Error('Network went down.'));
117
144
  }
118
145
  });
119
- if (!join) {
146
+ if (mode === 'run' || mode === 'write') {
120
147
  capture(ezsp, record => {
121
148
  if (signal.aborted) {
122
149
  return;
@@ -135,13 +162,18 @@ async function run(options, mode) {
135
162
  }
136
163
 
137
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
+
138
170
  await readWrites(ezsp, options.writeTimeout, signal);
139
171
  if (!options.exitAfterWrite && !signal.aborted) {
140
172
  await once(signal, 'abort');
141
173
  }
142
174
  signal.throwIfAborted();
143
175
  } catch (error) {
144
- if (error?.name !== 'AbortError' && error?.code !== 'EPIPE') {
176
+ if (mode === 'read' || (error?.name !== 'AbortError' && error?.code !== 'EPIPE')) {
145
177
  throw error;
146
178
  }
147
179
  } finally {
@@ -155,7 +187,7 @@ async function run(options, mode) {
155
187
  }
156
188
  }
157
189
 
158
- const program = new Command().name('ember-router')
190
+ const program = new Command().name('ember-router').version(packageJson.version)
159
191
  .description('Resume a saved Zigbee router network and stream packets, or join an open network')
160
192
  .requiredOption('-p, --path <path>', 'Serial port or tcp://host:port')
161
193
  .option('-b, --baud-rate <rate>', 'Serial baud rate', integer(1, 4_000_000), 115200)
@@ -180,6 +212,12 @@ function packetOptions(command) {
180
212
  .option('--write-timeout <ms>', 'Wait for each APS delivery status', integer(100, 300_000), 15000);
181
213
  }
182
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
+
183
221
  packetOptions(program.command('run', { isDefault: true }))
184
222
  .description('Resume, stream received packets, and accept writes on stdin')
185
223
  .action((_options, command) => {
@@ -194,6 +232,10 @@ packetOptions(program.command('write'))
194
232
  return run({ ...options, exitAfterWrite: true }, 'write');
195
233
  });
196
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
+
197
239
  program.command('reset').description('Leave the saved network and reset NVM3 tokens')
198
240
  .option('--yes', 'Confirm deletion of saved adapter state')
199
241
  .option('--preserve-frame-counters', 'Keep outgoing network and APS frame counter tokens', false)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ember-router",
3
- "version": "1.0.0",
3
+ "version": "1.1.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/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 check(status, operation) {
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 new Error(`${operation}: ${SLStatus[status] ?? status}`);
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(new Error(`Timed out waiting for ${description}.`)), timeout);
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
- export function capture(ezsp, emit) {
340
- const original = ezsp.ezspIncomingMessageHandler.bind(ezsp);
341
- let dispatching = false;
342
- const packet = (frame, source, lqi, payload) => emit({
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
- ezsp.on('incomingMessage', (_type, frame, lqi, source, payload) => {
363
- if (!dispatching) {
364
- packet(frame, source, lqi, payload);
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
- export async function sendPacket(ezsp, packet, tag, timeout, signal) {
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 new Error(`Invalid ${label}.`);
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 new Error('payload must be nonempty, even-length hex.');
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
- check(await delivery.promise, 'Deliver write');
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
  }