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,260 @@
1
+ '''Finding the port, and confirming what is on the other end of it.
2
+
3
+ Two separate questions, and they need separate answers. :func:`find_ports`
4
+ narrows the field by USB identity, which is cheap and wrong often enough to
5
+ matter -- ``0403:6001`` is the stock FTDI FT232 ID and sits in thousands of
6
+ unrelated products. :func:`identify` settles it by asking the device, which
7
+ costs two read-only commands and cannot be fooled.
8
+
9
+ The bridge, settled
10
+ -------------------
11
+
12
+ The reverse engineering notes inferred FTDI from a macOS device filename in a
13
+ screenshot and flagged it as unconfirmed. **Confirmed on the live sign:**
14
+
15
+ Bus 001 Device 014: ID 0403:6001 Future Technology Devices International,
16
+ Ltd FT232 Serial (UART) IC
17
+
18
+ So: FTDI FT232, VID ``0x0403``, PID ``0x6001``, driven by ``ftdi_sio`` on Linux,
19
+ appearing as ``/dev/ttyUSB*``. On macOS the FTDI driver names it
20
+ ``/dev/cu.usbserial-<eeprom serial>``, which is where the original inference
21
+ came from.
22
+
23
+ Permissions
24
+ -----------
25
+
26
+ On Linux the node is ``root:dialout`` mode 660, so you need to be in ``dialout``
27
+ (or ``uucp`` on Arch), or use ``sudo``. A udev rule is tidier::
28
+
29
+ SUBSYSTEM=="tty", ATTRS{idVendor}=="0403", ATTRS{idProduct}=="6001", \\
30
+ MODE="0660", GROUP="dialout"
31
+
32
+ Note that this matches *every* FT232, not just a sign. There is no USB-level
33
+ way to tell them apart: the sign ships a stock FTDI EEPROM, so the product
34
+ string, manufacturer string and serial are FTDI's, not Visionect's. That is
35
+ precisely why :func:`identify` exists.
36
+ '''
37
+
38
+ from __future__ import annotations
39
+
40
+ import logging
41
+ from collections.abc import Iterable, Sequence
42
+ from dataclasses import dataclass
43
+
44
+ __all__ = [
45
+ "FTDI_PIDS",
46
+ "FTDI_VID",
47
+ "KNOWN_BRIDGES",
48
+ "Candidate",
49
+ "Identity",
50
+ "find_ports",
51
+ "identify",
52
+ ]
53
+
54
+ log = logging.getLogger(__name__)
55
+
56
+ FTDI_VID = 0x0403
57
+ """Future Technology Devices International. Confirmed on the live sign."""
58
+
59
+ FTDI_PIDS: frozenset[int] = frozenset({0x6001, 0x6010, 0x6011, 0x6014, 0x6015})
60
+ """FT232 (``0x6001``, measured) plus the other common FTDI UART PIDs.
61
+
62
+ The rest are included because the vendor's hardware range spans several board
63
+ revisions and only one of them was in front of this library. A match on any of
64
+ them is a *candidate*, never an identification.
65
+ """
66
+
67
+ KNOWN_BRIDGES: dict[tuple[int, int], str] = {
68
+ (0x0403, 0x6001): "FTDI FT232 (measured on a 32\" sign, firmware 7.4.4407)",
69
+ (0x0403, 0x6015): "FTDI FT231X",
70
+ (0x0403, 0x6014): "FTDI FT232H",
71
+ (0x10C4, 0xEA60): "Silicon Labs CP2102 -- not observed on a sign",
72
+ (0x1A86, 0x7523): "WCH CH340 -- not observed on a sign",
73
+ }
74
+ """USB IDs and what they are, with provenance. Only the first was measured."""
75
+
76
+
77
+ @dataclass(frozen=True, slots=True)
78
+ class Candidate:
79
+ """A serial port that might be a sign.
80
+
81
+ Attributes:
82
+ device: the node path, e.g. ``/dev/ttyUSB0``.
83
+ vid: USB vendor id, or None if the port is not USB.
84
+ pid: USB product id, or None.
85
+ serial_number: the bridge's EEPROM serial. **The FTDI chip's, not the
86
+ sign's** -- it has nothing to do with the device UUID.
87
+ description: whatever pyserial reports.
88
+ likely: True when the USB id is in :data:`KNOWN_BRIDGES`. A weak signal:
89
+ ``0403:6001`` is the most common USB-serial id in existence.
90
+ """
91
+
92
+ device: str
93
+ vid: int | None = None
94
+ pid: int | None = None
95
+ serial_number: str | None = None
96
+ description: str | None = None
97
+ likely: bool = False
98
+
99
+ @property
100
+ def usb_id(self) -> str | None:
101
+ """``"0403:6001"``, or None for a non-USB port."""
102
+ if self.vid is None or self.pid is None:
103
+ return None
104
+ return f"{self.vid:04x}:{self.pid:04x}"
105
+
106
+ @property
107
+ def bridge(self) -> str | None:
108
+ """What :data:`KNOWN_BRIDGES` says this chip is."""
109
+ if self.vid is None or self.pid is None:
110
+ return None
111
+ return KNOWN_BRIDGES.get((self.vid, self.pid))
112
+
113
+
114
+ def find_ports(*, all_ports: bool = False) -> tuple[Candidate, ...]:
115
+ """List serial ports, likely candidates first.
116
+
117
+ Args:
118
+ all_ports: include ports whose USB id is not a known bridge. Useful when
119
+ a board revision uses a chip this module has not seen, and necessary
120
+ for a USB-serial adapter plugged into a sign's UART header rather
121
+ than its own connector.
122
+
123
+ Returns:
124
+ :class:`Candidate` objects, those with ``likely=True`` first.
125
+
126
+ Raises:
127
+ ImportError: if pyserial is not installed.
128
+
129
+ Note:
130
+ This cannot tell a sign from any other FT232. Follow it with
131
+ :func:`identify`.
132
+ """
133
+ try:
134
+ from serial.tools import list_ports
135
+ except ImportError as exc: # pragma: no cover - depends on the install
136
+ raise ImportError(
137
+ "port discovery needs pyserial: pip install 'pyvisionect[usb]'"
138
+ ) from exc
139
+
140
+ out: list[Candidate] = []
141
+ for port in list_ports.comports():
142
+ vid = getattr(port, "vid", None)
143
+ pid = getattr(port, "pid", None)
144
+ likely = (vid, pid) in KNOWN_BRIDGES
145
+ if not likely and not all_ports:
146
+ continue
147
+ out.append(
148
+ Candidate(
149
+ device=port.device,
150
+ vid=vid,
151
+ pid=pid,
152
+ serial_number=getattr(port, "serial_number", None),
153
+ description=getattr(port, "description", None),
154
+ likely=likely,
155
+ )
156
+ )
157
+ return tuple(sorted(out, key=lambda c: (not c.likely, c.device)))
158
+
159
+
160
+ @dataclass(frozen=True, slots=True)
161
+ class Identity:
162
+ """The answer to "is this a Visionect sign, and which one?".
163
+
164
+ Attributes:
165
+ is_sign: True only when both probes succeeded and agreed.
166
+ uuid: the device UUID as a string, or None.
167
+ firmware: e.g. ``"7.4.4407"``, or None.
168
+ cli_version: e.g. ``"1.2"``, or None.
169
+ hardware: e.g. ``"PP32 v1.1"``, or None.
170
+ app: the JS application name, e.g. ``"Joan"``.
171
+ reason: why :attr:`is_sign` is False, or None when it is True.
172
+ """
173
+
174
+ is_sign: bool
175
+ uuid: str | None = None
176
+ firmware: str | None = None
177
+ cli_version: str | None = None
178
+ hardware: str | None = None
179
+ app: str | None = None
180
+ reason: str | None = None
181
+
182
+ def describe(self) -> str:
183
+ if not self.is_sign:
184
+ return f"not a Visionect sign: {self.reason}"
185
+ bits = [b for b in (self.uuid, self.firmware, self.hardware, self.app) if b]
186
+ return "Visionect sign: " + ", ".join(bits)
187
+
188
+
189
+ def identify(port_or_console: object, *, timeout: float = 4.0) -> Identity:
190
+ """Confirm a port is a sign, by asking it.
191
+
192
+ Sends ``uuid_get`` and ``fw_version_get`` -- two read-only commands, nothing
193
+ else. A port that is not a sign will time out, answer nothing, or answer
194
+ something that does not parse as 16 UUID bytes, and all three come back as
195
+ ``is_sign=False`` with a reason rather than an exception: scanning ports
196
+ means expecting most of them to fail.
197
+
198
+ Args:
199
+ port_or_console: a device path, or an open
200
+ :class:`~pyvisionect.io.usb.console.SerialConsole`.
201
+ timeout: per-command, kept short because this is run across several
202
+ ports.
203
+
204
+ Returns:
205
+ An :class:`Identity`.
206
+
207
+ Example:
208
+ >>> for candidate in find_ports(): # doctest: +SKIP
209
+ ... print(candidate.device, identify(candidate.device).describe())
210
+ """
211
+ from . import parsers as P
212
+ from .console import SerialConsole
213
+
214
+ console: SerialConsole | None = None
215
+ owned = False
216
+ try:
217
+ if isinstance(port_or_console, SerialConsole):
218
+ console = port_or_console
219
+ else:
220
+ console = SerialConsole(
221
+ str(port_or_console), command_timeout=timeout, idle_timeout=0.6
222
+ )
223
+ owned = True
224
+ try:
225
+ console.sync()
226
+ except Exception as exc:
227
+ return Identity(is_sign=False, reason=f"no prompt: {exc}")
228
+
229
+ try:
230
+ device_uuid = P.parse_uuid(console.command("uuid_get", timeout=timeout).lines)
231
+ except Exception as exc:
232
+ return Identity(is_sign=False, reason=f"uuid_get did not parse: {exc}")
233
+
234
+ firmware = None
235
+ try:
236
+ firmware = P.parse_firmware_version(
237
+ console.command("fw_version_get", timeout=timeout).lines
238
+ )
239
+ except Exception as exc: # pragma: no cover - a sign always answers this
240
+ log.debug("fw_version_get failed on an otherwise-identified sign: %s", exc)
241
+
242
+ cli = None
243
+ try:
244
+ cli = console.command("cli_version_get", timeout=timeout).field("CLI version")
245
+ except Exception: # pragma: no cover
246
+ pass
247
+
248
+ return Identity(
249
+ is_sign=True,
250
+ uuid=str(device_uuid),
251
+ firmware=firmware.firmware if firmware else None,
252
+ cli_version=cli,
253
+ hardware=firmware.hardware if firmware else None,
254
+ app=firmware.app if firmware else None,
255
+ )
256
+ except Exception as exc:
257
+ return Identity(is_sign=False, reason=f"{type(exc).__name__}: {exc}")
258
+ finally:
259
+ if owned and console is not None:
260
+ console.close()
@@ -0,0 +1,262 @@
1
+ '''What is known about ``encryption_key_set`` / ``encryption_mode_set``, and how.
2
+
3
+ **No setter in this module has ever been executed.** Everything below comes from
4
+ three read-only sources: the device's own ``help`` text and
5
+ ``encryption_config_get`` reply, the vendor's TCLV descriptor table, and a
6
+ disassembly of the vendor's gateway. Where those run out, it says so.
7
+
8
+ The question this answers
9
+ -------------------------
10
+
11
+ The gateway's AES-128-CBC "Secure" mode cannot be turned on in a self-hosted
12
+ deployment, because the per-connection key is minted by an **escrow service** at
13
+ ``$VISIONECT_SERVER_EA`` which has no compiled-in default and is not part of the
14
+ shipped image. The obvious hope is that since the sign exposes
15
+ ``encryption_key_set`` over USB, you could set the key yourself on both ends and
16
+ have encryption without the vendor's cloud.
17
+
18
+ **That hope does not survive the evidence.** See :data:`VERDICT`. The short
19
+ version: the key the gateway encrypts with is 16 bytes of ``crypto/rand`` minted
20
+ fresh per activation, and the gateway never transmits it -- so a key stored in
21
+ the device's flash cannot be it. TCLV 131 is a long-term device secret used to
22
+ resolve the escrow blob, and reproducing that resolution means reading firmware
23
+ that ships encrypted.
24
+
25
+ The usable alternative is **TLS**, which is a different mechanism entirely and is
26
+ not gated on any of this. See :data:`TLS_ALTERNATIVE`.
27
+
28
+ Mode values -- solid
29
+ --------------------
30
+
31
+ ``encryption_mode_set <mode>`` writes TCLV **131**'s companion, TCLV **130**,
32
+ whose description in the vendor's own table reads verbatim:
33
+
34
+ ``Outbound encryption: 0=Disabled, 1=Enabled``
35
+
36
+ So the argument is a **boolean, 0 or 1**, and :data:`MODES` says so. It is *not*
37
+ the wire protocol's ``SecurityType``, which takes 0, 2 and 3 -- a confusion worth
38
+ heading off, because both are called a "mode" in different places:
39
+
40
+ ==== =================================== ===========================
41
+ mode ``ProtocolHeader.Security`` what it is
42
+ ==== =================================== ===========================
43
+ 0 0 plaintext
44
+ 1 2 (ordinary) / 3 (security packet) AES-128-CBC, session key
45
+ \\- 1 **not a socket value** -- the same
46
+ 20-byte header is reused as a
47
+ firmware file container, where 1
48
+ means "encrypted with the firmware
49
+ key"
50
+ ==== =================================== ===========================
51
+
52
+ The mapping ``mode 1 -> Security 2`` is itself an inference: the gateway picks 2
53
+ whenever it holds a key and 0 otherwise, with nothing in between, and the device
54
+ side could not be read.
55
+
56
+ Key format -- not solid
57
+ -----------------------
58
+
59
+ The primitive is **AES-128**, so 16 bytes of key material. That part is firm:
60
+ ``securityManager.IssueKey`` does ``key := make([]byte, 16);
61
+ crypto/rand.Read(key)`` and asserts the length. How those 16 bytes are
62
+ *spelled* on a CLI line is not known, and :data:`KEY_FORMAT_CANDIDATES` keeps
63
+ all three readings rather than picking one and pretending.
64
+
65
+ What constrains it:
66
+
67
+ * The CLI is whitespace-delimited and single-line, so the key is one token with
68
+ no spaces.
69
+ * ``encryption_config_get`` echoes the key back **inside single quotes**
70
+ (``Key: ''`` when unset), so the device stores and renders it as a printable
71
+ string, not as raw bytes.
72
+ * Every other key and IV in this system is a **16-character printable ASCII
73
+ literal** used directly as the 16 key bytes -- ``F@%gtb7;xLmXV$9a``,
74
+ ``J<lyAM$*B@<G{`9i``, ``thisbeemulatorke``, ``N3ls0#!Dba0f8*B>``. That is the
75
+ house style, and it is the single strongest hint available.
76
+ * The only place the system serialises a *generated* key is the escrow POST,
77
+ which uses ``base64.StdEncoding`` -- 24 characters for 16 bytes.
78
+
79
+ So "16 printable characters, used verbatim" is the best-supported reading and
80
+ base64 is second, but neither was tested and a length check in the firmware could
81
+ rule either out instantly. The firmware images are AES-encrypted under a key
82
+ that lives only on Visionect's servers, so the CLI handler cannot be read.
83
+
84
+ How to settle it, if you ever want to
85
+ -------------------------------------
86
+
87
+ Cheaply and reversibly, on hardware you are willing to inconvenience:
88
+
89
+ 1. ``encryption_config_get`` -- record the current state (it is
90
+ ``Disabled`` / ``''`` on a factory sign).
91
+ 2. ``encryption_key_set <candidate>`` with a 16-character ASCII string.
92
+ 3. ``encryption_config_get`` again. **This is the whole experiment**: the
93
+ command echoes the stored key, so if the device accepted and stored 16
94
+ characters verbatim you can see it, and if it hashed, truncated, rejected or
95
+ re-encoded them you can see that too.
96
+ 4. Do **not** run ``flash_save``. Power-cycle, and the sign is exactly as it
97
+ was.
98
+
99
+ That sequence never enables encryption -- it only writes TCLV 131, leaving TCLV
100
+ 130 at 0 -- so the link stays plaintext and the sign stays on its server
101
+ throughout. It was not run here because the sign in question is in service and
102
+ the question is not worth even a small risk to it. **Mode 1 is the dangerous
103
+ one**: enabling it points the device at a key exchange its server cannot
104
+ complete, and the recovery path (``IPV4_SERVER_IP``) is USB-only.
105
+ '''
106
+
107
+ from __future__ import annotations
108
+
109
+ from dataclasses import dataclass
110
+
111
+ __all__ = [
112
+ "AES_KEY_BYTES",
113
+ "KEY_FORMAT_CANDIDATES",
114
+ "MODES",
115
+ "TCLV_ENCRYPTION_KEY",
116
+ "TCLV_ENCRYPTION_MODE",
117
+ "TCLV_TLS_MODE",
118
+ "TLS_ALTERNATIVE",
119
+ "VERDICT",
120
+ "KeyFormatCandidate",
121
+ ]
122
+
123
+ TCLV_ENCRYPTION_MODE = 130
124
+ """``encryption_mode_set`` -> *"Outbound encryption: 0=Disabled, 1=Enabled"*."""
125
+
126
+ TCLV_ENCRYPTION_KEY = 131
127
+ """``encryption_key_set`` -> *"Encryption key"*. No further description exists."""
128
+
129
+ TCLV_TLS_MODE = 145
130
+ """*"TLS mode: 0=disabled, 1=TLS 1.3"*. A different mechanism -- see :data:`TLS_ALTERNATIVE`."""
131
+
132
+ AES_KEY_BYTES = 16
133
+ """AES-128. Firm: the gateway mints exactly 16 ``crypto/rand`` bytes and asserts it."""
134
+
135
+ MODES: dict[int, str] = {0: "Disabled", 1: "Enabled"}
136
+ """Valid ``encryption_mode_set`` arguments, from the vendor's TCLV 130 description.
137
+
138
+ Verbatim from the descriptor table, so this one is not a guess. Note it is a
139
+ boolean and **not** the wire ``SecurityType`` (0/2/3).
140
+ """
141
+
142
+
143
+ @dataclass(frozen=True, slots=True)
144
+ class KeyFormatCandidate:
145
+ """One possible spelling of the 16-byte key on a CLI line.
146
+
147
+ Attributes:
148
+ name: short label.
149
+ length: how many characters the CLI token would be.
150
+ example: a syntactically valid example. **Not a working key** -- there is
151
+ no such thing without the escrow service.
152
+ support: the evidence for this reading.
153
+ tested: always False. Nothing in this module was executed.
154
+ """
155
+
156
+ name: str
157
+ length: int
158
+ example: str
159
+ support: str
160
+ tested: bool = False
161
+
162
+
163
+ KEY_FORMAT_CANDIDATES: tuple[KeyFormatCandidate, ...] = (
164
+ KeyFormatCandidate(
165
+ name="16 printable ASCII characters, used verbatim",
166
+ length=16,
167
+ example="F@%gtb7;xLmXV$9a",
168
+ support=(
169
+ "Best supported. Every key and IV elsewhere in this system is a "
170
+ "16-character printable ASCII literal used directly as the 16 key "
171
+ "bytes (the two traffic IVs, the emulator key, the DeviceID hash "
172
+ "key). encryption_config_get echoing the key inside single quotes "
173
+ "fits a stored string, and 16 characters is exactly AES-128."
174
+ ),
175
+ ),
176
+ KeyFormatCandidate(
177
+ name="base64 of 16 raw bytes",
178
+ length=24,
179
+ example="AAECAwQFBgcICQoLDA0ODw==",
180
+ support=(
181
+ "Second. The one place the system serialises a generated key is the "
182
+ "escrow POST, which uses base64.StdEncoding on exactly these 16 "
183
+ "bytes. If the CLI mirrors the wire format, this is it. Against: the "
184
+ "'=' padding is an odd thing to type, and base64 is unusual in an "
185
+ "embedded CLI."
186
+ ),
187
+ ),
188
+ KeyFormatCandidate(
189
+ name="32 hex characters",
190
+ length=32,
191
+ example="464025677462373b784c6d5856243961",
192
+ support=(
193
+ "Third, on general priors rather than evidence: hex is the usual way "
194
+ "to type a key at an embedded prompt. Nothing in this system "
195
+ "actually does it, which is why it is last."
196
+ ),
197
+ ),
198
+ )
199
+ """The three readings of the key format, with their evidence. **None was tested.**
200
+
201
+ Ordered by how well the system's own conventions support them. The experiment
202
+ in the module docstring distinguishes all three in one command, because
203
+ ``encryption_config_get`` echoes whatever was stored.
204
+ """
205
+
206
+ VERDICT = '''A USB-set key does not buy you self-hosted link encryption.
207
+
208
+ The reasoning, in the order the evidence falls:
209
+
210
+ 1. The gateway encrypts with a key it mints itself, per activation:
211
+ ``securityManager.IssueKey`` does ``key := make([]byte, 16);
212
+ crypto/rand.Read(key)``. It is random and fresh every time.
213
+ 2. The gateway never sends that key to the device. ``activateSecurity`` sends a
214
+ ``packet.Raw`` containing the **escrow service's response bytes verbatim**,
215
+ which the gateway itself treats as opaque, and only then installs the key on
216
+ its own codec.
217
+ 3. So the device must derive or unwrap the session key from that blob, using
218
+ something it already holds -- which is what TCLV 131 is for. TCLV 131 is a
219
+ long-term device secret, not the session key.
220
+ 4. To issue a blob the device will accept, you would have to reproduce the
221
+ transform the device applies to it. That code is in the device firmware, and
222
+ the firmware images ship AES-encrypted under a key held only on Visionect's
223
+ servers.
224
+ 5. Therefore setting TCLV 131 over USB is necessary-but-not-sufficient, and the
225
+ missing piece is not something USB access provides.
226
+
227
+ A corollary worth knowing: with ``VISIONECT_SERVER_EA`` unset the escrow POST
228
+ fails, ``IssueKey`` errors, and ``SetSecurity`` fails -- so a self-hosted gateway
229
+ with ``Options["Secure"] = "true"`` does not fall back to plaintext, it fails the
230
+ connection. Leave ``Secure`` alone.
231
+
232
+ What this does *not* say: it does not say the mode values are unknown (they are
233
+ 0 and 1, from the vendor's own table), and it does not say encryption of any kind
234
+ is impossible. See TLS_ALTERNATIVE.
235
+ '''
236
+ """Why the USB key is not the route to encryption. Reasoned, not tested."""
237
+
238
+ TLS_ALTERNATIVE = '''Use TLS instead. It is the mechanism that actually works.
239
+
240
+ TCLV **145** is *"TLS mode: 0=disabled, 1=TLS 1.3"*, and three things make it the
241
+ better target:
242
+
243
+ * **It is network-writable.** 145 is not one of the eight ``canWrite: false``
244
+ ids, so a server can set it over the link it already has -- no USB, no cable,
245
+ no bootstrap.
246
+ * **The gateway's TLS is opportunistic on the same port.** A plain-TCP device and
247
+ a TLS device share port 11113; the server offers TLS 1.3 with P-521/384/256 and
248
+ ordinary system trust. So a reimplementation can wrap its listener in TLS and
249
+ serve both.
250
+ * **There is no certificate pinning on the device link**, so your own
251
+ certificate works. (That is also the security weakness, but it is what makes
252
+ self-hosting possible.)
253
+
254
+ Note firmware 7.4.4407 has **no CLI command for TCLV 145** -- nothing matching
255
+ ``tls_*`` appears in ``help``. It is a network-only parameter, which is the
256
+ opposite of the problem this module exists to work around.
257
+
258
+ Untested here: this library speaks plaintext and nothing has driven TCLV 145 on
259
+ hardware. The parameter's description and its absence from the read-only set are
260
+ both read out of the vendor's own tables.
261
+ '''
262
+ """The mechanism to use instead of chasing the AES key."""
@@ -0,0 +1,175 @@
1
+ """Errors raised by the USB serial console layer.
2
+
3
+ All of these subclass :class:`pyvisionect.wire.errors.VisionectError`, so a
4
+ caller can catch the whole library with one ``except``.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from ...wire.errors import VisionectError
10
+
11
+ __all__ = [
12
+ "ConsoleError",
13
+ "ConsoleNotOpen",
14
+ "ConsoleTimeout",
15
+ "PromptNotFound",
16
+ "UnknownCommand",
17
+ "IncorrectParameters",
18
+ "ConsoleAssertionFailed",
19
+ "CommandNotInFirmware",
20
+ "WriteNotAllowed",
21
+ "DangerousCommandRefused",
22
+ ]
23
+
24
+
25
+ class ConsoleError(VisionectError):
26
+ """Base class for serial-console faults."""
27
+
28
+
29
+ class ConsoleNotOpen(ConsoleError):
30
+ """A command was issued on a console that is closed."""
31
+
32
+
33
+ class ConsoleTimeout(ConsoleError):
34
+ """No prompt arrived inside the command timeout.
35
+
36
+ Attributes:
37
+ command: the line that was sent.
38
+ partial: whatever bytes did arrive, decoded. Worth printing: a firmware
39
+ assertion (see :class:`ConsoleAssertionFailed`) shows up here.
40
+ """
41
+
42
+ def __init__(self, command: str, partial: str, timeout: float) -> None:
43
+ self.command = command
44
+ self.partial = partial
45
+ self.timeout = timeout
46
+ super().__init__(
47
+ f"no prompt within {timeout:g}s after {command!r}; "
48
+ f"got {partial!r}. If the partial output contains 'assert:', the "
49
+ f"firmware's CLI task has died and only a device reboot brings it back."
50
+ )
51
+
52
+
53
+ class PromptNotFound(ConsoleError):
54
+ """:meth:`~pyvisionect.io.usb.console.SerialConsole.sync` could not find the prompt.
55
+
56
+ Either nothing is listening on the port, the baud rate is wrong, or the
57
+ firmware's ``usb_cli_task`` has died (see :class:`ConsoleAssertionFailed`).
58
+ """
59
+
60
+
61
+ class UnknownCommand(ConsoleError):
62
+ """The firmware does not have that command.
63
+
64
+ Verbatim from the device::
65
+
66
+ Command 'xyz' not recognised. Enter 'help' to view a list of available commands.
67
+
68
+ The documented command set is a superset of any one firmware's: commands are
69
+ guarded by compile-time switches. ``help`` on firmware 7.4.4407 on a 32"
70
+ board lists 111 of the 160 documented commands. See
71
+ :data:`pyvisionect.io.usb.commands.ABSENT_FROM_7_4_4407` -- and note that
72
+ membership there means "not listed", not "not there": this error is the only
73
+ reply that *proves* a command is missing, which is why
74
+ :data:`pyvisionect.io.usb.commands.HIDDEN_IN_7_4_4407` exists.
75
+ """
76
+
77
+ def __init__(self, command: str) -> None:
78
+ self.command = command
79
+ super().__init__(
80
+ f"the firmware does not recognise {command!r}. Run `help` -- it is "
81
+ f"authoritative for the firmware in front of you; the vendor's "
82
+ f"reference documents commands this build was not compiled with."
83
+ )
84
+
85
+
86
+ class IncorrectParameters(ConsoleError):
87
+ """Wrong argument count or an unparseable argument.
88
+
89
+ Verbatim from the device::
90
+
91
+ Incorrect command parameter(s). Enter "help" to view a list of available commands.
92
+
93
+ Note the device uses *double* quotes around ``help`` here and *single*
94
+ quotes in the unknown-command message. Both strings are matched literally.
95
+
96
+ This also fires for commands whose ``help`` line is simply wrong about its
97
+ arity: ``max17135_dump`` is documented as taking no arguments and rejects a
98
+ bare invocation.
99
+ """
100
+
101
+ def __init__(self, command: str) -> None:
102
+ self.command = command
103
+ super().__init__(
104
+ f"the firmware rejected the arguments to {command!r}. Check `help` "
105
+ f"for the real arity -- a few help lines on 7.4.4407 understate it "
106
+ f"(max17135_dump is documented as nullary but requires an i2c channel)."
107
+ )
108
+
109
+
110
+ class ConsoleAssertionFailed(ConsoleError):
111
+ """The firmware hit an ``assert:`` and the CLI task is now dead.
112
+
113
+ **Observed live on firmware 7.4.4407.** ``sf_rdid`` and ``sf_rdst`` both
114
+ assert immediately -- ``assert: spi_flash_cli.c:139`` and
115
+ ``assert: spi_flash_cli.c:188`` -- because neither checks that
116
+ ``sf_select`` has chosen a device first. The assertion kills
117
+ ``usb_cli_task`` (``task_list`` stops answering, the prompt never returns)
118
+ while the rest of the firmware keeps running: the sign stays on the network,
119
+ keeps its heartbeat, and keeps its picture. The software watchdog notices
120
+ (``W WD task timeout: cli_USB`` appears on the UART) but does not restart
121
+ the task; the console comes back only after a device reboot.
122
+
123
+ Attributes:
124
+ command: the command that asserted.
125
+ location: e.g. ``"spi_flash_cli.c:139"``.
126
+ """
127
+
128
+ def __init__(self, command: str, location: str) -> None:
129
+ self.command = command
130
+ self.location = location
131
+ super().__init__(
132
+ f"{command!r} tripped a firmware assertion at {location}. The CLI "
133
+ f"task is dead and will not recover on its own -- the sign itself is "
134
+ f"fine (network, heartbeat and display keep running), but the serial "
135
+ f"console needs a device reboot. Known offenders on 7.4.4407: "
136
+ f"sf_rdid, sf_rdst."
137
+ )
138
+
139
+
140
+ class CommandNotInFirmware(ConsoleError):
141
+ """A typed accessor was called for a command this firmware lacks.
142
+
143
+ Raised locally, before anything is written, when the console has learned the
144
+ firmware's command list (via :meth:`~pyvisionect.io.usb.device.Sign.refresh_commands`)
145
+ and the command is not in it.
146
+ """
147
+
148
+ def __init__(self, command: str) -> None:
149
+ self.command = command
150
+ super().__init__(
151
+ f"{command!r} is not in this firmware's `help` output, so it was not "
152
+ f"sent. Pass check=False to send it anyway."
153
+ )
154
+
155
+
156
+ class WriteNotAllowed(ConsoleError):
157
+ """A setter was called on a console opened read-only.
158
+
159
+ Mirrors :class:`pyvisionect.wire.errors.ReadOnlyParameter`: the message
160
+ names the flag that unlocks the call rather than just refusing.
161
+ """
162
+
163
+ def __init__(self, command: str, flag: str, why: str) -> None:
164
+ self.command = command
165
+ self.flag = flag
166
+ super().__init__(f"{command!r} is a write and {why}. Pass {flag} to allow it.")
167
+
168
+
169
+ class DangerousCommandRefused(WriteNotAllowed):
170
+ """A destructive command was issued without its explicit opt-in.
171
+
172
+ Kept as a distinct type (and a distinct name, unchanged from the first
173
+ release of this module) because the opt-in it names is a different, louder
174
+ flag than the one ordinary setters need.
175
+ """