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,914 @@
1
+ '''The typed command surface: :class:`Sign`.
2
+
3
+ One method per useful command, each returning a dataclass from
4
+ :mod:`pyvisionect.io.usb.parsers` rather than a string. The gating mirrors
5
+ :func:`pyvisionect.devices.tclv.check_writable`: a refusal names the flag that
6
+ would allow the call, because a bare "permission denied" just makes the caller
7
+ go and read the source.
8
+
9
+ Three flags, three tiers
10
+ ------------------------
11
+
12
+ ``allow_writes=False`` (the default)
13
+ Only :data:`~pyvisionect.io.usb.commands.READ_COMMANDS` go out. A
14
+ :class:`Sign` built this way cannot change anything on the device, which is
15
+ the state you want while exploring somebody's hardware.
16
+
17
+ ``allow_destructive=False``
18
+ Gates the commands that can corrupt the panel, drop the sign off the network
19
+ or make it unreachable -- ``display_conf_set``, every network setter,
20
+ ``app_sleep``, ``reboot``, ``flash_save``, the ``dcm*`` display-driver pokes
21
+ and the battery/temperature simulators. Implies ``allow_writes``.
22
+
23
+ ``i_really_mean_it=False``
24
+ Gates ``fs_format``, ``cc3100_format``, ``cc3100_fw_upgrade``,
25
+ ``feat_enable``/``feat_disable``, ``cli_password_set``, ``sf_unprot`` and
26
+ ``sf_wrst``. Formats, firmware flashes, licence keys and a password you
27
+ then have to know. Implies both of the above.
28
+
29
+ Nothing persists until ``flash_save``
30
+ -------------------------------------
31
+
32
+ Verbatim from the vendor: *"All changes to device configuration are by default
33
+ retained only in the working RAM."* So a setter on its own is reversible by
34
+ power-cycling, and ``flash_save`` is the point of no return. That is why
35
+ ``flash_save`` sits in the ``DESTRUCTIVE`` tier alongside the setters it
36
+ commits, rather than being treated as a harmless bookkeeping call.
37
+
38
+ Commands this firmware does not list
39
+ ------------------------------------
40
+
41
+ :meth:`Sign.refresh_commands` reads ``help`` and remembers the result, after
42
+ which an accessor for a command ``help`` did not mention raises
43
+ :class:`~pyvisionect.io.usb.errors.CommandNotInFirmware` locally, without
44
+ writing anything. Worth doing once per session: ``help`` on 7.4.4407 lists 111
45
+ of the 160 documented commands, so 95 of them are unlisted, ``flash_print``
46
+ among them.
47
+
48
+ That gate is deliberately built on ``help`` alone, and ``help`` is not a
49
+ complete index: ``wifi_ssid_set`` is present and working on 7.4.4407 and is
50
+ still not in the listing (see
51
+ :data:`pyvisionect.io.usb.commands.HIDDEN_IN_7_4_4407`). So a *hidden* command
52
+ is refused locally after a refresh even though it would work. That is the
53
+ conservative choice -- on firmware this library has not seen, ``help`` is the
54
+ only evidence available -- and ``_run(..., check=False)`` is the escape hatch:
55
+ it sends the line and lets the device be the one that says no.
56
+ :meth:`Sign.set_wifi` is the one place in this module that takes it, for
57
+ ``wifi_ssid_set`` and only when the SSID has a space in it.
58
+ '''
59
+
60
+ from __future__ import annotations
61
+
62
+ import logging
63
+ import uuid as _uuid
64
+ from collections.abc import Mapping, Sequence
65
+ from dataclasses import dataclass, field
66
+ from typing import Any
67
+
68
+ from . import parsers as P
69
+ from .commands import (
70
+ COMMANDS,
71
+ VLOG_DESTINATIONS,
72
+ VLOG_LEVELS,
73
+ VLOG_QUIET,
74
+ VLOG_VERBOSE,
75
+ Kind,
76
+ lookup,
77
+ )
78
+ from .console import CommandResult, SerialConsole
79
+ from .errors import (
80
+ CommandNotInFirmware,
81
+ ConsoleAssertionFailed,
82
+ DangerousCommandRefused,
83
+ WriteNotAllowed,
84
+ )
85
+
86
+ __all__ = ["Sign", "SignInfo"]
87
+
88
+ log = logging.getLogger(__name__)
89
+
90
+
91
+ @dataclass(frozen=True, slots=True)
92
+ class SignInfo:
93
+ """Everything :meth:`Sign.dump` could read, in one object.
94
+
95
+ Every field is optional: a command may be absent from the firmware, or may
96
+ fail, and a dump that aborted on the first missing command would be useless
97
+ on exactly the hardware you most want to inspect. :attr:`errors` records
98
+ what went wrong per command so a partial dump is still honest about being
99
+ partial.
100
+ """
101
+
102
+ uuid: _uuid.UUID | None = None
103
+ gtin: str | None = None
104
+ firmware: P.FirmwareVersion | None = None
105
+ cli_version: str | None = None
106
+ uptime_minutes: int | None = None
107
+ features: P.Features | None = None
108
+ encryption: P.EncryptionConfig | None = None
109
+ display: P.DisplayConfig | None = None
110
+ border: P.BorderConfig | None = None
111
+ image_rotate: P.ImageRotateConfig | None = None
112
+ connectivity: P.ConnectivityType | None = None
113
+ connectivity_options: tuple[P.ConnectivityOption, ...] = ()
114
+ connectivity_state: P.ConnectivityState | None = None
115
+ connectivity_firmware: P.ConnectivityFirmware | None = None
116
+ conn_retry_minutes: int | None = None
117
+ wifi: P.WifiConfig | None = None
118
+ wifi_mac: P.WifiMacConfig | None = None
119
+ wifi_firmware: P.WifiFirmware | None = None
120
+ bssid: str | None = None
121
+ rssi_dbm: int | None = None
122
+ eap: P.EapConfig | None = None
123
+ certificates: P.CertificateConfig | None = None
124
+ ipv4: P.Ipv4Config | None = None
125
+ ethernet: P.EthernetConfig | None = None
126
+ server: P.ServerConfig | None = None
127
+ battery: P.BatteryConfig | None = None
128
+ charger: P.ChargerState | None = None
129
+ temperature_c: int | None = None
130
+ system: P.SystemConfig | None = None
131
+ logging_config: P.LogConfig | None = None
132
+ files: tuple[P.FileEntry, ...] = ()
133
+ filesystem: P.FilesystemStats | None = None
134
+ spi_flash: tuple[P.SpiFlashDevice, ...] = ()
135
+ tasks: P.TaskList | None = None
136
+ status: P.StatusDump | None = None
137
+ errors: Mapping[str, str] = field(default_factory=dict)
138
+
139
+ def describe(self) -> str:
140
+ """A short human summary, for a CLI banner or a log line."""
141
+ bits: list[str] = []
142
+ if self.uuid is not None:
143
+ bits.append(str(self.uuid))
144
+ if self.firmware is not None:
145
+ bits.append(f"fw {self.firmware.firmware}")
146
+ if self.firmware.hardware:
147
+ bits.append(self.firmware.hardware)
148
+ if self.firmware.app:
149
+ bits.append(f"app {self.firmware.app}")
150
+ if self.server is not None and self.server.host:
151
+ bits.append(f"-> {self.server.host}:{self.server.port}")
152
+ if self.connectivity is not None:
153
+ bits.append(f"via {self.connectivity.name}")
154
+ return ", ".join(bits) or "unidentified device"
155
+
156
+
157
+ class Sign:
158
+ """A typed client for one sign's serial console.
159
+
160
+ Args:
161
+ console: an open :class:`~pyvisionect.io.usb.console.SerialConsole`.
162
+ allow_writes: let ordinary setters and actions through.
163
+ allow_destructive: let the panel/network/lifecycle commands through.
164
+ i_really_mean_it: let the format/flash/password commands through.
165
+
166
+ Example:
167
+ >>> from pyvisionect.io.usb import SerialConsole, Sign
168
+ >>> with SerialConsole("/dev/ttyUSB0") as console: # doctest: +SKIP
169
+ ... sign = Sign(console)
170
+ ... console.sync()
171
+ ... print(sign.uuid())
172
+ ... print(sign.firmware_version().firmware)
173
+ ... print(sign.dump().describe())
174
+ """
175
+
176
+ def __init__(
177
+ self,
178
+ console: SerialConsole,
179
+ *,
180
+ allow_writes: bool = False,
181
+ allow_destructive: bool = False,
182
+ i_really_mean_it: bool = False,
183
+ ) -> None:
184
+ self.console = console
185
+ self.allow_writes = allow_writes or allow_destructive or i_really_mean_it
186
+ self.allow_destructive = allow_destructive or i_really_mean_it
187
+ self.i_really_mean_it = i_really_mean_it
188
+ self._firmware_commands: frozenset[str] | None = None
189
+
190
+ # ------------------------------------------------------------ gatekeeping
191
+
192
+ def _check(self, command: str) -> None:
193
+ """Refuse a command whose tier is above the flags this object was given."""
194
+ name = command.split()[0].lower() if command.split() else command
195
+ entry = lookup(name)
196
+ kind = entry.kind if entry is not None else Kind.WRITE
197
+ if entry is not None and entry.asserts and not self.i_really_mean_it:
198
+ raise ConsoleAssertionFailed(name, entry.asserts)
199
+ if kind is Kind.READ:
200
+ return
201
+ if kind is Kind.HARD and not self.i_really_mean_it:
202
+ raise DangerousCommandRefused(
203
+ name,
204
+ "i_really_mean_it=True",
205
+ "formats, flashes firmware, or sets a credential you will then "
206
+ "need in order to undo it",
207
+ )
208
+ if kind is Kind.DESTRUCTIVE and not self.allow_destructive:
209
+ raise DangerousCommandRefused(
210
+ name,
211
+ "allow_destructive=True",
212
+ "can corrupt the panel, strand the sign off the network, or make "
213
+ "it unreachable (IPV4_SERVER_IP is USB-only to recover)",
214
+ )
215
+ if not self.allow_writes:
216
+ raise WriteNotAllowed(
217
+ name, "allow_writes=True", "this console was opened read-only"
218
+ )
219
+
220
+ def refresh_commands(self) -> frozenset[str]:
221
+ """Read ``help`` and remember which commands this firmware has.
222
+
223
+ After this, an accessor for a missing command raises
224
+ :class:`~pyvisionect.io.usb.errors.CommandNotInFirmware` without
225
+ writing anything to the port.
226
+
227
+ Returns:
228
+ The command names, which is also stored as
229
+ :attr:`firmware_commands`.
230
+ """
231
+ import re
232
+
233
+ text = self.console.command("help").text
234
+ names: set[str] = set()
235
+ for line in text.splitlines():
236
+ match = re.match(r"^([a-z0-9_]+)(?:\s+<[^:]*>)?\s*[: ]", line.strip())
237
+ if match:
238
+ names.add(match.group(1))
239
+ names.discard("rv")
240
+ self._firmware_commands = frozenset(names)
241
+ return self._firmware_commands
242
+
243
+ @property
244
+ def firmware_commands(self) -> frozenset[str] | None:
245
+ """What :meth:`refresh_commands` found, or None if it was never called."""
246
+ return self._firmware_commands
247
+
248
+ def has(self, command: str) -> bool | None:
249
+ """Whether this firmware has *command*.
250
+
251
+ Returns None when :meth:`refresh_commands` has not been called, so a
252
+ caller can tell "no" from "unknown" -- which matters, because the
253
+ library's built-in table describes *one* firmware build and yours may
254
+ differ.
255
+ """
256
+ if self._firmware_commands is None:
257
+ return None
258
+ return command in self._firmware_commands
259
+
260
+ def _run(self, command: str, *, check: bool = True, **kwargs: Any) -> CommandResult:
261
+ if check and self._firmware_commands is not None:
262
+ name = command.split()[0].lower() if command.split() else command
263
+ if name not in self._firmware_commands:
264
+ raise CommandNotInFirmware(name)
265
+ self._check(command)
266
+ return self.console.command(command, **kwargs)
267
+
268
+ # --------------------------------------------------------------- identity
269
+
270
+ def uuid(self) -> _uuid.UUID:
271
+ """``uuid_get`` -- the 16-byte identity the packet header carries.
272
+
273
+ Factory-programmed; there is no setter, over USB or over the network.
274
+ """
275
+ return P.parse_uuid(self._run("uuid_get").lines)
276
+
277
+ def gtin(self) -> str:
278
+ """``gtin_get`` (TCLV 108), as a string: leading zeros are significant."""
279
+ return P.parse_gtin(self._run("gtin_get").lines)
280
+
281
+ def firmware_version(self) -> P.FirmwareVersion:
282
+ """``fw_version_get`` -- app, bootloader, board, BOM, JS app and panel."""
283
+ return P.parse_firmware_version(self._run("fw_version_get").lines)
284
+
285
+ def cli_version(self) -> str:
286
+ """``cli_version_get`` -- ``"1.2"`` on firmware 7.4.4407."""
287
+ return self._run("cli_version_get").field("CLI version")
288
+
289
+ def uptime(self) -> int:
290
+ """``uptime``, in **minutes**. Same unit as the wire's ``DeviceUptime``."""
291
+ return P.parse_uptime(self._run("uptime").lines)
292
+
293
+ def features(self) -> P.Features:
294
+ """``feat_get`` -- which licensed features are on."""
295
+ return P.parse_features(self._run("feat_get").lines)
296
+
297
+ # ------------------------------------------------------------- encryption
298
+
299
+ def encryption_config(self) -> P.EncryptionConfig:
300
+ """``encryption_config_get`` -- outbound encryption mode and key.
301
+
302
+ Read-only and safe. See :mod:`pyvisionect.io.usb.encryption` for the
303
+ state of knowledge about the key format; the setters are gated at the
304
+ ``DESTRUCTIVE`` tier because enabling encryption with a key the server
305
+ does not share silently takes the sign off its server.
306
+ """
307
+ return P.parse_encryption_config(self._run("encryption_config_get").lines)
308
+
309
+ # ---------------------------------------------------------------- display
310
+
311
+ def display_config(self) -> P.DisplayConfig:
312
+ """``display_conf_get`` -- the VCOM rails (8, not 16) and display type."""
313
+ return P.parse_display_config(self._run("display_conf_get").lines)
314
+
315
+ def border(self) -> P.BorderConfig:
316
+ """``border_get`` (TCLV 109)."""
317
+ return P.parse_border(self._run("border_get").lines)
318
+
319
+ def image_rotate_config(self) -> P.ImageRotateConfig:
320
+ """``image_rotate_config_get`` -- the local image carousel."""
321
+ return P.parse_image_rotate_config(self._run("image_rotate_config_get").lines)
322
+
323
+ # ----------------------------------------------------------- connectivity
324
+
325
+ def connectivity(self) -> P.ConnectivityType:
326
+ """``conn_type_get`` -- the live driver and its ``CONN_TYPE`` value."""
327
+ return P.parse_conn_type(self._run("conn_type_get").lines)
328
+
329
+ def connectivity_options(self) -> tuple[P.ConnectivityOption, ...]:
330
+ """``conn_type_list`` -- the **only** trustworthy ``CONN_TYPE`` enum.
331
+
332
+ This firmware offers three (``W5500 (3)``, ``CC3100 (6)``, ``None (0)``)
333
+ where the vendor's table lists eight. Call this before
334
+ :meth:`set_connectivity_type`.
335
+ """
336
+ return P.parse_conn_type_list(self._run("conn_type_list").lines)
337
+
338
+ def connectivity_state(self) -> P.ConnectivityState:
339
+ """``conn_state_get`` -- ``"tcp open"`` when the sign holds its session."""
340
+ return P.parse_conn_state(self._run("conn_state_get").lines)
341
+
342
+ def connectivity_firmware(self) -> P.ConnectivityFirmware:
343
+ """``conn_fw_ver``. Mostly uninitialised; prefer :meth:`wifi_firmware`."""
344
+ return P.parse_conn_firmware(self._run("conn_fw_ver").lines)
345
+
346
+ def conn_retry(self) -> int:
347
+ """``conn_retry_get`` (TCLV 30), in minutes."""
348
+ return P.parse_conn_retry(self._run("conn_retry_get").lines)
349
+
350
+ # -------------------------------------------------------------------- WiFi
351
+
352
+ def wifi_config(self) -> P.WifiConfig:
353
+ """``wifi_conf_get`` -- SSID, security, band. Does **not** echo the PSK."""
354
+ return P.parse_wifi_config(self._run("wifi_conf_get").lines)
355
+
356
+ def wifi_mac(self) -> P.WifiMacConfig:
357
+ """``wifi_mac_conf_get`` (TCLV 110)."""
358
+ return P.parse_wifi_mac_config(self._run("wifi_mac_conf_get").lines)
359
+
360
+ def wifi_firmware(self) -> P.WifiFirmware:
361
+ """``cc3100_fw_version`` -- the radio's NWP/MAC/PHY versions."""
362
+ return P.parse_wifi_firmware(self._run("cc3100_fw_version").lines)
363
+
364
+ def wifi_mac_address(self) -> str:
365
+ """``cc3100_mac_address`` -- the radio's MAC, straight from the chip.
366
+
367
+ Same value as :meth:`wifi_mac`, which reads the stored TCLV 110.
368
+ """
369
+ return P.parse_mac(self._run("cc3100_mac_address").one())
370
+
371
+ def bssid(self) -> str:
372
+ """``wifi_bssid_get`` (TCLV 170) -- the AP currently associated.
373
+
374
+ Cross-checks against :attr:`~pyvisionect.io.usb.parsers.StatusDump.bssid`.
375
+ """
376
+ return P.parse_bssid(self._run("wifi_bssid_get").lines)
377
+
378
+ def rssi(self) -> int:
379
+ """``cc3100_rssi`` -- **signed** dBm."""
380
+ return P.parse_rssi(self._run("cc3100_rssi").lines)
381
+
382
+ def eap_config(self) -> P.EapConfig:
383
+ """``wifi_eap_conf_get`` -- WPA2-Enterprise method and username."""
384
+ return P.parse_eap_config(self._run("wifi_eap_conf_get").lines)
385
+
386
+ def certificates(self) -> P.CertificateConfig:
387
+ """``certs_config_get`` -- the EAP certificate slots (TCLV 60-64)."""
388
+ return P.parse_certs_config(self._run("certs_config_get").lines)
389
+
390
+ # --------------------------------------------------------- network/server
391
+
392
+ def ipv4_config(self) -> P.Ipv4Config:
393
+ """``ipv4_conf_get`` -- the **stored static** block, not the live lease."""
394
+ return P.parse_ipv4_config(self._run("ipv4_conf_get").lines)
395
+
396
+ def ethernet_config(self) -> P.EthernetConfig:
397
+ """``eth_conf_get`` -- the W5500's MAC and retry policy."""
398
+ return P.parse_eth_config(self._run("eth_conf_get").lines)
399
+
400
+ def server_config(self) -> P.ServerConfig:
401
+ """``server_tcp_get`` plus ``server_hb_get`` -- where the sign dials out.
402
+
403
+ Both reads, so this is safe on a read-only console even though the pair
404
+ it reads is the pair that USB provisioning exists to write.
405
+ """
406
+ tcp = self._run("server_tcp_get").lines
407
+ try:
408
+ hb = self._run("server_hb_get").lines
409
+ except Exception: # pragma: no cover - server_hb_get is present on 7.4.4407
410
+ hb = None
411
+ return P.parse_server_config(tcp, hb)
412
+
413
+ def heartbeat(self) -> int:
414
+ """``server_hb_get`` (TCLV 29), in minutes."""
415
+ return P.parse_heartbeat(self._run("server_hb_get").lines)
416
+
417
+ # ---------------------------------------------------------- power/hardware
418
+
419
+ def battery_config(self) -> P.BatteryConfig:
420
+ """``battery_conf_get`` -- the shutdown thresholds (TCLV 36/37/38)."""
421
+ return P.parse_battery_config(self._run("battery_conf_get").lines)
422
+
423
+ def charger(self) -> P.ChargerState:
424
+ """``bq24023_mode_get`` -- live charge mode, current and pack voltage."""
425
+ return P.parse_charger(self._run("bq24023_mode_get").lines)
426
+
427
+ def temperature(self) -> int:
428
+ """``lmr`` -- the LM75 board sensor, whole degrees Celsius."""
429
+ return P.parse_temperature(self._run("lmr").lines)
430
+
431
+ def system_config(self) -> P.SystemConfig:
432
+ """``system_conf_get`` -- battery screens, touch mode, shipping mode."""
433
+ return P.parse_system_config(self._run("system_conf_get").lines)
434
+
435
+ def log_config(self) -> P.LogConfig:
436
+ """``log_config_get`` -- per-module debug levels."""
437
+ return P.parse_log_config(self._run("log_config_get").lines)
438
+
439
+ def pmic_dump(self, i2c_channel: int) -> P.PmicRegisters:
440
+ """``max17135_dump <i2c_channel>`` -- the display PMIC's registers.
441
+
442
+ ``help`` lists this nullary and a bare call is rejected, so the channel
443
+ is required here. **The reply shape is unverified**: the channel was not
444
+ guessed at on the sign this library was written against, because its
445
+ sibling commands power the panel rails. See :class:`~pyvisionect.io.usb.parsers.PmicRegisters`.
446
+ """
447
+ return P.parse_pmic_dump(self._run(f"max17135_dump {i2c_channel}").lines)
448
+
449
+ # ----------------------------------------------------------- filesystem
450
+
451
+ def files(self) -> tuple[P.FileEntry, ...]:
452
+ """``fs_ls`` -- the ``.pv2`` images stored on the device."""
453
+ return P.parse_fs_ls(self._run("fs_ls").lines)
454
+
455
+ def filesystem_stats(self) -> P.FilesystemStats:
456
+ """``fs_stats`` -- block usage. 4096 bytes per block on this hardware."""
457
+ return P.parse_fs_stats(self._run("fs_stats").lines)
458
+
459
+ def spi_flash_devices(self) -> tuple[P.SpiFlashDevice, ...]:
460
+ """``sf_list`` -- the registered SPI flash chips and their SPI channels.
461
+
462
+ The safe member of the family. :meth:`spi_flash_id` and
463
+ :meth:`spi_flash_status` are not.
464
+ """
465
+ return P.parse_sf_list(self._run("sf_list").lines)
466
+
467
+ def spi_flash_id(self) -> CommandResult:
468
+ """``sf_rdid``. **Do not call this.**
469
+
470
+ Implemented so the surface is complete and so the hazard is documented
471
+ where someone will find it, but it asserts at
472
+ ``spi_flash_cli.c:139`` on firmware 7.4.4407 and kills ``usb_cli_task``
473
+ -- the console is gone until the device reboots, which it will do on its
474
+ own roughly 25 minutes later when the software watchdog gives up.
475
+
476
+ Gated behind ``i_really_mean_it`` for that reason alone; it reads
477
+ nothing and writes nothing.
478
+
479
+ Raises:
480
+ ConsoleAssertionFailed: immediately, without sending anything,
481
+ unless ``i_really_mean_it=True``.
482
+ """
483
+ return self._run("sf_rdid", expect_prompt=False)
484
+
485
+ def spi_flash_status(self) -> CommandResult:
486
+ """``sf_rdst``. **Do not call this** -- asserts at ``spi_flash_cli.c:188``.
487
+
488
+ Same hazard as :meth:`spi_flash_id`.
489
+ """
490
+ return self._run("sf_rdst", expect_prompt=False)
491
+
492
+ # ---------------------------------------------------------------- runtime
493
+
494
+ def tasks(self) -> P.TaskList:
495
+ """``task_list`` -- the FreeRTOS tasks and the free heap."""
496
+ return P.parse_task_list(self._run("task_list").lines)
497
+
498
+ def status(self) -> P.StatusDump:
499
+ """``status_get`` -- the whole PV3 status record, as text.
500
+
501
+ The same information a type-3 heartbeat carries, without waiting for one
502
+ or decoding a frame.
503
+ """
504
+ return P.parse_status_dump(self._run("status_get").lines)
505
+
506
+ # ----------------------------------------------------------------- setters
507
+
508
+ def set_wifi(
509
+ self, ssid: str, psk: str, security: str = "wpa2", band: int = 0
510
+ ) -> CommandResult:
511
+ '''``wifi_conf_set <ssid> <psk> <security> <band>`` -- TCLV 65/67/66/68.
512
+
513
+ Note the argument order is SSID, **password**, security, band, while the
514
+ TCLV ids run SSID, security, password: ``(65, 67, 66, 68)``.
515
+
516
+ **A spaced SSID is supported**, and takes a different route.
517
+ ``wifi_conf_set`` is positional, so a space in the SSID would shift the
518
+ psk, security and band arguments along by one; when *ssid* contains
519
+ whitespace this sends three single-argument setters instead --
520
+ ``wifi_psk_set``, ``wifi_security_set``, then ``wifi_ssid_set`` -- and
521
+ returns the result of the last. ``wifi_ssid_set`` takes everything
522
+ after the command name and one space **verbatim**, measured on firmware
523
+ 7.4.4407 (``OPEN-QUESTIONS.md`` A2), so the SSID is sent unquoted and
524
+ unescaped: quotes or backslashes would land in the SSID itself.
525
+
526
+ ``wifi_ssid_set`` is absent from ``help``, so that one command is sent
527
+ with ``check=False`` -- the gate in :meth:`_run` is built on ``help``
528
+ and ``help`` is an incomplete index. It is still in the ``DESTRUCTIVE``
529
+ tier, so ``allow_destructive=True`` is required either way.
530
+
531
+ Raises:
532
+ ValueError: if *psk* contains whitespace (no read path for TCLV 67,
533
+ so nothing can be verified -- see
534
+ :func:`pyvisionect.io.usb.provisioning.plan_wifi`); if *ssid*
535
+ contains a tab, CR or LF; if *ssid* contains whitespace and
536
+ *band* is not 0, since only ``wifi_conf_set`` writes TCLV 68 and
537
+ there is no ``wifi_band_set``; or if *security* is not one of
538
+ :attr:`~pyvisionect.io.usb.provisioning.WifiSecurity.ALL`. That
539
+ last check is new: this method shares its validation with
540
+ ``plan_wifi`` now, so the typed setter and the dry-runnable plan
541
+ cannot disagree about what is sendable. Use
542
+ :meth:`set_wifi_security` to write an unvalidated value.
543
+ '''
544
+ from .provisioning import plan_wifi
545
+
546
+ # plan_wifi owns the validation and the command sequence, so the typed
547
+ # setter and the dry-runnable plan cannot drift apart.
548
+ plan = plan_wifi(ssid, psk, security=security, band=band)
549
+ result: CommandResult | None = None
550
+ for step in plan.steps:
551
+ result = self._run(step.command, check=not step.hidden)
552
+ assert result is not None
553
+ return result
554
+
555
+ def set_wifi_psk(self, psk: str) -> CommandResult:
556
+ """``wifi_psk_set <psk>`` -- TCLV 67. Whitespace is still refused.
557
+
558
+ Not because the parser cannot carry it: ``wifi_ssid_set`` is the same
559
+ shape and provably takes the rest of the line verbatim, so this one
560
+ probably does too. Because **TCLV 67 has no read path** --
561
+ ``wifi_conf_get`` never returns the passphrase -- so a truncated one
562
+ cannot be detected, and the symptom is a sign that will not associate
563
+ and then power-cycles itself. Guessing here is not recoverable without
564
+ the cable.
565
+ """
566
+ if any(c.isspace() for c in psk):
567
+ raise ValueError(
568
+ "a PSK containing whitespace is refused: wifi_psk_set probably "
569
+ "would carry it, since the same-shaped wifi_ssid_set takes the "
570
+ "rest of the line verbatim, but TCLV 67 has no read path so "
571
+ "there is no way to confirm what landed. See OPEN-QUESTIONS.md A2."
572
+ )
573
+ return self._run(f"wifi_psk_set {psk}")
574
+
575
+ def set_wifi_security(self, security: str) -> CommandResult:
576
+ """``wifi_security_set <none|wpa2|wpa2e>`` -- TCLV 66, an ASCII string."""
577
+ return self._run(f"wifi_security_set {security}")
578
+
579
+ def set_server(self, host: str, port: int = 11113) -> CommandResult:
580
+ """``server_tcp_set <ip|dns> <port>`` -- TCLV 18 and 19.
581
+
582
+ A DNS name works and is what the live sign holds, which is why
583
+ re-pointing that name is a no-touch alternative to writing this field.
584
+ """
585
+ return self._run(f"server_tcp_set {host} {port}")
586
+
587
+ def set_connectivity_type(self, value: int) -> CommandResult:
588
+ """``conn_type_set <type>`` -- TCLV 2.
589
+
590
+ Enumerate with :meth:`connectivity_options` first. The vendor's own 4G
591
+ example uses 8 and this firmware offers only 0, 3 and 6.
592
+ """
593
+ return self._run(f"conn_type_set {value}")
594
+
595
+ def set_heartbeat(self, minutes: int) -> CommandResult:
596
+ """``server_hb_set <time>`` -- TCLV 29. Network-writable too, unusually."""
597
+ return self._run(f"server_hb_set {minutes}")
598
+
599
+ def set_conn_retry(self, minutes: int) -> CommandResult:
600
+ """``conn_retry_set <time>`` -- TCLV 30."""
601
+ return self._run(f"conn_retry_set {minutes}")
602
+
603
+ def set_system_config(
604
+ self, battery_mode: int, touch_mode: int, shipping_mode: int = 0
605
+ ) -> CommandResult:
606
+ """``system_conf_set <batt_ind_en> <touch_en> <ship_en>`` -- TCLV 49/50/51.
607
+
608
+ Raises:
609
+ DangerousCommandRefused: for ``shipping_mode=1`` without
610
+ ``i_really_mean_it``. A sign in shipping mode does not wake up
611
+ normally, and the argument -- not the command name -- is what
612
+ makes the call dangerous, so it is checked separately.
613
+ """
614
+ if shipping_mode and not self.i_really_mean_it:
615
+ raise DangerousCommandRefused(
616
+ "system_conf_set",
617
+ "i_really_mean_it=True",
618
+ "ship_en=1 enables shipping mode, which the sign does not wake "
619
+ "out of normally",
620
+ )
621
+ return self._run(
622
+ f"system_conf_set {battery_mode} {touch_mode} {shipping_mode}"
623
+ )
624
+
625
+ def set_ipv4(
626
+ self, ip: str, netmask: str, gateway: str, dns: str, mode: int
627
+ ) -> CommandResult:
628
+ """``ipv4_conf_set <ip> <nm> <gw> <dns> <mode>`` -- TCLV 13-17.
629
+
630
+ ``mode`` is 0 for static and 1 for DHCP.
631
+ """
632
+ return self._run(f"ipv4_conf_set {ip} {netmask} {gateway} {dns} {mode}")
633
+
634
+ def set_display_config(
635
+ self, vcoms: Sequence[int], display_id: int
636
+ ) -> CommandResult:
637
+ """``display_conf_set <vcom1> ... <vcom16> <display_id>``.
638
+
639
+ ``help`` demands 16 VCOM arguments even though ``display_conf_get``
640
+ prints 8 and TCLV defines ``VCOM_0..7``. Both counts are accepted here
641
+ and 8 is padded out to 16 with zeros, because an 8-element list is what
642
+ a round-trip from :meth:`display_config` gives you.
643
+
644
+ **A wrong VCOM can damage an e-ink panel**, which is why this sits in
645
+ the ``DESTRUCTIVE`` tier.
646
+ """
647
+ values = list(vcoms)
648
+ if len(values) not in (8, 16):
649
+ raise ValueError(
650
+ f"display_conf_set takes 8 or 16 VCOM values, got {len(values)}"
651
+ )
652
+ if len(values) == 8:
653
+ values = values + [0] * 8
654
+ args = " ".join(str(v) for v in values)
655
+ return self._run(f"display_conf_set {args} {display_id}")
656
+
657
+ def set_battery_config(
658
+ self, threshold_off_mv: int, threshold_on_mv: int, count: int
659
+ ) -> CommandResult:
660
+ """``battery_conf_set <thr_off> <thr_on> <thr_cnt>`` -- TCLV 36/37/38."""
661
+ return self._run(
662
+ f"battery_conf_set {threshold_off_mv} {threshold_on_mv} {count}"
663
+ )
664
+
665
+ def flash_save(self) -> CommandResult:
666
+ """``flash_save`` (TCLV 53) -- **the point of no return**.
667
+
668
+ Everything a setter did was RAM-only until this runs. That cuts both
669
+ ways: it is what makes a mistake permanent, and it is also what makes a
670
+ mistake recoverable right up until you call it.
671
+ """
672
+ return self._run("flash_save")
673
+
674
+ def flash_load(self) -> CommandResult:
675
+ """``flash_load`` -- discard RAM changes and reload from flash.
676
+
677
+ The undo for an uncommitted setter, which is why it is worth knowing
678
+ about before you need it.
679
+ """
680
+ return self._run("flash_load")
681
+
682
+ def reboot(self) -> CommandResult:
683
+ """``reboot``. The link drops, so no prompt comes back.
684
+
685
+ The sign takes roughly a minute to come back and chirps when it does
686
+ (with ``touch_mode`` 3, which is the factory default here).
687
+ """
688
+ return self._run("reboot", expect_prompt=False)
689
+
690
+ def unify_usb_log_levels(self, level: int) -> CommandResult:
691
+ """``vlog_unify_levels <usb_level>`` -- set one level for every log source
692
+ on the USB destination.
693
+
694
+ **Level 1 silences the port and level 5 floods it.** The scale runs
695
+ quiet-to-loud over ``1..5`` and ``0`` is not a valid argument at all --
696
+ all measured on firmware 7.4.4407 on 2026-10-05, settling what used to be
697
+ open question ``A3``.
698
+
699
+ The command is absent from the vendor's published reference, so the
700
+ device's own one-liner is the only vendor documentation that exists::
701
+
702
+ vlog_unify_levels <usb_level>: Reset logger levels to default for USB
703
+
704
+ That help line is simply wrong about "reset to default": the command uses
705
+ its argument. ``vlog_set_default_levels`` is the one that resets, and it
706
+ is nullary. (This firmware's help text is unreliable elsewhere too --
707
+ ``conn_fw_ver`` is described as "Scan for WiFi APs".)
708
+
709
+ What the levels do, by line kind:
710
+
711
+ ===== ==================================================================
712
+ level what reaches the USB UART
713
+ ===== ==================================================================
714
+ 1 nothing
715
+ 2, 3 ``E:`` error lines only
716
+ 4 + state narration (``From state N going to state N``, DHCP/IP/DNS)
717
+ 5 + debug detail (``Frame send N bytes``, image transfer, EPD temp)
718
+ ===== ==================================================================
719
+
720
+ Measured: 0 lines in 90 s at level 1, against 18-61 lines per 90 s at
721
+ level 5 on a healthy link -- and ~1 400 lines/min at level 5 while the
722
+ radio was reconnect-flapping, which is the case that matters, because
723
+ that is when the port is least usable.
724
+
725
+ **Level 1 does suppress the asynchronous interleaving**
726
+ :mod:`pyvisionect.io.usb.console` works to tolerate: the lines it goes
727
+ quiet on are exactly the heartbeat narration its ``LOG_PATTERNS``
728
+ exist to filter. Two caveats before relying on that:
729
+
730
+ * **It does not persist, by design or by accident.** Nothing survives
731
+ without ``flash_save``, and the sign reboots on its own when it cannot
732
+ reach its server (``E: Max conn errs. Reboot``), which restores the
733
+ default verbosity underneath a long-running session. Re-apply it
734
+ after any reconnect; do not assume it is still in force.
735
+ * **It hides the diagnostics too.** At level 1 you also lose
736
+ ``E: TCP connection Error: -111`` and friends, which are often the
737
+ only sign that the far end is dead. Prefer level 2 or 3 if you want a
738
+ quiet port that still reports faults.
739
+
740
+ Args:
741
+ level: the level to apply, 1 (silent) to 5 (everything).
742
+ Deliberately has no default: which end you want depends on
743
+ whether you are driving the console or debugging the link.
744
+
745
+ Raises:
746
+ ValueError: if *level* is outside :data:`~pyvisionect.io.usb.commands.VLOG_LEVELS`.
747
+ The firmware would answer ``E: Invalid argument(s)`` anyway;
748
+ this just says so without a round trip.
749
+ """
750
+ if level not in VLOG_LEVELS:
751
+ raise ValueError(
752
+ f"vlog level must be in {VLOG_LEVELS.start}..{VLOG_LEVELS.stop - 1} "
753
+ f"({VLOG_QUIET}=silent, {VLOG_VERBOSE}=everything); got {level!r}. "
754
+ "0 is not a valid level on 7.4.4407."
755
+ )
756
+ return self._run(f"vlog_unify_levels {level}")
757
+
758
+ def silence_usb_logs(self) -> CommandResult:
759
+ """``vlog_unify_levels 1`` -- stop the sign narrating to the serial port.
760
+
761
+ The quiet end of :meth:`unify_usb_log_levels`, named so that callers do
762
+ not have to remember which end of the scale it is. Undo with
763
+ :meth:`default_logs`.
764
+
765
+ Read the caveats on :meth:`unify_usb_log_levels` first: this does not
766
+ persist across the sign's own reboots, and it suppresses the error lines
767
+ as well as the chatter.
768
+ """
769
+ return self.unify_usb_log_levels(VLOG_QUIET)
770
+
771
+ def set_log_source_level(self, source: int, level: int) -> CommandResult:
772
+ """``vlog_set_source_level <source> <level>`` -- one producer's level.
773
+
774
+ The *source* namespace is still **not enumerated**. The firmware
775
+ validates the level but accepts any source id at all -- ``-1``, ``32``,
776
+ ``9999`` are all taken silently -- so probing cannot reveal the range,
777
+ and an out-of-range id is an unchecked index into firmware state. This
778
+ method therefore refuses a negative *source* on its own authority, which
779
+ is more than the device does.
780
+
781
+ Args:
782
+ source: the log source id. Non-negative; the upper bound is unknown.
783
+ level: 1 (silent) to 5 (everything).
784
+
785
+ Raises:
786
+ ValueError: if *level* is not a valid level, or *source* is negative.
787
+ """
788
+ if level not in VLOG_LEVELS:
789
+ raise ValueError(
790
+ f"vlog level must be in {VLOG_LEVELS.start}..{VLOG_LEVELS.stop - 1}; "
791
+ f"got {level!r}"
792
+ )
793
+ if source < 0:
794
+ raise ValueError(
795
+ f"log source id must be non-negative; got {source!r}. The firmware "
796
+ "does not range-check this argument, so a bad id is not refused "
797
+ "by the device -- which is why it is refused here."
798
+ )
799
+ return self._run(f"vlog_set_source_level {source} {level}")
800
+
801
+ def set_log_destination_level(self, destination: int, level: int) -> CommandResult:
802
+ """``vlog_set_destination_level <destination> <level>`` -- one sink's level.
803
+
804
+ There are exactly **nine** sinks, ids ``0..8``: unlike the source
805
+ argument, the firmware range-checks this one and refuses ``-1`` and
806
+ anything from ``9`` up. Which id is the USB UART is still unknown --
807
+ identifying it needs a reliable stimulus, and the attempt on 2026-10-05
808
+ was defeated by the sign having nothing to narrate once its link went
809
+ stable. Sinks plausibly include the USB UART, the filesystem (TCLV 161
810
+ flushes a syslog to it) and the network link.
811
+
812
+ Args:
813
+ destination: the sink id, 0 to 8.
814
+ level: 1 (silent) to 5 (everything).
815
+
816
+ Raises:
817
+ ValueError: if either argument is outside its measured range.
818
+ """
819
+ if level not in VLOG_LEVELS:
820
+ raise ValueError(
821
+ f"vlog level must be in {VLOG_LEVELS.start}..{VLOG_LEVELS.stop - 1}; "
822
+ f"got {level!r}"
823
+ )
824
+ if destination not in VLOG_DESTINATIONS:
825
+ raise ValueError(
826
+ f"log destination must be in {VLOG_DESTINATIONS.start}.."
827
+ f"{VLOG_DESTINATIONS.stop - 1}; got {destination!r}"
828
+ )
829
+ return self._run(f"vlog_set_destination_level {destination} {level}")
830
+
831
+ def default_logs(self) -> CommandResult:
832
+ """``vlog_set_default_levels`` -- put the whole level matrix back.
833
+
834
+ The undo for the three ``vlog`` setters above. Nullary, and the one
835
+ member of the family whose help line and signature agree.
836
+ """
837
+ return self._run("vlog_set_default_levels")
838
+
839
+ def send_status_packet(self) -> CommandResult:
840
+ """``pss`` -- make the sign emit a PV3 status packet now.
841
+
842
+ Very useful while bringing up a listener: it decouples protocol work
843
+ from the one-minute heartbeat. An ``ACTION``, so it needs
844
+ ``allow_writes`` even though it changes nothing.
845
+ """
846
+ return self._run("pss")
847
+
848
+ # -------------------------------------------------------------------- dump
849
+
850
+ def dump(self, *, include_status: bool = True) -> SignInfo:
851
+ """Read everything readable, in one pass, tolerating failures.
852
+
853
+ This is the replacement for ``flash_print``, which firmware 7.4.4407
854
+ does not have: there is no single-command settings dump, so this walks
855
+ the per-area getters instead. Only ``READ`` commands are issued, so it
856
+ is safe on a read-only console.
857
+
858
+ A command that is missing, errors, or returns something a parser cannot
859
+ read is recorded in :attr:`SignInfo.errors` and the dump continues.
860
+
861
+ Returns:
862
+ A :class:`SignInfo`.
863
+ """
864
+ errors: dict[str, str] = {}
865
+
866
+ def attempt(name: str, call: Any, default: Any = None) -> Any:
867
+ try:
868
+ return call()
869
+ except Exception as exc:
870
+ errors[name] = f"{type(exc).__name__}: {exc}"
871
+ log.debug("dump: %s failed: %s", name, exc)
872
+ return default
873
+
874
+ info = SignInfo(
875
+ uuid=attempt("uuid_get", self.uuid),
876
+ gtin=attempt("gtin_get", self.gtin),
877
+ firmware=attempt("fw_version_get", self.firmware_version),
878
+ cli_version=attempt("cli_version_get", self.cli_version),
879
+ uptime_minutes=attempt("uptime", self.uptime),
880
+ features=attempt("feat_get", self.features),
881
+ encryption=attempt("encryption_config_get", self.encryption_config),
882
+ display=attempt("display_conf_get", self.display_config),
883
+ border=attempt("border_get", self.border),
884
+ image_rotate=attempt("image_rotate_config_get", self.image_rotate_config),
885
+ connectivity=attempt("conn_type_get", self.connectivity),
886
+ connectivity_options=attempt(
887
+ "conn_type_list", self.connectivity_options, ()
888
+ ),
889
+ connectivity_state=attempt("conn_state_get", self.connectivity_state),
890
+ connectivity_firmware=attempt("conn_fw_ver", self.connectivity_firmware),
891
+ conn_retry_minutes=attempt("conn_retry_get", self.conn_retry),
892
+ wifi=attempt("wifi_conf_get", self.wifi_config),
893
+ wifi_mac=attempt("wifi_mac_conf_get", self.wifi_mac),
894
+ wifi_firmware=attempt("cc3100_fw_version", self.wifi_firmware),
895
+ bssid=attempt("wifi_bssid_get", self.bssid),
896
+ rssi_dbm=attempt("cc3100_rssi", self.rssi),
897
+ eap=attempt("wifi_eap_conf_get", self.eap_config),
898
+ certificates=attempt("certs_config_get", self.certificates),
899
+ ipv4=attempt("ipv4_conf_get", self.ipv4_config),
900
+ ethernet=attempt("eth_conf_get", self.ethernet_config),
901
+ server=attempt("server_tcp_get", self.server_config),
902
+ battery=attempt("battery_conf_get", self.battery_config),
903
+ charger=attempt("bq24023_mode_get", self.charger),
904
+ temperature_c=attempt("lmr", self.temperature),
905
+ system=attempt("system_conf_get", self.system_config),
906
+ logging_config=attempt("log_config_get", self.log_config),
907
+ files=attempt("fs_ls", self.files, ()),
908
+ filesystem=attempt("fs_stats", self.filesystem_stats),
909
+ spi_flash=attempt("sf_list", self.spi_flash_devices, ()),
910
+ tasks=attempt("task_list", self.tasks),
911
+ status=attempt("status_get", self.status) if include_status else None,
912
+ errors=errors,
913
+ )
914
+ return info