dynet-cli 0.1.0__py3-none-any.whl

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.
dynet_cli/__init__.py ADDED
@@ -0,0 +1,5 @@
1
+ """A command-line tool for the Signify Dynalite DyNet bus, built on aiodynet."""
2
+
3
+ from importlib.metadata import version
4
+
5
+ __version__ = version("dynet-cli")
dynet_cli/__main__.py ADDED
@@ -0,0 +1,5 @@
1
+ """Allow ``python -m dynet_cli``."""
2
+
3
+ from .cli import main
4
+
5
+ main()
dynet_cli/capture.py ADDED
@@ -0,0 +1,198 @@
1
+ """Capture files: one JSON object per line, written by ``monitor`` and ``sniff``.
2
+
3
+ A packet line looks like::
4
+
5
+ {"t": 1794969681.956, "dir": "rx", "hex": "1c0c0000000000ffd5"}
6
+
7
+ where ``dir`` is ``rx`` (from the gateway) or ``tx`` (to the gateway). Lines
8
+ with an ``event`` key record something that isn't a packet, such as a
9
+ connection or a gap in a sniffed stream. ``decode`` also accepts plain hex
10
+ packets, one per line.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import json
16
+ from collections import Counter
17
+ from dataclasses import dataclass, field
18
+ from typing import TYPE_CHECKING, Any, Literal, TextIO
19
+
20
+ from aiodynet import (
21
+ PACKET_LENGTH,
22
+ InvalidPacketError,
23
+ Packet,
24
+ PacketFramer,
25
+ UnknownMessage,
26
+ decode,
27
+ )
28
+
29
+ from .render import message_area, message_kind
30
+
31
+ if TYPE_CHECKING:
32
+ from collections.abc import Iterable, Iterator
33
+
34
+ type Direction = Literal["rx", "tx"]
35
+
36
+
37
+ @dataclass(frozen=True, slots=True)
38
+ class PacketRecord:
39
+ """A packet seen on the wire."""
40
+
41
+ time: float | None
42
+ direction: Direction | None
43
+ packet: Packet
44
+
45
+
46
+ @dataclass(frozen=True, slots=True)
47
+ class EventRecord:
48
+ """Something in a capture that isn't a packet."""
49
+
50
+ time: float | None
51
+ event: str
52
+ details: dict[str, Any]
53
+
54
+
55
+ type Record = PacketRecord | EventRecord
56
+
57
+
58
+ class CaptureWriter:
59
+ """Write capture records as JSON lines, flushing each one."""
60
+
61
+ def __init__(self, stream: TextIO) -> None:
62
+ """Write to `stream`."""
63
+ self._stream = stream
64
+
65
+ def packet(self, time: float, direction: Direction, packet: Packet) -> None:
66
+ """Record a packet."""
67
+ self._write({"t": round(time, 3), "dir": direction, "hex": packet.hex("")})
68
+
69
+ def event(self, time: float, event: str, **details: Any) -> None: # noqa: ANN401
70
+ """Record an event, such as ``connect`` or ``gap``."""
71
+ self._write({"t": round(time, 3), "event": event, **details})
72
+
73
+ def _write(self, record: dict[str, Any]) -> None:
74
+ self._stream.write(json.dumps(record, separators=(",", ":")) + "\n")
75
+ self._stream.flush()
76
+
77
+
78
+ class CaptureFormatError(ValueError):
79
+ """A line in a capture file that can't be read."""
80
+
81
+
82
+ def read_records(lines: Iterable[str]) -> Iterator[Record]:
83
+ """Read records from capture lines or plain hex packets.
84
+
85
+ A plain hex line of 7 or 8 bytes is one packet (the checksum is added or
86
+ checked). Any other length is treated as part of a raw byte stream and
87
+ framed the way the client frames a TCP stream.
88
+ """
89
+ framer = PacketFramer()
90
+ for number, raw_line in enumerate(lines, start=1):
91
+ line = raw_line.strip()
92
+ if not line or line.startswith("#"):
93
+ continue
94
+ if line.startswith("{"):
95
+ yield _parse_json(line, number)
96
+ continue
97
+ try:
98
+ data = bytes.fromhex("".join(line.replace(":", " ").split()))
99
+ except ValueError as err:
100
+ msg = f"Line {number}: not JSON or hex: {line[:60]!r}"
101
+ raise CaptureFormatError(msg) from err
102
+ if len(data) in {PACKET_LENGTH - 1, PACKET_LENGTH} and not framer.pending:
103
+ # One packet per line, as people type them: with or without checksum.
104
+ try:
105
+ packet = Packet.from_hex(data.hex())
106
+ except InvalidPacketError as err:
107
+ msg = f"Line {number}: {err}"
108
+ raise CaptureFormatError(msg) from err
109
+ yield PacketRecord(time=None, direction=None, packet=packet)
110
+ continue
111
+ for packet in framer.feed(data):
112
+ yield PacketRecord(time=None, direction=None, packet=packet)
113
+
114
+
115
+ def _parse_json(line: str, number: int) -> Record:
116
+ try:
117
+ record = json.loads(line)
118
+ time = record.get("t")
119
+ if "event" in record:
120
+ details = {k: v for k, v in record.items() if k not in {"t", "event"}}
121
+ return EventRecord(time=time, event=str(record["event"]), details=details)
122
+ direction = record.get("dir")
123
+ if direction not in {"rx", "tx", None}:
124
+ msg = f"unknown direction {direction!r}"
125
+ raise ValueError(msg) # noqa: TRY301
126
+ return PacketRecord(
127
+ time=time, direction=direction, packet=Packet.from_hex(record["hex"])
128
+ )
129
+ except (ValueError, KeyError, AttributeError, InvalidPacketError) as err:
130
+ msg = f"Line {number}: {err}"
131
+ raise CaptureFormatError(msg) from err
132
+
133
+
134
+ @dataclass
135
+ class Summary:
136
+ """Counts over a capture, to spot anything unexpected."""
137
+
138
+ packets: int = 0
139
+ by_kind: Counter[str] = field(default_factory=Counter)
140
+ by_direction: Counter[str] = field(default_factory=Counter)
141
+ areas: Counter[int] = field(default_factory=Counter)
142
+ unknown: Counter[str] = field(default_factory=Counter)
143
+ """Undecoded packets by hex, so each distinct one is listed once."""
144
+ events: Counter[str] = field(default_factory=Counter)
145
+ first_time: float | None = None
146
+ last_time: float | None = None
147
+
148
+ def add(self, record: Record) -> None:
149
+ """Count one record."""
150
+ if record.time is not None:
151
+ if self.first_time is None:
152
+ self.first_time = record.time
153
+ self.last_time = record.time
154
+ if isinstance(record, EventRecord):
155
+ self.events[record.event] += 1
156
+ return
157
+ message = decode(record.packet)
158
+ self.packets += 1
159
+ self.by_kind[message_kind(message)] += 1
160
+ self.by_direction[record.direction or "?"] += 1
161
+ if (area := message_area(message)) is not None:
162
+ self.areas[area] += 1
163
+ if isinstance(message, UnknownMessage):
164
+ self.unknown[record.packet.hex("")] += 1
165
+
166
+ def render(self) -> str:
167
+ """Return a readable report."""
168
+ lines = [f"{self.packets} packet(s)"]
169
+ if self.first_time is not None and self.last_time is not None:
170
+ hours = (self.last_time - self.first_time) / 3600
171
+ lines[0] += f" over {hours:.2f} h"
172
+ if self.by_direction:
173
+ lines.append(
174
+ " direction: "
175
+ + ", ".join(f"{k} {v}" for k, v in sorted(self.by_direction.items()))
176
+ )
177
+ lines.append("By type:")
178
+ lines.extend(
179
+ f" {count:>7} {kind}" for kind, count in self.by_kind.most_common()
180
+ )
181
+ if self.areas:
182
+ lines.append(
183
+ "Areas: "
184
+ + ", ".join(f"{a} ({n})" for a, n in sorted(self.areas.items()))
185
+ )
186
+ if self.events:
187
+ lines.append("Events:")
188
+ lines.extend(
189
+ f" {count:>7} {event}" for event, count in self.events.most_common()
190
+ )
191
+ if self.unknown:
192
+ lines.append(f"Undecoded packets ({len(self.unknown)} distinct):")
193
+ lines.extend(
194
+ f" {count:>7} {raw}" for raw, count in self.unknown.most_common()
195
+ )
196
+ else:
197
+ lines.append("Every packet decoded to a typed message.")
198
+ return "\n".join(lines)
dynet_cli/cli.py ADDED
@@ -0,0 +1,535 @@
1
+ """The ``dynet`` command."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import asyncio
7
+ import contextlib
8
+ import json
9
+ import logging
10
+ import os
11
+ import sys
12
+ import time
13
+ from pathlib import Path
14
+ from typing import TYPE_CHECKING, TextIO, cast
15
+
16
+ from aiodynet import (
17
+ MAX_CHANNEL_FADE,
18
+ MAX_PRESET_FADE,
19
+ DynetClient,
20
+ DynetError,
21
+ Level,
22
+ Packet,
23
+ PresetSelect,
24
+ Received,
25
+ RequestChannelLevel,
26
+ RequestPreset,
27
+ SetChannelLevel,
28
+ check_connection,
29
+ decode,
30
+ )
31
+
32
+ from . import __version__
33
+ from .capture import (
34
+ CaptureFormatError,
35
+ CaptureWriter,
36
+ PacketRecord,
37
+ Summary,
38
+ read_records,
39
+ )
40
+ from .render import describe, message_area, to_json
41
+ from .sniff import Reassembler, open_raw_socket, sniff
42
+
43
+ if TYPE_CHECKING:
44
+ from collections.abc import Sequence
45
+
46
+ EXIT_OK = 0
47
+ EXIT_ERROR = 1
48
+ EXIT_USAGE = 2
49
+ EXIT_TIMEOUT = 3
50
+
51
+
52
+ class UsageError(Exception):
53
+ """Bad input that argparse can't catch on its own."""
54
+
55
+
56
+ # Argument types
57
+
58
+
59
+ def _int_in(low: int, high: int, what: str) -> type[int]:
60
+ def parse(text: str) -> int:
61
+ try:
62
+ value = int(text, 0)
63
+ except ValueError:
64
+ msg = f"{what} must be a whole number, got {text!r}"
65
+ raise argparse.ArgumentTypeError(msg) from None
66
+ if not low <= value <= high:
67
+ msg = f"{what} must be {low}-{high}, got {value}"
68
+ raise argparse.ArgumentTypeError(msg)
69
+ return value
70
+
71
+ parse.__name__ = what
72
+ return parse # type: ignore[return-value]
73
+
74
+
75
+ def parse_level(text: str) -> Level:
76
+ """Parse ``40``, ``40%``, ``off``, ``on``/``full`` or ``raw:0x80``."""
77
+ lowered = text.strip().lower()
78
+ try:
79
+ if lowered == "off":
80
+ return Level.OFF
81
+ if lowered in {"on", "full"}:
82
+ return Level.FULL
83
+ if lowered.startswith("raw:"):
84
+ return Level(int(lowered[4:], 0))
85
+ return Level.from_percent(float(lowered.removesuffix("%")))
86
+ except ValueError as err:
87
+ msg = f"level must be 0-100 (%), off, on or raw:<byte>, got {text!r} ({err})"
88
+ raise argparse.ArgumentTypeError(msg) from None
89
+
90
+
91
+ def parse_fade(limit: float) -> type[float]:
92
+ """Make a parser for a fade of up to `limit` seconds."""
93
+
94
+ def parse(text: str) -> float:
95
+ try:
96
+ value = float(text.removesuffix("s"))
97
+ except ValueError:
98
+ msg = f"fade must be seconds, got {text!r}"
99
+ raise argparse.ArgumentTypeError(msg) from None
100
+ if not 0 <= value <= limit:
101
+ msg = f"fade must be 0-{limit:g} seconds, got {value:g}"
102
+ raise argparse.ArgumentTypeError(msg)
103
+ return value
104
+
105
+ parse.__name__ = "fade"
106
+ return parse # type: ignore[return-value]
107
+
108
+
109
+ def parse_areas(text: str) -> list[int]:
110
+ """Parse an area list such as ``1-10,12,20-22``."""
111
+ areas: set[int] = set()
112
+ area = _int_in(0, 255, "area")
113
+ for part in text.split(","):
114
+ first, sep, last = part.strip().partition("-")
115
+ low = area(first)
116
+ high = area(last) if sep else low
117
+ if high < low:
118
+ msg = f"area range {part!r} runs backwards"
119
+ raise argparse.ArgumentTypeError(msg)
120
+ areas.update(range(low, high + 1))
121
+ return sorted(areas)
122
+
123
+
124
+ def parse_endpoint(text: str) -> tuple[str, int]:
125
+ """Parse ``HOST:PORT``."""
126
+ host, sep, port = text.rpartition(":")
127
+ if not sep or not host:
128
+ msg = f"expected HOST:PORT, got {text!r}"
129
+ raise argparse.ArgumentTypeError(msg)
130
+ return host, _int_in(1, 65535, "port")(port)
131
+
132
+
133
+ AREA = _int_in(0, 255, "area")
134
+ CHANNEL = _int_in(1, 1024, "channel")
135
+ PRESET = _int_in(1, 2048, "preset")
136
+ JOIN = _int_in(0, 255, "join")
137
+
138
+
139
+ # Parser
140
+
141
+
142
+ def build_parser() -> argparse.ArgumentParser: # noqa: PLR0915
143
+ """Build the argument parser."""
144
+ parser = argparse.ArgumentParser(
145
+ prog="dynet",
146
+ description="Watch, control and capture a Signify Dynalite DyNet bus "
147
+ "through a TCP gateway.",
148
+ epilog="The gateway can also be set with DYNET_HOST and DYNET_PORT.",
149
+ )
150
+ parser.add_argument(
151
+ "--version", action="version", version=f"%(prog)s {__version__}"
152
+ )
153
+ parser.add_argument(
154
+ "-v", "--verbose", action="count", default=0, help="more logging"
155
+ )
156
+
157
+ connection = argparse.ArgumentParser(add_help=False)
158
+ group = connection.add_argument_group("gateway")
159
+ group.add_argument("-H", "--host", default=os.environ.get("DYNET_HOST"))
160
+ group.add_argument(
161
+ "-p",
162
+ "--port",
163
+ type=_int_in(1, 65535, "port"),
164
+ default=os.environ.get("DYNET_PORT"),
165
+ )
166
+ group.add_argument(
167
+ "--send-interval",
168
+ type=float,
169
+ default=0.2,
170
+ metavar="SECONDS",
171
+ help="gap between packets sent (default 0.2)",
172
+ )
173
+
174
+ commands = parser.add_subparsers(dest="command", required=True, metavar="COMMAND")
175
+
176
+ commands.add_parser(
177
+ "check", parents=[connection], help="check the gateway accepts connections"
178
+ )
179
+
180
+ monitor = commands.add_parser(
181
+ "monitor", parents=[connection], help="show bus traffic as it happens"
182
+ )
183
+ monitor.add_argument(
184
+ "-a",
185
+ "--area",
186
+ type=parse_areas,
187
+ action="extend",
188
+ help="only these areas, e.g. 1-10,12",
189
+ )
190
+ monitor.add_argument("--json", action="store_true", help="one JSON object per line")
191
+ monitor.add_argument(
192
+ "--duration", type=float, metavar="SECONDS", help="stop after this long"
193
+ )
194
+ monitor.add_argument(
195
+ "--record",
196
+ metavar="FILE",
197
+ help="also append a capture file",
198
+ )
199
+
200
+ preset = commands.add_parser("preset", parents=[connection], help="select a preset")
201
+ preset.add_argument("area", type=AREA)
202
+ preset.add_argument("preset", type=PRESET)
203
+ preset.add_argument("-f", "--fade", type=parse_fade(MAX_PRESET_FADE), default=0.0)
204
+ preset.add_argument("-j", "--join", type=JOIN, default=0xFF)
205
+
206
+ level = commands.add_parser(
207
+ "level", parents=[connection], help="set a channel level"
208
+ )
209
+ level.add_argument("area", type=AREA)
210
+ level.add_argument("channel", type=CHANNEL)
211
+ level.add_argument("level", type=parse_level, help="40, 40%%, off, on or raw:0x80")
212
+ level.add_argument("-f", "--fade", type=parse_fade(MAX_CHANNEL_FADE), default=0.0)
213
+ level.add_argument("-j", "--join", type=JOIN, default=0xFF)
214
+
215
+ query = commands.add_parser("query", help="ask an area or channel for its state")
216
+ what = query.add_subparsers(dest="what", required=True, metavar="WHAT")
217
+ query_preset = what.add_parser(
218
+ "preset", parents=[connection], help="current preset"
219
+ )
220
+ query_preset.add_argument("area", type=AREA)
221
+ query_preset.add_argument(
222
+ "-c", "--channel", type=_int_in(1, 256, "channel"), default=1
223
+ )
224
+ query_level = what.add_parser("level", parents=[connection], help="channel level")
225
+ query_level.add_argument("area", type=AREA)
226
+ query_level.add_argument("channel", type=_int_in(1, 256, "channel"))
227
+ for sub in (query_preset, query_level):
228
+ sub.add_argument("-t", "--timeout", type=float, default=2.0)
229
+ sub.add_argument("--json", action="store_true")
230
+
231
+ scan = commands.add_parser(
232
+ "scan",
233
+ parents=[connection],
234
+ help="ask each area for its preset, to find the areas in use",
235
+ description="Sends one request per area, so it adds traffic to the bus.",
236
+ )
237
+ scan.add_argument("--areas", type=parse_areas, default=list(range(1, 256)))
238
+ scan.add_argument("-c", "--channel", type=_int_in(1, 256, "channel"), default=1)
239
+ scan.add_argument("-t", "--timeout", type=float, default=0.5, help="wait per area")
240
+ scan.add_argument("--json", action="store_true")
241
+
242
+ send = commands.add_parser("send", parents=[connection], help="send raw packets")
243
+ send.add_argument("packets", nargs="+", type=Packet.from_hex, metavar="HEX")
244
+
245
+ decode_cmd = commands.add_parser(
246
+ "decode",
247
+ help="decode packets from a capture file or hex (no gateway needed)",
248
+ )
249
+ decode_cmd.add_argument(
250
+ "file",
251
+ nargs="?",
252
+ default="-",
253
+ help="default: stdin",
254
+ )
255
+ decode_cmd.add_argument("--json", action="store_true")
256
+ decode_cmd.add_argument(
257
+ "--summary", action="store_true", help="report counts and anything undecoded"
258
+ )
259
+
260
+ sniff_cmd = commands.add_parser(
261
+ "sniff",
262
+ help="passively capture another client's gateway traffic (Linux, root)",
263
+ description="Records the traffic between a gateway and the client already\n"
264
+ "connected to it, without connecting or sending anything.",
265
+ epilog="Step-by-step guide:\n"
266
+ " https://github.com/sdunster/dynet-cli/blob/main/docs/capturing-traffic.md",
267
+ formatter_class=argparse.RawDescriptionHelpFormatter,
268
+ )
269
+ sniff_cmd.add_argument("gateway", type=parse_endpoint, metavar="HOST:PORT")
270
+ sniff_cmd.add_argument(
271
+ "-i", "--interface", default="eth0", help="network interface (default: eth0)"
272
+ )
273
+ sniff_cmd.add_argument("--duration", type=float, metavar="SECONDS")
274
+ sniff_cmd.add_argument(
275
+ "-o",
276
+ "--output",
277
+ default="-",
278
+ help="file to append to (default: stdout)",
279
+ )
280
+ return parser
281
+
282
+
283
+ # Commands
284
+
285
+
286
+ def _client(args: argparse.Namespace) -> DynetClient:
287
+ if not args.host or args.port is None:
288
+ msg = "set the gateway with --host and --port (or DYNET_HOST and DYNET_PORT)"
289
+ raise UsageError(msg)
290
+ return DynetClient(args.host, int(args.port), send_interval=args.send_interval)
291
+
292
+
293
+ async def cmd_check(args: argparse.Namespace, out: TextIO) -> int:
294
+ """Check the gateway is reachable."""
295
+ client = _client(args)
296
+ await check_connection(client.host, client.port)
297
+ print(f"{client.host}:{client.port} is accepting connections", file=out)
298
+ return EXIT_OK
299
+
300
+
301
+ def _timestamp(now: float) -> str:
302
+ millis = int(now * 1000) % 1000
303
+ return time.strftime("%H:%M:%S", time.localtime(now)) + f".{millis:03d}"
304
+
305
+
306
+ def _open_text(path: str, mode: str) -> contextlib.AbstractContextManager[TextIO]:
307
+ """Open `path` as UTF-8 text, or stdin/stdout for ``-``."""
308
+ if path == "-":
309
+ return contextlib.nullcontext(sys.stdin if mode == "r" else sys.stdout)
310
+ stream = Path(path).open(mode, encoding="utf-8") # noqa: SIM115 - returned
311
+ return cast("contextlib.AbstractContextManager[TextIO]", stream)
312
+
313
+
314
+ async def cmd_monitor(args: argparse.Namespace, out: TextIO) -> int:
315
+ """Print bus traffic until interrupted or `--duration` passes."""
316
+ with contextlib.ExitStack() as stack:
317
+ recorder = (
318
+ CaptureWriter(stack.enter_context(_open_text(args.record, "a")))
319
+ if args.record
320
+ else None
321
+ )
322
+ return await _monitor(args, out, recorder)
323
+
324
+
325
+ async def _monitor(
326
+ args: argparse.Namespace, out: TextIO, recorder: CaptureWriter | None
327
+ ) -> int:
328
+ areas = set(args.area) if args.area else None
329
+
330
+ def show(received: Received) -> None:
331
+ now = time.time()
332
+ if recorder is not None:
333
+ recorder.packet(now, "rx", received.packet)
334
+ if areas is not None and message_area(received.message) not in areas:
335
+ return
336
+ if args.json:
337
+ record = {"t": round(now, 3), "hex": received.packet.hex("")}
338
+ print(json.dumps(record | to_json(received.message)), file=out, flush=True)
339
+ else:
340
+ text = describe(received.message)
341
+ print(
342
+ f"{_timestamp(now)} {received.packet.hex()} {text}",
343
+ file=out,
344
+ flush=True,
345
+ )
346
+
347
+ def connection(connected: bool) -> None: # noqa: FBT001
348
+ state = "reconnected" if connected else "connection lost, reconnecting"
349
+ print(f"-- {state}", file=sys.stderr, flush=True)
350
+
351
+ async with _client(args) as client:
352
+ client.subscribe(show)
353
+ client.subscribe_connection(connection)
354
+ if not args.json:
355
+ print(
356
+ f"-- watching {client.host}:{client.port}", file=sys.stderr, flush=True
357
+ )
358
+ if args.duration is None: # pragma: no cover - runs until interrupted
359
+ await asyncio.Event().wait()
360
+ await asyncio.sleep(args.duration)
361
+ return EXIT_OK
362
+
363
+
364
+ async def cmd_preset(args: argparse.Namespace, out: TextIO) -> int:
365
+ """Select a preset."""
366
+ message = PresetSelect(
367
+ area=args.area, preset=args.preset, fade=args.fade, join=args.join
368
+ )
369
+ async with _client(args) as client:
370
+ await client.send(message)
371
+ print(f"sent: {describe(message)}", file=out)
372
+ return EXIT_OK
373
+
374
+
375
+ async def cmd_level(args: argparse.Namespace, out: TextIO) -> int:
376
+ """Set a channel level."""
377
+ message = SetChannelLevel(
378
+ area=args.area,
379
+ channel=args.channel,
380
+ level=args.level,
381
+ fade=args.fade,
382
+ join=args.join,
383
+ )
384
+ async with _client(args) as client:
385
+ await client.send(message)
386
+ print(f"sent: {describe(message)}", file=out)
387
+ return EXIT_OK
388
+
389
+
390
+ async def cmd_query(args: argparse.Namespace, out: TextIO) -> int:
391
+ """Query an area's preset or a channel's level."""
392
+ request = (
393
+ RequestPreset(area=args.area, channel=args.channel)
394
+ if args.what == "preset"
395
+ else RequestChannelLevel(area=args.area, channel=args.channel)
396
+ )
397
+ async with _client(args) as client:
398
+ try:
399
+ report = await client.query(request, timeout=args.timeout)
400
+ except TimeoutError:
401
+ print(f"no answer within {args.timeout:g}s", file=sys.stderr)
402
+ return EXIT_TIMEOUT
403
+ print(json.dumps(to_json(report)) if args.json else describe(report), file=out)
404
+ return EXIT_OK
405
+
406
+
407
+ async def cmd_scan(args: argparse.Namespace, out: TextIO) -> int:
408
+ """Ask every area in a range for its preset."""
409
+ found = 0
410
+ print(
411
+ f"-- asking {len(args.areas)} area(s); this sends one packet per area",
412
+ file=sys.stderr,
413
+ flush=True,
414
+ )
415
+ async with _client(args) as client:
416
+ for area in args.areas:
417
+ request = RequestPreset(area=area, channel=args.channel)
418
+ try:
419
+ report = await client.query(request, timeout=args.timeout)
420
+ except TimeoutError:
421
+ continue
422
+ found += 1
423
+ print(
424
+ json.dumps(to_json(report)) if args.json else describe(report),
425
+ file=out,
426
+ flush=True,
427
+ )
428
+ print(f"-- {found} area(s) answered", file=sys.stderr)
429
+ return EXIT_OK
430
+
431
+
432
+ async def cmd_send(args: argparse.Namespace, out: TextIO) -> int:
433
+ """Send raw packets."""
434
+ async with _client(args) as client:
435
+ for packet in args.packets:
436
+ await client.send(packet)
437
+ print(f"sent {packet.hex()} {describe(decode(packet))}", file=out)
438
+ return EXIT_OK
439
+
440
+
441
+ def cmd_decode(args: argparse.Namespace, out: TextIO) -> int:
442
+ """Decode a capture file or hex."""
443
+ summary = Summary()
444
+ with _open_text(args.file, "r") as lines:
445
+ for record in read_records(lines):
446
+ if args.summary:
447
+ summary.add(record)
448
+ elif isinstance(record, PacketRecord):
449
+ message = decode(record.packet)
450
+ if args.json:
451
+ line = {"hex": record.packet.hex("")} | to_json(message)
452
+ if record.time is not None:
453
+ line = {"t": record.time, "dir": record.direction} | line
454
+ print(json.dumps(line), file=out)
455
+ else:
456
+ prefix = (
457
+ f"{_timestamp(record.time)} "
458
+ if record.time is not None
459
+ else ""
460
+ )
461
+ direction = f"{record.direction} " if record.direction else ""
462
+ text = f"{record.packet.hex()} {describe(message)}"
463
+ print(f"{prefix}{direction}{text}", file=out)
464
+ else:
465
+ details = " ".join(f"{k}={v}" for k, v in record.details.items())
466
+ print(f"-- {record.event} {details}".rstrip(), file=out)
467
+ if args.summary:
468
+ print(summary.render(), file=out)
469
+ return EXIT_OK
470
+
471
+
472
+ def cmd_sniff(args: argparse.Namespace) -> int:
473
+ """Capture another client's gateway traffic."""
474
+ host, port = args.gateway
475
+ with _open_text(args.output, "a") as output:
476
+ return _sniff(args, host, port, CaptureWriter(output))
477
+
478
+
479
+ def _sniff(
480
+ args: argparse.Namespace, host: str, port: int, writer: CaptureWriter
481
+ ) -> int:
482
+ reassembler = Reassembler(host, port, writer)
483
+ sock = open_raw_socket(args.interface)
484
+ print(
485
+ f"-- capturing {host}:{port} on {args.interface}"
486
+ + (f" for {args.duration:g}s" if args.duration else ""),
487
+ file=sys.stderr,
488
+ flush=True,
489
+ )
490
+ try:
491
+ sniff(sock, reassembler, duration=args.duration)
492
+ finally:
493
+ sock.close()
494
+ print(f"-- captured {reassembler.packets} packet(s)", file=sys.stderr)
495
+ return EXIT_OK
496
+
497
+
498
+ ASYNC_COMMANDS = {
499
+ "check": cmd_check,
500
+ "monitor": cmd_monitor,
501
+ "preset": cmd_preset,
502
+ "level": cmd_level,
503
+ "query": cmd_query,
504
+ "scan": cmd_scan,
505
+ "send": cmd_send,
506
+ }
507
+
508
+
509
+ async def run(argv: Sequence[str] | None = None, out: TextIO | None = None) -> int:
510
+ """Run the command line `argv` and return the exit code."""
511
+ out = out or sys.stdout
512
+ args = build_parser().parse_args(argv)
513
+ logging.basicConfig(
514
+ level=[logging.WARNING, logging.INFO, logging.DEBUG][min(args.verbose, 2)],
515
+ format="%(asctime)s %(levelname)s %(name)s: %(message)s",
516
+ )
517
+ try:
518
+ if args.command == "decode":
519
+ return cmd_decode(args, out)
520
+ if args.command == "sniff":
521
+ return cmd_sniff(args)
522
+ return await ASYNC_COMMANDS[args.command](args, out)
523
+ except UsageError as err:
524
+ print(f"dynet: error: {err}", file=sys.stderr)
525
+ return EXIT_USAGE
526
+ except (DynetError, CaptureFormatError, OSError) as err:
527
+ print(f"dynet: {err}", file=sys.stderr)
528
+ return EXIT_ERROR
529
+
530
+
531
+ def main() -> None: # pragma: no cover - thin wrapper over run()
532
+ """Entry point for the ``dynet`` script."""
533
+ with contextlib.suppress(KeyboardInterrupt):
534
+ sys.exit(asyncio.run(run()))
535
+ sys.exit(130)
dynet_cli/py.typed ADDED
File without changes
dynet_cli/render.py ADDED
@@ -0,0 +1,201 @@
1
+ """Turn DyNet messages into text for people and JSON for tools."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import fields
6
+ from enum import Enum
7
+ from typing import TYPE_CHECKING, Any, assert_never
8
+
9
+ from aiodynet import (
10
+ JOIN_ALL,
11
+ AreaCommand,
12
+ AreaCommandType,
13
+ AreaOff,
14
+ AreaToLevel,
15
+ ChannelLevelReport,
16
+ ChannelOff,
17
+ ChannelOn,
18
+ ClockDate,
19
+ ClockTime,
20
+ FadeChannelToLevel,
21
+ FadeChannelToPreset,
22
+ Level,
23
+ LinearPresetSelect,
24
+ LogicalMessage,
25
+ MotionActivitySync,
26
+ Panic,
27
+ PresetLevelReport,
28
+ PresetReport,
29
+ PresetSelect,
30
+ RequestChannelLevel,
31
+ RequestPreset,
32
+ RequestPresetLevel,
33
+ RequestUserPreference,
34
+ ResetPreset,
35
+ RestoreSavedPreset,
36
+ SetChannelLevel,
37
+ SetUserPreference,
38
+ StopFade,
39
+ SyncType,
40
+ UnknownMessage,
41
+ Unpanic,
42
+ UserPreferenceReport,
43
+ )
44
+
45
+ if TYPE_CHECKING:
46
+ from aiodynet import AnyMessage, Packet
47
+
48
+ AREA_COMMAND_TEXT = {
49
+ AreaCommandType.DECREMENT_LEVEL: "step level down",
50
+ AreaCommandType.INCREMENT_LEVEL: "step level up",
51
+ AreaCommandType.PROGRAM_CURRENT_PRESET: "program current preset",
52
+ AreaCommandType.DISABLE_PANELS: "disable panels",
53
+ AreaCommandType.ENABLE_PANELS: "enable panels",
54
+ AreaCommandType.SAVE_CURRENT_PRESET: "save current preset",
55
+ }
56
+
57
+
58
+ def _fade(seconds: float) -> str:
59
+ return f" fade {seconds:g}s" if seconds else ""
60
+
61
+
62
+ def _raw(name: str, value: int) -> str:
63
+ return f" {name} 0x{value:02x}" if value else ""
64
+
65
+
66
+ def _channel(channel: int | None) -> str:
67
+ return "all channels" if channel is None else f"channel {channel}"
68
+
69
+
70
+ def describe(message: AnyMessage) -> str:
71
+ """Describe a message in one line, for example ``area 12: select preset 3``."""
72
+ match message:
73
+ case UnknownMessage(packet=packet):
74
+ return describe_unknown(packet)
75
+ case ClockTime(device_code=device, box=box, hour=h, minute=m, second=sec):
76
+ return f"device 0x{device:02x} box {box}: time is {h:02d}:{m:02d}:{sec:02d}"
77
+ case ClockDate(
78
+ device_code=device, box=box, year=y, month=mo, day=d, day_of_week=dow
79
+ ):
80
+ return (
81
+ f"device 0x{device:02x} box {box}: "
82
+ f"date is {y:04d}-{mo:02d}-{d:02d} (day of week {dow})"
83
+ )
84
+ case _:
85
+ text = _describe_logical(message)
86
+ join = "" if message.join == JOIN_ALL else f" join 0x{message.join:02x}"
87
+ return f"area {message.area}{text}{join}"
88
+
89
+
90
+ def _describe_logical(message: AnyMessage) -> str: # noqa: C901, PLR0911, PLR0912
91
+ """Describe a logical message, after the ``area N`` prefix."""
92
+ match message:
93
+ case PresetSelect(preset=preset, fade=fade):
94
+ return f": select preset {preset}{_fade(fade)}"
95
+ case LinearPresetSelect(preset=preset, fade=fade):
96
+ return f": select preset {preset} (linear){_fade(fade)}"
97
+ case PresetReport(preset=preset):
98
+ return f": is at preset {preset}"
99
+ case RequestPreset(channel=channel):
100
+ return f": which preset? (channel {channel})"
101
+ case SetChannelLevel(channel=channel, level=level, fade=fade):
102
+ return f" channel {channel}: set {level}{_fade(fade)}"
103
+ case ChannelLevelReport(channel=channel, target_level=target, actual_level=now):
104
+ moving = "" if target == now else f", heading to {target}"
105
+ return f" channel {channel}: is at {now}{moving}"
106
+ case RequestChannelLevel(channel=channel):
107
+ return f" channel {channel}: which level?"
108
+ case FadeChannelToPreset(channel=channel, preset=preset, fade_raw=fade_raw):
109
+ fade_text = _raw("fade byte", fade_raw)
110
+ return f" {_channel(channel)}: fade to preset {preset}{fade_text}"
111
+ case AreaCommand(command=command):
112
+ return f": {AREA_COMMAND_TEXT[command]}"
113
+ case AreaOff(fade=fade):
114
+ return f": all off{_fade(fade)}"
115
+ case ResetPreset(fade=fade):
116
+ return f": reset to current preset{_fade(fade)}"
117
+ case Panic(fade=fade):
118
+ return f": panic{_fade(fade)}"
119
+ case Unpanic(fade=fade):
120
+ return f": end panic{_fade(fade)}"
121
+ case AreaToLevel(level=level, fade=fade):
122
+ return f": all channels to {level}{_fade(fade)}"
123
+ case ChannelOff(channel=channel, fade=fade):
124
+ return f" {_channel(channel)}: off{_fade(fade)}"
125
+ case ChannelOn(channel=channel, fade=fade):
126
+ return f" {_channel(channel)}: on{_fade(fade)}"
127
+ case StopFade(channel=channel):
128
+ return f" {_channel(channel)}: stop fading"
129
+ case FadeChannelToLevel(
130
+ channel=channel, level=level, scale=scale, fade_raw=raw
131
+ ):
132
+ unit = scale.name.lower()
133
+ return f" {_channel(channel)}: fade to {level} (fade {raw} {unit})"
134
+ case RestoreSavedPreset(fade_raw=fade_raw):
135
+ return f": restore saved preset{_raw('fade byte', fade_raw)}"
136
+ case MotionActivitySync(channel=channel, time_raw=time_raw):
137
+ return f" {_channel(channel)}: motion activity (time {time_raw})"
138
+ case SetUserPreference(preference=pref, value=value):
139
+ return f": set preference 0x{pref:02x} to 0x{value:04x}"
140
+ case RequestUserPreference(preference=pref):
141
+ return f": which value for preference 0x{pref:02x}?"
142
+ case UserPreferenceReport(preference=pref, value=value):
143
+ return f": preference 0x{pref:02x} is 0x{value:04x}"
144
+ case RequestPresetLevel(channel=channel, preset=preset):
145
+ return f" channel {channel}: which level for preset {preset}?"
146
+ case PresetLevelReport(channel=channel, preset=preset, level=level):
147
+ return f" channel {channel}: preset {preset} is {level}"
148
+ case UnknownMessage() | ClockTime() | ClockDate():
149
+ msg = "describe() handles these itself"
150
+ raise AssertionError(msg)
151
+ case _:
152
+ assert_never(message)
153
+
154
+
155
+ def describe_unknown(packet: Packet) -> str:
156
+ """Describe a packet aiodynet has no typed message for."""
157
+ data = packet.data
158
+ if packet.sync == SyncType.LOGICAL:
159
+ return f"area {data[1]}: opcode 0x{data[3]:02x} (not decoded)"
160
+ if packet.sync == SyncType.PHYSICAL:
161
+ return (
162
+ f"device 0x{data[1]:02x} box {data[2]}: "
163
+ f"physical opcode 0x{data[3]:02x} (not decoded)"
164
+ )
165
+ return f"sync 0x{packet.sync:02x} (not decoded)"
166
+
167
+
168
+ def message_kind(message: AnyMessage) -> str:
169
+ """Name the message type, refining unknown ones by sync byte and opcode."""
170
+ if isinstance(message, UnknownMessage):
171
+ packet = message.packet
172
+ if packet.sync in {SyncType.LOGICAL, SyncType.PHYSICAL}:
173
+ label = "logical" if packet.sync == SyncType.LOGICAL else "physical"
174
+ return f"Unknown {label} 0x{packet.data[3]:02x}"
175
+ return f"Unknown sync 0x{packet.sync:02x}"
176
+ return type(message).__name__
177
+
178
+
179
+ def message_area(message: AnyMessage) -> int | None:
180
+ """Return the area a message is about, if it is a logical message."""
181
+ if isinstance(message, LogicalMessage):
182
+ return message.area
183
+ if isinstance(message, UnknownMessage) and message.packet.sync == SyncType.LOGICAL:
184
+ return message.packet.data[1]
185
+ return None
186
+
187
+
188
+ def to_json(message: AnyMessage) -> dict[str, Any]:
189
+ """Convert a message to a JSON-ready dict: its type and its fields."""
190
+ result: dict[str, Any] = {"type": type(message).__name__}
191
+ if isinstance(message, UnknownMessage):
192
+ result["packet"] = message.packet.hex("")
193
+ return result
194
+ for field in fields(message):
195
+ value = getattr(message, field.name)
196
+ if isinstance(value, Level):
197
+ value = {"raw": value.raw, "percent": value.percent}
198
+ elif isinstance(value, Enum):
199
+ value = value.name
200
+ result[field.name] = value
201
+ return result
dynet_cli/sniff.py ADDED
@@ -0,0 +1,223 @@
1
+ """Passively capture the DyNet traffic between a gateway and its client.
2
+
3
+ This watches the TCP connection something else (such as Home Assistant) has
4
+ open to a gateway, from the same host, without connecting to the gateway or
5
+ sending anything. It needs Linux (``AF_PACKET``) and root.
6
+
7
+ Each direction of each TCP connection is put back in order by sequence
8
+ number. Segments already seen (retransmits, and the one-byte keepalive probes
9
+ some gateways send) are dropped. If data is missing, a ``gap`` event is
10
+ recorded and framing restarts, so a lost segment can't produce a bogus packet.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import ipaddress
16
+ import socket
17
+ import struct
18
+ import time
19
+ from dataclasses import dataclass
20
+ from typing import TYPE_CHECKING, Protocol
21
+
22
+ from aiodynet import PacketFramer
23
+
24
+ if TYPE_CHECKING:
25
+ from collections.abc import Callable
26
+
27
+ from .capture import CaptureWriter, Direction
28
+
29
+ ETH_P_ALL = 0x0003
30
+ _ETHERTYPE_IPV4 = 0x0800
31
+ _ETHERTYPE_VLAN = 0x8100
32
+ _PROTO_TCP = 6
33
+ _TCP_SYN = 0x02
34
+ _TCP_FIN = 0x01
35
+ _TCP_RST = 0x04
36
+ _SEQ_MODULO = 1 << 32
37
+
38
+
39
+ @dataclass(frozen=True, slots=True)
40
+ class Segment:
41
+ """The parts of a TCP/IPv4 segment the sniffer needs."""
42
+
43
+ src: str
44
+ sport: int
45
+ dst: str
46
+ dport: int
47
+ seq: int
48
+ flags: int
49
+ payload: bytes
50
+
51
+
52
+ def parse_frame(frame: bytes) -> Segment | None:
53
+ """Parse an Ethernet frame. Returns ``None`` unless it is TCP over IPv4."""
54
+ if len(frame) < 14:
55
+ return None
56
+ ethertype = struct.unpack_from("!H", frame, 12)[0]
57
+ offset = 14
58
+ if ethertype == _ETHERTYPE_VLAN:
59
+ if len(frame) < 18:
60
+ return None
61
+ ethertype = struct.unpack_from("!H", frame, 16)[0]
62
+ offset = 18
63
+ if ethertype != _ETHERTYPE_IPV4 or len(frame) < offset + 20:
64
+ return None
65
+ ip = frame[offset:]
66
+ header_length = (ip[0] & 0x0F) * 4
67
+ total_length = struct.unpack_from("!H", ip, 2)[0]
68
+ if ip[9] != _PROTO_TCP or len(ip) < header_length + 20:
69
+ return None
70
+ tcp = ip[header_length:total_length]
71
+ if len(tcp) < 20:
72
+ return None
73
+ sport, dport, seq = struct.unpack_from("!HHI", tcp)
74
+ data_offset = (tcp[12] >> 4) * 4
75
+ return Segment(
76
+ src=str(ipaddress.IPv4Address(ip[12:16])),
77
+ sport=sport,
78
+ dst=str(ipaddress.IPv4Address(ip[16:20])),
79
+ dport=dport,
80
+ seq=seq,
81
+ flags=tcp[13],
82
+ payload=bytes(tcp[data_offset:]),
83
+ )
84
+
85
+
86
+ def _seq_diff(a: int, b: int) -> int:
87
+ """Return ``a - b`` in TCP sequence space, allowing for wraparound."""
88
+ diff = (a - b) % _SEQ_MODULO
89
+ return diff - _SEQ_MODULO if diff >= _SEQ_MODULO // 2 else diff
90
+
91
+
92
+ class _Stream:
93
+ """One direction of one TCP connection."""
94
+
95
+ def __init__(self) -> None:
96
+ self.next_seq: int | None = None
97
+ self.framer = PacketFramer()
98
+
99
+
100
+ type StreamKey = tuple[str, int, str, int]
101
+
102
+
103
+ class Reassembler:
104
+ """Turn TCP segments between a client and a gateway into DyNet packets."""
105
+
106
+ def __init__(
107
+ self, gateway_host: str, gateway_port: int, writer: CaptureWriter
108
+ ) -> None:
109
+ """Capture traffic to and from `gateway_host`:`gateway_port`."""
110
+ self._host = gateway_host
111
+ self._port = gateway_port
112
+ self._writer = writer
113
+ self._streams: dict[StreamKey, _Stream] = {}
114
+ self.packets = 0
115
+
116
+ def direction(self, segment: Segment) -> Direction | None:
117
+ """Return ``rx``/``tx`` for gateway traffic, or ``None`` for anything else."""
118
+ if segment.src == self._host and segment.sport == self._port:
119
+ return "rx"
120
+ if segment.dst == self._host and segment.dport == self._port:
121
+ return "tx"
122
+ return None
123
+
124
+ def add(self, segment: Segment, now: float) -> None:
125
+ """Process one segment."""
126
+ direction = self.direction(segment)
127
+ if direction is None:
128
+ return
129
+ key = (segment.src, segment.sport, segment.dst, segment.dport)
130
+ client = (
131
+ f"{segment.dst}:{segment.dport}"
132
+ if direction == "rx"
133
+ else f"{segment.src}:{segment.sport}"
134
+ )
135
+ if segment.flags & _TCP_SYN:
136
+ self._streams[key] = stream = _Stream()
137
+ stream.next_seq = (segment.seq + 1) % _SEQ_MODULO
138
+ if direction == "tx":
139
+ self._writer.event(now, "connect", client=client)
140
+ return
141
+ stream = self._streams.setdefault(key, _Stream())
142
+ self._take_data(stream, segment, direction, client, now)
143
+ if segment.flags & (_TCP_FIN | _TCP_RST):
144
+ self._streams.pop(key, None)
145
+ name = "reset" if segment.flags & _TCP_RST else "close"
146
+ self._writer.event(now, name, dir=direction, client=client)
147
+
148
+ def _take_data(
149
+ self,
150
+ stream: _Stream,
151
+ segment: Segment,
152
+ direction: Direction,
153
+ client: str,
154
+ now: float,
155
+ ) -> None:
156
+ data = segment.payload
157
+ if not data:
158
+ return
159
+ if stream.next_seq is None: # joined mid-connection
160
+ stream.next_seq = segment.seq
161
+ ahead = _seq_diff(segment.seq, stream.next_seq)
162
+ if ahead > 0:
163
+ self._writer.event(now, "gap", dir=direction, client=client, missing=ahead)
164
+ stream.framer.reset()
165
+ elif ahead < 0:
166
+ if len(data) <= -ahead:
167
+ return # already seen: a retransmit or a keepalive probe
168
+ data = data[-ahead:]
169
+ stream.next_seq = (segment.seq + len(segment.payload)) % _SEQ_MODULO
170
+ before = stream.framer.discarded
171
+ for packet in stream.framer.feed(data):
172
+ self.packets += 1
173
+ self._writer.packet(now, direction, packet)
174
+ if skipped := stream.framer.discarded - before:
175
+ self._writer.event(
176
+ now, "noise", dir=direction, client=client, bytes=skipped
177
+ )
178
+
179
+
180
+ class RawSocket(Protocol):
181
+ """The parts of a raw packet socket the sniffer uses."""
182
+
183
+ def recv(self, bufsize: int, /) -> bytes:
184
+ """Read one frame."""
185
+ ...
186
+
187
+ def settimeout(self, value: float | None, /) -> None:
188
+ """Set the read timeout."""
189
+ ...
190
+
191
+ def close(self) -> None:
192
+ """Close the socket."""
193
+ ...
194
+
195
+
196
+ def open_raw_socket(interface: str) -> RawSocket: # pragma: no cover - needs Linux root
197
+ """Open a packet socket that sees every frame on `interface`."""
198
+ family = getattr(socket, "AF_PACKET", None)
199
+ if family is None:
200
+ msg = "Sniffing needs Linux (AF_PACKET sockets)"
201
+ raise OSError(msg)
202
+ sock = socket.socket(family, socket.SOCK_RAW, socket.ntohs(ETH_P_ALL))
203
+ sock.bind((interface, 0))
204
+ return sock
205
+
206
+
207
+ def sniff(
208
+ sock: RawSocket,
209
+ reassembler: Reassembler,
210
+ *,
211
+ duration: float | None,
212
+ clock: Callable[[], float] = time.time,
213
+ ) -> None:
214
+ """Read frames until `duration` seconds pass (or forever if ``None``)."""
215
+ end = None if duration is None else clock() + duration
216
+ sock.settimeout(1.0)
217
+ while end is None or clock() < end:
218
+ try:
219
+ frame = sock.recv(65535)
220
+ except TimeoutError:
221
+ continue
222
+ if (segment := parse_frame(frame)) is not None:
223
+ reassembler.add(segment, clock())
@@ -0,0 +1,154 @@
1
+ Metadata-Version: 2.5
2
+ Name: dynet-cli
3
+ Version: 0.1.0
4
+ Summary: Command-line tool to watch, control and capture a Signify Dynalite DyNet bus
5
+ Project-URL: Homepage, https://github.com/sdunster/dynet-cli
6
+ Project-URL: Issues, https://github.com/sdunster/dynet-cli/issues
7
+ Author-email: Sam Dunster <me@sdunster.com>
8
+ License-Expression: MIT
9
+ License-File: LICENSE
10
+ Keywords: cli,dynalite,dynet,lighting,signify
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Environment :: Console
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Intended Audience :: End Users/Desktop
15
+ Classifier: Operating System :: OS Independent
16
+ Classifier: Programming Language :: Python :: 3 :: Only
17
+ Classifier: Programming Language :: Python :: 3.13
18
+ Classifier: Programming Language :: Python :: 3.14
19
+ Classifier: Topic :: Home Automation
20
+ Classifier: Typing :: Typed
21
+ Requires-Python: >=3.13
22
+ Requires-Dist: aiodynet>=0.1.0
23
+ Description-Content-Type: text/markdown
24
+
25
+ # dynet-cli
26
+
27
+ `dynet` is a command-line tool for the Signify Dynalite **DyNet** bus: watch
28
+ traffic, recall presets, set channel levels, query state, discover areas, and
29
+ capture or decode traffic for later analysis. It is built on
30
+ [aiodynet](https://github.com/sdunster/aiodynet) and doubles as a worked
31
+ example of that library.
32
+
33
+ Requires Python 3.13 or newer. Install it with
34
+ [uv](https://docs.astral.sh/uv/), which also fetches a suitable Python if
35
+ needed, or with pipx:
36
+
37
+ ```sh
38
+ uv tool install dynet-cli # or: pipx install dynet-cli
39
+ export DYNET_HOST=192.0.2.10 DYNET_PORT=50000
40
+ ```
41
+
42
+ > **Asked to capture traffic from your system?** Follow
43
+ > [Capturing DyNet traffic](https://github.com/sdunster/dynet-cli/blob/main/docs/capturing-traffic.md). It walks through
44
+ > recording a day of traffic and sending it in.
45
+
46
+ ## Commands
47
+
48
+ | Command | What it does | Sends to the bus? |
49
+ |---|---|---|
50
+ | `dynet check` | Checks the gateway accepts TCP connections | No |
51
+ | `dynet monitor` | Shows bus traffic as it happens, decoded | No |
52
+ | `dynet preset AREA PRESET` | Selects a preset | Yes |
53
+ | `dynet level AREA CHANNEL LEVEL` | Fades a channel to a level | Yes |
54
+ | `dynet query preset AREA` | Asks an area for its current preset and waits for the answer | Yes (one request) |
55
+ | `dynet query level AREA CHANNEL` | Asks a channel for its level | Yes (one request) |
56
+ | `dynet scan` | Asks every area for its preset, to find the areas in use | Yes (one request per area) |
57
+ | `dynet send HEX...` | Sends raw packets (the checksum is added if you leave it off) | Yes |
58
+ | `dynet decode [FILE]` | Decodes hex or a capture file. Needs no gateway | No |
59
+ | `dynet sniff HOST:PORT` | Passively records another client's gateway traffic (Linux, root) | No |
60
+
61
+ Run `dynet COMMAND --help` for every option.
62
+
63
+ ### Watching the bus
64
+
65
+ ```console
66
+ $ dynet monitor
67
+ -- watching 192.0.2.10:50000
68
+ 19:02:11.402 1c 0c 00 00 00 00 ff d9 area 12: select preset 1
69
+ 19:02:11.630 1c 0c 00 60 01 01 ff 77 area 12 channel 1: is at 100%
70
+ 19:02:15.017 5c aa 55 53 18 71 26 a3 device 0xaa box 85: physical opcode 0x53 (not decoded)
71
+ ```
72
+
73
+ - `--area 1-10,12` shows only those areas.
74
+ - `--json` prints one JSON object per line.
75
+ - `--record FILE` also appends every packet to a capture file.
76
+ - `--duration SECONDS` stops after that long.
77
+
78
+ ### Control
79
+
80
+ ```sh
81
+ dynet preset 12 1 --fade 2 # area 12, preset 1, 2 s fade
82
+ dynet level 12 3 40% --fade 1 # area 12 channel 3 to 40 %
83
+ dynet level 12 3 off
84
+ dynet level 12 3 raw:0x80 # the raw DyNet level byte
85
+ ```
86
+
87
+ Out-of-range values are rejected before anything is sent. For example, a
88
+ channel fade is at most 5.1 s, which is all the packet can carry.
89
+
90
+ ### Finding your areas
91
+
92
+ `dynet scan --areas 1-255` asks each area for its current preset and lists
93
+ the ones that answer. It sends one packet per area, 0.2 s apart, so a full
94
+ scan takes about a minute. Some areas only answer for a channel they actually
95
+ have, so try `--channel` if an area you know about stays silent.
96
+
97
+ ### Capturing traffic
98
+
99
+ There are two ways to record traffic to a file:
100
+
101
+ - `dynet sniff GATEWAY:PORT -i IFACE` records the traffic between a gateway
102
+ and a client already connected to it, such as Home Assistant, from that
103
+ client's machine. It never connects to the gateway and never sends
104
+ anything. It needs Linux and root, because it reads raw frames from the
105
+ network interface.
106
+ - `dynet monitor --record FILE` records through its own connection to the
107
+ gateway, on any OS.
108
+
109
+ [Capturing DyNet traffic](https://github.com/sdunster/dynet-cli/blob/main/docs/capturing-traffic.md) covers both step by
110
+ step, including running a capture for a day under systemd. Each line of the file is one packet (`{"t": ..., "dir": "rx"|"tx", "hex":
111
+ ...}`) or one event (`connect`, `close`, `reset`, `gap`, `noise`). TCP is put
112
+ back in order first: keepalive probes and retransmits are dropped, and lost
113
+ data shows up as a `gap` rather than as a bogus packet.
114
+
115
+ ### Checking a capture
116
+
117
+ ```console
118
+ $ dynet decode --summary sample.jsonl
119
+ 4 packet(s) over 24.00 h
120
+ direction: rx 3, tx 1
121
+ By type:
122
+ 1 PresetSelect
123
+ 1 RequestPreset
124
+ 1 PresetReport
125
+ 1 Unknown physical 0x53
126
+ Areas: 12 (3)
127
+ Undecoded packets (1 distinct):
128
+ 1 5caa5553187126a3
129
+ ```
130
+
131
+ The "Undecoded packets" list shows everything aiodynet doesn't yet have a
132
+ typed message for. Without `--summary`, `decode` prints each packet the same
133
+ way `monitor` does, or as JSON with `--json`.
134
+
135
+ ## Exit codes
136
+
137
+ | Code | Meaning |
138
+ |---|---|
139
+ | 0 | Success |
140
+ | 1 | Gateway or file error |
141
+ | 2 | Bad arguments |
142
+ | 3 | `query` got no answer in time |
143
+
144
+ ## Development
145
+
146
+ ```sh
147
+ uv sync
148
+ uv run pytest --cov # 100 % branch coverage is enforced
149
+ uv run ruff check && uv run ruff format --check && uv run mypy
150
+ ```
151
+
152
+ ## Licence
153
+
154
+ MIT. Not affiliated with or endorsed by Signify.
@@ -0,0 +1,12 @@
1
+ dynet_cli/__init__.py,sha256=i6K9mGmh7MIT-J8Hj861KwvtQJH8WVPMXyI3GCAayPE,157
2
+ dynet_cli/__main__.py,sha256=9qMwjMUhMS22s2m7iORyPvtlxQDP2bVHbVcqy_n9LBk,68
3
+ dynet_cli/capture.py,sha256=HREoDQlDIOOIFCmz2tyhdpeMkxzz94IZJr-ZfHqJb28,6992
4
+ dynet_cli/cli.py,sha256=UBIg1EY5Z_JZYlcAtI8irfsFPCcAtgonRjCmy1fgmeU,18256
5
+ dynet_cli/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
6
+ dynet_cli/render.py,sha256=jdwGrx5kNpw6bzJ4aSn5qI7DkNIon5_ncjuuJ-aR0Xk,7912
7
+ dynet_cli/sniff.py,sha256=AJhE2JECkG8LXrtteymJ3cM0J1hm-DuZYbouTpdgdl8,7189
8
+ dynet_cli-0.1.0.dist-info/METADATA,sha256=iIitEUGb_n12tfo1MhXZPGruq-RyT6UsVyrOniYQOvQ,5747
9
+ dynet_cli-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
10
+ dynet_cli-0.1.0.dist-info/entry_points.txt,sha256=zB9HaGXfSZz_KxgbVy0vS0vxRyirFq-oKP2bfA267s0,45
11
+ dynet_cli-0.1.0.dist-info/licenses/LICENSE,sha256=xpAkjOPNnbsf0icoqTHgNnfqj-5zTVjWID9XDAO3FHI,1068
12
+ dynet_cli-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ dynet = dynet_cli.cli:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Sam Dunster
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.