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.
- pyvisionect/__init__.py +120 -0
- pyvisionect/devices/__init__.py +92 -0
- pyvisionect/devices/enums.py +403 -0
- pyvisionect/devices/panels.py +242 -0
- pyvisionect/devices/tclv.py +460 -0
- pyvisionect/imaging/README.md +175 -0
- pyvisionect/imaging/__init__.py +181 -0
- pyvisionect/imaging/checksum.py +114 -0
- pyvisionect/imaging/constants.py +131 -0
- pyvisionect/imaging/data/blue_noise_64.npy +0 -0
- pyvisionect/imaging/decode.py +172 -0
- pyvisionect/imaging/dither.py +357 -0
- pyvisionect/imaging/encoder.py +594 -0
- pyvisionect/imaging/geometry.py +129 -0
- pyvisionect/imaging/grey.py +104 -0
- pyvisionect/imaging/interlace.py +244 -0
- pyvisionect/imaging/pack.py +142 -0
- pyvisionect/imaging/panel.py +339 -0
- pyvisionect/imaging/partial.py +931 -0
- pyvisionect/imaging/rects.py +466 -0
- pyvisionect/io/__init__.py +33 -0
- pyvisionect/io/tcp.py +795 -0
- pyvisionect/io/usb/__init__.py +237 -0
- pyvisionect/io/usb/cli.py +278 -0
- pyvisionect/io/usb/commands.py +781 -0
- pyvisionect/io/usb/console.py +730 -0
- pyvisionect/io/usb/device.py +914 -0
- pyvisionect/io/usb/discovery.py +260 -0
- pyvisionect/io/usb/encryption.py +262 -0
- pyvisionect/io/usb/errors.py +175 -0
- pyvisionect/io/usb/fake.py +292 -0
- pyvisionect/io/usb/parsers.py +1464 -0
- pyvisionect/io/usb/provisioning.py +502 -0
- pyvisionect/packets/__init__.py +135 -0
- pyvisionect/packets/control.py +95 -0
- pyvisionect/packets/file.py +325 -0
- pyvisionect/packets/image.py +234 -0
- pyvisionect/packets/misc.py +202 -0
- pyvisionect/packets/param.py +284 -0
- pyvisionect/packets/status.py +518 -0
- pyvisionect/packets/stored.py +217 -0
- pyvisionect/py.typed +0 -0
- pyvisionect/session/__init__.py +100 -0
- pyvisionect/session/connection.py +1043 -0
- pyvisionect/session/device.py +587 -0
- pyvisionect/session/events.py +196 -0
- pyvisionect/session/filetransfer.py +251 -0
- pyvisionect/session/pending.py +425 -0
- pyvisionect/wire/__init__.py +91 -0
- pyvisionect/wire/blocks.py +350 -0
- pyvisionect/wire/checksum.py +115 -0
- pyvisionect/wire/errors.py +176 -0
- pyvisionect/wire/framing.py +334 -0
- pyvisionect-0.1.0.dist-info/METADATA +1030 -0
- pyvisionect-0.1.0.dist-info/RECORD +58 -0
- pyvisionect-0.1.0.dist-info/WHEEL +4 -0
- pyvisionect-0.1.0.dist-info/entry_points.txt +3 -0
- pyvisionect-0.1.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,730 @@
|
|
|
1
|
+
r"""The serial transport: one command in, one structured reply out.
|
|
2
|
+
|
|
3
|
+
Line discipline, measured on a live sign
|
|
4
|
+
----------------------------------------
|
|
5
|
+
|
|
6
|
+
Firmware 7.4.4407, FTDI FT232 (``0403:6001``) on ``/dev/ttyUSB0``, 115200 8N1.
|
|
7
|
+
Everything in this section was observed, not inferred:
|
|
8
|
+
|
|
9
|
+
* **CR (``\r``) is the submit character. LF is not.** Sending
|
|
10
|
+
``cli_version_get\n`` makes the device *echo* the text and then sit there with
|
|
11
|
+
the line still in its edit buffer, so the next command is appended to it and
|
|
12
|
+
the pair is rejected as one unrecognised word::
|
|
13
|
+
|
|
14
|
+
>>> write(b"cli_version_get\n") # echoes, does not execute
|
|
15
|
+
>>> write(b"definitely_not_a_command\r")
|
|
16
|
+
Command 'cli_version_getdefinitely_not_a_command' not recognised.
|
|
17
|
+
|
|
18
|
+
``\r\n`` does work -- the CR submits -- but the trailing LF is echoed back
|
|
19
|
+
*after* the prompt and pollutes the next read. :data:`TERMINATOR` is
|
|
20
|
+
therefore a bare ``\r``, which is a correction to this module's first release.
|
|
21
|
+
|
|
22
|
+
* **The device echoes the command line**, terminated ``\r\n``. That echo is the
|
|
23
|
+
anchor this module synchronises on.
|
|
24
|
+
|
|
25
|
+
* **The prompt is ``"> "``** with no trailing newline, emitted after every reply.
|
|
26
|
+
So a reply has a real terminator and there is no need to read until the port
|
|
27
|
+
goes quiet.
|
|
28
|
+
|
|
29
|
+
* **Commands are case-insensitive.** ``UPTIME`` works.
|
|
30
|
+
|
|
31
|
+
* **Only some commands emit a return code**, and it is not always last:
|
|
32
|
+
``certs_config_get`` prints ``rv: 0`` *before* its body. It appears in two
|
|
33
|
+
spellings, decimal (``rv: 0``) and hex (``rv: 0x0``), from different commands
|
|
34
|
+
in the same firmware.
|
|
35
|
+
|
|
36
|
+
* Errors are followed by a blank line, then the prompt.
|
|
37
|
+
|
|
38
|
+
Asynchronous log lines -- the actual problem
|
|
39
|
+
--------------------------------------------
|
|
40
|
+
|
|
41
|
+
The firmware logs to this same UART, unprompted. A heartbeat fires every minute
|
|
42
|
+
and dumps eight lines; an image push dumps a ``Profiling:`` line. Captured
|
|
43
|
+
verbatim between two commands::
|
|
44
|
+
|
|
45
|
+
sys evt vplatform_heartbeat.c:19, Heartbeat (7)
|
|
46
|
+
Received event: Heartbeat (7)
|
|
47
|
+
Heart-beat event
|
|
48
|
+
sending pv2 status on heartbeat
|
|
49
|
+
make packet type=3, id=4
|
|
50
|
+
Frame send 552 bytes
|
|
51
|
+
Setting heartbeat after 1 min
|
|
52
|
+
Got response (id=4)
|
|
53
|
+
|
|
54
|
+
Any of those can land in the middle of a reply, so a parser that assumes "every
|
|
55
|
+
line between my command and the prompt is my answer" corrupts intermittently --
|
|
56
|
+
which is the worst failure mode, because it passes every test you write by hand.
|
|
57
|
+
|
|
58
|
+
:class:`SerialConsole` separates the two streams with four mechanisms, in
|
|
59
|
+
descending order of how much they are relied on:
|
|
60
|
+
|
|
61
|
+
1. **Drain before send.** Anything already in the buffer when
|
|
62
|
+
:meth:`command` is called arrived unsolicited by definition, so it is read
|
|
63
|
+
out and classified as log *before* the command is written. This alone
|
|
64
|
+
handles the common case, because log bursts are short relative to the gap
|
|
65
|
+
between commands.
|
|
66
|
+
2. **Echo anchor.** The reply frame starts at the echoed command line.
|
|
67
|
+
Anything between the write and that echo is log.
|
|
68
|
+
3. **Prompt terminator.** The frame ends at a ``"> "`` at the start of a line.
|
|
69
|
+
Between those two anchors the extent of the reply is exact; only its
|
|
70
|
+
*contents* can still be contaminated.
|
|
71
|
+
4. **Pattern classification.** Lines inside the frame that match
|
|
72
|
+
:data:`LOG_PATTERNS` are moved to the log stream. This is the only
|
|
73
|
+
heuristic in the chain, and it is the only one that can be wrong, so it is
|
|
74
|
+
a plain editable tuple of regexes rather than something clever.
|
|
75
|
+
|
|
76
|
+
**The log sink can be turned off at source**, which makes all of the above
|
|
77
|
+
unnecessary while it holds: ``vlog_unify_levels 1`` silences the USB
|
|
78
|
+
destination. Measured on 7.4.4407 -- 0 lines in 90 s, against 18-61 at level 5
|
|
79
|
+
on a healthy link and ~1 400 lines/min at level 5 while the radio was
|
|
80
|
+
reconnect-flapping -- and the lines it silences are exactly the heartbeat
|
|
81
|
+
narration :data:`LOG_PATTERNS` exists to filter. The scale runs ``1`` (quiet)
|
|
82
|
+
to ``5`` (everything) and ``0`` is rejected outright, which is the answer to a
|
|
83
|
+
question this docstring previously recorded as open.
|
|
84
|
+
|
|
85
|
+
**It is still not a substitute for the four mechanisms above**, for one reason
|
|
86
|
+
that is not about the logger: it does not persist. Nothing survives without
|
|
87
|
+
``flash_save``, and the sign reboots itself when it cannot reach its server
|
|
88
|
+
(``E: Max conn errs. Reboot``), so a long-lived console session will silently
|
|
89
|
+
get its default verbosity back partway through. Treat ``vlog_unify_levels 1``
|
|
90
|
+
as an optimisation for a known-quiet window, not as an invariant -- and note
|
|
91
|
+
that it also hides ``E: TCP connection Error`` and friends, so level ``2`` or
|
|
92
|
+
``3`` is the better choice if you still want to see faults. See
|
|
93
|
+
:meth:`pyvisionect.io.usb.device.Sign.silence_usb_logs`.
|
|
94
|
+
|
|
95
|
+
One assumption remains: that the firmware emits whole log lines atomically, so
|
|
96
|
+
an interloper never splits a reply line down the middle. It held across every
|
|
97
|
+
capture taken for this module, and a FreeRTOS logger taking a mutex per message
|
|
98
|
+
is the usual reason, but it is an assumption and not a measurement.
|
|
99
|
+
"""
|
|
100
|
+
|
|
101
|
+
from __future__ import annotations
|
|
102
|
+
|
|
103
|
+
import logging
|
|
104
|
+
import re
|
|
105
|
+
import time
|
|
106
|
+
from collections import deque
|
|
107
|
+
from collections.abc import Callable, Iterable, Iterator, Sequence
|
|
108
|
+
from dataclasses import dataclass, field
|
|
109
|
+
from typing import Protocol, runtime_checkable
|
|
110
|
+
|
|
111
|
+
from .errors import (
|
|
112
|
+
ConsoleAssertionFailed,
|
|
113
|
+
ConsoleNotOpen,
|
|
114
|
+
ConsoleTimeout,
|
|
115
|
+
IncorrectParameters,
|
|
116
|
+
PromptNotFound,
|
|
117
|
+
UnknownCommand,
|
|
118
|
+
)
|
|
119
|
+
|
|
120
|
+
__all__ = [
|
|
121
|
+
"BAUD_RATE",
|
|
122
|
+
"LOG_PATTERNS",
|
|
123
|
+
"PROMPT",
|
|
124
|
+
"TERMINATOR",
|
|
125
|
+
"CommandResult",
|
|
126
|
+
"LogLine",
|
|
127
|
+
"SerialConsole",
|
|
128
|
+
"SerialTransport",
|
|
129
|
+
"classify",
|
|
130
|
+
]
|
|
131
|
+
|
|
132
|
+
log = logging.getLogger(__name__)
|
|
133
|
+
|
|
134
|
+
BAUD_RATE = 115200
|
|
135
|
+
"""115200 8N1 -- from the vendor reference, confirmed on the wire."""
|
|
136
|
+
|
|
137
|
+
TERMINATOR = b"\r"
|
|
138
|
+
r"""Bare CR. See the module docstring: LF alone does not submit a line."""
|
|
139
|
+
|
|
140
|
+
PROMPT = b"> "
|
|
141
|
+
"""The device prompt. No trailing newline, which is why it is matched on bytes."""
|
|
142
|
+
|
|
143
|
+
_UNKNOWN_RE = re.compile(
|
|
144
|
+
r"^Command '(?P<cmd>.*)' not recognised\.\s+Enter 'help' to view a list of "
|
|
145
|
+
r"available commands\.$"
|
|
146
|
+
)
|
|
147
|
+
_BAD_PARAMS = (
|
|
148
|
+
'Incorrect command parameter(s). Enter "help" to view a list of available commands.'
|
|
149
|
+
)
|
|
150
|
+
_ASSERT_RE = re.compile(r"^assert: (?P<where>\S+:\d+)$")
|
|
151
|
+
_RV_RE = re.compile(r"^rv:\s*(?P<value>-?(?:0[xX][0-9a-fA-F]+|\d+))$")
|
|
152
|
+
|
|
153
|
+
LOG_PATTERNS: tuple[re.Pattern[str], ...] = (
|
|
154
|
+
# vlog severity prefix: "W WD task timeout: cli_USB", "E ...", "I ...".
|
|
155
|
+
re.compile(r"^[DIWEF] \S"),
|
|
156
|
+
# "sys evt vplatform_heartbeat.c:19, Heartbeat (7)" -- source file and line.
|
|
157
|
+
re.compile(r"^sys evt \S+\.c:\d+,"),
|
|
158
|
+
re.compile(r"^Received event: "),
|
|
159
|
+
re.compile(r"^Heart-beat event$"),
|
|
160
|
+
re.compile(r"^sending pv2 status"),
|
|
161
|
+
re.compile(r"^make packet type=\d+"),
|
|
162
|
+
re.compile(r"^Frame send \d+ bytes$"),
|
|
163
|
+
re.compile(r"^Frame recv \d+ bytes$"),
|
|
164
|
+
re.compile(r"^Setting heartbeat after "),
|
|
165
|
+
re.compile(r"^Got response \(id=\d+\)$"),
|
|
166
|
+
re.compile(r"^Profiling:"),
|
|
167
|
+
re.compile(r"^WD task timeout:"),
|
|
168
|
+
)
|
|
169
|
+
"""Regexes that identify an *unsolicited* line.
|
|
170
|
+
|
|
171
|
+
Every entry was taken from a real capture off ``/dev/ttyUSB0``; none is
|
|
172
|
+
speculative. The list is deliberately a module-level tuple so a caller whose
|
|
173
|
+
firmware logs something new can extend it::
|
|
174
|
+
|
|
175
|
+
console = SerialConsole("/dev/ttyUSB0", log_patterns=LOG_PATTERNS + (
|
|
176
|
+
re.compile(r"^my new log line"),
|
|
177
|
+
))
|
|
178
|
+
|
|
179
|
+
A false positive here *silently eats a reply line*, so prefer anchored,
|
|
180
|
+
specific patterns over loose ones.
|
|
181
|
+
"""
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def classify(line: str, patterns: Sequence[re.Pattern[str]] = LOG_PATTERNS) -> bool:
|
|
185
|
+
"""True if *line* looks like an asynchronous log line rather than a reply.
|
|
186
|
+
|
|
187
|
+
Pure, so it is the one piece of the interleaving logic that can be tested
|
|
188
|
+
without any transport at all.
|
|
189
|
+
"""
|
|
190
|
+
return any(p.search(line) for p in patterns)
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
@runtime_checkable
|
|
194
|
+
class SerialTransport(Protocol):
|
|
195
|
+
"""The slice of ``serial.Serial`` this module uses.
|
|
196
|
+
|
|
197
|
+
Deliberately four members. Anything satisfying it can be injected, which is
|
|
198
|
+
how the whole module is tested without hardware; see
|
|
199
|
+
:class:`pyvisionect.io.usb.fake.FakeTransport`.
|
|
200
|
+
"""
|
|
201
|
+
|
|
202
|
+
@property
|
|
203
|
+
def in_waiting(self) -> int:
|
|
204
|
+
"""Bytes buffered and readable without blocking."""
|
|
205
|
+
|
|
206
|
+
def write(self, data: bytes, /) -> int | None: ...
|
|
207
|
+
|
|
208
|
+
def read(self, size: int = 1, /) -> bytes: ...
|
|
209
|
+
|
|
210
|
+
def close(self) -> None: ...
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
@dataclass(frozen=True, slots=True)
|
|
214
|
+
class LogLine:
|
|
215
|
+
"""One asynchronous line, with the moment it was read.
|
|
216
|
+
|
|
217
|
+
Attributes:
|
|
218
|
+
text: the line, without its terminator.
|
|
219
|
+
monotonic: ``time.monotonic()`` at the read that completed it. Monotonic
|
|
220
|
+
rather than wall-clock because the only useful question is
|
|
221
|
+
"how long before/after that command?".
|
|
222
|
+
during: the command whose reply window this arrived in, or None if it
|
|
223
|
+
was drained between commands.
|
|
224
|
+
"""
|
|
225
|
+
|
|
226
|
+
text: str
|
|
227
|
+
monotonic: float
|
|
228
|
+
during: str | None = None
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
@dataclass(frozen=True, slots=True)
|
|
232
|
+
class CommandResult:
|
|
233
|
+
"""The structured outcome of one command.
|
|
234
|
+
|
|
235
|
+
Attributes:
|
|
236
|
+
command: exactly what was written, minus the terminator.
|
|
237
|
+
raw: the whole decoded frame, echo and prompt included. Keep this: it is
|
|
238
|
+
the only lossless record, and it is what belongs in a bug report.
|
|
239
|
+
lines: the reply's own lines -- echo removed, prompt removed, ``rv:``
|
|
240
|
+
removed, blank lines removed, asynchronous log lines removed.
|
|
241
|
+
rv: the integer from the ``rv:`` line, or None when the command does not
|
|
242
|
+
emit one (most getters do not). Parsed from either spelling, so
|
|
243
|
+
``rv: 0`` and ``rv: 0x0`` both give ``0``.
|
|
244
|
+
logs: the asynchronous lines that landed inside this command's window.
|
|
245
|
+
Non-empty is normal, not an error.
|
|
246
|
+
echoed: whether the device's echo of the command line was found. False
|
|
247
|
+
means the stream was out of sync, so treat ``lines`` with suspicion
|
|
248
|
+
and call :meth:`SerialConsole.sync`.
|
|
249
|
+
terminated_by: ``"prompt"`` normally. ``"idle"`` or ``"timeout"`` only
|
|
250
|
+
when ``expect_prompt=False`` was passed, since otherwise the
|
|
251
|
+
absence of a prompt raises.
|
|
252
|
+
"""
|
|
253
|
+
|
|
254
|
+
command: str
|
|
255
|
+
raw: str
|
|
256
|
+
lines: tuple[str, ...]
|
|
257
|
+
rv: int | None = None
|
|
258
|
+
logs: tuple[LogLine, ...] = ()
|
|
259
|
+
echoed: bool = True
|
|
260
|
+
terminated_by: str = "prompt"
|
|
261
|
+
|
|
262
|
+
@property
|
|
263
|
+
def text(self) -> str:
|
|
264
|
+
""":attr:`lines` joined with newlines -- for printing, not for parsing."""
|
|
265
|
+
return "\n".join(self.lines)
|
|
266
|
+
|
|
267
|
+
@property
|
|
268
|
+
def ok(self) -> bool:
|
|
269
|
+
"""True when no ``rv:`` was emitted, or the one emitted was zero."""
|
|
270
|
+
return self.rv in (None, 0)
|
|
271
|
+
|
|
272
|
+
def one(self) -> str:
|
|
273
|
+
"""The single reply line, for commands that emit exactly one.
|
|
274
|
+
|
|
275
|
+
Raises:
|
|
276
|
+
ValueError: if there was not exactly one line. Better than
|
|
277
|
+
``lines[0]`` silently reading the first of several, which is how
|
|
278
|
+
a changed firmware reply turns into a wrong value instead of an
|
|
279
|
+
error.
|
|
280
|
+
"""
|
|
281
|
+
if len(self.lines) != 1:
|
|
282
|
+
raise ValueError(
|
|
283
|
+
f"{self.command!r} returned {len(self.lines)} reply lines, expected 1: "
|
|
284
|
+
f"{self.lines!r}"
|
|
285
|
+
)
|
|
286
|
+
return self.lines[0]
|
|
287
|
+
|
|
288
|
+
def field(self, label: str) -> str:
|
|
289
|
+
"""The value of the ``"<label>: <value>"`` line with this *label*.
|
|
290
|
+
|
|
291
|
+
The device's reply format is overwhelmingly ``Label: value``, with
|
|
292
|
+
padding after the colon on some lines (``"Feature EAP: enabled"``), so
|
|
293
|
+
the value is stripped.
|
|
294
|
+
|
|
295
|
+
Raises:
|
|
296
|
+
KeyError: if no line carries that label.
|
|
297
|
+
"""
|
|
298
|
+
for line in self.lines:
|
|
299
|
+
name, sep, value = line.partition(":")
|
|
300
|
+
if sep and name.strip() == label:
|
|
301
|
+
return value.strip()
|
|
302
|
+
raise KeyError(f"{label!r} not in reply to {self.command!r}: {self.lines!r}")
|
|
303
|
+
|
|
304
|
+
def fields(self) -> dict[str, str]:
|
|
305
|
+
"""Every ``"<label>: <value>"`` line as a dict.
|
|
306
|
+
|
|
307
|
+
Later duplicates win. Lines without a colon are skipped, so a reply that
|
|
308
|
+
mixes prose and fields (``certs_config_get`` emits ``No EAP cert
|
|
309
|
+
found!``) still yields its fields.
|
|
310
|
+
"""
|
|
311
|
+
out: dict[str, str] = {}
|
|
312
|
+
for line in self.lines:
|
|
313
|
+
name, sep, value = line.partition(":")
|
|
314
|
+
if sep:
|
|
315
|
+
out[name.strip()] = value.strip()
|
|
316
|
+
return out
|
|
317
|
+
|
|
318
|
+
|
|
319
|
+
class SerialConsole:
|
|
320
|
+
"""A line-oriented client for the sign's ASCII serial console.
|
|
321
|
+
|
|
322
|
+
Either pass *port* and let this open a ``serial.Serial``, or pass
|
|
323
|
+
*transport* (anything matching :class:`SerialTransport`) and keep I/O out of
|
|
324
|
+
it entirely.
|
|
325
|
+
|
|
326
|
+
Args:
|
|
327
|
+
port: e.g. ``/dev/ttyUSB0``, or ``/dev/cu.usbserial-XXXXXXXX`` on macOS.
|
|
328
|
+
Ignored when *transport* is given.
|
|
329
|
+
transport: an already-open transport, for tests or for a port someone
|
|
330
|
+
else owns.
|
|
331
|
+
baudrate: :data:`BAUD_RATE` unless you have a reason.
|
|
332
|
+
terminator: :data:`TERMINATOR`. Changing it to ``b"\\n"`` will not work;
|
|
333
|
+
the firmware does not submit on LF.
|
|
334
|
+
read_timeout: the underlying port's per-``read`` timeout. Small, because
|
|
335
|
+
this class does its own waiting.
|
|
336
|
+
command_timeout: how long :meth:`command` waits for the prompt. ``help``
|
|
337
|
+
emits ~5 KB and still lands well inside the default.
|
|
338
|
+
idle_timeout: how long a silent port counts as "the reply is over", used
|
|
339
|
+
only when ``expect_prompt=False``.
|
|
340
|
+
on_log: called with each :class:`LogLine` as it is classified. Exceptions
|
|
341
|
+
from it are logged and swallowed -- a noisy callback must not break
|
|
342
|
+
the command that happened to be in flight.
|
|
343
|
+
log_history: how many :class:`LogLine` to keep in :attr:`logs`.
|
|
344
|
+
log_patterns: see :data:`LOG_PATTERNS`.
|
|
345
|
+
encoding_errors: how to handle non-ASCII bytes. ``"replace"`` by
|
|
346
|
+
default: the port emits the occasional NUL at open and a decode
|
|
347
|
+
error there would be a useless failure.
|
|
348
|
+
|
|
349
|
+
Example:
|
|
350
|
+
>>> with SerialConsole("/dev/ttyUSB0") as c: # doctest: +SKIP
|
|
351
|
+
... c.sync()
|
|
352
|
+
... print(c.command("uptime").field("Uptime in min"))
|
|
353
|
+
... for entry in c.logs:
|
|
354
|
+
... print("async:", entry.text)
|
|
355
|
+
"""
|
|
356
|
+
|
|
357
|
+
def __init__(
|
|
358
|
+
self,
|
|
359
|
+
port: str | None = None,
|
|
360
|
+
*,
|
|
361
|
+
transport: SerialTransport | None = None,
|
|
362
|
+
baudrate: int = BAUD_RATE,
|
|
363
|
+
terminator: bytes = TERMINATOR,
|
|
364
|
+
read_timeout: float = 0.05,
|
|
365
|
+
command_timeout: float = 25.0,
|
|
366
|
+
idle_timeout: float = 1.2,
|
|
367
|
+
on_log: Callable[[LogLine], None] | None = None,
|
|
368
|
+
log_history: int = 512,
|
|
369
|
+
log_patterns: Sequence[re.Pattern[str]] = LOG_PATTERNS,
|
|
370
|
+
encoding_errors: str = "replace",
|
|
371
|
+
) -> None:
|
|
372
|
+
if transport is None and port is None:
|
|
373
|
+
raise ValueError("either port or transport must be given")
|
|
374
|
+
self.port = port
|
|
375
|
+
self.baudrate = baudrate
|
|
376
|
+
self.terminator = terminator
|
|
377
|
+
self.read_timeout = read_timeout
|
|
378
|
+
self.command_timeout = command_timeout
|
|
379
|
+
self.idle_timeout = idle_timeout
|
|
380
|
+
self.on_log = on_log
|
|
381
|
+
self.log_patterns = tuple(log_patterns)
|
|
382
|
+
self.encoding_errors = encoding_errors
|
|
383
|
+
self.logs: deque[LogLine] = deque(maxlen=log_history)
|
|
384
|
+
self.transcript: list[CommandResult] = []
|
|
385
|
+
self._holdover = ""
|
|
386
|
+
self._transport: SerialTransport | None = transport
|
|
387
|
+
self._owned = transport is None
|
|
388
|
+
if transport is None:
|
|
389
|
+
self.open()
|
|
390
|
+
|
|
391
|
+
# --------------------------------------------------------------- lifecycle
|
|
392
|
+
|
|
393
|
+
def open(self) -> None:
|
|
394
|
+
"""Open the port. A no-op if it is already open."""
|
|
395
|
+
if self._transport is not None:
|
|
396
|
+
return
|
|
397
|
+
assert self.port is not None
|
|
398
|
+
try:
|
|
399
|
+
import serial as pyserial
|
|
400
|
+
except ImportError as exc: # pragma: no cover - depends on the install
|
|
401
|
+
raise ImportError(
|
|
402
|
+
"the USB console needs pyserial: pip install 'pyvisionect[usb]'"
|
|
403
|
+
) from exc
|
|
404
|
+
self._transport = pyserial.Serial(
|
|
405
|
+
self.port,
|
|
406
|
+
self.baudrate,
|
|
407
|
+
bytesize=8,
|
|
408
|
+
parity="N",
|
|
409
|
+
stopbits=1,
|
|
410
|
+
timeout=self.read_timeout,
|
|
411
|
+
)
|
|
412
|
+
self._owned = True
|
|
413
|
+
|
|
414
|
+
def close(self) -> None:
|
|
415
|
+
"""Close the port, if this object opened it."""
|
|
416
|
+
transport, self._transport = self._transport, None
|
|
417
|
+
if transport is not None and self._owned:
|
|
418
|
+
transport.close()
|
|
419
|
+
|
|
420
|
+
@property
|
|
421
|
+
def is_open(self) -> bool:
|
|
422
|
+
return self._transport is not None
|
|
423
|
+
|
|
424
|
+
def __enter__(self) -> SerialConsole:
|
|
425
|
+
self.open()
|
|
426
|
+
return self
|
|
427
|
+
|
|
428
|
+
def __exit__(self, *exc: object) -> None:
|
|
429
|
+
self.close()
|
|
430
|
+
|
|
431
|
+
def _require(self) -> SerialTransport:
|
|
432
|
+
if self._transport is None:
|
|
433
|
+
raise ConsoleNotOpen("the console is closed; call open() first")
|
|
434
|
+
return self._transport
|
|
435
|
+
|
|
436
|
+
# ------------------------------------------------------------------- reads
|
|
437
|
+
|
|
438
|
+
def _emit_log(self, text: str, during: str | None) -> LogLine:
|
|
439
|
+
entry = LogLine(text=text, monotonic=time.monotonic(), during=during)
|
|
440
|
+
self.logs.append(entry)
|
|
441
|
+
log.debug("async <- %s", text)
|
|
442
|
+
if self.on_log is not None:
|
|
443
|
+
try:
|
|
444
|
+
self.on_log(entry)
|
|
445
|
+
except Exception: # pragma: no cover - a callback's problem, not ours
|
|
446
|
+
log.exception("on_log callback raised for %r", text)
|
|
447
|
+
return entry
|
|
448
|
+
|
|
449
|
+
def drain_logs(self, *, during: str | None = None) -> tuple[LogLine, ...]:
|
|
450
|
+
"""Read everything already buffered and record it as asynchronous.
|
|
451
|
+
|
|
452
|
+
Correct by construction: bytes sitting in the buffer before a command is
|
|
453
|
+
written cannot be that command's reply. Called automatically at the top
|
|
454
|
+
of :meth:`command`.
|
|
455
|
+
|
|
456
|
+
A partial trailing line (one with no terminator yet) is kept in an
|
|
457
|
+
internal holdover and prepended to the next read, so a log line split
|
|
458
|
+
across two drains is not reported as two lines.
|
|
459
|
+
"""
|
|
460
|
+
transport = self._require()
|
|
461
|
+
waiting = transport.in_waiting
|
|
462
|
+
data = transport.read(waiting) if waiting else b""
|
|
463
|
+
if not data:
|
|
464
|
+
return ()
|
|
465
|
+
return tuple(self._lines_as_logs(data, during))
|
|
466
|
+
|
|
467
|
+
def _lines_as_logs(self, data: bytes, during: str | None) -> Iterator[LogLine]:
|
|
468
|
+
text = self._holdover + data.decode("ascii", self.encoding_errors)
|
|
469
|
+
parts = text.replace("\r\n", "\n").replace("\r", "\n").split("\n")
|
|
470
|
+
self._holdover = parts.pop() # incomplete tail, or "" if data ended cleanly
|
|
471
|
+
# A bare prompt at the end of the holdover is not a log line.
|
|
472
|
+
if self._holdover.strip() in ("", ">"):
|
|
473
|
+
self._holdover = ""
|
|
474
|
+
for part in parts:
|
|
475
|
+
if part.strip() and part.strip() != ">":
|
|
476
|
+
yield self._emit_log(part.rstrip(), during)
|
|
477
|
+
|
|
478
|
+
def _read_frame(
|
|
479
|
+
self, command: str, timeout: float, expect_prompt: bool
|
|
480
|
+
) -> tuple[bytes, str]:
|
|
481
|
+
"""Read until the prompt, or until idle/timeout. Returns (bytes, how)."""
|
|
482
|
+
transport = self._require()
|
|
483
|
+
buf = bytearray()
|
|
484
|
+
start = last = time.monotonic()
|
|
485
|
+
while time.monotonic() - start < timeout:
|
|
486
|
+
waiting = transport.in_waiting
|
|
487
|
+
chunk = transport.read(waiting) if waiting else transport.read(1)
|
|
488
|
+
if chunk:
|
|
489
|
+
buf += chunk
|
|
490
|
+
last = time.monotonic()
|
|
491
|
+
if self._at_prompt(buf):
|
|
492
|
+
return bytes(buf), "prompt"
|
|
493
|
+
# A dead CLI task never sends a prompt. Fail fast instead of
|
|
494
|
+
# burning the whole timeout: the assertion text is already here.
|
|
495
|
+
if not expect_prompt and _ASSERT_RE.search(
|
|
496
|
+
buf.decode("ascii", "replace").strip().rsplit("\n", 1)[-1].strip()
|
|
497
|
+
):
|
|
498
|
+
return bytes(buf), "assert"
|
|
499
|
+
elif time.monotonic() - last >= self.idle_timeout:
|
|
500
|
+
return bytes(buf), "idle"
|
|
501
|
+
return bytes(buf), "timeout"
|
|
502
|
+
|
|
503
|
+
@staticmethod
|
|
504
|
+
def _at_prompt(buf: bytes | bytearray) -> bool:
|
|
505
|
+
"""True when *buf* ends with a prompt that starts a line.
|
|
506
|
+
|
|
507
|
+
The ``len == 2`` arm matters: after a bare CR the device replies
|
|
508
|
+
``b"\\r\\n> "``, but a freshly-synced console can also see just
|
|
509
|
+
``b"> "``.
|
|
510
|
+
"""
|
|
511
|
+
if not buf.endswith(PROMPT):
|
|
512
|
+
return False
|
|
513
|
+
return len(buf) == len(PROMPT) or buf[-3:-2] in (b"\n", b"\r")
|
|
514
|
+
|
|
515
|
+
# ---------------------------------------------------------------- commands
|
|
516
|
+
|
|
517
|
+
def sync(self, *, attempts: int = 3) -> None:
|
|
518
|
+
"""Get the stream to a known boundary: at a fresh prompt, buffer empty.
|
|
519
|
+
|
|
520
|
+
Sends a bare CR and reads to the prompt, discarding whatever comes back
|
|
521
|
+
as log. Cheap, and worth doing at the start of a session and after any
|
|
522
|
+
result whose :attr:`~CommandResult.echoed` is False.
|
|
523
|
+
|
|
524
|
+
Raises:
|
|
525
|
+
PromptNotFound: after *attempts* tries with no prompt. On a sign
|
|
526
|
+
whose ``usb_cli_task`` has asserted, this is what you get, and
|
|
527
|
+
only a reboot fixes it.
|
|
528
|
+
"""
|
|
529
|
+
transport = self._require()
|
|
530
|
+
for _ in range(attempts):
|
|
531
|
+
self.drain_logs()
|
|
532
|
+
transport.write(self.terminator)
|
|
533
|
+
raw, how = self._read_frame("<sync>", min(self.command_timeout, 5.0), True)
|
|
534
|
+
if how == "prompt":
|
|
535
|
+
self._holdover = ""
|
|
536
|
+
tail = raw[: -len(PROMPT)]
|
|
537
|
+
if tail:
|
|
538
|
+
tuple(self._lines_as_logs(tail, None))
|
|
539
|
+
return
|
|
540
|
+
raise PromptNotFound(
|
|
541
|
+
"no prompt on the serial port after "
|
|
542
|
+
f"{attempts} attempts at {self.baudrate} baud. Either nothing is "
|
|
543
|
+
"listening, the baud rate is wrong, or the firmware's usb_cli_task "
|
|
544
|
+
"has died on an assertion (sf_rdid and sf_rdst do that on 7.4.4407) "
|
|
545
|
+
"-- in which case only a device reboot brings the console back."
|
|
546
|
+
)
|
|
547
|
+
|
|
548
|
+
def command(
|
|
549
|
+
self,
|
|
550
|
+
line: str,
|
|
551
|
+
*,
|
|
552
|
+
timeout: float | None = None,
|
|
553
|
+
expect_prompt: bool = True,
|
|
554
|
+
raise_on_error: bool = True,
|
|
555
|
+
) -> CommandResult:
|
|
556
|
+
"""Send one command line and return its parsed reply.
|
|
557
|
+
|
|
558
|
+
Args:
|
|
559
|
+
line: the command and its arguments, no terminator. Must be one
|
|
560
|
+
line: the firmware has no statement separator, so ``"a; b"`` is
|
|
561
|
+
rejected as a single unrecognised command, and an embedded
|
|
562
|
+
newline would desynchronise the stream. Both are refused here.
|
|
563
|
+
timeout: override :attr:`command_timeout`.
|
|
564
|
+
expect_prompt: when False, a reply that ends in silence instead of a
|
|
565
|
+
prompt is returned with ``terminated_by="idle"`` rather than
|
|
566
|
+
raising. Needed for ``reboot``, which never prompts again.
|
|
567
|
+
raise_on_error: when False, the firmware's own error replies are
|
|
568
|
+
returned as :attr:`~CommandResult.lines` instead of raising.
|
|
569
|
+
Useful for probing whether a command exists.
|
|
570
|
+
|
|
571
|
+
Returns:
|
|
572
|
+
A :class:`CommandResult`. Asynchronous log lines seen during the
|
|
573
|
+
exchange are in :attr:`~CommandResult.logs`, never in
|
|
574
|
+
:attr:`~CommandResult.lines`.
|
|
575
|
+
|
|
576
|
+
Raises:
|
|
577
|
+
UnknownCommand: the firmware has no such command.
|
|
578
|
+
IncorrectParameters: wrong arity or an unparseable argument.
|
|
579
|
+
ConsoleAssertionFailed: the command tripped a firmware assertion and
|
|
580
|
+
took the CLI task down with it.
|
|
581
|
+
ConsoleTimeout: no prompt arrived in time.
|
|
582
|
+
"""
|
|
583
|
+
if "\n" in line or "\r" in line:
|
|
584
|
+
raise ValueError(
|
|
585
|
+
f"a command must be a single line; {line!r} contains a line break"
|
|
586
|
+
)
|
|
587
|
+
if ";" in line:
|
|
588
|
+
raise ValueError(
|
|
589
|
+
f"the firmware has no statement separator, so {line!r} would be "
|
|
590
|
+
"sent as one command name and rejected; issue the commands separately"
|
|
591
|
+
)
|
|
592
|
+
transport = self._require()
|
|
593
|
+
timeout = self.command_timeout if timeout is None else timeout
|
|
594
|
+
|
|
595
|
+
# 1. whatever is buffered now is unsolicited, by construction.
|
|
596
|
+
before = self.drain_logs(during=None)
|
|
597
|
+
|
|
598
|
+
log.debug("-> %s", line)
|
|
599
|
+
transport.write(line.encode("ascii") + self.terminator)
|
|
600
|
+
flush = getattr(transport, "flush", None)
|
|
601
|
+
if flush is not None:
|
|
602
|
+
flush()
|
|
603
|
+
|
|
604
|
+
raw, how = self._read_frame(line, timeout, expect_prompt)
|
|
605
|
+
text = raw.decode("ascii", self.encoding_errors)
|
|
606
|
+
result = self._parse_frame(line, text, how, before)
|
|
607
|
+
self.transcript.append(result)
|
|
608
|
+
|
|
609
|
+
if how in ("timeout", "assert") or (how == "idle" and expect_prompt):
|
|
610
|
+
assertion = self._find_assertion(text)
|
|
611
|
+
if assertion is not None:
|
|
612
|
+
raise ConsoleAssertionFailed(line, assertion)
|
|
613
|
+
raise ConsoleTimeout(line, text, timeout)
|
|
614
|
+
|
|
615
|
+
if raise_on_error:
|
|
616
|
+
self._raise_for_error(line, result)
|
|
617
|
+
return result
|
|
618
|
+
|
|
619
|
+
def _parse_frame(
|
|
620
|
+
self, line: str, text: str, how: str, before: Iterable[LogLine]
|
|
621
|
+
) -> CommandResult:
|
|
622
|
+
"""Split one frame into reply lines, a return code and log lines.
|
|
623
|
+
|
|
624
|
+
Pure apart from recording log lines, and the reason the whole
|
|
625
|
+
interleaving story is testable: hand it a frame with a heartbeat burst
|
|
626
|
+
spliced into the middle and the burst comes out in ``logs``.
|
|
627
|
+
"""
|
|
628
|
+
body = text[: -len(PROMPT.decode())] if how == "prompt" else text
|
|
629
|
+
parts = body.replace("\r\n", "\n").replace("\r", "\n").split("\n")
|
|
630
|
+
|
|
631
|
+
# 2. the echo anchors the start of the reply.
|
|
632
|
+
echoed = False
|
|
633
|
+
pre: list[str] = []
|
|
634
|
+
while parts:
|
|
635
|
+
head = parts.pop(0)
|
|
636
|
+
if head.strip().lower() == line.strip().lower():
|
|
637
|
+
echoed = True
|
|
638
|
+
break
|
|
639
|
+
pre.append(head)
|
|
640
|
+
if not echoed:
|
|
641
|
+
# No echo: the stream was out of sync. Keep everything as reply
|
|
642
|
+
# candidates rather than throwing the answer away.
|
|
643
|
+
parts = pre + parts
|
|
644
|
+
pre = []
|
|
645
|
+
|
|
646
|
+
during: list[LogLine] = list(before)
|
|
647
|
+
for stray in pre:
|
|
648
|
+
if stray.strip():
|
|
649
|
+
during.append(self._emit_log(stray.rstrip(), line))
|
|
650
|
+
|
|
651
|
+
# 3. classify, and pull the return code out wherever it sits.
|
|
652
|
+
lines: list[str] = []
|
|
653
|
+
rv: int | None = None
|
|
654
|
+
for part in parts:
|
|
655
|
+
stripped = part.strip()
|
|
656
|
+
if not stripped or stripped == ">":
|
|
657
|
+
continue
|
|
658
|
+
match = _RV_RE.match(stripped)
|
|
659
|
+
if match is not None:
|
|
660
|
+
rv = int(match.group("value"), 0)
|
|
661
|
+
continue
|
|
662
|
+
if classify(stripped, self.log_patterns):
|
|
663
|
+
during.append(self._emit_log(part.rstrip(), line))
|
|
664
|
+
continue
|
|
665
|
+
lines.append(stripped)
|
|
666
|
+
|
|
667
|
+
return CommandResult(
|
|
668
|
+
command=line,
|
|
669
|
+
raw=text,
|
|
670
|
+
lines=tuple(lines),
|
|
671
|
+
rv=rv,
|
|
672
|
+
logs=tuple(during),
|
|
673
|
+
echoed=echoed,
|
|
674
|
+
terminated_by=how,
|
|
675
|
+
)
|
|
676
|
+
|
|
677
|
+
@staticmethod
|
|
678
|
+
def _find_assertion(text: str) -> str | None:
|
|
679
|
+
for part in text.replace("\r\n", "\n").split("\n"):
|
|
680
|
+
match = _ASSERT_RE.match(part.strip())
|
|
681
|
+
if match is not None:
|
|
682
|
+
return match.group("where")
|
|
683
|
+
return None
|
|
684
|
+
|
|
685
|
+
@staticmethod
|
|
686
|
+
def _raise_for_error(line: str, result: CommandResult) -> None:
|
|
687
|
+
for reply in result.lines:
|
|
688
|
+
match = _UNKNOWN_RE.match(reply)
|
|
689
|
+
if match is not None:
|
|
690
|
+
raise UnknownCommand(match.group("cmd"))
|
|
691
|
+
if reply == _BAD_PARAMS:
|
|
692
|
+
raise IncorrectParameters(line)
|
|
693
|
+
|
|
694
|
+
# ------------------------------------------------------------- convenience
|
|
695
|
+
|
|
696
|
+
def exists(self, command: str) -> bool:
|
|
697
|
+
"""Probe whether the firmware has *command*, by sending it bare.
|
|
698
|
+
|
|
699
|
+
The oracle: a command the firmware does not have answers
|
|
700
|
+
``Command '<x>' not recognised.``, while one it *does* have but was
|
|
701
|
+
handed no arguments answers ``E: Invalid argument(s)`` or
|
|
702
|
+
``Incorrect command parameter(s).`` That is how ``wifi_ssid_set`` was
|
|
703
|
+
shown to exist despite ``help`` never printing it, and how the 49
|
|
704
|
+
entries in :data:`~pyvisionect.io.usb.commands.PROBED_ABSENT_7_4_4407`
|
|
705
|
+
were shown not to.
|
|
706
|
+
|
|
707
|
+
.. danger::
|
|
708
|
+
|
|
709
|
+
**Only safe for a command that takes at least one required
|
|
710
|
+
argument.** Argument validation then rejects the call before the
|
|
711
|
+
command body runs. Sent bare, a *nullary* command is not rejected
|
|
712
|
+
-- it **executes**, and the nullary members of this firmware's
|
|
713
|
+
command set include ``fs_format``, ``cc3100_format``, ``scpu_reset``,
|
|
714
|
+
``scpu_upgrade``, ``vcom_test`` and ``24aa256_test``.
|
|
715
|
+
|
|
716
|
+
So establish the arity from the vendor reference first and skip
|
|
717
|
+
anything you cannot establish. Do not infer it from the name, and do
|
|
718
|
+
not trust this firmware's own ``help``, which lists
|
|
719
|
+
``max17135_dump`` as nullary although it rejects a bare call.
|
|
720
|
+
|
|
721
|
+
Prefer :meth:`pyvisionect.io.usb.device.Sign.has` once ``help`` has been
|
|
722
|
+
read: it costs nothing and risks nothing. Reach for this only to test
|
|
723
|
+
whether an *unlisted* command is nevertheless present.
|
|
724
|
+
"""
|
|
725
|
+
result = self.command(command, raise_on_error=False)
|
|
726
|
+
return not any(_UNKNOWN_RE.match(reply) for reply in result.lines)
|
|
727
|
+
|
|
728
|
+
def help_text(self) -> str:
|
|
729
|
+
"""The raw ``help`` output. ~5 KB on firmware 7.4.4407."""
|
|
730
|
+
return self.command("help").text
|