pyvisionect 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.
Files changed (58) hide show
  1. pyvisionect/__init__.py +120 -0
  2. pyvisionect/devices/__init__.py +92 -0
  3. pyvisionect/devices/enums.py +403 -0
  4. pyvisionect/devices/panels.py +242 -0
  5. pyvisionect/devices/tclv.py +460 -0
  6. pyvisionect/imaging/README.md +175 -0
  7. pyvisionect/imaging/__init__.py +181 -0
  8. pyvisionect/imaging/checksum.py +114 -0
  9. pyvisionect/imaging/constants.py +131 -0
  10. pyvisionect/imaging/data/blue_noise_64.npy +0 -0
  11. pyvisionect/imaging/decode.py +172 -0
  12. pyvisionect/imaging/dither.py +357 -0
  13. pyvisionect/imaging/encoder.py +594 -0
  14. pyvisionect/imaging/geometry.py +129 -0
  15. pyvisionect/imaging/grey.py +104 -0
  16. pyvisionect/imaging/interlace.py +244 -0
  17. pyvisionect/imaging/pack.py +142 -0
  18. pyvisionect/imaging/panel.py +339 -0
  19. pyvisionect/imaging/partial.py +931 -0
  20. pyvisionect/imaging/rects.py +466 -0
  21. pyvisionect/io/__init__.py +33 -0
  22. pyvisionect/io/tcp.py +795 -0
  23. pyvisionect/io/usb/__init__.py +237 -0
  24. pyvisionect/io/usb/cli.py +278 -0
  25. pyvisionect/io/usb/commands.py +781 -0
  26. pyvisionect/io/usb/console.py +730 -0
  27. pyvisionect/io/usb/device.py +914 -0
  28. pyvisionect/io/usb/discovery.py +260 -0
  29. pyvisionect/io/usb/encryption.py +262 -0
  30. pyvisionect/io/usb/errors.py +175 -0
  31. pyvisionect/io/usb/fake.py +292 -0
  32. pyvisionect/io/usb/parsers.py +1464 -0
  33. pyvisionect/io/usb/provisioning.py +502 -0
  34. pyvisionect/packets/__init__.py +135 -0
  35. pyvisionect/packets/control.py +95 -0
  36. pyvisionect/packets/file.py +325 -0
  37. pyvisionect/packets/image.py +234 -0
  38. pyvisionect/packets/misc.py +202 -0
  39. pyvisionect/packets/param.py +284 -0
  40. pyvisionect/packets/status.py +518 -0
  41. pyvisionect/packets/stored.py +217 -0
  42. pyvisionect/py.typed +0 -0
  43. pyvisionect/session/__init__.py +100 -0
  44. pyvisionect/session/connection.py +1043 -0
  45. pyvisionect/session/device.py +587 -0
  46. pyvisionect/session/events.py +196 -0
  47. pyvisionect/session/filetransfer.py +251 -0
  48. pyvisionect/session/pending.py +425 -0
  49. pyvisionect/wire/__init__.py +91 -0
  50. pyvisionect/wire/blocks.py +350 -0
  51. pyvisionect/wire/checksum.py +115 -0
  52. pyvisionect/wire/errors.py +176 -0
  53. pyvisionect/wire/framing.py +334 -0
  54. pyvisionect-0.1.0.dist-info/METADATA +1030 -0
  55. pyvisionect-0.1.0.dist-info/RECORD +58 -0
  56. pyvisionect-0.1.0.dist-info/WHEEL +4 -0
  57. pyvisionect-0.1.0.dist-info/entry_points.txt +3 -0
  58. pyvisionect-0.1.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,1464 @@
