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,95 @@
1
+ """Control packets (type 1) -- the ack/nack channel.
2
+
3
+ Wire format (``packet/control.go:35-43``), requires ``8 + len(payload)`` bytes::
4
+
5
+ offset size field
6
+ 0 4 Flags uint32 LE (packet.ControlFlags)
7
+ 4 4 Length uint32 LE (= len(Payload))
8
+ 8 ... Payload
9
+
10
+ Semantics
11
+ ---------
12
+
13
+ * ``Flags & 1`` -> **ACK**. ``packet.(*Control).Ack`` is literally ``return flags & 1``.
14
+ * ``Flags == 0`` -> **NACK**. A captured device NACK carries 4 extra bytes of
15
+ error code, e.g. ``0x00008a00`` for "no such file".
16
+ * **Bit 25** (``0x02000000``) -> NACK because the device is charging
17
+ (``vio.ErrNackCharging``, ``pv3.go:498``).
18
+
19
+ The responder echoes the originator's ``DataHeader.ID``. ``ID == 0xFFFFFFFF`` is
20
+ the "do not ack" sentinel in ``WriteControl`` (``pv3.go:512``).
21
+ """
22
+
23
+ from __future__ import annotations
24
+
25
+ import struct
26
+ from dataclasses import dataclass
27
+
28
+ from ..devices.enums import ControlFlags, PacketType
29
+ from ..wire.errors import PayloadError
30
+
31
+ __all__ = ["NO_ACK_ID", "ControlPacket"]
32
+
33
+ NO_ACK_ID = 0xFFFFFFFF
34
+ """``WriteControl`` is a no-op for this id (``pv3.go:512`` ``CMPL BX, $-0x1``)."""
35
+
36
+ _HDR = struct.Struct("<II")
37
+
38
+
39
+ @dataclass(frozen=True, slots=True)
40
+ class ControlPacket:
41
+ """A control payload."""
42
+
43
+ flags: int
44
+ payload: bytes = b""
45
+
46
+ TYPE = PacketType.CONTROL
47
+
48
+ @property
49
+ def is_ack(self) -> bool:
50
+ return bool(self.flags & ControlFlags.ACK)
51
+
52
+ @property
53
+ def is_nack(self) -> bool:
54
+ return not self.is_ack
55
+
56
+ @property
57
+ def nack_charging(self) -> bool:
58
+ """Bit 25: the device refused because it is charging."""
59
+ return bool(self.flags & ControlFlags.NACK_CHARGING)
60
+
61
+ @property
62
+ def error_code(self) -> int | None:
63
+ """The uint32 a device NACK carries in its payload, if any."""
64
+ if len(self.payload) >= 4:
65
+ return int.from_bytes(self.payload[:4], "little")
66
+ return None
67
+
68
+ @classmethod
69
+ def ack(cls) -> "ControlPacket":
70
+ """The ack every handler sends: ``Control{Flags: 1}``, empty payload."""
71
+ return cls(flags=ControlFlags.ACK)
72
+
73
+ @classmethod
74
+ def nack(cls, error_code: int | None = None) -> "ControlPacket":
75
+ """``Flags == 0``; the dispatcher's unknown-packet-type reply."""
76
+ payload = b"" if error_code is None else error_code.to_bytes(4, "little")
77
+ return cls(flags=0, payload=payload)
78
+
79
+ @classmethod
80
+ def decode(cls, payload: bytes) -> "ControlPacket":
81
+ if len(payload) < 8:
82
+ raise PayloadError(f"control payload is {len(payload)} bytes, need >= 8")
83
+ flags, length = _HDR.unpack_from(payload, 0)
84
+ return cls(flags=flags, payload=payload[8 : 8 + length])
85
+
86
+ def encode(self) -> bytes:
87
+ return _HDR.pack(self.flags, len(self.payload)) + self.payload
88
+
89
+ def __str__(self) -> str:
90
+ kind = "ack" if self.is_ack else "nack"
91
+ if self.nack_charging:
92
+ kind = "nack(charging)"
93
+ code = self.error_code
94
+ suffix = f" code=0x{code:08x}" if code is not None else ""
95
+ return f"Control{{{kind} flags=0x{self.flags:08x}{suffix}}}"
@@ -0,0 +1,325 @@
1
+ """File packets (type 10) -- the device's on-flash filesystem.
2
+
3
+ Layout::
4
+
5
+ FileHeader (8 bytes)
6
+ 0 4 Op uint32 LE (packet.FileOperation)
7
+ 4 4 Length uint32 LE (= len of the operation payload)
8
+ 8 ... payload, shape selected by Op through packet.filePayloadFunc
9
+
10
+ Payload shapes:
11
+
12
+ * ``open`` (0): ``Mode uint32`` + NUL-terminated filename
13
+ * ``read`` (2) / ``write`` (3): raw bytes
14
+ * ``erase`` (4): a filename
15
+ * ``write descriptor`` (5): ``Length uint32`` + ``Checksum uint32``
16
+ * ``close`` (1): no payload
17
+ * ``event`` (6): **this is how every reply from the device arrives.**
18
+
19
+ The device answers a read with ``event``, not ``read``
20
+ ------------------------------------------------------
21
+
22
+ Measured against firmware 7.4.4407 on 2026-10-05: every reply the device sends
23
+ -- the directory listing, and every chunk of a file read -- comes back as a
24
+ ``packet.File`` whose ``Op`` is ``6`` (``event``), carrying the bytes verbatim
25
+ as its payload. ``Op 2`` (``read``) is the **request** direction only.
26
+
27
+ That matters because an earlier reading of this module had ``event`` as
28
+ "no payload in the observed traffic" and decoded nothing for it, so
29
+ :meth:`FilePacket.parsed` returned ``None`` for every reply the device ever
30
+ sends and a consumer that checked ``isinstance(parsed, FileBytes)`` silently
31
+ saw an empty filesystem. :data:`_DECODERS` now maps ``event`` to
32
+ :class:`FileBytes`.
33
+
34
+ Reads are capped at 1024 bytes and there is no seek
35
+ ----------------------------------------------------
36
+
37
+ The device honours a read request of up to :data:`DEVICE_FILE_READ_CHUNK`
38
+ bytes and silently truncates anything larger -- asking for 32768 returns 1024.
39
+ There is no seek opcode, so the only cursor control is ``open`` (which rewinds
40
+ to zero) and the implicit advance of each read. A reply that never arrives
41
+ therefore costs the whole transfer: you cannot resume, only restart.
42
+
43
+ Measured throughput is **~2.3 KiB/s** (about 420 ms per 1 KiB round trip), so
44
+ one of this sign's 134 KB-1.2 MB stored frames takes 1-9 minutes. Budget for
45
+ that before exposing a file read to a user.
46
+
47
+ There is no ``list`` opcode
48
+ ---------------------------
49
+
50
+ The vendor's directory listing is a **read of ``"."``**: a path of ``"/"`` or
51
+ ``""`` is rewritten to the one-byte string ``"."``, and ``Read(".", 10240)``
52
+ returns an ASCII blob that ``vio.GetFiles`` splits on newline, then on space,
53
+ into ``{name: {size, checksum}}``. :func:`parse_file_listing` does that.
54
+ The columns are ``name checksum size``, and **the checksum column reads ``"0"``
55
+ for every file on this firmware**, so it identifies nothing. The order was
56
+ confirmed against the files themselves: ``/image0.pv2 0 134409`` and that
57
+ file's own ``ProtocolHeader.Length`` is ``134389``, which is ``134409`` minus
58
+ the 20-byte header -- so the third column is the byte size and the middle one
59
+ is the useless checksum. Reading them the other way round (which this module
60
+ used to do) reports every file as zero bytes long.
61
+
62
+ ``@screen_N`` has nothing to do with image updates
63
+ --------------------------------------------------
64
+
65
+ An earlier reading of this had the gateway opening ``@screen_<N>`` "before
66
+ deciding how to update the screen", making the NACK "the mechanism behind
67
+ incremental updates". **That was wrong**, and it invented a constraint that does
68
+ not exist: the file protocol is not entangled with image pushes at all.
69
+
70
+ A scan of the whole executable segment of ``gateway`` for references to
71
+ ``"@screen_2"`` finds **exactly one**, inside
72
+ ``main.(*grpcHandlers).handleLiveView`` (``grpc_handlers.go:240``), and the
73
+ literal is a hardcoded ``"@screen_2"`` rather than a ``@screen_%d`` format -- so
74
+ it is not even per-screen. The NACKs in the capture are replies to the
75
+ ``ac-device`` **live-view** request; the admin UI only offers that button for
76
+ ``HardwareNameID`` in {11, 13, 24, 34, 42} and this sign is 8, so the firmware
77
+ NACKs a filename it does not implement. It says nothing about update strategy.
78
+
79
+ Separately, and for a different reason: for ``HardwareNameID == 8`` the server's
80
+ ``getRectangleSupport`` returns false unconditionally, so every push to this
81
+ sign really is full-screen. Do not build session logic that depends on partial
82
+ updates landing.
83
+ """
84
+
85
+ from __future__ import annotations
86
+
87
+ import struct
88
+ from dataclasses import dataclass
89
+
90
+ from ..devices.enums import FileMode, FileOperation, PacketType
91
+ from ..wire.errors import PayloadError
92
+
93
+ __all__ = [
94
+ "DEVICE_FILE_READ_CHUNK",
95
+ "DEVICE_IMAGE_FILES",
96
+ "FILE_LIST_PATH",
97
+ "FILE_LIST_LENGTH",
98
+ "FileListEntry",
99
+ "FilePacket",
100
+ "parse_file_listing",
101
+ "FileOpen",
102
+ "FileBytes",
103
+ "FileErase",
104
+ "FileWriteDone",
105
+ "screen_cache_name",
106
+ ]
107
+
108
+ _HDR = struct.Struct("<II")
109
+
110
+ FILE_LIST_PATH = "."
111
+ """The path a listing reads. ``"/"`` and ``""`` are rewritten to this."""
112
+
113
+ FILE_LIST_LENGTH = 10240
114
+ """The read length the vendor uses for a listing.
115
+
116
+ Larger than :data:`DEVICE_FILE_READ_CHUNK` on purpose and harmless: the
117
+ listing of this firmware's six files is 129 bytes, so it fits in one reply
118
+ whatever you ask for.
119
+ """
120
+
121
+ DEVICE_FILE_READ_CHUNK = 1024
122
+ """The most bytes one ``read`` reply ever carries.
123
+
124
+ Measured: asking for 256 returns 256, asking for 1024 returns 1024, and asking
125
+ for 4824, 10240 or 32768 all return 1024. Ask for more and you merely waste
126
+ the round trip accounting.
127
+ """
128
+
129
+ DEVICE_IMAGE_FILES: tuple[str, ...] = tuple(f"/image{i}.pv2" for i in range(6))
130
+ """The six ``.pv2`` files firmware 7.4.4407 holds on its flash.
131
+
132
+ **They are not framebuffers.** Each is a complete, stored type-5 image packet
133
+ for the whole 1440x2560 canvas, and they are Visionect's shipped demo content
134
+ -- a wayfinding board ("Welcome to Nanotech inc."), a museum label ("Room 35 --
135
+ Michelangelo and the Florentines") and four more. Verified by pulling two of
136
+ them whole and rendering them, and by pushing a distinctive frame and
137
+ re-listing: **not one of the six changed size, and ``/image0.pv2``'s first
138
+ bytes were identical before and after.** They also carry
139
+ ``DataHeader.DeviceID == 00000000...`` and ``ImageHeader.Checksum == 0``, which
140
+ no frame we send ever does.
141
+
142
+ So there is no device-side readback of what the panel is currently showing on
143
+ this firmware, and the ``ImageHeader.Checksum``-matching trick that
144
+ ``OPEN-QUESTIONS.md`` B7 proposed cannot work -- the field is zero in all six.
145
+ ``DisplayStateCRC`` (status tag 9) remains the only way to ask the device what
146
+ it is displaying, and it is enough.
147
+ """
148
+
149
+
150
+ @dataclass(frozen=True, slots=True)
151
+ class FileListEntry:
152
+ """One row of a directory listing."""
153
+
154
+ name: str
155
+ size: int
156
+ """Bytes on flash, including the 20-byte ``ProtocolHeader``."""
157
+ checksum: str
158
+ """Verbatim text from the middle column. Reads ``"0"`` for every file on
159
+ this firmware, so it identifies nothing -- do not build on it."""
160
+
161
+
162
+ def parse_file_listing(raw: bytes | str) -> dict[str, FileListEntry]:
163
+ """Parse the ASCII blob a ``Read(".", 10240)`` returns.
164
+
165
+ The vendor's ``vio.GetFiles`` splits on newline, then on space, into
166
+ ``{name: {size, checksum}}``. Rows that do not have at least a name and a
167
+ size are skipped rather than raising, because this is a device-formatted
168
+ blob and a strict parser would be the wrong trade.
169
+ """
170
+ text = raw.decode("ascii", errors="replace") if isinstance(raw, bytes) else raw
171
+ out: dict[str, FileListEntry] = {}
172
+ for line in text.splitlines():
173
+ parts = line.split()
174
+ if len(parts) < 2:
175
+ continue
176
+ name = parts[0]
177
+ # "name checksum size". A two-column row is not something this firmware
178
+ # emits; read its one number as the size rather than dropping the row.
179
+ checksum, raw_size = ("", parts[1]) if len(parts) == 2 else (parts[1], parts[2])
180
+ try:
181
+ size = int(raw_size)
182
+ except ValueError:
183
+ continue
184
+ out[name] = FileListEntry(name=name, size=size, checksum=checksum)
185
+ return out
186
+
187
+
188
+ def screen_cache_name(screen_id: int) -> str:
189
+ """The device-side cached-frame filename, ``@screen_<N>``.
190
+
191
+ Captured verbatim as ``"@screen_2\\0"`` in a ``file/open`` with mode ``read``.
192
+ """
193
+ return f"@screen_{screen_id}"
194
+
195
+
196
+ @dataclass(frozen=True, slots=True)
197
+ class FileOpen:
198
+ """``FilePayloadOpen{Mode uint32; Filename string}``."""
199
+
200
+ filename: str
201
+ mode: int = FileMode.READ
202
+
203
+ def encode(self) -> bytes:
204
+ return struct.pack("<I", self.mode) + self.filename.encode("ascii") + b"\x00"
205
+
206
+ @classmethod
207
+ def decode(cls, raw: bytes) -> "FileOpen":
208
+ if len(raw) < 4:
209
+ raise PayloadError("file/open payload needs at least a 4-byte Mode")
210
+ (mode,) = struct.unpack_from("<I", raw, 0)
211
+ name = raw[4:].split(b"\x00")[0].decode("ascii", errors="replace")
212
+ return cls(filename=name, mode=mode)
213
+
214
+
215
+ @dataclass(frozen=True, slots=True)
216
+ class FileBytes:
217
+ """``FilePayloadBytes`` -- raw bytes for ``read``/``write``."""
218
+
219
+ data: bytes
220
+
221
+ def encode(self) -> bytes:
222
+ return self.data
223
+
224
+ @classmethod
225
+ def decode(cls, raw: bytes) -> "FileBytes":
226
+ return cls(data=raw)
227
+
228
+
229
+ @dataclass(frozen=True, slots=True)
230
+ class FileErase:
231
+ """``FilePayloadErase`` -- a filename."""
232
+
233
+ filename: str
234
+
235
+ def encode(self) -> bytes:
236
+ return self.filename.encode("ascii") + b"\x00"
237
+
238
+ @classmethod
239
+ def decode(cls, raw: bytes) -> "FileErase":
240
+ return cls(filename=raw.split(b"\x00")[0].decode("ascii", errors="replace"))
241
+
242
+
243
+ @dataclass(frozen=True, slots=True)
244
+ class FileWriteDone:
245
+ """``FilePayloadWriteDone{Length uint32; Checksum uint32}``."""
246
+
247
+ length: int
248
+ checksum: int
249
+
250
+ def encode(self) -> bytes:
251
+ return struct.pack("<II", self.length, self.checksum)
252
+
253
+ @classmethod
254
+ def decode(cls, raw: bytes) -> "FileWriteDone":
255
+ if len(raw) < 8:
256
+ raise PayloadError("file/write-descriptor payload needs 8 bytes")
257
+ return cls(*struct.unpack_from("<II", raw, 0))
258
+
259
+
260
+ _DECODERS = {
261
+ FileOperation.OPEN: FileOpen.decode,
262
+ FileOperation.READ: FileBytes.decode,
263
+ FileOperation.WRITE: FileBytes.decode,
264
+ FileOperation.ERASE: FileErase.decode,
265
+ FileOperation.WRITE_DESCRIPTOR: FileWriteDone.decode,
266
+ # Every reply the device sends is op 6 with the bytes in the payload.
267
+ FileOperation.EVENT: FileBytes.decode,
268
+ }
269
+
270
+
271
+ @dataclass(slots=True)
272
+ class FilePacket:
273
+ """A ``packet.File`` payload."""
274
+
275
+ op: int
276
+ raw: bytes = b""
277
+ """The operation payload bytes, kept verbatim so re-encoding is exact."""
278
+
279
+ TYPE = PacketType.FILE
280
+
281
+ @property
282
+ def op_name(self) -> str:
283
+ return FileOperation.NAMES.get(self.op, "(unknown)")
284
+
285
+ def parsed(self) -> FileOpen | FileBytes | FileErase | FileWriteDone | None:
286
+ """Decode :attr:`raw` into the shape *op* selects, or None if unknown."""
287
+ decoder = _DECODERS.get(self.op)
288
+ return decoder(self.raw) if decoder else None
289
+
290
+ @classmethod
291
+ def open(cls, filename: str, mode: int = FileMode.READ) -> "FilePacket":
292
+ return cls(op=FileOperation.OPEN, raw=FileOpen(filename, mode).encode())
293
+
294
+ @classmethod
295
+ def close(cls) -> "FilePacket":
296
+ return cls(op=FileOperation.CLOSE, raw=b"")
297
+
298
+ @classmethod
299
+ def read(cls, length: int) -> "FilePacket":
300
+ return cls(op=FileOperation.READ, raw=struct.pack("<I", length))
301
+
302
+ @classmethod
303
+ def write(cls, data: bytes) -> "FilePacket":
304
+ return cls(op=FileOperation.WRITE, raw=data)
305
+
306
+ @classmethod
307
+ def erase(cls, filename: str) -> "FilePacket":
308
+ return cls(op=FileOperation.ERASE, raw=FileErase(filename).encode())
309
+
310
+ @classmethod
311
+ def write_descriptor(cls, length: int, checksum: int) -> "FilePacket":
312
+ return cls(
313
+ op=FileOperation.WRITE_DESCRIPTOR,
314
+ raw=FileWriteDone(length, checksum).encode(),
315
+ )
316
+
317
+ @classmethod
318
+ def decode(cls, payload: bytes) -> "FilePacket":
319
+ if len(payload) < 8:
320
+ raise PayloadError(f"file payload is {len(payload)} bytes, need >= 8")
321
+ op, length = _HDR.unpack_from(payload, 0)
322
+ return cls(op=op, raw=payload[8 : 8 + length])
323
+
324
+ def encode(self) -> bytes:
325
+ return _HDR.pack(self.op, len(self.raw)) + self.raw
@@ -0,0 +1,234 @@
1
+ """Image packets (type 5) -- server to device only.
2
+
3
+ The device receives **already-quantised, already-bit-packed** data and does only
4
+ waveform drive, so the whole imaging pipeline is the server's job. This module
5
+ only does the framing; :mod:`pyvisionect.imaging` produces the pixel payloads.
6
+
7
+ Layout (all little-endian)::
8
+
9
+ ImageHeader (20 bytes)
10
+ 0 4 Checksum uint32 XXHash32 over the 8-bit state image
11
+ 4 4 NrPrimitives uint32 number of rectangles
12
+ 8 4 Options uint32
13
+ 12 4 PayloadLength uint32 total bytes of rectangles that follow
14
+ 16 4 Reserved uint32
15
+
16
+ RectangleHeader (24 bytes) + PayloadLength bytes, NrPrimitives times
17
+ 0 2 ImageType uint16 (1 = gray)
18
+ 2 2 ScreenID uint16
19
+ 4 2 X uint16
20
+ 6 2 Y uint16
21
+ 8 2 Width uint16
22
+ 10 2 Height uint16
23
+ 12 2 RectangleUpdateOptions uint16
24
+ 14 2 Options uint16
25
+ 16 2 Encoding uint16 (packet.EncodingType: 1 or 4)
26
+ 18 2 Reserved uint16
27
+ 20 4 PayloadLength uint32
28
+
29
+ Two things that bite
30
+ --------------------
31
+
32
+ * ``RectangleUpdateOptions`` is **auto-filled at marshal time when it is 0**
33
+ (``packet/image.go:271-277``): ``0x0101`` for 1-bit, ``0x0102`` for 4-bit.
34
+ The captured push carries ``0x0102``, which proves it left the renderer as 0.
35
+ :meth:`Rectangle.encode` reproduces that auto-fill, so a re-encode of the
36
+ capture is byte-exact.
37
+ * ``ImageHeader.Checksum`` is literally what the device reports back as
38
+ ``DisplayStateCRC`` (status tag 9) -- the server's free "is the device in sync"
39
+ test. It is **XXHash32 (seed 0) over the raw 8-bit state image**, not a CRC
40
+ and not over the encoded data. Getting it wrong causes silent redundant
41
+ redraws. :mod:`pyvisionect.imaging` computes it.
42
+
43
+ ``Rectangle.options`` bit ``0x0002`` **cleared** on all rectangles of one
44
+ full-screen packet requests an inverse update. Verified on hardware by A/B:
45
+ ``options=0`` makes the firmware log ``inv: 1`` and ``Force Inverse and full
46
+ area update``, ``options=2`` makes it log ``inv: 0`` with no such line. So
47
+ *clear* means inverse, and the vendor's shipped default of 0 inverts on every
48
+ full-screen push.
49
+ """
50
+
51
+ from __future__ import annotations
52
+
53
+ import struct
54
+ from dataclasses import dataclass, field
55
+
56
+ from ..devices.enums import EncodingType, ImageType, PacketType
57
+ from ..wire.errors import PayloadError
58
+
59
+ __all__ = [
60
+ "IMAGE_HEADER_SIZE",
61
+ "RECT_HEADER_SIZE",
62
+ "RECT_UPDATE_OPTIONS_DEFAULT",
63
+ "MAX_RECTANGLES",
64
+ "Rectangle",
65
+ "ImagePacket",
66
+ ]
67
+
68
+ IMAGE_HEADER_SIZE = 20
69
+ RECT_HEADER_SIZE = 24
70
+
71
+ RECT_UPDATE_OPTIONS_DEFAULT: dict[int, int] = {
72
+ EncodingType.ONE_BIT: 0x0101,
73
+ EncodingType.FOUR_BIT: 0x0102,
74
+ }
75
+ """``packet/image.go:271-277``: when ``RectangleUpdateOptions == 0`` the marshaller
76
+ substitutes these per-encoding constants."""
77
+
78
+ MAX_RECTANGLES = 15
79
+ """The server merges/limits dirty regions to at most 15 rectangles per packet."""
80
+
81
+ OPTION_NOT_INVERSE = 0x0002
82
+ """``RectangleHeader.Options`` bit. Cleared on every rectangle of a full-screen
83
+ packet = inverse update; set = ordinary update. Verified on hardware (A/B
84
+ against the firmware's ``inv:`` log line), and the vendor's admin UI labels the
85
+ value ``0`` "Enable" and ``2`` "Disable" for exactly this key."""
86
+
87
+ _IMG = struct.Struct("<5I")
88
+ _RECT = struct.Struct("<10HI")
89
+
90
+
91
+ @dataclass(frozen=True, slots=True)
92
+ class Rectangle:
93
+ """One ``RectangleHeader`` plus its pixel payload."""
94
+
95
+ x: int
96
+ y: int
97
+ width: int
98
+ height: int
99
+ data: bytes = field(repr=False, default=b"")
100
+ screen_id: int = 0
101
+ encoding: int = EncodingType.FOUR_BIT
102
+ image_type: int = ImageType.GRAY
103
+ options: int = 0
104
+ update_options: int = 0
105
+ """0 means "let the marshaller fill it in" -- see
106
+ :data:`RECT_UPDATE_OPTIONS_DEFAULT`."""
107
+ reserved: int = 0
108
+
109
+ @property
110
+ def effective_update_options(self) -> int:
111
+ """What actually goes on the wire."""
112
+ if self.update_options:
113
+ return self.update_options
114
+ return RECT_UPDATE_OPTIONS_DEFAULT.get(self.encoding, 0)
115
+
116
+ @property
117
+ def expected_data_length(self) -> int:
118
+ """Bytes of packed pixel data for this geometry and encoding."""
119
+ bits = self.width * self.height * self.encoding
120
+ return (bits + 7) // 8
121
+
122
+ def encode(self) -> bytes:
123
+ return (
124
+ _RECT.pack(
125
+ self.image_type,
126
+ self.screen_id,
127
+ self.x,
128
+ self.y,
129
+ self.width,
130
+ self.height,
131
+ self.effective_update_options,
132
+ self.options,
133
+ self.encoding,
134
+ self.reserved,
135
+ len(self.data),
136
+ )
137
+ + self.data
138
+ )
139
+
140
+ @classmethod
141
+ def decode_from(cls, payload: bytes, offset: int) -> tuple["Rectangle", int]:
142
+ """Decode one rectangle at *offset*; return it and the next offset."""
143
+ if len(payload) - offset < RECT_HEADER_SIZE:
144
+ raise PayloadError(
145
+ f"need {RECT_HEADER_SIZE} bytes for a RectangleHeader at {offset}"
146
+ )
147
+ (
148
+ image_type,
149
+ screen_id,
150
+ x,
151
+ y,
152
+ width,
153
+ height,
154
+ update_options,
155
+ options,
156
+ encoding,
157
+ reserved,
158
+ length,
159
+ ) = _RECT.unpack_from(payload, offset)
160
+ start = offset + RECT_HEADER_SIZE
161
+ end = start + length
162
+ if end > len(payload):
163
+ raise PayloadError(
164
+ f"rectangle at {offset} declares {length} bytes, only "
165
+ f"{len(payload) - start} remain"
166
+ )
167
+ return (
168
+ cls(
169
+ x=x,
170
+ y=y,
171
+ width=width,
172
+ height=height,
173
+ data=payload[start:end],
174
+ screen_id=screen_id,
175
+ encoding=encoding,
176
+ image_type=image_type,
177
+ options=options,
178
+ update_options=update_options,
179
+ reserved=reserved,
180
+ ),
181
+ end,
182
+ )
183
+
184
+
185
+ @dataclass(slots=True)
186
+ class ImagePacket:
187
+ """A ``packet.Image`` payload."""
188
+
189
+ checksum: int = 0
190
+ """XXHash32 of the 8-bit state image. Echoed back as status tag 9."""
191
+
192
+ rectangles: list[Rectangle] = field(default_factory=list)
193
+ options: int = 0
194
+ reserved: int = 0
195
+
196
+ TYPE = PacketType.IMAGE
197
+
198
+ @classmethod
199
+ def decode(cls, payload: bytes) -> "ImagePacket":
200
+ if len(payload) < IMAGE_HEADER_SIZE:
201
+ raise PayloadError(
202
+ f"image payload is {len(payload)} bytes, need >= {IMAGE_HEADER_SIZE}"
203
+ )
204
+ checksum, count, options, declared, reserved = _IMG.unpack_from(payload, 0)
205
+ offset = IMAGE_HEADER_SIZE
206
+ rects: list[Rectangle] = []
207
+ for _ in range(count):
208
+ rect, offset = Rectangle.decode_from(payload, offset)
209
+ rects.append(rect)
210
+ body_len = offset - IMAGE_HEADER_SIZE
211
+ if declared and declared != body_len:
212
+ raise PayloadError(
213
+ f"ImageHeader.PayloadLength = {declared} but the rectangles "
214
+ f"consumed {body_len} bytes"
215
+ )
216
+ return cls(
217
+ checksum=checksum, rectangles=rects, options=options, reserved=reserved
218
+ )
219
+
220
+ def encode(self) -> bytes:
221
+ body = b"".join(rect.encode() for rect in self.rectangles)
222
+ return (
223
+ _IMG.pack(
224
+ self.checksum,
225
+ len(self.rectangles),
226
+ self.options,
227
+ len(body),
228
+ self.reserved,
229
+ )
230
+ + body
231
+ )
232
+
233
+ def __len__(self) -> int:
234
+ return len(self.rectangles)