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,1043 @@
1
+ """The sans-io device connection state machine.
2
+
3
+ Contract
4
+ --------
5
+
6
+ ::
7
+
8
+ conn = DeviceConnection(store=DeviceStateStore())
9
+ events = conn.feed(data) # bytes in -> list[Event]
10
+ out = conn.drain() # -> bytes the caller must send
11
+ events = conn.advance(now) # timers, with the clock passed in
12
+ conn.send_image(frame) # queues; no I/O
13
+
14
+ Nothing in this module (or anywhere under ``wire/``, ``packets/``, ``session/``,
15
+ ``devices/``) imports ``socket`` or ``asyncio``, or calls ``time.time()``. There
16
+ is a test that enforces that by AST-scanning the package.
17
+
18
+ We are the server
19
+ -----------------
20
+
21
+ The sign is a client. It dials out to TCP 11113 and speaks first; there is no
22
+ handshake, no auth and no negotiation. So this object is driven by whatever the
23
+ device sends, and the only thing it must do unprompted is ack.
24
+
25
+ Timers
26
+ ------
27
+
28
+ Two independent ones, plus a read timeout:
29
+
30
+ * **Device heartbeat** -- device-driven, interval = TCLV parameter 29, and the
31
+ device announces ``NextStatus`` (status tag 27, in **minutes**) in every
32
+ status. We only watch it; :class:`~pyvisionect.session.events.HeartbeatOverdue`
33
+ is advisory.
34
+ * **Server inactivity watchdog** -- ``DeviceStatePolling`` minutes plus
35
+ ``rand(0..10 s)`` of jitter, falling back to 900 s when the config value is 0
36
+ (``pv3.go:1122-1131``). Reset on every received **status** packet, not on any
37
+ packet. On expiry the gateway sends ``Command{Type: 11}`` ("status request")
38
+ and closes the connection if that request fails.
39
+ Firmware revisions **at or below 269** get no watchdog at all
40
+ (``pv3.go:1049``); the live sign reports 7.4.4407, so it does.
41
+ * **Read timeout** -- ``PacketTimeout``, config default **300 s**
42
+ (``Configuration`` offset 192, ``cfg.go:239-240``).
43
+ """
44
+
45
+ from __future__ import annotations
46
+
47
+ import random
48
+ from dataclasses import dataclass
49
+ from typing import Any, Callable, Iterable, Sequence
50
+
51
+ from ..devices.enums import CommandType, ControlFlags, PacketType
52
+ from ..packets import (
53
+ FILE_LIST_LENGTH,
54
+ FILE_LIST_PATH,
55
+ ButtonPacket,
56
+ CborPacket,
57
+ CommandPacket,
58
+ ControlPacket,
59
+ FilePacket,
60
+ GpsPacket,
61
+ ImagePacket,
62
+ ParamPacket,
63
+ Rectangle,
64
+ StatusPacket,
65
+ TouchPacket,
66
+ decode_payload,
67
+ screen_cache_name,
68
+ )
69
+ from ..devices.enums import FileMode
70
+ from ..wire import (
71
+ Compression,
72
+ DataHeader,
73
+ Direction,
74
+ Frame,
75
+ FrameDecoder,
76
+ ProtocolError,
77
+ encode_frame,
78
+ lz4_compress_block,
79
+ )
80
+ from ..wire.errors import CommandPacketsDisabled
81
+ from . import events as ev
82
+ from .device import DeviceState, DeviceStateStore
83
+ from .pending import (
84
+ PENDING_ORDER,
85
+ SLOT_FLASH_SAVE,
86
+ SLOT_GHOST_CLEAR,
87
+ SLOT_IMAGE,
88
+ SLOT_PARAM_READS,
89
+ SLOT_PARAM_WRITES,
90
+ SLOT_REBOOT,
91
+ SLOT_SLEEP,
92
+ TCLV_CMD_FLASH_SAVE,
93
+ PendingWork,
94
+ )
95
+
96
+ __all__ = [
97
+ "DEFAULT_PACKET_TIMEOUT",
98
+ "DEFAULT_DEVICE_STATE_POLLING",
99
+ "WATCHDOG_FALLBACK",
100
+ "WATCHDOG_JITTER_MAX",
101
+ "MIN_WATCHDOG_FIRMWARE_REVISION",
102
+ "ConnectionConfig",
103
+ "DeviceConnection",
104
+ "SLEEP_MIN_MINUTES",
105
+ ]
106
+
107
+ SLEEP_MIN_MINUTES = 1
108
+ """``stdcmd.Sleep.Done`` rejects a zero duration with ``errSleepTime``."""
109
+
110
+ DEFAULT_PACKET_TIMEOUT = 300.0
111
+ """``Global.PacketTimeout``, template default 300 s (``Configuration`` offset 192)."""
112
+
113
+ DEFAULT_DEVICE_STATE_POLLING = 15
114
+ """``Global.DeviceStatePolling``, in **minutes**; template default 15
115
+ (``main.go:382-383`` ``MOVQ $0xf, Config+232``)."""
116
+
117
+ WATCHDOG_FALLBACK = 900.0
118
+ """The hardcoded fallback when ``DeviceStatePolling == 0``: ``0xd18c2e2800`` ns."""
119
+
120
+ WATCHDOG_JITTER_MAX = 10.0
121
+ """``rand.Intn(10000)`` milliseconds of jitter (``pv3.go:1129``/``:1131``)."""
122
+
123
+ MIN_WATCHDOG_FIRMWARE_REVISION = 269
124
+ """``pv3.go:1049``: ``if fwVersion.Revision <= 269 { return nil }`` -- no watchdog."""
125
+
126
+
127
+ @dataclass(slots=True)
128
+ class ConnectionConfig:
129
+ """Knobs that map 1:1 onto the vendor's ``common.Configuration`` fields."""
130
+
131
+ packet_timeout: float = DEFAULT_PACKET_TIMEOUT
132
+ device_state_polling_minutes: int = DEFAULT_DEVICE_STATE_POLLING
133
+ strict: bool = False
134
+ """Verify the inbound checksum and block-chain invariants. Off by default;
135
+ the real gateway validates neither."""
136
+ compression: int = Compression.LZ4
137
+ """What the gateway always does, even for an 8-byte ack.
138
+
139
+ ``Compression.NONE`` on the **outbound** path is unverified: the gateway was
140
+ never observed sending an uncompressed frame to a device, so whether the
141
+ firmware accepts one is unknown. To drop the LZ4 dependency, keep
142
+ ``Compression.LZ4`` here and set :attr:`compressor` to
143
+ :data:`~pyvisionect.wire.STORED_ONLY` instead -- that produces an ordinary
144
+ block chain with every block ``Stored=1``, which is a code path the device
145
+ demonstrably handles (60 of the captured push's 385 blocks were stored).
146
+ """
147
+
148
+ compressor: Callable[[bytes], bytes] = lz4_compress_block
149
+ """Per-block compressor.
150
+
151
+ :data:`~pyvisionect.wire.STORED_ONLY` emits every block uncompressed and
152
+ needs no ``lz4`` install. The captured push shows LZ4 buying almost nothing
153
+ on dithered halftone data (mean ratio 0.956), so the trade is roughly 4%
154
+ more bytes for zero C extensions.
155
+ """
156
+
157
+ allow_command_packets: bool = True
158
+ """Whether ``packet.Type 2`` (command) may be sent at all.
159
+
160
+ Set ``False`` for a "safe mode" that guarantees none are emitted. **Two of
161
+ the 24 command ids have been observed on the wire** -- ``sleep`` (4) and
162
+ ``status request`` (11), captured 2026-10-05 -- which settles the 12-byte
163
+ header for all of them but leaves the other 22 ids' payloads and effects
164
+ code-read only. See the note at the top of
165
+ :mod:`pyvisionect.packets.misc` for why that is still worth being careful
166
+ about.
167
+ """
168
+ ack_handled_packets: bool = True
169
+ """Ack every packet we handle, as every vendor handler does."""
170
+ require_first_status: bool = True
171
+ """``main.ErrNotFirstStatusPacket``: the first packet of a connection must be
172
+ a status packet."""
173
+ watchdog_enabled: bool = True
174
+
175
+
176
+ def _random_server_id() -> int:
177
+ """Server-originated packet IDs are a random uint32.
178
+
179
+ ``Conn.SetSecurity`` uses ``math/rand/v2`` and takes the high 32 bits
180
+ (``rand.go:274`` then ``SHRQ $0x20``). Captured examples: ``0x3FA3A4F1``,
181
+ ``0x691DED39``, ``0xD35B7CC1``.
182
+ """
183
+ return random.getrandbits(32)
184
+
185
+
186
+ def _random_jitter() -> float:
187
+ return random.uniform(0.0, WATCHDOG_JITTER_MAX)
188
+
189
+
190
+ def _perturb_checksum(checksum: int) -> int:
191
+ """Return a value that cannot equal *checksum*, for the full-screen lever.
192
+
193
+ The device stores the ``ImageHeader.Checksum`` of the last frame it applied
194
+ and reports it back as ``DisplayStateCRC``. Sending a tag it cannot already
195
+ hold is the verified way to guarantee the frame is treated as new. ``0`` is
196
+ avoided because the vendor reserves it for "unknown" (it remaps a computed
197
+ 0 to 1).
198
+ """
199
+ out = (checksum ^ 0x8000_0000) & 0xFFFFFFFF
200
+ return out or 1
201
+
202
+
203
+ class DeviceConnection:
204
+ """One TCP connection to one sign. Pure.
205
+
206
+ Args:
207
+ store: the per-UUID durable state map. Share one across connections so a
208
+ reconnect keeps its state. A private one is created if omitted.
209
+ config: timer and strictness knobs.
210
+ id_source: callable returning the next server-originated packet ID.
211
+ Injectable for deterministic tests.
212
+ jitter: callable returning the watchdog's 0..10 s jitter. Injectable.
213
+ """
214
+
215
+ def __init__(
216
+ self,
217
+ *,
218
+ store: DeviceStateStore | None = None,
219
+ config: ConnectionConfig | None = None,
220
+ id_source: Callable[[], int] = _random_server_id,
221
+ jitter: Callable[[], float] = _random_jitter,
222
+ ) -> None:
223
+ self.store = store if store is not None else DeviceStateStore()
224
+ self.config = config or ConnectionConfig()
225
+ self._id_source = id_source
226
+ self._jitter = jitter
227
+
228
+ self._decoder = FrameDecoder(
229
+ Direction.DEVICE_TO_SERVER, strict=self.config.strict
230
+ )
231
+ self._out = bytearray()
232
+ self._device_id: bytes | None = None
233
+ self._state: DeviceState | None = None
234
+ self._seen_first_packet = False
235
+ self._pending: dict[int, str] = {}
236
+ """Outstanding server-originated request IDs -> a short description."""
237
+
238
+ self._last_status_at: float | None = None
239
+ self._last_frame_at: float | None = None
240
+ self._watchdog_deadline: float | None = None
241
+ self._read_deadline: float | None = None
242
+ self._heartbeat_deadline: float | None = None
243
+ self._closed = False
244
+
245
+ # ------------------------------------------------------------ identity
246
+
247
+ @property
248
+ def device_id(self) -> bytes | None:
249
+ """The 16 UUID bytes, once the first status packet has arrived."""
250
+ return self._device_id
251
+
252
+ @property
253
+ def state(self) -> DeviceState | None:
254
+ """The durable per-UUID state, once the device has identified itself."""
255
+ return self._state
256
+
257
+ @property
258
+ def closed(self) -> bool:
259
+ return self._closed
260
+
261
+ @property
262
+ def pending_requests(self) -> dict[int, str]:
263
+ return dict(self._pending)
264
+
265
+ # ------------------------------------------------------------- sans-io
266
+
267
+ def feed(self, data: bytes) -> list[ev.Event]:
268
+ """Consume *data* and return the resulting events.
269
+
270
+ Does not raise on a protocol violation: it emits
271
+ :class:`~pyvisionect.session.events.ProtocolViolation` and marks the
272
+ connection closed, because the caller owns the socket.
273
+ """
274
+ out: list[ev.Event] = []
275
+ try:
276
+ frames = self._decoder.feed(data)
277
+ except ProtocolError as exc:
278
+ self._closed = True
279
+ return [
280
+ ev.ProtocolViolation(
281
+ reason=str(exc), error=exc, device_id=self._device_id or b""
282
+ )
283
+ ]
284
+ for frame in frames:
285
+ out.extend(self._handle_frame(frame))
286
+ return out
287
+
288
+ def drain(self) -> bytes:
289
+ """Return and clear the bytes queued for the wire."""
290
+ data = bytes(self._out)
291
+ self._out.clear()
292
+ return data
293
+
294
+ @property
295
+ def pending_bytes(self) -> int:
296
+ return len(self._out)
297
+
298
+ def advance(self, now: float) -> list[ev.Event]:
299
+ """Run the timers against the caller's clock.
300
+
301
+ *now* is a monotonic-ish float in seconds. The library never reads a
302
+ clock itself; this is the only way time enters it.
303
+ """
304
+ out: list[ev.Event] = []
305
+ if self._last_frame_at is None:
306
+ # Arm the deadlines on the first advance() so a caller that never
307
+ # calls feed() still gets a read timeout.
308
+ self._last_frame_at = now
309
+ self._read_deadline = now + self.config.packet_timeout
310
+
311
+ if self._read_deadline is not None and now >= self._read_deadline:
312
+ quiet = now - (self._last_frame_at or now)
313
+ self._read_deadline = None
314
+ out.append(ev.ReadTimeout(quiet_for=quiet, device_id=self._device_id or b""))
315
+
316
+ if (
317
+ self._heartbeat_deadline is not None
318
+ and now >= self._heartbeat_deadline
319
+ and self._last_status_at is not None
320
+ ):
321
+ expected = self._heartbeat_deadline - self._last_status_at
322
+ self._heartbeat_deadline = None
323
+ out.append(
324
+ ev.HeartbeatOverdue(
325
+ expected_within=expected,
326
+ quiet_for=now - self._last_status_at,
327
+ device_id=self._device_id or b"",
328
+ )
329
+ )
330
+
331
+ if self._watchdog_deadline is not None and now >= self._watchdog_deadline:
332
+ quiet = now - (self._last_status_at or now)
333
+ self._arm_watchdog(now)
334
+ self.request_status()
335
+ out.append(
336
+ ev.WatchdogFired(quiet_for=quiet, device_id=self._device_id or b"")
337
+ )
338
+
339
+ return out
340
+
341
+ def next_deadline(self) -> float | None:
342
+ """The earliest armed deadline, so an event loop can sleep until it."""
343
+ candidates = [
344
+ d
345
+ for d in (
346
+ self._read_deadline,
347
+ self._watchdog_deadline,
348
+ self._heartbeat_deadline,
349
+ )
350
+ if d is not None
351
+ ]
352
+ return min(candidates) if candidates else None
353
+
354
+ # ----------------------------------------------------------- queueing
355
+
356
+ def send(self, packet_type: int, payload: bytes, *, packet_id: int | None = None,
357
+ description: str = "") -> int:
358
+ """Queue one frame and return its packet ID.
359
+
360
+ Raises:
361
+ RuntimeError: if the device has not identified itself yet. We cannot
362
+ address a frame without its UUID.
363
+ """
364
+ if self._device_id is None:
365
+ raise RuntimeError(
366
+ "the device has not sent its first status packet yet, so its UUID "
367
+ "is unknown and no frame can be addressed to it"
368
+ )
369
+ pid = self._id_source() if packet_id is None else packet_id
370
+ header = DataHeader(
371
+ device_id=self._device_id, type=packet_type, id=pid, length=len(payload)
372
+ )
373
+ self._out += encode_frame(
374
+ header,
375
+ payload,
376
+ direction=Direction.SERVER_TO_DEVICE,
377
+ compression=self.config.compression,
378
+ compressor=self.config.compressor,
379
+ )
380
+ if description:
381
+ self._pending[pid] = description
382
+ return pid
383
+
384
+ # -- control ---------------------------------------------------------
385
+
386
+ def write_control(self, packet_id: int, flags: int) -> None:
387
+ """``main.(*pv3Connection).WriteControl``.
388
+
389
+ ``packet_id == 0xFFFFFFFF`` is a no-op, exactly as ``pv3.go:512``.
390
+ """
391
+ if packet_id == 0xFFFFFFFF:
392
+ return
393
+ self.send(PacketType.CONTROL, ControlPacket(flags=flags).encode(),
394
+ packet_id=packet_id)
395
+
396
+ def ack(self, packet_id: int) -> None:
397
+ """``Control{Flags: 1}`` echoing *packet_id*."""
398
+ self.write_control(packet_id, ControlFlags.ACK)
399
+
400
+ def nack(self, packet_id: int) -> None:
401
+ """``Control{Flags: 0}`` -- what the dispatcher sends for an unknown type."""
402
+ self.write_control(packet_id, 0)
403
+
404
+ # -- commands --------------------------------------------------------
405
+
406
+ def send_command(self, command_type: int, payload: bytes = b"") -> int:
407
+ """Queue a ``packet.Command`` (type 2, server to device only).
408
+
409
+ .. note:: **The framing is verified; most of the command ids are
410
+ not.** Two type-2 frames were captured on 2026-10-05 -- ``sleep``
411
+ (4) and ``status request`` (11) -- and
412
+ :class:`~pyvisionect.packets.CommandPacket` decoded both unmodified,
413
+ ``Reserved`` included, so the 12-byte ``CommandHeader`` this emits is
414
+ right. What remains unverified is the payload and effect of the other
415
+ 22 ids. See :mod:`pyvisionect.packets.misc`.
416
+
417
+ Raises:
418
+ CommandPacketsDisabled: if
419
+ ``ConnectionConfig(allow_command_packets=False)``.
420
+ """
421
+ if not self.config.allow_command_packets:
422
+ raise CommandPacketsDisabled(
423
+ f"refusing to send packet type 2 (command "
424
+ f"{CommandType.NAMES.get(command_type, command_type)}): "
425
+ "ConnectionConfig(allow_command_packets=False). Only "
426
+ "sleep (4) and status request (11) have ever been seen on the "
427
+ "wire; the other 22 ids have never been observed, which is "
428
+ "what this switch is for."
429
+ )
430
+ name = CommandType.NAMES.get(command_type, f"command({command_type})")
431
+ return self.send(
432
+ PacketType.COMMAND,
433
+ CommandPacket(type=command_type, payload=payload).encode(),
434
+ description=name,
435
+ )
436
+
437
+ def request_status(self) -> int:
438
+ """``CommandType 11`` -- what the watchdog sends on expiry.
439
+
440
+ **Captured on the wire** (2026-10-05): ``0b000000 00000000 00000000``,
441
+ i.e. 12 bytes of header with ``PayloadLength = 0`` and no payload. The
442
+ device logs ``Command status get received`` and answers with an
443
+ unsolicited status packet carrying ``ConnectReason == 8`` ("by server
444
+ request"), on top of the ordinary ``Control{Flags: 1}`` ack. The vendor's
445
+ emitter is the inactivity watchdog (``(*ping).resumePing.func1.1``,
446
+ ``pv3.go:1087-1088``).
447
+ """
448
+ return self.send_command(CommandType.STATUS_REQUEST)
449
+
450
+ def reboot(self) -> int:
451
+ """``CommandType 1``.
452
+
453
+ ``1`` is reboot and ``0`` is echo, in both the v1 and the v2 enum --
454
+ ``bin/networkmanager``'s ``main.(*Panda).Reboot`` writes ``Command = 1``
455
+ with a 4-byte payload. An earlier revision of this library had the two
456
+ swapped, so this call would have sent ``echo``.
457
+
458
+ .. warning:: Never observed on the wire. Worth noting that a reboot
459
+ *is* observable after the fact: the device reconnects with
460
+ ``ConnectReason == 1`` (reboot), which
461
+ :attr:`~pyvisionect.packets.StatusPacket.connect_reason_name`
462
+ reports. That is the cheapest confirmation available that the command
463
+ landed.
464
+ """
465
+ return self.send_command(CommandType.REBOOT)
466
+
467
+ def refresh(self) -> int:
468
+ """``CommandType -1`` ("refresh").
469
+
470
+ .. warning:: **No emission site for this id exists anywhere in the
471
+ vendor server.** It is an entry in ``packet.CommandType.String``'s
472
+ jump table and nothing more -- nothing in the suite ever sends it.
473
+ Prefer the verified route: re-encode with
474
+ ``encode_frame(force_full_screen=True)`` and push. See
475
+ :meth:`send_image`, which documents both full-screen levers.
476
+ """
477
+ return self.send_command(CommandType.REFRESH)
478
+
479
+ def clear_screen(self) -> int:
480
+ """``CommandType -2`` ("clear screen").
481
+
482
+ .. warning:: Like :meth:`refresh`, an enum entry with **no emission
483
+ site in the vendor server**. The verified way to blank the panel is
484
+ to push a white full-screen frame.
485
+ """
486
+ return self.send_command(CommandType.CLEAR_SCREEN)
487
+
488
+ def sleep(self, minutes: int) -> int:
489
+ """``CommandType 4`` -- deep-sleep for *minutes*.
490
+
491
+ **Captured on the wire** (2026-10-05):
492
+ ``04000000 04000000 00000000 8e030000`` -- the 12-byte header plus one
493
+ little-endian uint32 of minutes, 910 in that frame. The device logged
494
+ ``Command sleep received`` / ``Wake after 910 minutes!`` and slept. The
495
+ server-side builder is ``stdcmd.Sleep.Done``
496
+ (``vss/pkg/command/stdcmd/sleep.go:30-38``), which rejects
497
+ ``duration == 0`` with ``errSleepTime``.
498
+
499
+ **Order this last-but-one.** The device leaves when it gets this, so the
500
+ image bytes have to be on the wire first. :meth:`apply_pending` enforces
501
+ that ordering; if you queue by hand, do the same.
502
+
503
+ There is **no network route to wake the device early** -- nothing can be
504
+ pushed to it while it sleeps. ``app_wakeup`` on the USB console is the
505
+ one early-wake route that works: it recovered the reference sign from a
506
+ 910-minute deep sleep on the spot, twice, and the sign reconnected with
507
+ ``ConnectReason`` ``"wakeup"``.
508
+
509
+ Args:
510
+ minutes: a positive number of minutes.
511
+
512
+ Raises:
513
+ ValueError: for ``minutes <= 0``, matching ``errSleepTime``.
514
+ """
515
+ if int(minutes) < SLEEP_MIN_MINUTES:
516
+ raise ValueError(
517
+ f"sleep duration must be at least {SLEEP_MIN_MINUTES} minute, "
518
+ f"got {minutes!r}; the vendor rejects 0 with errSleepTime"
519
+ )
520
+ return self.send_command(
521
+ CommandType.SLEEP, int(minutes).to_bytes(4, "little")
522
+ )
523
+
524
+ def set_heartbeat(self, minutes: int) -> int:
525
+ """``CommandType 7``. The same setting as TCLV parameter 29.
526
+
527
+ .. warning:: Never observed on the wire. The type-2 framing is
528
+ settled, but this id's payload is read out of the binary only.
529
+ Writing TCLV 29 with :meth:`write_params` is the attested route --
530
+ the param channel was captured end to end.
531
+ """
532
+ return self.send_command(
533
+ CommandType.SET_HEARTBEAT, int(minutes).to_bytes(4, "little")
534
+ )
535
+
536
+ # -- params ----------------------------------------------------------
537
+
538
+ def read_params(self, ids: Sequence[int]) -> int:
539
+ """Queue a TCLV read for *ids*."""
540
+ return self.send(
541
+ PacketType.PARAM,
542
+ ParamPacket.read(list(ids)).encode(),
543
+ description=f"param read {list(ids)}",
544
+ )
545
+
546
+ def write_params(
547
+ self, values: dict[int, int | str | bytes], *, allow_read_only: bool = False
548
+ ) -> int:
549
+ """Queue a TCLV write.
550
+
551
+ Raises:
552
+ ReadOnlyParameter: for any of the eight network-read-only ids, with
553
+ the USB command that can set it instead.
554
+ """
555
+ packet = ParamPacket.write(values, allow_read_only=allow_read_only)
556
+ return self.send(
557
+ PacketType.PARAM,
558
+ packet.encode(),
559
+ description=f"param write {sorted(values)}",
560
+ )
561
+
562
+ # -- files -----------------------------------------------------------
563
+
564
+ def file_open(self, filename: str, mode: int = FileMode.READ) -> int:
565
+ return self.send(
566
+ PacketType.FILE,
567
+ FilePacket.open(filename, mode).encode(),
568
+ description=f"file open {filename!r}",
569
+ )
570
+
571
+ def file_close(self) -> int:
572
+ return self.send(
573
+ PacketType.FILE, FilePacket.close().encode(), description="file close"
574
+ )
575
+
576
+ def file_read(self, length: int) -> int:
577
+ return self.send(
578
+ PacketType.FILE,
579
+ FilePacket.read(length).encode(),
580
+ description=f"file read {length}",
581
+ )
582
+
583
+ def file_write(self, data: bytes) -> int:
584
+ return self.send(
585
+ PacketType.FILE,
586
+ FilePacket.write(data).encode(),
587
+ description=f"file write {len(data)}B",
588
+ )
589
+
590
+ def file_erase(self, filename: str) -> int:
591
+ return self.send(
592
+ PacketType.FILE,
593
+ FilePacket.erase(filename).encode(),
594
+ description=f"file erase {filename!r}",
595
+ )
596
+
597
+ def file_list(self) -> int:
598
+ """List the device's filesystem root.
599
+
600
+ **There is no ``list`` opcode.** ``packet.FileOperation`` is
601
+ ``0 open, 1 close, 2 read, 3 write, 4 erase, 5 write-descriptor,
602
+ 6 event`` -- and the vendor's directory listing is a plain
603
+ ``Read(".", 10240)``: a path of ``"/"`` or ``""`` is rewritten to the
604
+ one-byte string ``"."``. The reply is an ASCII blob that ``vio.GetFiles``
605
+ splits on newline, then on space, into ``{name: {size, checksum}}``.
606
+ :func:`~pyvisionect.packets.parse_file_listing` does that parsing for
607
+ you. This method queues only the ``open``; once it is acked, follow with
608
+ ``read_file_range(FILE_LIST_LENGTH)`` and parse the reply.
609
+
610
+ Note the listing's ``checksum`` column reads ``"0"`` for every file on
611
+ this firmware, so it identifies nothing. To tell *which* cached frame is
612
+ which, read the first ~256 bytes of each ``.pv2`` and match the stored
613
+ ``ImageHeader.Checksum`` against :attr:`DeviceState.pushed_checksum` --
614
+ a value we generated ourselves, so it is a match rather than a guess.
615
+ """
616
+ return self.send(
617
+ PacketType.FILE,
618
+ FilePacket.open(FILE_LIST_PATH, FileMode.READ).encode(),
619
+ description=f"file list {FILE_LIST_PATH!r}",
620
+ )
621
+
622
+ def read_file_range(self, length: int) -> int:
623
+ """Read at most *length* bytes from the open file.
624
+
625
+ A short read is the point: identifying a cached frame needs ~256 bytes
626
+ (``ProtocolHeader`` -> block 0 -> ``DataHeader`` + ``ImageHeader`` +
627
+ both ``RectangleHeader``s all live in the first block), not the whole
628
+ file. Six 256-byte probes instead of a 3.79 MB sweep, on a link that
629
+ exists for minutes a day.
630
+ """
631
+ return self.file_read(length)
632
+
633
+ def open_screen_cache(self, screen_id: int) -> int:
634
+ """Open ``@screen_<N>`` for reading.
635
+
636
+ .. note::
637
+ This is the vendor's **live-view** path, not part of the image-update
638
+ path. The only reference to ``"@screen_2"`` in the whole gateway
639
+ binary is a hardcoded literal inside
640
+ ``main.(*grpcHandlers).handleLiveView`` (``grpc_handlers.go:240``) --
641
+ not even a ``@screen_%d`` format. The 32" sign NACKs it with
642
+ ``0x00008a00`` because this firmware does not implement that
643
+ filename; the admin UI only offers the button for
644
+ ``HardwareNameID`` in {11, 13, 24, 34, 42}. It says nothing about
645
+ update strategy.
646
+ """
647
+ return self.file_open(screen_cache_name(screen_id), FileMode.READ)
648
+
649
+ # -- images ----------------------------------------------------------
650
+
651
+ def send_image(
652
+ self,
653
+ frame: Any,
654
+ *,
655
+ options: int = 0,
656
+ force_full: bool = False,
657
+ checksum_override: int | None = None,
658
+ now: float | None = None,
659
+ ) -> int:
660
+ """Queue an image push from an :class:`~pyvisionect.imaging.EncodedFrame`.
661
+
662
+ Accepts any object with ``.rectangles`` (each having ``x``, ``y``, ``w``,
663
+ ``h``, ``screen_id``, ``options``, ``data``) and ``.state_checksum`` --
664
+ i.e. the imaging module's output, without importing it.
665
+
666
+ The frame's ``state_checksum`` becomes ``ImageHeader.Checksum``, which is
667
+ what the device echoes back as ``DisplayStateCRC``, and
668
+ ``frame.state`` is stashed in the device's durable state for the next
669
+ call's ``prev_state``.
670
+
671
+ **This is CPU-cheap but memory-heavy and byte-heavy.** A full-screen push
672
+ to the 32" panel is ~1.84 MB. Producing *frame* is the expensive part and
673
+ must not happen on an event loop; see :func:`pyvisionect.imaging.encode_frame`.
674
+
675
+ Forcing a full-screen redraw
676
+ ----------------------------
677
+
678
+ There are two levers, and they are not equivalent:
679
+
680
+ * ``encode_frame(..., force_full_screen=True)`` -- the **verified** one.
681
+ It skips change detection and emits rectangles covering every display,
682
+ so the device repaints everything because it was sent everything.
683
+ * ``force_full=True`` here -- the *checksum* lever. It perturbs
684
+ ``ImageHeader.Checksum`` so it cannot match the tag the device
685
+ currently holds. Verified end to end that the device never refuses a
686
+ mismatched tag, and that a mismatch costs exactly one extra
687
+ full-screen redraw. It does **not** change which pixels are sent, so
688
+ on a partial frame it is not a full repaint on its own.
689
+
690
+ On ``HardwareNameID == 8`` -- the 32" sign -- ``getRectangleSupport``
691
+ returns false unconditionally and every push is full-screen anyway, so
692
+ ``force_full`` is a no-op there. :attr:`DeviceState.supports_rectangles`
693
+ tells you which case you are in.
694
+
695
+ Args:
696
+ options: ``ImageHeader.Options``.
697
+ force_full: perturb the checksum so the device cannot consider
698
+ itself in sync. Mutually exclusive with *checksum_override*.
699
+ checksum_override: send this exact ``ImageHeader.Checksum`` instead
700
+ of the frame's. For replaying a captured push, or for driving
701
+ the mismatch lever by hand.
702
+ now: a clock value, recorded against the push so that
703
+ :meth:`DeviceState.sync_status` can tell "has not answered
704
+ yet" from "is showing the wrong thing". Optional, like
705
+ everywhere else in this library; without it the verdict falls
706
+ back to counting the device's contacts, which needs no clock.
707
+ """
708
+ if force_full and checksum_override is not None:
709
+ raise ValueError(
710
+ "pass force_full or checksum_override, not both: they both set "
711
+ "ImageHeader.Checksum"
712
+ )
713
+ rects = [
714
+ Rectangle(
715
+ x=r.x,
716
+ y=r.y,
717
+ width=r.w,
718
+ height=r.h,
719
+ data=r.data,
720
+ screen_id=r.screen_id,
721
+ encoding=getattr(r, "encoding", 4),
722
+ options=getattr(r, "options", 0),
723
+ )
724
+ for r in frame.rectangles
725
+ ]
726
+ checksum = frame.state_checksum
727
+ if checksum_override is not None:
728
+ checksum = checksum_override & 0xFFFFFFFF
729
+ elif force_full:
730
+ checksum = _perturb_checksum(checksum)
731
+ return self.send_image_packet(
732
+ ImagePacket(checksum=checksum, rectangles=rects, options=options),
733
+ imaging_state=getattr(frame, "state", None),
734
+ now=now,
735
+ )
736
+
737
+ def send_image_packet(
738
+ self,
739
+ packet: ImagePacket,
740
+ *,
741
+ imaging_state: Any = None,
742
+ now: float | None = None,
743
+ ) -> int:
744
+ """Queue an already-built :class:`~pyvisionect.packets.ImagePacket`."""
745
+ pid = self.send(
746
+ PacketType.IMAGE,
747
+ packet.encode(),
748
+ description=f"image push ({len(packet.rectangles)} rects)",
749
+ )
750
+ if self._state is not None:
751
+ self._state.note_push(packet.checksum, now=now)
752
+ if imaging_state is not None:
753
+ self._state.imaging_state = imaging_state
754
+ return pid
755
+
756
+ # ------------------------------------------------------- pending work
757
+
758
+ def apply_pending(
759
+ self,
760
+ work: PendingWork | None = None,
761
+ *,
762
+ now: float | None = None,
763
+ phases: Sequence[str] | None = None,
764
+ ) -> dict[str, int]:
765
+ """Put this device's deferred work on the wire, in the vendor's order.
766
+
767
+ Call this once per connection, right after the first status packet --
768
+ i.e. on a :class:`~pyvisionect.session.events.DeviceConnected` event.
769
+
770
+ The order is :data:`~pyvisionect.session.pending.PENDING_ORDER` and it
771
+ is not arbitrary. In particular **sleep is queued after the image
772
+ bytes** and **reboot is last**: the device leaves when it is told to
773
+ sleep, and nothing survives a reboot. The vendor waits for its renderer
774
+ before publishing its sleep packet for exactly this reason; get it wrong
775
+ and the user stares at yesterday's dashboard for a day. Because
776
+ :meth:`drain` returns bytes in queue order and TCP preserves order,
777
+ queueing sleep after the image *is* "the image lands first".
778
+
779
+ Each slot is recorded as in-flight and clears only when the device acks
780
+ it (feed the library's ``Acked``/``Nacked`` events to
781
+ :meth:`PendingWork.on_acked` / :meth:`PendingWork.on_nacked`), so a
782
+ connection that drops mid-reconcile leaves the remainder queued.
783
+
784
+ Args:
785
+ work: the register to drain. Defaults to this device's own
786
+ (``conn.state.pending``).
787
+ now: a clock value, recorded against each slot. Optional; the
788
+ library never reads a clock itself.
789
+ phases: restrict to these slots, for a caller that wants to await an
790
+ ack between phases. Order is still
791
+ :data:`PENDING_ORDER`, whatever order you pass.
792
+
793
+ Returns:
794
+ ``{slot: packet_id}`` for the work queued by this call.
795
+
796
+ Raises:
797
+ RuntimeError: if the device has not identified itself yet.
798
+ """
799
+ if work is None:
800
+ if self._state is None:
801
+ raise RuntimeError(
802
+ "no device state yet; apply_pending needs the device's first "
803
+ "status packet, or an explicit work= argument"
804
+ )
805
+ work = self._state.pending
806
+
807
+ wanted = set(phases) if phases is not None else None
808
+ sent: dict[str, int] = {}
809
+
810
+ for slot in work.slots():
811
+ if wanted is not None and slot not in wanted:
812
+ continue
813
+ packet_id = self._apply_slot(slot, work, now=now)
814
+ if packet_id is None:
815
+ continue
816
+ sent[slot] = packet_id
817
+ work.note_sent(slot, packet_id, now=now)
818
+ return sent
819
+
820
+ def _apply_slot(
821
+ self, slot: str, work: PendingWork, *, now: float | None = None
822
+ ) -> int | None:
823
+ if slot == SLOT_PARAM_READS:
824
+ return self.read_params(sorted(work.param_reads))
825
+ if slot == SLOT_PARAM_WRITES:
826
+ return self.write_params(dict(work.params))
827
+ if slot == SLOT_FLASH_SAVE:
828
+ # TCLV 53 is a command-shaped parameter: writing it persists
829
+ # everything above. Without it every write is RAM-only.
830
+ return self.write_params({TCLV_CMD_FLASH_SAVE: 1})
831
+ if slot == "framebuffer_read":
832
+ return self.file_list()
833
+ if slot == SLOT_IMAGE:
834
+ return self.send_image(work.frame, force_full=work.force_push, now=now)
835
+ if slot == SLOT_GHOST_CLEAR:
836
+ # An inverse / anti-ghosting pass is a second full-screen push of
837
+ # the same content; the caller supplies the inverse-encoded frame by
838
+ # re-encoding with inverse=True. With only the normal frame in hand
839
+ # the honest thing is to repeat it with the checksum lever set.
840
+ return (
841
+ self.send_image(work.frame, force_full=True, now=now)
842
+ if work.frame
843
+ else None
844
+ )
845
+ if slot == SLOT_SLEEP:
846
+ assert work.sleep_minutes is not None
847
+ return self.sleep(work.sleep_minutes)
848
+ if slot == SLOT_REBOOT:
849
+ return self.reboot()
850
+ raise ValueError(f"unknown slot {slot!r}")
851
+
852
+ # ------------------------------------------------------------ handling
853
+
854
+ def _handle_frame(self, frame: Frame) -> list[ev.Event]:
855
+ out: list[ev.Event] = []
856
+ first = not self._seen_first_packet
857
+ self._seen_first_packet = True
858
+
859
+ if first and self.config.require_first_status:
860
+ if frame.type != PacketType.STATUS:
861
+ self._closed = True
862
+ return [
863
+ ev.ProtocolViolation(
864
+ reason="first packet is not a status packet",
865
+ device_id=frame.device_id,
866
+ )
867
+ ]
868
+
869
+ if self._device_id is None:
870
+ self._device_id = frame.device_id
871
+ self._state = self.store.get(frame.device_id)
872
+ self._state.connections += 1
873
+ elif frame.device_id != self._device_id:
874
+ # One connection carries exactly one UUID in practice. Treat a change
875
+ # as a violation rather than silently re-keying.
876
+ self._closed = True
877
+ return [
878
+ ev.ProtocolViolation(
879
+ reason=(
880
+ f"DeviceID changed mid-connection: "
881
+ f"{self._device_id.hex()} -> {frame.device_id.hex()}"
882
+ ),
883
+ device_id=self._device_id,
884
+ )
885
+ ]
886
+
887
+ try:
888
+ payload = decode_payload(frame.type, frame.payload)
889
+ except ProtocolError as exc:
890
+ out.append(
891
+ ev.ProtocolViolation(
892
+ reason=f"type {frame.type} payload: {exc}",
893
+ error=exc,
894
+ device_id=frame.device_id,
895
+ )
896
+ )
897
+ self.nack(frame.id)
898
+ return out
899
+
900
+ kwargs = {"device_id": frame.device_id, "packet_id": frame.id}
901
+
902
+ if frame.type == PacketType.CONTROL:
903
+ out.extend(self._handle_control(frame, payload))
904
+ return out
905
+
906
+ if payload is None:
907
+ # No handler: NACK, exactly as the dispatcher does at pv3.go:473.
908
+ self.nack(frame.id)
909
+ out.append(
910
+ ev.UnknownPacketType(
911
+ packet_type=frame.type, payload=frame.payload, **kwargs
912
+ )
913
+ )
914
+ return out
915
+
916
+ if frame.type == PacketType.STATUS:
917
+ assert isinstance(payload, StatusPacket)
918
+ if self._state is not None:
919
+ self._state.apply_status(payload)
920
+ if first:
921
+ out.append(
922
+ ev.DeviceConnected(
923
+ status=payload,
924
+ connect_reason=payload.connect_reason,
925
+ **kwargs,
926
+ )
927
+ )
928
+ out.append(ev.StatusReceived(status=payload, **kwargs))
929
+ elif frame.type == PacketType.PARAM:
930
+ assert isinstance(payload, ParamPacket)
931
+ out.append(ev.ParamsReceived(params=payload, **kwargs))
932
+ elif frame.type == PacketType.FILE:
933
+ assert isinstance(payload, FilePacket)
934
+ out.append(ev.FileEventReceived(file=payload, **kwargs))
935
+ elif frame.type == PacketType.TOUCH:
936
+ assert isinstance(payload, TouchPacket)
937
+ out.append(ev.TouchReceived(touch=payload, **kwargs))
938
+ elif frame.type == PacketType.BUTTON:
939
+ assert isinstance(payload, ButtonPacket)
940
+ out.append(ev.ButtonReceived(button=payload, **kwargs))
941
+ elif frame.type == PacketType.GPS:
942
+ assert isinstance(payload, GpsPacket)
943
+ out.append(ev.GpsReceived(gps=payload, **kwargs))
944
+ elif frame.type == PacketType.CBOR:
945
+ assert isinstance(payload, CborPacket)
946
+ out.append(ev.CborReceived(cbor=payload, **kwargs))
947
+ else:
948
+ # A type we can decode but do not route (e.g. command/image echoed
949
+ # back). Ack it; do not pretend to understand it.
950
+ out.append(
951
+ ev.UnknownPacketType(
952
+ packet_type=frame.type, payload=frame.payload, **kwargs
953
+ )
954
+ )
955
+
956
+ if self.config.ack_handled_packets:
957
+ self.ack(frame.id)
958
+ return out
959
+
960
+ def _handle_control(self, frame: Frame, control: Any) -> list[ev.Event]:
961
+ """``main.(*pv3Connection).handlePacketControl`` (``pv3.go:485-506``).
962
+
963
+ Note we do *not* ack a control packet -- that would loop forever.
964
+ """
965
+ assert isinstance(control, ControlPacket)
966
+ self._pending.pop(frame.id, None)
967
+ if control.is_ack:
968
+ return [
969
+ ev.Acked(packet_id=frame.id, control=control, device_id=frame.device_id)
970
+ ]
971
+ return [
972
+ ev.Nacked(
973
+ packet_id=frame.id,
974
+ control=control,
975
+ charging=control.nack_charging,
976
+ error_code=control.error_code,
977
+ device_id=frame.device_id,
978
+ )
979
+ ]
980
+
981
+ # ------------------------------------------------------------- timers
982
+
983
+ def note_frame(self, now: float) -> None:
984
+ """Record that a frame arrived at *now* (for the read timeout).
985
+
986
+ Called for you by :meth:`feed_at`; exposed separately so a caller that
987
+ already knows its own clock can drive the timers explicitly.
988
+ """
989
+ self._last_frame_at = now
990
+ self._read_deadline = now + self.config.packet_timeout
991
+
992
+ def feed_at(self, data: bytes, now: float) -> list[ev.Event]:
993
+ """:meth:`feed` plus timer bookkeeping against *now*.
994
+
995
+ This is what an io adapter should call.
996
+ """
997
+ self.note_frame(now)
998
+ out = self.feed(data)
999
+ if any(isinstance(e, (ev.StatusReceived, ev.DeviceConnected)) for e in out):
1000
+ self._note_status(now)
1001
+ return out
1002
+
1003
+ def _note_status(self, now: float) -> None:
1004
+ self._last_status_at = now
1005
+ self._arm_watchdog(now)
1006
+ self._arm_heartbeat(now)
1007
+
1008
+ def _watchdog_enabled_for_device(self) -> bool:
1009
+ """``pv3.go:1046-1049``: no version -> no ping; revision <= 269 -> no ping."""
1010
+ if not self.config.watchdog_enabled:
1011
+ return False
1012
+ if self._state is None or self._state.last_status is None:
1013
+ return False
1014
+ version = self._state.last_status.firmware_version
1015
+ if version is None:
1016
+ return False
1017
+ return version[2] > MIN_WATCHDOG_FIRMWARE_REVISION
1018
+
1019
+ def watchdog_timeout(self) -> float:
1020
+ """``main.(*ping).timeoutDuration`` (``pv3.go:1122-1131``)."""
1021
+ minutes = self.config.device_state_polling_minutes
1022
+ base = WATCHDOG_FALLBACK if minutes == 0 else minutes * 60.0
1023
+ return base + self._jitter()
1024
+
1025
+ def _arm_watchdog(self, now: float) -> None:
1026
+ if self._watchdog_enabled_for_device():
1027
+ self._watchdog_deadline = now + self.watchdog_timeout()
1028
+ else:
1029
+ self._watchdog_deadline = None
1030
+
1031
+ def _arm_heartbeat(self, now: float) -> None:
1032
+ """Arm the advisory heartbeat deadline from status tag 27 (minutes)."""
1033
+ if self._state is None or self._state.last_status is None:
1034
+ self._heartbeat_deadline = None
1035
+ return
1036
+ next_status = self._state.last_status.next_status_minutes
1037
+ if not next_status:
1038
+ self._heartbeat_deadline = None
1039
+ return
1040
+ # Allow a generous grace period: the observed cadence is 60.0 s with
1041
+ # NextStatus == 1, so the unit is minutes and one extra minute of slack
1042
+ # costs nothing.
1043
+ self._heartbeat_deadline = now + next_status * 60.0 + 60.0