dx5ii-cli 0.0.1__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.
dx5ii/cli.py ADDED
@@ -0,0 +1,579 @@
1
+ """Command-line interface.
2
+
3
+ Two calling styles share one parser:
4
+
5
+ ``dx5ii`` (no subcommand)
6
+ read the full state, optionally switching the output port and/or EQ preset
7
+ first; this is what the game watcher uses.
8
+ ``dx5ii <command> ...``
9
+ ``get`` / ``set`` / ``raw`` / ``watch`` / ``configs`` -- see ``--help``.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import argparse
15
+ import io
16
+ import json
17
+ import sys
18
+ import textwrap
19
+ import time
20
+ from typing import Any, Optional, Sequence
21
+
22
+ from .actions import apply_changes, state_summary
23
+ from .bands import Band, parse_apo_filters
24
+ from .constants import (
25
+ CMD_SWITCH_MCU_CONFIG,
26
+ DESTRUCTIVE_COMMANDS,
27
+ PT_READ,
28
+ PT_WRITE,
29
+ )
30
+ from .device import Dx5ii, list_interfaces
31
+ from .errors import Dx5iiError
32
+ from .fields import FIELD_ACTIONS, FIELD_SPECS, encode_field, field_raw, field_state
33
+ from .formatting import print_field_rows, print_snapshot, print_switch_report
34
+ from . import __version__
35
+ from .peq import (
36
+ create_preset,
37
+ delete_preset,
38
+ find_preset,
39
+ read_presets,
40
+ rename_preset,
41
+ )
42
+ from .protocol import format_firmware
43
+
44
+
45
+ def _open(path: Optional[str] = None) -> Dx5ii:
46
+ return Dx5ii(path=path)
47
+
48
+
49
+ def _epilog() -> str:
50
+ fields = textwrap.fill(
51
+ ", ".join(FIELD_SPECS), width=74,
52
+ initial_indent=" ", subsequent_indent=" ")
53
+ actions = textwrap.fill(
54
+ ", ".join(FIELD_ACTIONS), width=74,
55
+ initial_indent=" ", subsequent_indent=" ")
56
+ return (
57
+ "fields (%d)\n%s\n\n"
58
+ "actions (%d, no value; fire and forget)\n%s\n\n"
59
+ "exit codes: 0 ok, 2 device error, 3 write did not take effect"
60
+ % (len(FIELD_SPECS), fields, len(FIELD_ACTIONS), actions)
61
+ )
62
+
63
+
64
+ def build_parser() -> argparse.ArgumentParser:
65
+ """Build the argument parser (also used by ``--help``)."""
66
+ parser = argparse.ArgumentParser(
67
+ prog="dx5ii",
68
+ description="Control a Topping DX5 II over its HID interface.",
69
+ formatter_class=argparse.RawDescriptionHelpFormatter,
70
+ epilog=_epilog(),
71
+ )
72
+ parser.add_argument("--version", action="version",
73
+ version=f"dx5ii {__version__}")
74
+ parser.add_argument("--json", action="store_true",
75
+ help="emit JSON instead of text")
76
+ parser.add_argument("--devices", action="store_true",
77
+ help="list matching HID interfaces and exit")
78
+ parser.add_argument("--raw", action="store_true",
79
+ help="include every received frame in the snapshot")
80
+ parser.add_argument("--fast", action="store_true",
81
+ help="skip the EQ preset list (saves ~3 s)")
82
+ parser.add_argument("--path", help="explicit HID path (interface 2)")
83
+ parser.add_argument("--set-output", metavar="NAME",
84
+ help="switch the output port, e.g. hp_balanced")
85
+ parser.add_argument("--set-config", metavar="NAME|INDEX",
86
+ help="switch the active EQ preset, e.g. IER-M7.Harman")
87
+
88
+ sub = parser.add_subparsers(dest="command", metavar="command")
89
+
90
+ def add_common(target: argparse.ArgumentParser) -> None:
91
+ target.add_argument("--json", action="store_true", help="emit JSON")
92
+ target.add_argument("--path", help="explicit HID path (interface 2)")
93
+
94
+ p_get = sub.add_parser("get", help="print current state")
95
+ p_get.add_argument("fields", nargs="*", metavar="field",
96
+ help="field names (default: all)")
97
+ add_common(p_get)
98
+
99
+ p_set = sub.add_parser("set", help="write one or more fields, then read back")
100
+ p_set.add_argument("pairs", nargs="+", metavar="field value")
101
+ add_common(p_set)
102
+
103
+ p_raw = sub.add_parser("raw", help="send one frame and print the reply")
104
+ p_raw.add_argument("cmd", help="command number, e.g. 0x7137")
105
+ p_raw.add_argument("data", nargs="?", help="payload word")
106
+ p_raw.add_argument("--pt", choices=("read", "write"), default="write")
107
+ p_raw.add_argument("--total", type=lambda s: int(s, 0), default=1)
108
+ p_raw.add_argument("--cur", type=lambda s: int(s, 0), default=1)
109
+ p_raw.add_argument("--path")
110
+ p_raw.add_argument("--force", action="store_true",
111
+ help="allow commands that cannot be undone "
112
+ "(factory reset, firmware update mode)")
113
+
114
+ p_watch = sub.add_parser("watch", help="stream frames the device pushes")
115
+ p_watch.add_argument("seconds", nargs="?", type=int, default=3)
116
+ p_watch.add_argument("--path")
117
+
118
+ p_cfg = sub.add_parser("configs", help="list the EQ presets on the device")
119
+ add_common(p_cfg)
120
+
121
+ p_peq = sub.add_parser("peq", help="manage EQ presets")
122
+ peq_sub = p_peq.add_subparsers(dest="peq_command", required=True)
123
+
124
+ p_plist = peq_sub.add_parser("list", help="list presets with band counts")
125
+ add_common(p_plist)
126
+
127
+ p_pshow = peq_sub.add_parser("show", help="print one preset's bands")
128
+ p_pshow.add_argument("preset", help="preset name or index")
129
+ add_common(p_pshow)
130
+
131
+ p_pcreate = peq_sub.add_parser(
132
+ "create", help="upload a new preset (never modifies existing ones)")
133
+ p_pcreate.add_argument("name", help="new preset name (max 32 UTF-8 bytes)")
134
+ source = p_pcreate.add_mutually_exclusive_group(required=True)
135
+ source.add_argument("--copy", metavar="PRESET",
136
+ help="copy the bands of an existing preset")
137
+ source.add_argument("--from-apo", metavar="FILE",
138
+ help="read 'Filter N: ON PK Fc ...' lines from FILE")
139
+ p_pcreate.add_argument("--activate", action="store_true",
140
+ help="keep the new preset active (default: restore "
141
+ "whatever was active before)")
142
+ p_pcreate.add_argument("--json", action="store_true")
143
+ p_pcreate.add_argument("--path")
144
+
145
+ p_pdel = peq_sub.add_parser("delete", help="delete a preset")
146
+ p_pdel.add_argument("preset", help="preset name or index")
147
+ p_pdel.add_argument("--switch", required=True, metavar="PRESET",
148
+ help="preset to activate after deletion")
149
+ p_pdel.add_argument("--json", action="store_true")
150
+ p_pdel.add_argument("--path")
151
+
152
+ p_pren = peq_sub.add_parser("rename", help="rename a preset")
153
+ p_pren.add_argument("preset", help="preset name or index")
154
+ p_pren.add_argument("new_name")
155
+ p_pren.add_argument("--json", action="store_true")
156
+ p_pren.add_argument("--path")
157
+
158
+ return parser
159
+
160
+
161
+ # ---------------------------------------------------------------------------
162
+ # subcommand implementations
163
+ # ---------------------------------------------------------------------------
164
+
165
+ def _cmd_get(path: Optional[str], fields: Sequence[str], as_json: bool) -> int:
166
+ with _open(path) as dev:
167
+ snap = dev.snapshot(include_configs=False)
168
+
169
+ if not fields or list(fields) == ["all"]:
170
+ if as_json:
171
+ print(json.dumps(snap, indent=2, ensure_ascii=False))
172
+ else:
173
+ print_snapshot(snap)
174
+ return 0
175
+
176
+ selected: dict[str, Any] = {}
177
+ for name in fields:
178
+ if name not in FIELD_SPECS:
179
+ print(f"error: unknown field {name!r}", file=sys.stderr)
180
+ return 2
181
+ value = field_state(snap, name)
182
+ selected[name] = value
183
+ raw = field_raw(snap, name)
184
+ if isinstance(value, str) and raw is not None:
185
+ selected[name + "_raw"] = raw
186
+
187
+ if as_json:
188
+ print(json.dumps(selected, indent=2, ensure_ascii=False))
189
+ else:
190
+ print_field_rows(selected.items())
191
+ return 0
192
+
193
+
194
+ def _cmd_set(path: Optional[str], pairs: Sequence[str], as_json: bool) -> int:
195
+ if len(pairs) % 2 != 0:
196
+ print("error: set needs field/value pairs", file=sys.stderr)
197
+ return 2
198
+ items = [(pairs[i], pairs[i + 1]) for i in range(0, len(pairs), 2)]
199
+
200
+ with _open(path) as dev:
201
+ before = dev.snapshot(include_configs=False)
202
+ results: list[dict[str, Any]] = []
203
+ for name, value in items:
204
+ for cmd, data, total, cur in encode_field(name, value, before["settings"]):
205
+ dev.send(cmd, data, PT_WRITE, total, cur)
206
+ time.sleep(0.35)
207
+ results.append({"field": name, "requested": value})
208
+ time.sleep(0.25)
209
+ after = dev.snapshot(include_configs=False)
210
+
211
+ ok = True
212
+ for item in results:
213
+ name = item["field"]
214
+ item["from"] = field_state(before, name)
215
+ item["observed"] = field_state(after, name)
216
+ if isinstance(item["from"], str) or isinstance(item["observed"], str):
217
+ item["from_raw"] = field_raw(before, name)
218
+ item["observed_raw"] = field_raw(after, name)
219
+ item["changed"] = item["from"] != item["observed"]
220
+ if not item["changed"] and name not in FIELD_ACTIONS:
221
+ ok = False
222
+ item["note"] = "read-back unchanged"
223
+
224
+ report = {
225
+ "ok": ok,
226
+ "actions": results,
227
+ "before": state_summary(before),
228
+ "after": state_summary(after),
229
+ }
230
+ if as_json:
231
+ print(json.dumps(report, indent=2, ensure_ascii=False))
232
+ else:
233
+ for item in results:
234
+ name = item["field"]
235
+ if name in FIELD_ACTIONS:
236
+ print(f"{name:<20} sent")
237
+ else:
238
+ note = "" if item["changed"] else " (unchanged)"
239
+ print(f"{name:<20} {item['from']} -> {item['observed']}{note}")
240
+ return 0 if ok else 3
241
+
242
+
243
+ def _cmd_raw(path: Optional[str], args: argparse.Namespace) -> int:
244
+ cmd = int(args.cmd, 0)
245
+ data = int(args.data, 0) if args.data else 0
246
+
247
+ danger = DESTRUCTIVE_COMMANDS.get(cmd)
248
+ if danger and not args.force:
249
+ print("refusing 0x%04X: %s.\nPass --force if you really mean it."
250
+ % (cmd, danger), file=sys.stderr)
251
+ return 2
252
+
253
+ protocol = PT_READ if args.pt == "read" else PT_WRITE
254
+ with _open(path) as dev:
255
+ dev.send(cmd, data, protocol, args.total, args.cur)
256
+ frames = dev.read_for(800)
257
+
258
+ for frame in frames:
259
+ print("cmd=0x%04X pt=0x%02X total=%d cur=%d data=%d (0x%X)"
260
+ % (frame["cmd"], frame["protocol"], frame["total"],
261
+ frame["index"], frame["data"], frame["data"]))
262
+ print(f"{len(frames)} frames")
263
+ return 0
264
+
265
+
266
+ def _cmd_watch(path: Optional[str], seconds: int) -> int:
267
+ with _open(path) as dev:
268
+ print(f"watching push frames for {seconds}s ...")
269
+ frames = dev.read_for(seconds * 1000)
270
+ counts: dict[tuple[int, int], int] = {}
271
+ for frame in frames:
272
+ key = (frame["cmd"], frame["protocol"])
273
+ counts[key] = counts.get(key, 0) + 1
274
+ for (cmd, protocol), count in sorted(counts.items()):
275
+ print("cmd=0x%04X pt=0x%02X x%d" % (cmd, protocol, count))
276
+ print(f"{len(frames)} frames total")
277
+ return 0
278
+
279
+
280
+ def _cmd_configs(path: Optional[str], as_json: bool) -> int:
281
+ with _open(path) as dev:
282
+ snap = dev.snapshot(include_configs=True)
283
+ configs = snap["configs"]
284
+ if as_json:
285
+ print(json.dumps(configs, indent=2, ensure_ascii=False))
286
+ return 0
287
+ print("current=%s (%s) count=%s"
288
+ % (configs.get("current_index"), configs.get("current_name"),
289
+ configs.get("count")))
290
+ for item in configs.get("configs") or []:
291
+ mark = "<- active" if item.get("active") else ""
292
+ print(" %d %-20s %s" % (item["index"], item["name"], mark))
293
+ return 0
294
+
295
+
296
+ # ---------------------------------------------------------------------------
297
+ # eq preset management
298
+ # ---------------------------------------------------------------------------
299
+
300
+ def _resolve_preset(presets: dict[str, Any], ref: str) -> Optional[dict[str, Any]]:
301
+ """Resolve a preset by index or case-insensitive name."""
302
+ text = ref.strip()
303
+ if text.lstrip("-").isdigit():
304
+ index = int(text)
305
+ for preset in presets.get("presets", []):
306
+ if preset["index"] == index:
307
+ return preset
308
+ return None
309
+ return find_preset(presets, text)
310
+
311
+
312
+ def _used_bands(preset: dict[str, Any]) -> tuple[list[Band], list[Band]]:
313
+ """Drop the device's spare 11th band from a decoded preset."""
314
+ return (
315
+ [Band(**b) for b in preset["bands_left"]],
316
+ [Band(**b) for b in preset["bands_right"]],
317
+ )
318
+
319
+
320
+ def _print_bands(preset: dict[str, Any], which: str) -> None:
321
+ print("%s (index %d%s)" % (preset["name"], preset["index"],
322
+ ", active" if preset["active"] else ""))
323
+ for channel, key in (("L", "bands_left"), ("R", "bands_right")):
324
+ if which not in ("both", channel.lower()):
325
+ continue
326
+ for i, band in enumerate(preset[key]):
327
+ if not band["enabled"] and i >= 10:
328
+ continue
329
+ kind = band["type"]
330
+ state = "ON " if band["enabled"] else "OFF"
331
+ print(" %s%2d %s %-2s Fc %7.1f Hz Gain %+5.1f dB Q %.4f"
332
+ % (channel, i + 1, state, kind, band["freq_hz"],
333
+ band["gain_db"], band["q"]))
334
+
335
+
336
+ def _cmd_peq(args: argparse.Namespace) -> int:
337
+ path = getattr(args, "path", None)
338
+ as_json = bool(getattr(args, "json", False))
339
+
340
+ try:
341
+ with _open(path) as dev:
342
+ presets = read_presets(dev)
343
+
344
+ if args.peq_command == "list":
345
+ if as_json:
346
+ print(json.dumps(presets, indent=2, ensure_ascii=False))
347
+ return 0
348
+ print("current=%s count=%s"
349
+ % (presets.get("current_index"), presets.get("count")))
350
+ for preset in presets["presets"]:
351
+ used = sum(1 for b in preset["bands_left"] if b["enabled"])
352
+ mark = "<- active" if preset["active"] else ""
353
+ print(" %d %-24s %2d bands hash=0x%08X %s"
354
+ % (preset["index"], preset["name"], used,
355
+ preset["hash"], mark))
356
+ return 0
357
+
358
+ if args.peq_command == "show":
359
+ preset = _resolve_preset(presets, args.preset)
360
+ if preset is None:
361
+ print("error: no preset %r" % args.preset, file=sys.stderr)
362
+ return 2
363
+ if as_json:
364
+ print(json.dumps(preset, indent=2, ensure_ascii=False))
365
+ else:
366
+ _print_bands(preset, "both")
367
+ return 0
368
+
369
+ if args.peq_command == "create":
370
+ name = args.name.strip()
371
+ if not name:
372
+ print("error: empty preset name", file=sys.stderr)
373
+ return 2
374
+ if len(name.encode("utf-8")) > 32:
375
+ print("error: name longer than 32 UTF-8 bytes", file=sys.stderr)
376
+ return 2
377
+ if find_preset(presets, name):
378
+ print("error: preset %r already exists; refusing to "
379
+ "overwrite an existing preset" % name, file=sys.stderr)
380
+ return 2
381
+
382
+ if args.copy:
383
+ source = _resolve_preset(presets, args.copy)
384
+ if source is None:
385
+ print("error: no preset %r to copy" % args.copy,
386
+ file=sys.stderr)
387
+ return 2
388
+ left, right = _used_bands(source)
389
+ else:
390
+ text = io.open(args.from_apo, encoding="utf-8",
391
+ errors="replace").read()
392
+ left = parse_apo_filters(text)
393
+ if not left:
394
+ print("error: no filters parsed from %s" % args.from_apo,
395
+ file=sys.stderr)
396
+ return 2
397
+ right = list(left)
398
+
399
+ index = create_preset(dev, name, left, right)
400
+ # Creating a preset makes the device activate it; put the old
401
+ # one back unless the caller asked for the new one.
402
+ if not args.activate:
403
+ now = dev.current_config_index()
404
+ if now != presets.get("current_index"):
405
+ dev.send(CMD_SWITCH_MCU_CONFIG,
406
+ presets.get("current_index") or 0, PT_WRITE)
407
+ time.sleep(0.15)
408
+ after = read_presets(dev)
409
+ found = find_preset(after, name)
410
+ report = {
411
+ "created": name,
412
+ "index": index,
413
+ "found": found is not None,
414
+ "count_before": presets.get("count"),
415
+ "count_after": after.get("count"),
416
+ "bands": len(left),
417
+ "current_index": after.get("current_index"),
418
+ }
419
+ if as_json:
420
+ print(json.dumps(report, indent=2, ensure_ascii=False))
421
+ else:
422
+ print("created %r at index %d (count %s -> %s)"
423
+ % (name, index, report["count_before"],
424
+ report["count_after"]))
425
+ return 0 if report["found"] else 3
426
+
427
+ if args.peq_command == "delete":
428
+ preset = _resolve_preset(presets, args.preset)
429
+ if preset is None:
430
+ print("error: no preset %r" % args.preset, file=sys.stderr)
431
+ return 2
432
+ target = _resolve_preset(presets, args.switch)
433
+ if target is None:
434
+ print("error: no preset %r to switch to" % args.switch,
435
+ file=sys.stderr)
436
+ return 2
437
+ if target["index"] == preset["index"]:
438
+ print("error: --switch must name a different preset",
439
+ file=sys.stderr)
440
+ return 2
441
+ delete_preset(dev, preset["index"], target["index"])
442
+ after = read_presets(dev)
443
+ report = {
444
+ "deleted": preset["name"],
445
+ "index": preset["index"],
446
+ "count_before": presets.get("count"),
447
+ "count_after": after.get("count"),
448
+ "current_index": after.get("current_index"),
449
+ "presets": [p["name"] for p in after["presets"]],
450
+ }
451
+ if as_json:
452
+ print(json.dumps(report, indent=2, ensure_ascii=False))
453
+ else:
454
+ print("deleted %r (count %s -> %s), active=%s"
455
+ % (preset["name"], report["count_before"],
456
+ report["count_after"], report["current_index"]))
457
+ return 0
458
+
459
+ if args.peq_command == "rename":
460
+ preset = _resolve_preset(presets, args.preset)
461
+ if preset is None:
462
+ print("error: no preset %r" % args.preset, file=sys.stderr)
463
+ return 2
464
+ new_name = args.new_name.strip()
465
+ if not new_name or len(new_name.encode("utf-8")) > 32:
466
+ print("error: name must be 1..32 UTF-8 bytes", file=sys.stderr)
467
+ return 2
468
+ rename_preset(dev, preset["index"], new_name)
469
+ after = read_presets(dev)
470
+ renamed = any(p["name"] == new_name for p in after["presets"])
471
+ report = {
472
+ "from": preset["name"],
473
+ "to": new_name,
474
+ "index": preset["index"],
475
+ "renamed": renamed,
476
+ }
477
+ if as_json:
478
+ print(json.dumps(report, indent=2, ensure_ascii=False))
479
+ else:
480
+ print("renamed %r -> %r (%s)"
481
+ % (preset["name"], new_name,
482
+ "ok" if renamed else "not observed"))
483
+ return 0 if renamed else 3
484
+ except Dx5iiError as exc:
485
+ print(f"error: {exc}", file=sys.stderr)
486
+ return 2
487
+
488
+ raise AssertionError(f"unhandled peq command {args.peq_command!r}")
489
+
490
+
491
+ # ---------------------------------------------------------------------------
492
+ # entry point
493
+ # ---------------------------------------------------------------------------
494
+
495
+ def _run_subcommand(args: argparse.Namespace) -> int:
496
+ if args.command == "get":
497
+ return _cmd_get(args.path, args.fields, args.json)
498
+ if args.command == "set":
499
+ return _cmd_set(args.path, args.pairs, args.json)
500
+ if args.command == "raw":
501
+ return _cmd_raw(args.path, args)
502
+ if args.command == "watch":
503
+ return _cmd_watch(args.path, args.seconds)
504
+ if args.command == "configs":
505
+ return _cmd_configs(args.path, args.json)
506
+ if args.command == "peq":
507
+ return _cmd_peq(args)
508
+ raise AssertionError(f"unhandled command {args.command!r}")
509
+
510
+
511
+ def _read_snapshot(args: argparse.Namespace) -> int:
512
+ """No subcommand: read the state, optionally switching first."""
513
+ write_mode = bool(args.set_output or args.set_config)
514
+ try:
515
+ with _open(args.path) as dev:
516
+ if write_mode:
517
+ snap = dev.snapshot(include_configs=True, keep_raw=args.raw)
518
+ report = apply_changes(dev, snap, args.set_output, args.set_config)
519
+ else:
520
+ snap = dev.snapshot(include_configs=not args.fast,
521
+ keep_raw=args.raw)
522
+ report = None
523
+ except Dx5iiError as exc:
524
+ print(f"error: {exc}", file=sys.stderr)
525
+ return 2
526
+
527
+ if report is None:
528
+ if args.json:
529
+ print(json.dumps(snap, indent=2, ensure_ascii=False))
530
+ else:
531
+ print_snapshot(snap)
532
+ return 0
533
+
534
+ if args.json:
535
+ print(json.dumps(report, indent=2, ensure_ascii=False))
536
+ else:
537
+ print_switch_report(report)
538
+ return 0 if report["ok"] else 3
539
+
540
+
541
+ def main(argv: Optional[Sequence[str]] = None) -> int:
542
+ """CLI entry point; returns the process exit code."""
543
+ if hasattr(sys.stdout, "reconfigure"):
544
+ try:
545
+ sys.stdout.reconfigure(encoding="utf-8", errors="replace")
546
+ except Exception: # pragma: no cover - stream may be closed
547
+ pass
548
+
549
+ parser = build_parser()
550
+ args = parser.parse_args(argv)
551
+
552
+ if args.command:
553
+ try:
554
+ return _run_subcommand(args)
555
+ except Dx5iiError as exc:
556
+ print(f"error: {exc}", file=sys.stderr)
557
+ return 2
558
+
559
+ if args.devices:
560
+ interfaces = list_interfaces()
561
+ printable = [{k: v for k, v in item.items() if k != "path_bytes"}
562
+ for item in interfaces]
563
+ if args.json:
564
+ print(json.dumps(printable, indent=2, ensure_ascii=False))
565
+ else:
566
+ for item in printable:
567
+ marker = " <- protocol" if item["interface_number"] == 2 else ""
568
+ print("iface %-2s usage_page=%-3s usage=%-2s %s firmware=%s%s"
569
+ % (item["interface_number"], item["usage_page"],
570
+ item["usage"], item["product"],
571
+ format_firmware(item.get("release_number")),
572
+ marker))
573
+ return 0
574
+
575
+ return _read_snapshot(args)
576
+
577
+
578
+ if __name__ == "__main__": # pragma: no cover
579
+ raise SystemExit(main())