1
+ '''Typed results: every getter returns a dataclass, not a string.
2
+
3
+ Each parser in this module was written against a capture taken off a live sign
4
+ (firmware 7.4.4407, 32" board, ``APP: Joan``). The verbatim replies are in
5
+ :mod:`pyvisionect.io.usb.fake`, which is also what the tests run against, so
6
+ the parsers and the fixtures cannot drift apart.
7
+
8
+ Shapes you have to cope with
9
+ ----------------------------
10
+
11
+ The replies are *mostly* ``Label: value`` lines, but not uniformly, and the
12
+ exceptions are the whole reason this module is longer than a dict comprehension:
13
+
14
+ * ``uuid_get`` emits a **blank line first**, then space-separated ``0x`` bytes
15
+ with a **trailing space** -- not a dashed UUID string.
16
+ * ``certs_config_get`` prints ``rv: 0`` **before** its body, so "the return code
17
+ is the last line" is false.
18
+ * ``rv:`` comes in two spellings from different commands in the same firmware:
19
+ ``rv: 0`` (``fs_ls``) and ``rv: 0x0`` (``sf_list``, ``wifi_bssid_get``).
20
+ * ``fs_ls`` and ``sf_list`` are tables, not fields; ``sf_list`` has a rule line
21
+ and a trailing blank.
22
+ * ``status_get`` is 60 ``KEY: value`` lines in SCREAMING_SNAKE, ended by a
23
+ ``STATUS_END`` sentinel, mixing decimal and ``0x`` hex -- and one key,
24
+ ``PROTOCOL VERSION``, has a **space** where every other key has an underscore.
25
+ * ``display_conf_get`` prints **8** VCOMs while ``display_conf_set`` takes
26
+ **16** arguments. The getter is right about this hardware (TCLV has
27
+ ``VCOM_0..7``, ids 20-27); the setter's arity is for a 16-panel board. Do not
28
+ "fix" the parser to expect 16.
29
+
30
+ Numbers that look wrong and are not
31
+ -----------------------------------
32
+
33
+ * ``conn_fw_ver`` reports ``6.4294967295.3310684876``. Those are an
34
+ uninitialised ``0xFFFFFFFF`` and a junk word, and the same two values appear
35
+ in ``status_get`` as ``CONN_VER_MINOR: -1`` and
36
+ ``CONN_VER_REVISION: -984282420`` -- the *same bytes* rendered unsigned by one
37
+ command and signed by the other, in one firmware build.
38
+ :class:`ConnectivityFirmware` keeps both views.
39
+ * ``ipv4_conf_get`` on a DHCP device shows a stale static address
40
+ (``MODE: 1`` is DHCP, so IP/NM/GW/DNS are unused leftovers). It is the
41
+ *stored configuration*, never the live lease. :attr:`Ipv4Config.in_use` says
42
+ so.
43
+ * ``SIGNAL_STRENGTH: 31`` in ``status_get`` against ``RSSI:-31 dBm`` from
44
+ ``cc3100_rssi``: the status field is a **dBm magnitude with the sign
45
+ dropped**, which is exactly what
46
+ :mod:`pyvisionect.packets.status` documents for the wire field. Live
47
+ confirmation of a fact that was read out of a disassembler.
48
+ '''
49
+
50
+ from __future__ import annotations
51
+
52
+ import re
53
+ import uuid as _uuid
54
+ from collections.abc import Iterable, Mapping, Sequence
55
+ from dataclasses import dataclass, field
56
+
57
+ __all__ = [
58
+ "BatteryConfig",
59
+ "BorderConfig",
60
+ "CertificateConfig",
61
+ "ChargerState",
62
+ "ConnectivityFirmware",
63
+ "ConnectivityOption",
64
+ "ConnectivityState",
65
+ "ConnectivityType",
66
+ "DisplayConfig",
67
+ "EapConfig",
68
+ "EncryptionConfig",
69
+ "EthernetConfig",
70
+ "Features",
71
+ "FileEntry",
72
+ "FilesystemStats",
73
+ "FirmwareVersion",
74
+ "ImageRotateConfig",
75
+ "Ipv4Config",
76
+ "LogConfig",
77
+ "PmicRegisters",
78
+ "ServerConfig",
79
+ "SpiFlashDevice",
80
+ "SpiFlashStatus",
81
+ "StatusDump",
82
+ "SystemConfig",
83
+ "Task",
84
+ "TaskList",
85
+ "WifiConfig",
86
+ "WifiFirmware",
87
+ "WifiMacConfig",
88
+ "parse_battery_config",
89
+ "parse_border",
90
+ "parse_certs_config",
91
+ "parse_charger",
92
+ "parse_conn_firmware",
93
+ "parse_conn_state",
94
+ "parse_conn_type",
95
+ "parse_conn_type_list",
96
+ "parse_display_config",
97
+ "parse_eap_config",
98
+ "parse_encryption_config",
99
+ "parse_eth_config",
100
+ "parse_features",
101
+ "parse_firmware_version",
102
+ "parse_fs_ls",
103
+ "parse_fs_stats",
104
+ "parse_gtin",
105
+ "parse_image_rotate_config",
106
+ "parse_ipv4_config",
107
+ "parse_log_config",
108
+ "parse_mac",
109
+ "parse_rssi",
110
+ "parse_sf_list",
111
+ "parse_status_dump",
112
+ "parse_system_config",
113
+ "parse_task_list",
114
+ "parse_temperature",
115
+ "parse_uptime",
116
+ "parse_uuid",
117
+ "parse_wifi_config",
118
+ "parse_wifi_firmware",
119
+ "parse_wifi_mac_config",
120
+ ]
121
+
122
+ _MAC_RE = re.compile(r"^(?:[0-9A-Fa-f]{2}:){5}[0-9A-Fa-f]{2}$")
123
+
124
+
125
+ def _int(text: str) -> int:
126
+ """Parse a decimal or ``0x``-prefixed integer, tolerating a trailing unit.
127
+
128
+ The device appends units inconsistently (``"2400 mV"``, ``"24 degC"``,
129
+ ``"75 sec"``, ``"-44 dBm"``), so the unit is dropped rather than demanded.
130
+ """
131
+ token = text.strip().split()[0] if text.strip() else text
132
+ return int(token, 0)
133
+
134
+
135
+ def _fields(lines: Sequence[str]) -> dict[str, str]:
136
+ out: dict[str, str] = {}
137
+ for line in lines:
138
+ name, sep, value = line.partition(":")
139
+ if sep:
140
+ out[name.strip()] = value.strip()
141
+ return out
142
+
143
+
144
+ def parse_mac(text: str) -> str:
145
+ """Normalise a MAC to lowercase colon form.
146
+
147
+ The firmware is inconsistent about case in its own output --
148
+ ``wifi_mac_conf_get`` lowercases, ``eth_conf_get`` uppercases -- so
149
+ comparing two of its MACs as strings without this is a bug waiting to
150
+ happen.
151
+
152
+ Raises:
153
+ ValueError: if *text* is not six colon-separated octets.
154
+ """
155
+ token = text.strip()
156
+ if not _MAC_RE.match(token):
157
+ raise ValueError(f"not a MAC address: {text!r}")
158
+ return token.lower()
159
+
160
+
161
+ # ---------------------------------------------------------------- identity
162
+
163
+
164
+ @dataclass(frozen=True, slots=True)
165
+ class FirmwareVersion:
166
+ """``fw_version_get``: eight lines covering app, bootloader, board and panel.
167
+
168
+ Attributes:
169
+ firmware: e.g. ``"7.4.4407"``.
170
+ firmware_build_date: the three integers from ``"FW Build date: 10 9 2025"``
171
+ as ``(10, 9, 2025)``. **Field order is not stated by the device**;
172
+ day-month-year is the reading that makes 10/9/2025 a plausible build
173
+ date either way, so this is kept as a raw triple rather than being
174
+ turned into a ``date`` that would be wrong half the year.
175
+ crc: the ``FW Crc=0x...`` word. Matches ``FW_CRC`` in ``status_get``
176
+ and ``FirmwareCRC`` on the wire.
177
+ image_hash: the ``Hash=0x...`` word.
178
+ image_length: ``Length=`` in bytes.
179
+ bootloader: the ``BL Version`` string.
180
+ build: the ``Build Version`` string.
181
+ hardware: ``"PP32 v1.1"`` -- board name and revision.
182
+ bom: the ``BOM:`` integer.
183
+ app: ``"Joan"`` -- the JS application identity.
184
+ panel: the raw ``EPD:`` line, e.g.
185
+ ``'31.2",2x2880x640,WF=31.2_C296,IC=31.2_p224rev0050'``.
186
+ """
187
+
188
+ firmware: str
189
+ firmware_build_date: tuple[int, int, int] | None
190
+ crc: int | None
191
+ image_hash: int | None
192
+ image_length: int | None
193
+ bootloader: str | None
194
+ bootloader_build_date: tuple[int, int, int] | None
195
+ build: str | None
196
+ hardware: str | None
197
+ bom: int | None
198
+ app: str | None
199
+ panel: str | None
200
+
201
+ @property
202
+ def version_tuple(self) -> tuple[int, ...]:
203
+ """:attr:`firmware` split on dots, for comparison."""
204
+ return tuple(int(p) for p in self.firmware.split(".") if p.isdigit())
205
+
206
+ @property
207
+ def panel_count(self) -> int | None:
208
+ """How many physical panels the ``EPD:`` line names.
209
+
210
+ ``"2x2880x640"`` means two 2880x640 panels. Worth having because
211
+ ``status_get``'s ``NUMBER_OF_SUPPORTED_DISPLAYS`` agrees (2) while the
212
+ reverse engineering notes said four 1440x640 panels -- the panel line is
213
+ the one that comes from the firmware's own display table.
214
+ """
215
+ if not self.panel:
216
+ return None
217
+ match = re.search(r"(\d+)x(\d+)x(\d+)", self.panel)
218
+ return int(match.group(1)) if match else None
219
+
220
+ @property
221
+ def panel_size(self) -> tuple[int, int] | None:
222
+ """``(width, height)`` of a single panel from the ``EPD:`` line."""
223
+ if not self.panel:
224
+ return None
225
+ match = re.search(r"(\d+)x(\d+)x(\d+)", self.panel)
226
+ return (int(match.group(2)), int(match.group(3))) if match else None
227
+
228
+
229
+ def _date_triple(text: str) -> tuple[int, int, int] | None:
230
+ parts = text.split()
231
+ if len(parts) == 3 and all(p.isdigit() for p in parts):
232
+ a, b, c = (int(p) for p in parts)
233
+ return (a, b, c)
234
+ return None
235
+
236
+
237
+ def parse_firmware_version(lines: Sequence[str]) -> FirmwareVersion:
238
+ """Parse ``fw_version_get``."""
239
+ f = _fields(lines)
240
+ crc = image_hash = image_length = None
241
+ for line in lines:
242
+ if line.startswith("FW Crc="):
243
+ for key, value in re.findall(r"(\w+)=((?:0x)?[0-9a-fA-F]+)", line):
244
+ if key == "Crc":
245
+ crc = int(value, 16)
246
+ elif key == "Hash":
247
+ image_hash = int(value, 16)
248
+ elif key == "Length":
249
+ image_length = int(value, 0)
250
+ hardware = bom = app = None
251
+ if "HW" in f:
252
+ # "PP32 v1.1, BOM: 0, APP: Joan" -- the line has nested "k: v" pairs, so
253
+ # it cannot go through _fields.
254
+ raw = f["HW"]
255
+ hardware = raw.split(",")[0].strip()
256
+ bom_match = re.search(r"BOM:\s*(\d+)", raw)
257
+ bom = int(bom_match.group(1)) if bom_match else None
258
+ app_match = re.search(r"APP:\s*(\S+)", raw)
259
+ app = app_match.group(1) if app_match else None
260
+ return FirmwareVersion(
261
+ firmware=f.get("FW Version", ""),
262
+ firmware_build_date=_date_triple(f.get("FW Build date", "")),
263
+ crc=crc,
264
+ image_hash=image_hash,
265
+ image_length=image_length,
266
+ bootloader=f.get("BL Version"),
267
+ bootloader_build_date=_date_triple(f.get("BL Build date", "")),
268
+ build=f.get("Build Version"),
269
+ hardware=hardware,
270
+ bom=bom,
271
+ app=app,
272
+ panel=f.get("EPD"),
273
+ )
274
+
275
+
276
+ def parse_uuid(lines: Sequence[str]) -> _uuid.UUID:
277
+ """Parse ``uuid_get`` into a :class:`uuid.UUID`.
278
+
279
+ The device prints a blank line, then 16 space-separated ``0x`` bytes with a
280
+ trailing space -- *not* a dashed UUID. The trailing NUL bytes are real and
281
+ are preserved: a 12-byte factory identifier zero-padded to 16, so the
282
+ rendered form ends ``...00000000`` and that is correct, not truncation.
283
+
284
+ Use :func:`uuid.UUID.bytes` to get the 16 bytes the packet header carries.
285
+
286
+ Raises:
287
+ ValueError: if the reply does not carry exactly 16 byte literals.
288
+ """
289
+ tokens: list[str] = []
290
+ for line in lines:
291
+ _, _, tail = line.partition("UUID:")
292
+ tokens.extend(re.findall(r"0x([0-9a-fA-F]{1,2})", tail or line))
293
+ if len(tokens) != 16:
294
+ raise ValueError(
295
+ f"uuid_get should give 16 bytes, got {len(tokens)}: {list(lines)!r}"
296
+ )
297
+ return _uuid.UUID(bytes=bytes(int(t, 16) for t in tokens))
298
+
299
+
300
+ def parse_gtin(lines: Sequence[str]) -> str:
301
+ """Parse ``gtin_get``. Kept as a string: a GTIN has significant leading zeros."""
302
+ return _fields(lines)["GTIN"]
303
+
304
+
305
+ def parse_uptime(lines: Sequence[str]) -> int:
306
+ """Parse ``uptime``. **Minutes**, not seconds -- same unit as the wire field."""
307
+ return _int(_fields(lines)["Uptime in min"])
308
+
309
+
310
+ @dataclass(frozen=True, slots=True)
311
+ class Features:
312
+ """``feat_get``: which licensed features are on.
313
+
314
+ Attributes:
315
+ enabled: feature name -> bool. Names come from the device
316
+ (``"touch"``, ``"EAP"``), case as printed.
317
+
318
+ Turning one of these off is ``feat_disable <key>``, which is in the ``HARD``
319
+ tier: the key is a licence key you have to have in order to put it back.
320
+ """
321
+
322
+ enabled: Mapping[str, bool]
323
+
324
+ def __getitem__(self, name: str) -> bool:
325
+ return self.enabled[name]
326
+
327
+ @property
328
+ def touch(self) -> bool | None:
329
+ return self.enabled.get("touch")
330
+
331
+ @property
332
+ def eap(self) -> bool | None:
333
+ return self.enabled.get("EAP")
334
+
335
+
336
+ def parse_features(lines: Sequence[str]) -> Features:
337
+ """Parse ``feat_get``.
338
+
339
+ The reply pads the label to a column (``"Feature EAP: enabled"``), which
340
+ is why the value is stripped rather than sliced.
341
+ """
342
+ out: dict[str, bool] = {}
343
+ for line in lines:
344
+ match = re.match(r"^Feature\s+(\S+):\s*(\S+)\s*$", line)
345
+ if match:
346
+ out[match.group(1)] = match.group(2).lower() == "enabled"
347
+ return Features(enabled=out)
348
+
349
+
350
+ # -------------------------------------------------------------- encryption
351
+
352
+
353
+ @dataclass(frozen=True, slots=True)
354
+ class EncryptionConfig:
355
+ """``encryption_config_get``: outbound link encryption state.
356
+
357
+ Attributes:
358
+ enabled: from ``"Outbound enc: Disabled"`` / ``"Enabled"``. Maps to
359
+ TCLV 130, documented in the vendor table as
360
+ *"Outbound encryption: 0=Disabled, 1=Enabled"*.
361
+ key: whatever the device echoes back between the single quotes of
362
+ ``"Key: ''"``. Empty on an unprovisioned sign.
363
+
364
+ See :mod:`pyvisionect.io.usb.encryption` for what is and is not known about
365
+ the key format. Short version: the only two modes the TCLV table admits are
366
+ 0 and 1, and the key material has never been observed non-empty.
367
+ """
368
+
369
+ enabled: bool
370
+ key: str
371
+
372
+ @property
373
+ def configured(self) -> bool:
374
+ """True when a key is present, whether or not the mode is on."""
375
+ return bool(self.key)
376
+
377
+
378
+ def parse_encryption_config(lines: Sequence[str]) -> EncryptionConfig:
379
+ """Parse ``encryption_config_get``."""
380
+ f = _fields(lines)
381
+ raw_key = f.get("Key", "")
382
+ if len(raw_key) >= 2 and raw_key[0] == raw_key[-1] == "'":
383
+ raw_key = raw_key[1:-1]
384
+ return EncryptionConfig(
385
+ enabled=f.get("Outbound enc", "").strip().lower() == "enabled",
386
+ key=raw_key,
387
+ )
388
+
389
+
390
+ # ----------------------------------------------------------------- display
391
+
392
+
393
+ @dataclass(frozen=True, slots=True)
394
+ class DisplayConfig:
395
+ """``display_conf_get``: the VCOM rails and the display identifier.
396
+
397
+ Attributes:
398
+ vcom_mv: one entry per VCOM rail the getter prints, in millivolts.
399
+ **Eight on this hardware, not sixteen.** ``display_conf_set`` takes
400
+ 16 VCOM arguments, but TCLV only defines ``VCOM_0..7`` (ids 20-27)
401
+ and the getter prints 8. On the live 32" sign the first four are
402
+ 2400 mV and the last four are 0, i.e. four rails wired and four not.
403
+ display_type: the ``Display type:`` integer, printed unsigned decimal.
404
+ Compare :data:`pyvisionect.devices.panels.DISPLAY_TYPE_NAMES`.
405
+
406
+ Writing this is ``display_conf_set``, which is ``DESTRUCTIVE``: a wrong VCOM
407
+ is a way to damage an e-ink panel, not merely to make it look bad.
408
+ """
409
+
410
+ vcom_mv: tuple[int, ...]
411
+ display_type: int | None
412
+
413
+ @property
414
+ def active_rails(self) -> int:
415
+ """How many VCOM rails are non-zero."""
416
+ return sum(1 for v in self.vcom_mv if v)
417
+
418
+ @property
419
+ def display_type_hex(self) -> str:
420
+ """:attr:`display_type` as ``0x...``, which is how ``status_get`` prints it."""
421
+ return "" if self.display_type is None else f"0x{self.display_type:08X}"
422
+
423
+
424
+ def parse_display_config(lines: Sequence[str]) -> DisplayConfig:
425
+ """Parse ``display_conf_get``."""
426
+ vcoms: list[tuple[int, int]] = []
427
+ display_type = None
428
+ for line in lines:
429
+ match = re.match(r"^Vcom\s+(\d+):\s*(-?\d+)\s*mV\s*$", line)
430
+ if match:
431
+ vcoms.append((int(match.group(1)), int(match.group(2))))
432
+ continue
433
+ match = re.match(r"^Display type:\s*(\d+)\s*$", line)
434
+ if match:
435
+ display_type = int(match.group(1))
436
+ return DisplayConfig(
437
+ vcom_mv=tuple(v for _, v in sorted(vcoms)), display_type=display_type
438
+ )
439
+
440
+
441
+ @dataclass(frozen=True, slots=True)
442
+ class BorderConfig:
443
+ """``border_get``: the EPD border mode (TCLV 109).
444
+
445
+ Attributes:
446
+ supported: ``"Border support: No"`` on the 32" board -- the panel has no
447
+ controllable border, so :attr:`mode` is moot there.
448
+ mode: ``"Server"``, ``"White"`` or ``"Black"``, matching TCLV 109's
449
+ *"0=server, 1=white, 2=black"*.
450
+ """
451
+
452
+ supported: bool
453
+ mode: str
454
+
455
+
456
+ def parse_border(lines: Sequence[str]) -> BorderConfig:
457
+ """Parse ``border_get``."""
458
+ f = _fields(lines)
459
+ return BorderConfig(
460
+ supported=f.get("Border support", "").strip().lower() in ("yes", "true", "1"),
461
+ mode=f.get("Border", ""),
462
+ )
463
+
464
+
465
+ @dataclass(frozen=True, slots=True)
466
+ class ImageRotateConfig:
467
+ """``image_rotate_config_get``: the local image carousel.
468
+
469
+ Attributes:
470
+ mode: ``"off"`` on the live sign.
471
+ timeout_s: seconds between images.
472
+ image_count: how many images are in the rotation. Zero while off,
473
+ even though ``fs_ls`` shows six ``.pv2`` files -- the carousel count
474
+ is configuration, not a directory listing.
475
+ """
476
+
477
+ mode: str
478
+ timeout_s: int | None
479
+ image_count: int | None
480
+
481
+ @property
482
+ def enabled(self) -> bool:
483
+ return self.mode.strip().lower() not in ("off", "", "0", "disabled")
484
+
485
+
486
+ def parse_image_rotate_config(lines: Sequence[str]) -> ImageRotateConfig:
487
+ """Parse ``image_rotate_config_get``."""
488
+ f = _fields(lines)
489
+ return ImageRotateConfig(
490
+ mode=f.get("Mode", ""),
491
+ timeout_s=_int(f["Timeout"]) if "Timeout" in f else None,
492
+ image_count=_int(f["Number of images"]) if "Number of images" in f else None,
493
+ )
494
+
495
+
496
+ # ------------------------------------------------------------ connectivity
497
+
498
+
499
+ @dataclass(frozen=True, slots=True)
500
+ class ConnectivityOption:
501
+ """One row of ``conn_type_list``: a driver this firmware was built with.
502
+
503
+ Attributes:
504
+ name: the driver name, e.g. ``"CC3100"`` (TI WiFi) or ``"W5500"``
505
+ (WIZnet Ethernet MAC+PHY).
506
+ value: the ``CONN_TYPE`` (TCLV 2) integer to pass to ``conn_type_set``.
507
+ """
508
+
509
+ name: str
510
+ value: int
511
+
512
+
513
+ def parse_conn_type_list(lines: Sequence[str]) -> tuple[ConnectivityOption, ...]:
514
+ """Parse ``conn_type_list``.
515
+
516
+ **This is the only trustworthy source for ``CONN_TYPE`` values.** The
517
+ vendor's admin UI table lists 0-7 and the vendor's own CLI documentation
518
+ uses ``conn_type_set 8`` in a 4G example; this firmware offers exactly
519
+ three, ``W5500 (3)``, ``CC3100 (6)`` and ``None (0)``, and would reject the
520
+ rest. Enumerate, never guess.
521
+ """
522
+ out: list[ConnectivityOption] = []
523
+ for line in lines:
524
+ match = re.match(r"^(.+?)\s*\((\d+)\)\s*$", line)
525
+ if match:
526
+ out.append(
527
+ ConnectivityOption(name=match.group(1).strip(), value=int(match.group(2)))
528
+ )
529
+ return tuple(out)
530
+
531
+
532
+ @dataclass(frozen=True, slots=True)
533
+ class ConnectivityType:
534
+ """``conn_type_get``: which driver is live right now.
535
+
536
+ Attributes:
537
+ name: e.g. ``"CC3100"``.
538
+ value: the ``CONN_TYPE`` integer, 6 on the live sign.
539
+ active: whether the reply said ``active``.
540
+ """
541
+
542
+ name: str
543
+ value: int
544
+ active: bool = True
545
+
546
+
547
+ def parse_conn_type(lines: Sequence[str]) -> ConnectivityType:
548
+ """Parse ``conn_type_get`` (``"CC3100 (6) active"``)."""
549
+ for line in lines:
550
+ match = re.match(r"^(.+?)\s*\((\d+)\)\s*(\w+)?\s*$", line)
551
+ if match:
552
+ return ConnectivityType(
553
+ name=match.group(1).strip(),
554
+ value=int(match.group(2)),
555
+ active=(match.group(3) or "").lower() == "active",
556
+ )
557
+ raise ValueError(f"cannot parse conn_type_get: {list(lines)!r}")
558
+
559
+
560
+ @dataclass(frozen=True, slots=True)
561
+ class ConnectivityState:
562
+ """``conn_state_get``: the socket's state in words.
563
+
564
+ Attributes:
565
+ state: verbatim, e.g. ``"tcp open"``.
566
+ """
567
+
568
+ state: str
569
+
570
+ @property
571
+ def connected(self) -> bool:
572
+ """True for ``"tcp open"``.
573
+
574
+ Deliberately a substring test on ``"open"``: the firmware's state
575
+ vocabulary is not documented anywhere, so an unknown state is reported
576
+ as not-connected rather than crashing.
577
+ """
578
+ return "open" in self.state.lower()
579
+
580
+
581
+ def parse_conn_state(lines: Sequence[str]) -> ConnectivityState:
582
+ """Parse ``conn_state_get``."""
583
+ return ConnectivityState(state=_fields(lines).get("Conn", "").strip())
584
+
585
+
586
+ @dataclass(frozen=True, slots=True)
587
+ class ConnectivityFirmware:
588
+ """``conn_fw_ver``: the radio firmware triple, as the device renders it.
589
+
590
+ Attributes:
591
+ raw: the line verbatim, e.g. ``"6.4294967295.3310684876"``.
592
+ parts_unsigned: the three words read as unsigned.
593
+ parts_signed: the same words read as signed int32.
594
+
595
+ Both views are kept because **the firmware disagrees with itself**: this
596
+ command prints the words unsigned while ``status_get`` prints the identical
597
+ values as ``CONN_VER_MINOR: -1`` and ``CONN_VER_REVISION: -984282420``.
598
+ 4294967295 is ``0xFFFFFFFF``, i.e. never written, so on this hardware the
599
+ minor and revision are simply uninitialised and only the major (6, matching
600
+ ``CONN_TYPE`` 6) means anything. Use ``cc3100_fw_version`` for a real radio
601
+ version.
602
+ """
603
+
604
+ raw: str
605
+ parts_unsigned: tuple[int, ...]
606
+ parts_signed: tuple[int, ...]
607
+
608
+ @property
609
+ def initialised(self) -> bool:
610
+ """False when any word is ``0xFFFFFFFF``."""
611
+ return all(p != 0xFFFFFFFF for p in self.parts_unsigned)
612
+
613
+
614
+ def parse_conn_firmware(lines: Sequence[str]) -> ConnectivityFirmware:
615
+ """Parse ``conn_fw_ver``."""
616
+ raw = lines[0].strip() if lines else ""
617
+ unsigned = tuple(int(p) for p in raw.split(".") if p.lstrip("-").isdigit())
618
+ signed = tuple(p - 0x100000000 if p >= 0x80000000 else p for p in unsigned)
619
+ return ConnectivityFirmware(raw=raw, parts_unsigned=unsigned, parts_signed=signed)
620
+
621
+
622
+ def parse_conn_retry(lines: Sequence[str]) -> int:
623
+ """Parse ``conn_retry_get`` (TCLV 30), in minutes."""
624
+ return _int(_fields(lines)["Net error retry"])
625
+
626
+
627
+ # -------------------------------------------------------------------- WiFi
628
+
629
+
630
+ @dataclass(frozen=True, slots=True)
631
+ class WifiConfig:
632
+ """``wifi_conf_get``: SSID, security and band. **No PSK.**
633
+
634
+ Attributes:
635
+ ssid: TCLV 65.
636
+ security: TCLV 66, an ASCII string (``"none"``, ``"wpa2"``, ``"wpa2e"``),
637
+ not an integer.
638
+ band: TCLV 68 -- 0 dual, 1 2.4 GHz, 2 5 GHz.
639
+
640
+ The getter does **not** echo the passphrase, which is worth knowing before
641
+ you run it on someone's sign: there is no read path for TCLV 67 over USB
642
+ either.
643
+ """
644
+
645
+ ssid: str
646
+ security: str
647
+ band: int | None
648
+
649
+
650
+ def parse_wifi_config(lines: Sequence[str]) -> WifiConfig:
651
+ """Parse ``wifi_conf_get``."""
652
+ f = _fields(lines)
653
+ return WifiConfig(
654
+ ssid=f.get("SSID", ""),
655
+ security=f.get("Security", ""),
656
+ band=_int(f["Band"]) if "Band" in f else None,
657
+ )
658
+
659
+
660
+ @dataclass(frozen=True, slots=True)
661
+ class WifiMacConfig:
662
+ """``wifi_mac_conf_get``: the radio's MAC (TCLV 110).
663
+
664
+ Lowercased by :func:`parse_mac`, because this command prints lowercase and
665
+ ``eth_conf_get`` prints uppercase for the same kind of value.
666
+ """
667
+
668
+ mac: str
669
+
670
+
671
+ def parse_wifi_mac_config(lines: Sequence[str]) -> WifiMacConfig:
672
+ """Parse ``wifi_mac_conf_get``."""
673
+ return WifiMacConfig(mac=parse_mac(_fields(lines)["WiFi MAC"]))
674
+
675
+
676
+ @dataclass(frozen=True, slots=True)
677
+ class EapConfig:
678
+ """``wifi_eap_conf_get``: WPA2-Enterprise identity (TCLV 74/76).
679
+
680
+ Attributes:
681
+ method: e.g. ``"PEAP/MSCHAPV2"`` (TCLV 74).
682
+ username: TCLV 76.
683
+
684
+ The password (TCLV 75) is write-only; there is no read path.
685
+ """
686
+
687
+ method: str
688
+ username: str
689
+
690
+
691
+ def parse_eap_config(lines: Sequence[str]) -> EapConfig:
692
+ """Parse ``wifi_eap_conf_get``."""
693
+ f = _fields(lines)
694
+ return EapConfig(method=f.get("EAP method", ""), username=f.get("Username", ""))
695
+
696
+
697
+ @dataclass(frozen=True, slots=True)
698
+ class CertificateConfig:
699
+ """``certs_config_get``: the EAP certificate slots (TCLV 60-64).
700
+
701
+ Attributes:
702
+ present: False when the device says ``"No EAP cert found!"``.
703
+ lines: the reply verbatim, because the populated form has never been
704
+ observed -- the live sign has no certificate, so anything this
705
+ parser claimed about a loaded one would be invented.
706
+
707
+ Note this command prints its ``rv: 0`` **before** the body, which is the
708
+ counterexample to "the return code is the last line".
709
+ """
710
+
711
+ present: bool
712
+ lines: tuple[str, ...]
713
+
714
+
715
+ def parse_certs_config(lines: Sequence[str]) -> CertificateConfig:
716
+ """Parse ``certs_config_get``."""
717
+ text = " ".join(lines).lower()
718
+ return CertificateConfig(present="no eap cert" not in text, lines=tuple(lines))
719
+
720
+
721
+ def parse_rssi(lines: Sequence[str]) -> int:
722
+ """Parse ``cc3100_rssi`` into **signed dBm** (``-44``).
723
+
724
+ The reply is ``"RSSI:-44 dBm"`` with no space after the colon. Note that
725
+ ``status_get``'s ``SIGNAL_STRENGTH`` carries the same reading with the sign
726
+ *dropped*, so the two differ by a negation and not by a measurement.
727
+ """
728
+ for line in lines:
729
+ match = re.search(r"RSSI\s*:\s*(-?\d+)", line)
730
+ if match:
731
+ return int(match.group(1))
732
+ raise ValueError(f"cannot parse cc3100_rssi: {list(lines)!r}")
733
+
734
+
735
+ @dataclass(frozen=True, slots=True)
736
+ class WifiFirmware:
737
+ """``cc3100_fw_version``: the TI CC3100's own version words.
738
+
739
+ Attributes:
740
+ nwp: network processor, e.g. ``"2.12.2.8"``.
741
+ mac: MAC layer, e.g. ``"1.5.0.10"``.
742
+ phy: PHY, e.g. ``"1.0.3.37"``.
743
+ chip_id: ``67108864`` == ``0x04000000``.
744
+ rom: ``13107``.
745
+
746
+ Unlike ``conn_fw_ver``, these are real. Use this one.
747
+ """
748
+
749
+ nwp: str
750
+ mac: str
751
+ phy: str
752
+ chip_id: int | None
753
+ rom: int | None
754
+
755
+
756
+ def parse_wifi_firmware(lines: Sequence[str]) -> WifiFirmware:
757
+ """Parse ``cc3100_fw_version``.
758
+
759
+ The reply is space-separated (``"NWP 2.12.2.8"``), not colon-separated, so
760
+ it does not go through :func:`_fields`.
761
+ """
762
+ out: dict[str, str] = {}
763
+ for line in lines:
764
+ parts = line.split()
765
+ if len(parts) >= 2:
766
+ out[parts[0]] = parts[1]
767
+ return WifiFirmware(
768
+ nwp=out.get("NWP", ""),
769
+ mac=out.get("MAC", ""),
770
+ phy=out.get("PHY", ""),
771
+ chip_id=_int(out["ChipId"]) if "ChipId" in out else None,
772
+ rom=_int(out["ROM"]) if "ROM" in out else None,
773
+ )
774
+
775
+
776
+ def parse_bssid(lines: Sequence[str]) -> str:
777
+ """Parse ``wifi_bssid_get`` (TCLV 170) into a normalised MAC.
778
+
779
+ Cross-check: ``status_get`` carries the same six bytes split over two
780
+ uint32s, ``BSSID_1`` little-endian over bytes 0-3 and ``BSSID_2`` over bytes
781
+ 4-5. :attr:`StatusDump.bssid` reassembles them and the two agree.
782
+ """
783
+ for line in lines:
784
+ if _MAC_RE.match(line.strip()):
785
+ return parse_mac(line)
786
+ raise ValueError(f"cannot parse wifi_bssid_get: {list(lines)!r}")
787
+
788
+
789
+ # --------------------------------------------------------- network / server
790
+
791
+
792
+ @dataclass(frozen=True, slots=True)
793
+ class Ipv4Config:
794
+ """``ipv4_conf_get``: the **stored static** IPv4 configuration (TCLV 13-17).
795
+
796
+ Attributes:
797
+ ip, netmask, gateway, dns: TCLV 13, 14, 15, 16.
798
+ mode: TCLV 17 -- 0 static, 1 DHCP.
799
+
800
+ **This is configuration, not the live lease.** On the sign this was read
801
+ from, ``mode`` is 1 (DHCP) and the four addresses are a stale static block
802
+ from some earlier network -- the device was answering on a completely
803
+ different address at the time. :attr:`in_use` is the guard against
804
+ reporting those as the device's address.
805
+ """
806
+
807
+ ip: str
808
+ netmask: str
809
+ gateway: str
810
+ dns: str
811
+ mode: int | None
812
+
813
+ @property
814
+ def dhcp(self) -> bool:
815
+ return self.mode == 1
816
+
817
+ @property
818
+ def in_use(self) -> bool:
819
+ """True only when ``mode`` is static, so these addresses are the live ones."""
820
+ return self.mode == 0
821
+
822
+
823
+ def parse_ipv4_config(lines: Sequence[str]) -> Ipv4Config:
824
+ """Parse ``ipv4_conf_get``."""
825
+ f = _fields(lines)
826
+ return Ipv4Config(
827
+ ip=f.get("IP", ""),
828
+ netmask=f.get("NM", ""),
829
+ gateway=f.get("GW", ""),
830
+ dns=f.get("DNS", ""),
831
+ mode=_int(f["MODE"]) if "MODE" in f else None,
832
+ )
833
+
834
+
835
+ @dataclass(frozen=True, slots=True)
836
+ class EthernetConfig:
837
+ """``eth_conf_get``: the W5500's MAC and TCP retry policy (TCLV 8/9/10).
838
+
839
+ Attributes:
840
+ mac: TCLV 8. On the live WiFi sign this is a
841
+ locally-administered address -- the ``02`` bit of the first octet
842
+ is set -- i.e. a synthesised default for an Ethernet MAC that is
843
+ present in the build but not wired up, rather than a real
844
+ vendor-assigned address. :attr:`locally_administered` is the test.
845
+ retry_count: TCLV 9.
846
+ retry_timeout_ms: TCLV 10. The device prints ``TRT: 2000``; the TCLV
847
+ table calls the field "Ethernet TCP retry timeout [100ms]", so the
848
+ **unit is disputed** -- 2000 is a round number of milliseconds and
849
+ an odd number of 100 ms ticks. Reported verbatim and named for what
850
+ the device prints.
851
+ """
852
+
853
+ mac: str
854
+ retry_count: int | None
855
+ retry_timeout_ms: int | None
856
+
857
+ @property
858
+ def locally_administered(self) -> bool:
859
+ """True when bit 1 of the first octet is set, i.e. not a vendor MAC."""
860
+ return bool(int(self.mac.split(":")[0], 16) & 0x02) if self.mac else False
861
+
862
+
863
+ def parse_eth_config(lines: Sequence[str]) -> EthernetConfig:
864
+ """Parse ``eth_conf_get``."""
865
+ f = _fields(lines)
866
+ return EthernetConfig(
867
+ mac=parse_mac(f["MAC"]) if "MAC" in f else "",
868
+ retry_count=_int(f["TRC"]) if "TRC" in f else None,
869
+ retry_timeout_ms=_int(f["TRT"]) if "TRT" in f else None,
870
+ )
871
+
872
+
873
+ @dataclass(frozen=True, slots=True)
874
+ class ServerConfig:
875
+ """``server_tcp_get`` plus ``server_hb_get``: where the sign dials out to.
876
+
877
+ Attributes:
878
+ host: TCLV 18. **A DNS name works and is what the live sign holds**,
879
+ which is why re-pointing that name is an alternative to touching
880
+ the device at all.
881
+ port: TCLV 19, 11113 by default.
882
+ heartbeat_minutes: TCLV 29, from ``server_hb_get``. None when only
883
+ ``server_tcp_get`` was parsed.
884
+
885
+ TCLV 18 and 19 are both ``canWrite: false`` over the network, so this is the
886
+ pair that makes USB provisioning unavoidable.
887
+ """
888
+
889
+ host: str
890
+ port: int | None
891
+ heartbeat_minutes: int | None = None
892
+
893
+ @property
894
+ def is_hostname(self) -> bool:
895
+ """True when :attr:`host` is a name rather than a dotted quad."""
896
+ return bool(self.host) and not re.match(r"^\d+\.\d+\.\d+\.\d+$", self.host)
897
+
898
+
899
+ def parse_server_config(
900
+ lines: Sequence[str], heartbeat: Sequence[str] | None = None
901
+ ) -> ServerConfig:
902
+ """Parse ``server_tcp_get``, optionally folding in ``server_hb_get``."""
903
+ f = _fields(lines)
904
+ hb = None
905
+ if heartbeat is not None:
906
+ hb_fields = _fields(heartbeat)
907
+ if "HB interval" in hb_fields:
908
+ hb = _int(hb_fields["HB interval"])
909
+ return ServerConfig(
910
+ host=f.get("Server IP/DNS", ""),
911
+ port=_int(f["Server port"]) if "Server port" in f else None,
912
+ heartbeat_minutes=hb,
913
+ )
914
+
915
+
916
+ def parse_heartbeat(lines: Sequence[str]) -> int:
917
+ """Parse ``server_hb_get`` (TCLV 29), in minutes."""
918
+ return _int(_fields(lines)["HB interval"])
919
+
920
+
921
+ # ----------------------------------------------------------- power / system
922
+
923
+
924
+ @dataclass(frozen=True, slots=True)
925
+ class BatteryConfig:
926
+ """``battery_conf_get``: the low-battery shutdown thresholds (TCLV 36/37/38).
927
+
928
+ Attributes:
929
+ threshold_off_mv: TCLV 36 -- below this the sign powers down.
930
+ threshold_on_mv: TCLV 37 -- above this it comes back.
931
+ threshold_count: TCLV 38 -- consecutive readings before acting.
932
+
933
+ Note ``off`` (3500 mV) is *higher* than ``on`` (3400 mV) on the live sign,
934
+ which reads like inverted hysteresis. Reported as found; the firmware's
935
+ comparison direction was not traced.
936
+ """
937
+
938
+ threshold_off_mv: int | None
939
+ threshold_on_mv: int | None
940
+ threshold_count: int | None
941
+
942
+
943
+ def parse_battery_config(lines: Sequence[str]) -> BatteryConfig:
944
+ """Parse ``battery_conf_get``."""
945
+ f = _fields(lines)
946
+ return BatteryConfig(
947
+ threshold_off_mv=_int(f["Threshold OFF"]) if "Threshold OFF" in f else None,
948
+ threshold_on_mv=_int(f["Threshold ON"]) if "Threshold ON" in f else None,
949
+ threshold_count=_int(f["Threshold CNT"]) if "Threshold CNT" in f else None,
950
+ )
951
+
952
+
953
+ @dataclass(frozen=True, slots=True)
954
+ class ChargerState:
955
+ """``bq24023_mode_get``: live readings from the battery charger.
956
+
957
+ Attributes:
958
+ mode: e.g. ``"fast charge"``.
959
+ current_ma: ``Ibatt``.
960
+ voltage_mv: ``Vbatt``. 4214 mV on a full pack.
961
+ """
962
+
963
+ mode: str
964
+ current_ma: int | None
965
+ voltage_mv: int | None
966
+
967
+
968
+ def parse_charger(lines: Sequence[str]) -> ChargerState:
969
+ """Parse ``bq24023_mode_get``."""
970
+ f = _fields(lines)
971
+ return ChargerState(
972
+ mode=f.get("BQ", ""),
973
+ current_ma=_int(f["Ibatt"]) if "Ibatt" in f else None,
974
+ voltage_mv=_int(f["Vbatt"]) if "Vbatt" in f else None,
975
+ )
976
+
977
+
978
+ def parse_temperature(lines: Sequence[str]) -> int:
979
+ """Parse ``lmr`` -- the LM75 board sensor, in whole degrees Celsius.
980
+
981
+ **A different sensor from the panel's.** ``status_get``'s
982
+ ``EPD_TEMP_SENSOR`` is the panel's own reading, and the two were observed one
983
+ degree apart on a live sign (26 against 25) a second apart. They agree often
984
+ enough to look like the same value and they are not, so do not use one to
985
+ validate the other.
986
+ """
987
+ return _int(_fields(lines)["LM75"])
988
+
989
+
990
+ @dataclass(frozen=True, slots=True)
991
+ class SystemConfig:
992
+ """``system_conf_get``: the three system flags (TCLV 49/50/51).
993
+
994
+ Attributes:
995
+ battery_mode: TCLV 49, *"System screens: 1=Battery, 2=Not connected,
996
+ 3=Battery+Not connected"*.
997
+ touch_mode: TCLV 50, *"0=OFF, 1=ON, 3=ON+Beep"*. 3 on the live sign --
998
+ which is why it chirps.
999
+ shipping_mode: TCLV 51. **1 means the sign does not wake up normally**,
1000
+ so setting it is gated behind ``allow_destructive``.
1001
+ """
1002
+
1003
+ battery_mode: int | None
1004
+ touch_mode: int | None
1005
+ shipping_mode: int | None
1006
+
1007
+ @property
1008
+ def touch_enabled(self) -> bool:
1009
+ return bool(self.touch_mode)
1010
+
1011
+ @property
1012
+ def beeps(self) -> bool:
1013
+ return self.touch_mode == 3
1014
+
1015
+
1016
+ def parse_system_config(lines: Sequence[str]) -> SystemConfig:
1017
+ """Parse ``system_conf_get``."""
1018
+ f = _fields(lines)
1019
+ return SystemConfig(
1020
+ battery_mode=_int(f["Battery mode"]) if "Battery mode" in f else None,
1021
+ touch_mode=_int(f["Touch mode"]) if "Touch mode" in f else None,
1022
+ shipping_mode=_int(f["Shipping mode"]) if "Shipping mode" in f else None,
1023
+ )
1024
+
1025
+
1026
+ @dataclass(frozen=True, slots=True)
1027
+ class LogConfig:
1028
+ """``log_config_get``: per-module debug logging levels.
1029
+
1030
+ Attributes:
1031
+ modules: module name -> level. The live sign reports only
1032
+ ``{"Mobile": 0}`` -- one line, although ``log_config_set`` takes a
1033
+ ``<module> <value>`` pair and the ``vlog_*`` family implies a richer
1034
+ scheme. The getter simply does not print the rest.
1035
+
1036
+ The four ``vlog_*`` commands are the interesting ones here, because they
1037
+ expose a richer model than this getter does: levels are set per *source* and
1038
+ per *destination* independently, so logging is a matrix and ``log_config_get``
1039
+ shows one cell of it at most. ``vlog_unify_levels`` would collapse the USB
1040
+ column to a single level -- see
1041
+ :meth:`pyvisionect.io.usb.device.Sign.unify_usb_log_levels` for why that is
1042
+ not yet a usable answer to the interleaving problem.
1043
+ """
1044
+
1045
+ modules: Mapping[str, int]
1046
+
1047
+
1048
+ def parse_log_config(lines: Sequence[str]) -> LogConfig:
1049
+ """Parse ``log_config_get``."""
1050
+ out: dict[str, int] = {}
1051
+ for name, value in _fields(lines).items():
1052
+ try:
1053
+ out[name] = _int(value)
1054
+ except (ValueError, IndexError):
1055
+ continue
1056
+ return LogConfig(modules=out)
1057
+
1058
+
1059
+ @dataclass(frozen=True, slots=True)
1060
+ class PmicRegisters:
1061
+ """``max17135_dump <i2c_channel>``: the display PMIC's registers.
1062
+
1063
+ Attributes:
1064
+ registers: whatever ``name: value`` pairs the dump printed.
1065
+ lines: the reply verbatim.
1066
+
1067
+ **Unverified contents.** ``help`` lists this command as nullary
1068
+ (``"max17135_dump: Dump register values"``) and a bare call is rejected with
1069
+ ``Incorrect command parameter(s).`` -- the help line is wrong and the command
1070
+ wants an I2C channel like its ``max17135_sleep``/``_wakeup``/``_selftest``
1071
+ siblings. The channel was not guessed at on the sign this was written
1072
+ against, because the neighbouring commands in that family power the panel
1073
+ rails up and down. So this parser is written to the generic
1074
+ ``name: value`` shape and has never seen real output.
1075
+ """
1076
+
1077
+ registers: Mapping[str, int]
1078
+ lines: tuple[str, ...]
1079
+
1080
+
1081
+ def parse_pmic_dump(lines: Sequence[str]) -> PmicRegisters:
1082
+ """Parse ``max17135_dump``. See the caveat on :class:`PmicRegisters`."""
1083
+ out: dict[str, int] = {}
1084
+ for name, value in _fields(lines).items():
1085
+ try:
1086
+ out[name] = _int(value)
1087
+ except (ValueError, IndexError):
1088
+ continue
1089
+ return PmicRegisters(registers=out, lines=tuple(lines))
1090
+
1091
+
1092
+ # ------------------------------------------------------------- filesystem
1093
+
1094
+
1095
+ @dataclass(frozen=True, slots=True)
1096
+ class FileEntry:
1097
+ """One row of ``fs_ls``.
1098
+
1099
+ The row is three whitespace-separated columns, ``"/image0.pv2 0 134409"``.
1100
+ Only the first and last are labelled anywhere; the middle one is 0 for every
1101
+ file on the live sign.
1102
+
1103
+ Attributes:
1104
+ path: ``"/image0.pv2"``.
1105
+ flags: the middle column. **Meaning unknown** -- 0 for all six files, so
1106
+ there is no evidence to generalise from. Named ``flags`` rather than
1107
+ guessed at.
1108
+ size: bytes.
1109
+ """
1110
+
1111
+ path: str
1112
+ flags: int
1113
+ size: int
1114
+
1115
+ @property
1116
+ def name(self) -> str:
1117
+ return self.path.lstrip("/")
1118
+
1119
+
1120
+ def parse_fs_ls(lines: Sequence[str]) -> tuple[FileEntry, ...]:
1121
+ """Parse ``fs_ls``.
1122
+
1123
+ The live sign holds six ``.pv2`` files -- pre-rendered images in the device's
1124
+ own packed format, which is what ``image_rotate_config_set`` cycles through
1125
+ and what :mod:`pyvisionect.imaging` produces.
1126
+ """
1127
+ out: list[FileEntry] = []
1128
+ for line in lines:
1129
+ parts = line.split()
1130
+ if len(parts) == 3 and parts[0].startswith("/"):
1131
+ try:
1132
+ out.append(
1133
+ FileEntry(path=parts[0], flags=_int(parts[1]), size=_int(parts[2]))
1134
+ )
1135
+ except ValueError:
1136
+ continue
1137
+ return tuple(out)
1138
+
1139
+
1140
+ @dataclass(frozen=True, slots=True)
1141
+ class FilesystemStats:
1142
+ """``fs_stats``: block usage.
1143
+
1144
+ Attributes:
1145
+ total_blocks: 2048 on the live sign.
1146
+ used_blocks: 931.
1147
+
1148
+ ``status_get`` reports the same filesystem in **bytes**
1149
+ (``FS_TOTAL_SIZE: 8388608``, ``FS_FREE_SIZE: 4575232``), from which the
1150
+ block size falls out: 8388608 / 2048 = **4096 bytes per block**, and
1151
+ (2048 - 931) * 4096 = 4575232 exactly. The two commands agree, which is how
1152
+ :attr:`block_size` is derived rather than assumed.
1153
+ """
1154
+
1155
+ total_blocks: int | None
1156
+ used_blocks: int | None
1157
+
1158
+ @property
1159
+ def free_blocks(self) -> int | None:
1160
+ if self.total_blocks is None or self.used_blocks is None:
1161
+ return None
1162
+ return self.total_blocks - self.used_blocks
1163
+
1164
+ def block_size(self, total_bytes: int) -> int | None:
1165
+ """Bytes per block, given ``FS_TOTAL_SIZE`` from ``status_get``."""
1166
+ if not self.total_blocks:
1167
+ return None
1168
+ return total_bytes // self.total_blocks
1169
+
1170
+
1171
+ def parse_fs_stats(lines: Sequence[str]) -> FilesystemStats:
1172
+ """Parse ``fs_stats`` (``"total blocks: 2048, in use: 931"``).
1173
+
1174
+ One line carrying two fields separated by a comma, so it cannot go through
1175
+ :func:`_fields`.
1176
+ """
1177
+ total = used = None
1178
+ for line in lines:
1179
+ match = re.search(r"total blocks:\s*(\d+)", line)
1180
+ if match:
1181
+ total = int(match.group(1))
1182
+ match = re.search(r"in use:\s*(\d+)", line)
1183
+ if match:
1184
+ used = int(match.group(1))
1185
+ return FilesystemStats(total_blocks=total, used_blocks=used)
1186
+
1187
+
1188
+ # -------------------------------------------------------------- SPI flash
1189
+
1190
+
1191
+ @dataclass(frozen=True, slots=True)
1192
+ class SpiFlashDevice:
1193
+ """One row of ``sf_list``: a registered SPI flash and its bus.
1194
+
1195
+ Attributes:
1196
+ index: the ``IDX`` column, which is what ``sf_select`` takes.
1197
+ spi_channel: the ``SPI_CHANNEL`` column.
1198
+
1199
+ ``sf_list`` is the *safe* member of this family. ``sf_rdid`` and ``sf_rdst``
1200
+ both assert and kill the CLI task -- see
1201
+ :data:`pyvisionect.io.usb.commands.ASSERTS_AND_KILLS_CLI`.
1202
+ """
1203
+
1204
+ index: int
1205
+ spi_channel: int
1206
+
1207
+
1208
+ def parse_sf_list(lines: Sequence[str]) -> tuple[SpiFlashDevice, ...]:
1209
+ """Parse ``sf_list``.
1210
+
1211
+ The reply is an ASCII table with a header and a rule line::
1212
+
1213
+ IDX | SPI_CHANNEL
1214
+ ----|------------
1215
+ 00 | 2
1216
+
1217
+ Rows are matched structurally rather than by skipping a fixed line count, so
1218
+ a wider table would still parse.
1219
+ """
1220
+ out: list[SpiFlashDevice] = []
1221
+ for line in lines:
1222
+ if "|" not in line or set(line) <= set("-| "):
1223
+ continue
1224
+ left, _, right = line.partition("|")
1225
+ if left.strip().isdigit() and right.strip().isdigit():
1226
+ out.append(
1227
+ SpiFlashDevice(index=int(left.strip(), 10), spi_channel=int(right.strip()))
1228
+ )
1229
+ return tuple(out)
1230
+
1231
+
1232
+ @dataclass(frozen=True, slots=True)
1233
+ class SpiFlashStatus:
1234
+ """``sf_rdst``'s reply. **Never observed.**
1235
+
1236
+ ``sf_rdst`` asserts at ``spi_flash_cli.c:188`` on firmware 7.4.4407 and
1237
+ takes ``usb_cli_task`` with it, so no sample of a successful reply exists.
1238
+ This class is here so the accessor has a return type; its fields are a
1239
+ guess and are documented as such.
1240
+ """
1241
+
1242
+ raw: tuple[str, ...]
1243
+
1244
+
1245
+ # ------------------------------------------------------------ status dump
1246
+
1247
+
1248
+ _STATUS_SENTINEL = "STATUS_END"
1249
+
1250
+
1251
+ @dataclass(frozen=True, slots=True)
1252
+ class StatusDump:
1253
+ """``status_get``: the whole PV3 status record as text.
1254
+
1255
+ This is the same information the sign puts in a type-3 status packet every
1256
+ heartbeat -- :mod:`pyvisionect.packets.status` decodes the binary form -- but
1257
+ rendered as 60 ``KEY: value`` lines ending in a ``STATUS_END`` sentinel.
1258
+ Reading it over USB is the cheapest way to check a value without waiting for
1259
+ a heartbeat or decoding a frame.
1260
+
1261
+ Attributes:
1262
+ values: the keys verbatim, in the device's SCREAMING_SNAKE spelling,
1263
+ with values parsed to ``int`` where they parse. Note one key,
1264
+ ``PROTOCOL VERSION``, has a **space** where every other key has an
1265
+ underscore -- an inconsistency in the firmware's own table, kept
1266
+ as-is rather than normalised, so that a lookup matches what the
1267
+ device actually prints.
1268
+
1269
+ Several fields need interpreting rather than reading; the properties below
1270
+ do that, and each one is cross-checked against another command in the test
1271
+ suite.
1272
+ """
1273
+
1274
+ values: Mapping[str, int | str]
1275
+
1276
+ def __getitem__(self, key: str) -> int | str:
1277
+ return self.values[key]
1278
+
1279
+ def get(self, key: str, default: object = None) -> object:
1280
+ return self.values.get(key, default)
1281
+
1282
+ @property
1283
+ def rssi_dbm(self) -> int | None:
1284
+ """``SIGNAL_STRENGTH`` negated.
1285
+
1286
+ The field is a dBm magnitude with the sign dropped: ``status_get`` says
1287
+ 31, ``cc3100_rssi`` says ``-31 dBm``, same moment, same radio.
1288
+ """
1289
+ value = self.values.get("SIGNAL_STRENGTH")
1290
+ return -abs(int(value)) if isinstance(value, int) else None
1291
+
1292
+ @property
1293
+ def uptime_minutes(self) -> int | None:
1294
+ """``SYSTEM_UPTIME``, in minutes -- agrees with the ``uptime`` command."""
1295
+ value = self.values.get("SYSTEM_UPTIME")
1296
+ return int(value) if isinstance(value, int) else None
1297
+
1298
+ @property
1299
+ def bssid(self) -> str | None:
1300
+ """The AP's BSSID, rebuilt from ``BSSID_1`` and ``BSSID_2``.
1301
+
1302
+ Six bytes split over two uint32s: ``BSSID_1`` holds bytes 0-3
1303
+ little-endian, ``BSSID_2`` holds bytes 4-5. Verified against
1304
+ ``wifi_bssid_get``, which prints the same address directly.
1305
+ """
1306
+ one = self.values.get("BSSID_1")
1307
+ two = self.values.get("BSSID_2")
1308
+ if not isinstance(one, int) or not isinstance(two, int):
1309
+ return None
1310
+ octets = list(int(one).to_bytes(4, "little")) + list(
1311
+ int(two).to_bytes(4, "little")[:2]
1312
+ )
1313
+ return ":".join(f"{b:02x}" for b in octets)
1314
+
1315
+ @property
1316
+ def display_size(self) -> tuple[int, int] | None:
1317
+ """``(DISPLAY_WIDTH, DISPLAY_HEIGHT)`` -- of **one** panel.
1318
+
1319
+ 2880x640 on the live sign, with ``NUMBER_OF_SUPPORTED_DISPLAYS`` 2, so
1320
+ the whole canvas is 2880x1280 and these two keys do not describe it.
1321
+ """
1322
+ width = self.values.get("DISPLAY_WIDTH")
1323
+ height = self.values.get("DISPLAY_HEIGHT")
1324
+ if isinstance(width, int) and isinstance(height, int):
1325
+ return (int(width), int(height))
1326
+ return None
1327
+
1328
+ @property
1329
+ def firmware(self) -> str | None:
1330
+ """``"7.4.4407"``, assembled from the three ``FIRMWARE_VERSION_*`` keys."""
1331
+ parts = [
1332
+ self.values.get(f"FIRMWARE_VERSION_{part}")
1333
+ for part in ("MAJOR", "MINOR", "REVISION")
1334
+ ]
1335
+ if all(isinstance(p, int) for p in parts):
1336
+ return ".".join(str(p) for p in parts)
1337
+ return None
1338
+
1339
+ @property
1340
+ def gtin(self) -> str | None:
1341
+ """``GTIN``, as a string. Matches ``gtin_get``."""
1342
+ value = self.values.get("GTIN")
1343
+ return None if value is None else str(value)
1344
+
1345
+ @property
1346
+ def filesystem_block_size(self) -> int | None:
1347
+ """``FS_TOTAL_SIZE`` divided by ``fs_stats``' 2048 blocks, if both known.
1348
+
1349
+ Kept as a method-like property rather than a constant because the block
1350
+ count comes from a different command; see
1351
+ :meth:`FilesystemStats.block_size`.
1352
+ """
1353
+ total = self.values.get("FS_TOTAL_SIZE")
1354
+ return int(total) // 2048 if isinstance(total, int) else None
1355
+
1356
+
1357
+ def parse_status_dump(lines: Sequence[str]) -> StatusDump:
1358
+ """Parse ``status_get``.
1359
+
1360
+ Stops at the ``STATUS_END`` sentinel. Values that look like integers
1361
+ (decimal, signed decimal, or ``0x`` hex) become ``int``; anything else stays
1362
+ a string, so a future firmware adding a textual field does not break this.
1363
+ """
1364
+ out: dict[str, int | str] = {}
1365
+ for line in lines:
1366
+ if line.strip() == _STATUS_SENTINEL:
1367
+ break
1368
+ key, sep, value = line.partition(":")
1369
+ if not sep:
1370
+ continue
1371
+ key = key.strip()
1372
+ value = value.strip()
1373
+ try:
1374
+ out[key] = int(value, 0)
1375
+ except ValueError:
1376
+ out[key] = value
1377
+ return StatusDump(values=out)
1378
+
1379
+
1380
+ # ------------------------------------------------------------------ tasks
1381
+
1382
+
1383
+ @dataclass(frozen=True, slots=True)
1384
+ class Task:
1385
+ """One row of ``task_list`` -- a FreeRTOS task.
1386
+
1387
+ Attributes:
1388
+ name: as registered, e.g. ``"usb_cli_task"``, ``"CC3100 RX"``. Names can
1389
+ contain spaces, which is why the reply is tab-separated.
1390
+ state: the FreeRTOS one-letter state. ``X`` running, ``R`` ready,
1391
+ ``B`` blocked, ``S`` suspended, ``D`` deleted. The task that is
1392
+ answering the command is always ``X``.
1393
+ stack_free: the high-water mark in **words**, not bytes -- the
1394
+ ``uxTaskGetStackHighWaterMark`` unit.
1395
+ number: the task number.
1396
+ """
1397
+
1398
+ name: str
1399
+ state: str
1400
+ stack_free: int
1401
+ number: int
1402
+
1403
+ @property
1404
+ def running(self) -> bool:
1405
+ return self.state == "X"
1406
+
1407
+ @property
1408
+ def blocked(self) -> bool:
1409
+ return self.state == "B"
1410
+
1411
+
1412
+ @dataclass(frozen=True, slots=True)
1413
+ class TaskList:
1414
+ """``task_list``: the scheduler's tasks plus the free-heap figure.
1415
+
1416
+ Attributes:
1417
+ tasks: one :class:`Task` per row.
1418
+ heap_free: the ``Heap free:`` figure in bytes -- 19136 on the live sign,
1419
+ which is not a lot of headroom and is worth watching if you add
1420
+ work to the device.
1421
+
1422
+ ``usb_cli_task`` in here is the one that dies when ``sf_rdid`` asserts.
1423
+ """
1424
+
1425
+ tasks: tuple[Task, ...]
1426
+ heap_free: int | None = None
1427
+
1428
+ def __getitem__(self, name: str) -> Task:
1429
+ for task in self.tasks:
1430
+ if task.name == name:
1431
+ return task
1432
+ raise KeyError(name)
1433
+
1434
+ @property
1435
+ def names(self) -> tuple[str, ...]:
1436
+ return tuple(t.name for t in self.tasks)
1437
+
1438
+
1439
+ def parse_task_list(lines: Sequence[str]) -> TaskList:
1440
+ """Parse ``task_list``.
1441
+
1442
+ The columns are **tab**-separated and the name column is space-padded to a
1443
+ fixed width, so splitting on whitespace would shred a name like
1444
+ ``"CC3100 RX"`` or ``"timer ms"``.
1445
+ """
1446
+ tasks: list[Task] = []
1447
+ heap_free = None
1448
+ for line in lines:
1449
+ if line.startswith("Heap free"):
1450
+ try:
1451
+ heap_free = _int(line.partition(":")[2])
1452
+ except (ValueError, IndexError):
1453
+ pass
1454
+ continue
1455
+ parts = line.split("\t")
1456
+ if len(parts) != 4 or parts[0].strip() == "task name":
1457
+ continue
1458
+ name, state, stack, number = (p.strip() for p in parts)
1459
+ if not stack.isdigit() or not number.isdigit():
1460
+ continue
1461
+ tasks.append(
1462
+ Task(name=name, state=state, stack_free=int(stack), number=int(number))
1463
+ )
1464
+ return TaskList(tasks=tuple(tasks), heap_free=heap_free)