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,1030 @@
1
+ Metadata-Version: 2.5
2
+ Name: pyvisionect
3
+ Version: 0.1.0
4
+ Summary: Sans-io reimplementation of the Visionect e-ink sign wire protocol (protocol v3)
5
+ Author: schlarpc
6
+ License: MIT
7
+ License-File: LICENSE
8
+ Keywords: eink,epaper,reverse-engineering,sans-io,visionect
9
+ Classifier: Development Status :: 3 - Alpha
10
+ Classifier: Intended Audience :: Developers
11
+ Classifier: Programming Language :: Python :: 3.11
12
+ Classifier: Topic :: System :: Hardware
13
+ Requires-Python: >=3.11
14
+ Requires-Dist: cramjam>=2.13
15
+ Requires-Dist: xxhash>=3.0
16
+ Provides-Extra: imaging
17
+ Requires-Dist: numpy>=1.24; extra == 'imaging'
18
+ Requires-Dist: pillow>=10.0; extra == 'imaging'
19
+ Provides-Extra: lz4
20
+ Requires-Dist: lz4>=4.0; extra == 'lz4'
21
+ Provides-Extra: test
22
+ Requires-Dist: dpkt>=1.9; extra == 'test'
23
+ Requires-Dist: lz4>=4.0; extra == 'test'
24
+ Requires-Dist: pytest>=7.0; extra == 'test'
25
+ Provides-Extra: usb
26
+ Requires-Dist: pyserial>=3.5; extra == 'usb'
27
+ Description-Content-Type: text/markdown
28
+
29
+ # pyvisionect
30
+
31
+ A clean, **sans-io** Python reimplementation of the Visionect e-ink sign wire
32
+ protocol ("protocol v3"), so you can drive a sign directly and drop the vendor
33
+ server software entirely.
34
+
35
+ Built by reverse-engineering `visionect-server-v3:8.5.5` and validated against
36
+ 1.9 MB of real captured traffic from a 32" sign: a full connect, 20+ heartbeats,
37
+ a TCLV parameter round trip, a file open/NACK, and a 1.84 MB image push.
38
+
39
+ ```
40
+ io/ asyncio TCP listener; pyserial USB provisioning <- the ONLY I/O
41
+ session/ DeviceConnection: bytes in -> Events out
42
+ packets/ per-type payload codecs
43
+ wire/ framing, LZ4 block chain, direction-dependent CRC
44
+
45
+ imaging/ PIL/numpy -> dithered, bit-packed rectangles + XXHash32 state
46
+ devices/ capability tables: TCLV, status enums, panel geometry (data, not code)
47
+ ```
48
+
49
+ Nothing under `wire/`, `packets/`, `session/` or `devices/` imports `socket` or
50
+ `asyncio`, or reads a clock. There is a test that AST-scans the package to keep
51
+ it that way.
52
+
53
+ ## Install
54
+
55
+ Python 3.11+.
56
+
57
+ ```sh
58
+ pip install pyvisionect # wire/packets/session/devices + io.tcp
59
+ pip install 'pyvisionect[imaging]' # + numpy and Pillow, for the imaging pipeline
60
+ pip install 'pyvisionect[usb]' # + pyserial, for USB provisioning
61
+ pip install 'pyvisionect[test]' # + pytest and dpkt, to run the test suite
62
+ ```
63
+
64
+ Runtime dependencies are deliberately tiny: `cramjam` (the block codec the wire
65
+ uses) and `xxhash` (the display-state checksum). Keep `xxhash` installed even
66
+ though the imaging module has a pure-Python fallback — the native one is roughly
67
+ nine times faster per frame.
68
+
69
+
70
+ ### Which LZ4 binding
71
+
72
+ `cramjam` is the dependency rather than `python-lz4`, for one practical reason:
73
+ **`lz4` publishes no musllinux wheels**, so it cannot install in Home
74
+ Assistant's official Alpine container — which is exactly where this library is
75
+ meant to run. `cramjam` ships musllinux wheels and is verified working there.
76
+
77
+ Both produce **identical wire bytes**. They differ only in Python-side
78
+ convention: `cramjam.lz4.compress_block()` prepends a 4-byte little-endian
79
+ uncompressed size that is *not* part of a raw LZ4 block, and
80
+ `pyvisionect.wire.blocks` strips it. Either backend reads the other's output;
81
+ there are tests pinning that in both directions.
82
+
83
+ `python-lz4` is still supported as a fast path if it happens to be installed
84
+ (`pip install 'pyvisionect[lz4]'`), and `codec_name()` reports which is in use.
85
+ Neither is required if you pass `ConnectionConfig(compressor=STORED_ONLY)` —
86
+ the device never compresses, so a pure server needs no codec for inbound
87
+ traffic at all.
88
+
89
+ ## You are the server
90
+
91
+ This is the thing to internalise before anything else.
92
+
93
+ **A Visionect sign is a TCP client.** It dials out to port 11113 and speaks
94
+ first. There is no handshake, no authentication, no version negotiation and no
95
+ nonce exchange. The first thing on the wire is a status packet, and the 16-byte
96
+ UUID in its header is the entire identity claim. Registration is auto-create on
97
+ first sight.
98
+
99
+ So a reimplementation does not talk *to* a server — it **is** the server. It
100
+ listens, accepts whatever connects, and drives the sign. No VSS, no licence
101
+ server, no cloud, no account.
102
+
103
+ Two consequences:
104
+
105
+ 1. The library's primary object is a **listener owning N device connections**,
106
+ not a client. Home Assistant (or whatever you like) hosts that listener.
107
+ 2. Because there is no auth, **put the listener somewhere only your signs can
108
+ reach.** Anything that can open TCP 11113 can claim to be any UUID.
109
+
110
+ ### Hello, sign
111
+
112
+ ```python
113
+ import asyncio
114
+
115
+ from pyvisionect.io import VisionectServer
116
+ from pyvisionect.session import DeviceConnected, Nacked, StatusReceived
117
+
118
+
119
+ async def on_events(conn, events):
120
+ for event in events:
121
+ if isinstance(event, DeviceConnected):
122
+ print(f"{event.uuid} online: {conn.state.panel.describe()}")
123
+ conn.apply_pending() # drain work queued while it slept
124
+ elif isinstance(event, StatusReceived):
125
+ fields = event.status.fields()
126
+ print(f" battery {fields['BatteryLevel']}% "
127
+ f"rssi {fields['SignalStrength']} dBm "
128
+ f"temp {fields['AverageTemperature']} C")
129
+ elif isinstance(event, Nacked):
130
+ print(f" device refused request {event.packet_id}: {event.control}")
131
+
132
+
133
+ asyncio.run(VisionectServer(on_events=on_events).serve_forever())
134
+ ```
135
+
136
+ Queueing from inside the callback needs no explicit flush; the server drains
137
+ after every callback. To queue from elsewhere, use `server.connection_for(uuid)`
138
+ and then `await server.flush(uuid)`.
139
+
140
+ ### The sign is asleep. Queue, do not wait.
141
+
142
+ `server.connection_for(uuid)` returning `None` is **the normal case** — a
143
+ battery sign is awake for about a minute a day, and even a mains one reconnects
144
+ unpredictably. So the library owns the deferral, because the coalescing rules
145
+ are correctness rather than style:
146
+
147
+ ```python
148
+ work = store.queue(uuid) # durable, coalescing, per-UUID
149
+ work.set_image(frame) # content: last-write-wins, depth exactly one
150
+ work.write_param(29, 30) # TCLV writes: last-write-wins per id
151
+ work.read_params([18, 19]) # TCLV reads: set union
152
+ work.sleep(60) # replaces any prior sleep
153
+ ```
154
+
155
+ Ten pushes to a sleeping sign show the tenth, not all ten. Setting the heartbeat
156
+ to 5 and then 30 means 30. Pressing reboot twice is one reboot. Then, on the
157
+ `DeviceConnected` event:
158
+
159
+ ```python
160
+ sent = conn.apply_pending() # {slot: packet_id}, in PENDING_ORDER
161
+ ```
162
+
163
+ **The order is not arbitrary**, and `apply_pending` enforces it:
164
+
165
+ | # | slot | why here |
166
+ |--:|---|---|
167
+ | 1 | param reads | correct our view before anything acts on it, and before a write races them |
168
+ | 2 | param writes | cheap, small, may change heartbeat or power behaviour |
169
+ | 3 | `flash_save` (TCLV 53) | persist step 2 before anything can reboot |
170
+ | 4 | framebuffer read | expensive; do it while the link definitely exists |
171
+ | 5 | **image push** | the big one; it must land before the device leaves |
172
+ | 6 | ghost clear | a second full-screen push, only after 5 |
173
+ | 7 | **sleep** | the device leaves — everything above must already be on the wire |
174
+ | 8 | **reboot** | last, unconditionally. Nothing survives it |
175
+
176
+ Steps 5→7 are the one that bites: the vendor waits for its renderer before
177
+ publishing its sleep packet, and getting it wrong leaves the user staring at
178
+ yesterday's dashboard for a day. There is no network route to wake a sleeping
179
+ sign early; `app_wakeup` on the USB console is the only one, and it works — it
180
+ recovered a sign from a 910-minute sleep on the spot.
181
+
182
+ Each slot clears **only on an ack**, so a connection that drops mid-reconcile
183
+ leaves the remainder queued:
184
+
185
+ ```python
186
+ elif isinstance(event, Acked):
187
+ work.on_acked(event.packet_id)
188
+ elif isinstance(event, Nacked):
189
+ work.on_nacked(event.packet_id, charging=event.charging)
190
+ ```
191
+
192
+ A charging NACK (control flag bit 25) is a **retry-later, not a failure** —
193
+ treating it as fatal would make an integration look broken whenever someone
194
+ plugs the sign in.
195
+
196
+ `work.to_dict()` / `PendingWork.from_dict()` persist the register, so a
197
+ consumer restart does not silently drop a push the user queued ten minutes ago.
198
+ The `EncodedFrame` itself is deliberately not persisted — it is megabytes of
199
+ pixels and cheaper to re-encode; the revision counter survives so the intent is
200
+ not lost.
201
+
202
+ ### Pushing a frame
203
+
204
+ ```python
205
+ import functools
206
+
207
+ from PIL import Image
208
+
209
+ from pyvisionect.imaging import encode_frame
210
+
211
+ panel = conn.state.panel # from the device's own DisplayType
212
+
213
+ # encode_frame is CPU-bound and blocking -- see below. Never on the event loop.
214
+ frame = await loop.run_in_executor(None, functools.partial(
215
+ encode_frame,
216
+ Image.open("dashboard.png"),
217
+ panel=panel,
218
+ encoding=4, # 4 bpp, 16 greys
219
+ dithering=3, # floyd-steinberg
220
+ prev_state=conn.state.imaging_state, # survives reconnects
221
+ ))
222
+ store.queue(uuid).set_image(frame) # or conn.send_image(frame) if awake
223
+ ```
224
+
225
+ **`encode_frame` is CPU-bound, blocking, and releases no locks.** A 1440×2560
226
+ canvas goes through grey conversion, change detection, dithering
227
+ (Floyd–Steinberg is inherently serial), bit packing, 4-pixel interlacing and
228
+ LZ4: hundreds of milliseconds on a desktop, plausibly seconds on a Raspberry
229
+ Pi. Run it in an executor (`hass.async_add_executor_job` in Home Assistant).
230
+ On the event loop it stalls everything for the duration, which presents to a
231
+ user as "the whole instance freezes every hour". The resulting ~1.84 MB socket
232
+ write is fine on the loop — it is just a `write` plus a `drain` — but budget
233
+ roughly 6–8 MB of transient peak memory per device being pushed to.
234
+
235
+ `frame.state_checksum` becomes `ImageHeader.Checksum`, which is exactly what the
236
+ device echoes back as `DisplayStateCRC` (status tag 9).
237
+
238
+ ### Sync state is tri-state — and `False` is not yet a problem
239
+
240
+ ```python
241
+ conn.state.in_sync # True / False / None
242
+ conn.state.sync_status(now) # SyncStatus.{IN_SYNC, CONVERGING, DIVERGED, UNKNOWN}
243
+ ```
244
+
245
+ `None` means "we have never pushed, or the device has not said yet" — a fresh
246
+ install, not a problem. Present it differently from `False`.
247
+
248
+ `False` is not a problem *yet* either, which is the part that bites. A push
249
+ legitimately leaves the device disagreeing with us until it has drawn the frame
250
+ and reported the new `DisplayStateCRC`: **10–48 s on the live 31.2" sign**,
251
+ depending on where the push lands relative to the heartbeat. Anything that shows
252
+ `in_sync is False` as a fault therefore raises one after every normal update.
253
+ That is exactly what happened to the Home Assistant integration's
254
+ `binary_sensor.display_out_of_sync`.
255
+
256
+ `sync_status()` splits that `False` in two. It reports `DIVERGED` only when the
257
+ device has genuinely failed to converge — either it has been in touch
258
+ `CONVERGENCE_CONTACTS` times since the push **and** `settle_time()` has passed,
259
+ or `convergence_grace()` has passed with no word at all. Both windows are
260
+ derived from `NextStatus` (status tag 27), the device's own announcement of when
261
+ it will next be in touch, so a sign on an hourly heartbeat is not called broken
262
+ for the 59 minutes it is away.
263
+
264
+ The `settle_time()` gate on the contact counter is not belt-and-braces. The sign
265
+ **bursts** status packets around a draw — measured at nine in the first 55 s
266
+ after a push, then one a minute — so the bare counter can be satisfied in fifteen
267
+ seconds, before a 1.84 MB frame has finished transferring.
268
+
269
+ Pass the clock in, as everywhere else in this library:
270
+
271
+ ```python
272
+ conn.send_image(frame, now=time.monotonic())
273
+ ```
274
+
275
+ Without a `now` the verdict falls back to the contact counter alone, which is
276
+ the right behaviour for a state restored from disk: the push it remembers is
277
+ from before the restart and has long since had its chance.
278
+
279
+ E-ink keeps its image across a restart, so if you persist the encoder state and
280
+ the checksum, the correct action on first contact is often **nothing at all**:
281
+
282
+ ```python
283
+ blob = frame.state.to_bytes() # versioned, self-describing, tiny
284
+ ...
285
+ state.imaging_state = FrameState.from_bytes(blob)
286
+ state.pushed_checksum = saved_checksum
287
+ # on the next DeviceConnected: if state.in_sync is True, there is nothing to do
288
+ ```
289
+
290
+ The format is owned by the library, so adding a field to `FrameState` is not a
291
+ breaking change for everyone who persisted one. Both grey planes are deflated,
292
+ and real e-ink content is mostly flat white: a 1440×2560 state usually lands in
293
+ tens of kilobytes rather than 3.7 MB. `DeviceState.to_dict()` /
294
+ `DeviceStateStore.to_dict()` do the same for the rest of the store.
295
+
296
+ ### Forcing a full-screen redraw
297
+
298
+ Two levers, and they are not equivalent:
299
+
300
+ * `encode_frame(..., force_full_screen=True)` — the **verified** one. Skips
301
+ change detection and emits rectangles covering every display, so the device
302
+ repaints everything because it was sent everything.
303
+ * `conn.send_image(frame, force_full=True)` — the *checksum* lever. Perturbs
304
+ `ImageHeader.Checksum` so it cannot match the tag the device holds. Verified
305
+ end to end that the device never refuses a mismatched tag and that a mismatch
306
+ costs exactly one extra full-screen redraw. It does not change which pixels
307
+ are sent.
308
+
309
+ On `HardwareNameID == 8` — the 32" sign — every push is full-screen anyway, so
310
+ `force_full` is a no-op there. `conn.state.supports_rectangles` tells you which
311
+ case you are in.
312
+
313
+ ### Shutting down
314
+
315
+ ```python
316
+ await server.close() # closes live device connections too
317
+ await server.close(abort=True) # drops them without draining pending writes
318
+ ```
319
+
320
+ **This matters more than it looks.** Since Python 3.12, `Server.wait_closed()`
321
+ waits until the server is closed *and all active connections have finished* —
322
+ and a mains-powered sign holds its TCP connection open permanently. A naive
323
+ `close()` + `wait_closed()` therefore **never returns**. Downstream that shows
324
+ up as a config entry that cannot be reloaded and a port that stays bound, then
325
+ `EADDRINUSE` on the next attempt. `close()` here does
326
+ `close()` → `close_clients()` → `wait_closed()`, in that order (Python's own
327
+ docs mandate stopping the accept first, to avoid racing new clients). There is a
328
+ regression test that hangs without it.
329
+
330
+ `abort=True` is the shutdown path: finishing a half-written 1.84 MB frame is not
331
+ worth waiting for.
332
+
333
+ If binding fails you get a `ListenError` carrying `errno`, `host` and `port`,
334
+ rather than a bare `OSError` to string-match — `EADDRINUSE` (something else
335
+ holds 11113, very likely the vendor's own server) needs completely different
336
+ advice from `EADDRNOTAVAIL`. Note `errno` can legitimately be `None`: when
337
+ several candidate addresses all fail, asyncio raises a summary error and
338
+ discards the per-address errno.
339
+
340
+ ### "Nothing happens" — telling the two causes apart
341
+
342
+ ```python
343
+ server.stats.accepted # 0 -> nothing is reaching the port at all
344
+ server.stats.identified # 0 with accepted > 0 -> connects, but not a sign
345
+ server.stats.silent_connections # accepted, sent nothing. NORMAL, not an error
346
+ server.stats.last_seen_uuid() # {uuid: clock} of the last frame from each
347
+ ```
348
+
349
+ Those first two need opposite troubleshooting advice and neither raises an
350
+ exception, which is why they are counted. `silent_connections` is not a fault:
351
+ the reference capture shows the real sign opening and closing a connection
352
+ carrying zero protocol bytes, in normal operation.
353
+
354
+ ### Sans-io, if you want to bring your own transport
355
+
356
+ ```python
357
+ conn = DeviceConnection(store=DeviceStateStore())
358
+ events = conn.feed(data) # bytes in -> list[Event]
359
+ out = conn.drain() # -> bytes you must send
360
+ events = conn.advance(now) # timers, with YOUR clock
361
+ conn.send_image(frame) # queues; no I/O
362
+ ```
363
+
364
+ `feed_at(data, now)` is `feed` plus the timer bookkeeping, and is what the
365
+ asyncio adapter calls.
366
+
367
+ ## Pointing a sign at your server (USB or DNS)
368
+
369
+ There is **no discovery in either direction.** The sign has no open ports, answers
370
+ no mDNS/SSDP/NetBIOS/SNMP/CoAP probe, advertises nothing, and does not even do a
371
+ DNS lookup when its server address is already resolved in flash. The server
372
+ binaries contain no mDNS/SSDP/UPnP code at all. The only binding is a server
373
+ address typed into flash.
374
+
375
+ And you cannot change that over the network. Eight TCLV parameters are marked
376
+ `canWrite: false` in the vendor's own descriptor table, and they are exactly the
377
+ ones you would need:
378
+
379
+ | id | name | USB command |
380
+ |---:|---|---|
381
+ | 2 | Connectivity type | `conn_type_set <type>` |
382
+ | 18 | Server IP | `server_tcp_set <ip\|dns> <port>` |
383
+ | 19 | Server port | `server_tcp_set <ip\|dns> <port>` |
384
+ | 65 | WiFi SSID | `wifi_ssid_set <ssid>` (hidden from `help`, but present) |
385
+ | 66 | WiFi security mode | `wifi_security_set <none\|wpa2\|wpa2e>` |
386
+ | 67 | WiFi password | `wifi_psk_set <psk>` |
387
+ | 68 | WiFi band | `wifi_conf_set` arg 4 |
388
+ | 70 | Mobile security mode | `mobile_conf_set` arg 2 |
389
+
390
+ The library refuses a network write to any of them and the error names the USB
391
+ command that can do the job:
392
+
393
+ ```python
394
+ >>> conn.write_params({18: "homeassistant.local"})
395
+ ReadOnlyParameter: TCLV parameter 18 ('Server IP') is read-only over the network
396
+ (canWrite:false in the vendor's own descriptor table). Set it over the USB serial
397
+ CLI instead: server_tcp_set <ip|dns> <port>, then `flash_save`, then `reboot`.
398
+ ```
399
+
400
+ So you have two routes.
401
+
402
+ ### Route 1 — DNS re-point (no cables)
403
+
404
+ If the sign already holds a **hostname** rather than a literal IP, re-point that
405
+ name at your listener and change nothing on the device. Read what it currently
406
+ holds with a param read of ids 18 and 19 — that works fine over the network,
407
+ since only *writes* are blocked.
408
+
409
+ ### Route 2 — USB
410
+
411
+ An **FTDI FT232** (`0403:6001`, confirmed with `lsusb`) on the Micro-USB
412
+ connector, **115200 8N1**, carrying a line-oriented ASCII shell. Everything in
413
+ this section was measured on a live 32" sign running firmware **7.4.4407**.
414
+
415
+ ```sh
416
+ pyvisionect-usb ports # find candidate ports
417
+ pyvisionect-usb identify /dev/ttyUSB0 # confirm it is a sign (2 read-only commands)
418
+ pyvisionect-usb dump /dev/ttyUSB0 # read every readable setting
419
+ pyvisionect-usb commands # the 112 commands this firmware answers
420
+
421
+ # Provisioning prints the plan and exits. --execute to actually do it.
422
+ pyvisionect-usb provision /dev/ttyUSB0 \
423
+ --ssid MyNetwork --psk 's3cret' --server homeassistant.local
424
+ ```
425
+
426
+ From Python, read-only (the default — it cannot change anything):
427
+
428
+ ```python
429
+ from pyvisionect.io.usb import SerialConsole, Sign
430
+
431
+ with SerialConsole("/dev/ttyUSB0") as console:
432
+ console.sync()
433
+ sign = Sign(console)
434
+ info = sign.dump()
435
+ print(info.describe())
436
+ print(info.wifi.ssid, info.server.host, info.status.rssi_dbm)
437
+ ```
438
+
439
+ Every getter returns a dataclass, not a string. Writing needs a flag, and the
440
+ flag named in the refusal is the gentlest one that would work:
441
+
442
+ ```python
443
+ sign = Sign(console) # reads only
444
+ sign = Sign(console, allow_writes=True) # + ordinary setters
445
+ sign = Sign(console, allow_destructive=True) # + network/panel/lifecycle
446
+ sign = Sign(console, i_really_mean_it=True) # + formats, firmware, passwords
447
+ ```
448
+
449
+ Provisioning is a plan you read before you run:
450
+
451
+ ```python
452
+ from pyvisionect.io.usb import plan_repoint
453
+
454
+ plan = plan_repoint("homeassistant.local")
455
+ print(plan.describe()) # every command, what it does, and what it costs
456
+ plan.execute(Sign(console, allow_destructive=True))
457
+ ```
458
+
459
+ `plan_repoint` is `server_tcp_set` -> **`flash_save`** -> `reboot`. The
460
+ `flash_save` is not optional — verbatim from the vendor: *"All changes to device
461
+ configuration are by default retained only in the working RAM."* Which cuts both
462
+ ways: until it runs, a power-cycle undoes everything.
463
+
464
+ #### `help` lists 111 of the 162 documented commands — and the firmware has 112
465
+
466
+ Commands are compiled in behind switches, so the device in front of you is the
467
+ only authority — but **`help` is not a complete index of it.** `wifi_ssid_set`
468
+ is documented by the vendor, is not printed by `help`, and still answers: a bare
469
+ call returns `E: Invalid argument(s)`, where a command the firmware really lacks
470
+ returns `Command '<x>' not recognised.` So there is a third category, *hidden*,
471
+ and the delta is three sets in `pyvisionect.io.usb.commands` rather than two:
472
+ `LISTED_BY_HELP` (111), `HIDDEN_IN_7_4_4407` (1) and `ABSENT_FROM_7_4_4407`
473
+ (97, meaning **unlisted**). 49 of those 97 — every one the oracle can safely be
474
+ pointed at — have since been probed and are genuinely absent
475
+ (`PROBED_ABSENT_7_4_4407`), so `wifi_ssid_set` is a one-off rather than the tip
476
+ of an iceberg, and the uncompiled hardware families really are uncompiled.
477
+
478
+ Two findings change documented advice:
479
+
480
+ - **`wifi_ssid_set` is hidden, not missing — and it carries the space.** It is
481
+ the vendor's documented workaround for an SSID containing a space, it takes
482
+ the SSID alone with no PSK, and this firmware has it. Measured on the device:
483
+ it takes **everything after the command name and one separating space,
484
+ verbatim**, with no quoting or escaping convention, so `plan_wifi` and
485
+ `Sign.set_wifi` now emit it unquoted for a spaced SSID instead of refusing.
486
+ The passphrase is still refused, for a different reason: its field has no read
487
+ path, so a truncated one cannot be detected.
488
+ - **`flash_print` is not listed**, so there is no *known* one-shot settings
489
+ dump. `Sign.dump()` walks the per-area getters instead. It is nullary, and a
490
+ bare call to a nullary command executes it, so the existence probe that
491
+ settled `wifi_ssid_set` is not safe to run here.
492
+
493
+ Going the other way, 47 present commands are undocumented, including all three
494
+ `encryption_*` commands, the whole `fs_*` family and the four `vlog_*` log-level
495
+ controls.
496
+
497
+ #### `sf_rdid` and `sf_rdst` kill the console
498
+
499
+ Measured, the hard way. Both assert immediately — `assert: spi_flash_cli.c:139`
500
+ and `:188` — because neither checks that `sf_select` has chosen a device first.
501
+ The assertion kills `usb_cli_task`: the prompt never returns, and the software
502
+ watchdog notices (`W WD task timeout: cli_USB` appears on the UART) without
503
+ acting on it. The sign itself is fine throughout — it stays on the network,
504
+ keeps its heartbeat and keeps its picture — and the console comes back only when
505
+ the device reboots, which it does on its own roughly 25 minutes later.
506
+
507
+ Both are gated behind `i_really_mean_it` for that reason alone; they read
508
+ nothing and write nothing. `sf_list` is fine.
509
+
510
+ #### Asynchronous log lines, and why this is the hard part
511
+
512
+ The firmware logs to the same UART, unprompted. A heartbeat fires every minute
513
+ and dumps eight lines; an image push adds a `Profiling:` line. Any of them can
514
+ land in the middle of a reply, so "every line between my command and the prompt
515
+ is my answer" corrupts *intermittently* — which is the worst failure mode,
516
+ because it passes every test you write by hand.
517
+
518
+ `SerialConsole` separates the streams with four mechanisms, and only the last
519
+ one is a heuristic:
520
+
521
+ 1. **Drain before send** — bytes buffered before the write cannot be the reply.
522
+ 2. **Echo anchor** — the device echoes the command line; the reply starts there.
523
+ 3. **Prompt terminator** — the reply ends at a `"> "` starting a line.
524
+ 4. **Pattern match** — lines inside the frame matching `LOG_PATTERNS` (every
525
+ entry taken from a real capture) move to the log stream.
526
+
527
+ `CommandResult` carries `lines` (yours), `logs` (the firmware's) and `raw` (both,
528
+ lossless). There is also an `on_log` callback and a `logs` history.
529
+
530
+ The sink can also be turned off at source. The firmware has a `vlog_*` family
531
+ that sets log levels per *source* and per *destination* independently — logging
532
+ is a matrix — and `vlog_unify_levels <usb_level>` applies one level to every
533
+ source on the USB destination. The scale runs **1 (silent) to 5 (everything)**,
534
+ and **`0` is not a valid level at all** — the firmware rejects it. So
535
+ `vlog_unify_levels 1` silences the port, measured at 0 lines in 90 s against
536
+ ~1 400 lines/min at level 5 while the radio was flapping, and the command's own
537
+ help line ("Reset logger levels to default for USB") is simply wrong.
538
+ `Sign.silence_usb_logs()` is the shorthand; `Sign.unify_usb_log_levels(level)`
539
+ keeps the mandatory argument, because a console driver wants 1 and someone
540
+ debugging a dead link wants 3.
541
+
542
+ It does **not** replace the four mechanisms above. Nothing persists without
543
+ `flash_save`, and the sign reboots itself when it cannot reach its server
544
+ (`E: Max conn errs. Reboot`), so the default verbosity comes back underneath a
545
+ long-running session. It also hides the error lines along with the chatter.
546
+
547
+ #### Line discipline, measured
548
+
549
+ - **CR (`\r`) submits. LF does not.** `cli_version_get\n` is echoed and then
550
+ *held* in the edit buffer, so the next command is appended to it and the pair
551
+ is rejected as one unrecognised word. `\r\n` works but leaves a stray LF that
552
+ pollutes the next read, so the terminator is a bare `\r`.
553
+ - The prompt is `"> "`, with no trailing newline. The device echoes. Commands
554
+ are case-insensitive.
555
+ - **Only some commands emit `rv:`, and not always last** — `certs_config_get`
556
+ prints `rv: 0` *before* its body. It comes in two spellings in one firmware,
557
+ `rv: 0` and `rv: 0x0`.
558
+ - Two error strings, and they quote `help` differently:
559
+ `Command 'x' not recognised. Enter 'help' ...` and
560
+ `Incorrect command parameter(s). Enter "help" ...`
561
+
562
+ #### Soft sleep did not happen
563
+
564
+ The vendor documents a soft sleep that cuts the console after 15 seconds of
565
+ accelerometer inactivity, and recommends setting `SLEEP_MODE` (52) to 1 for a
566
+ working session. **It did not bite on 7.4.4407.** A console held its prompt
567
+ across an undisturbed 45-second idle and answered immediately after, on a sign
568
+ whose uptime had been 25 days — so the CLI had been reachable that whole time
569
+ untouched. This library therefore sends no keepalive and does not touch TCLV 52,
570
+ both of which would be writes on a read-only session.
571
+
572
+ #### Encryption: the USB key is not the way in
573
+
574
+ `encryption_mode_set` takes **0 or 1** — that is solid, it is TCLV 130, whose
575
+ vendor description reads *"Outbound encryption: 0=Disabled, 1=Enabled"*. Note
576
+ that is a boolean and **not** the wire protocol's `SecurityType` (0/2/3).
577
+
578
+ The key format is **not** solid. The primitive is AES-128, so 16 bytes; the CLI
579
+ takes one whitespace-delimited token and `encryption_config_get` echoes it back
580
+ in single quotes, so it is stored as a printable string. The best-supported
581
+ reading is **16 printable ASCII characters used verbatim**, because every other
582
+ key and IV in this system is exactly that (`F@%gtb7;xLmXV$9a`,
583
+ `thisbeemulatorke`, `N3ls0#!Dba0f8*B>`). Base64 (24 chars) is second — it is how
584
+ the gateway serialises such a key for escrow. None of this was tested.
585
+
586
+ And the conclusion that matters: **setting the key over USB does not buy you
587
+ self-hosted link encryption.** The gateway encrypts with 16 `crypto/rand` bytes
588
+ minted fresh per activation and never transmits them; it sends the escrow
589
+ service's opaque response verbatim and the device is expected to resolve it
590
+ using what it already holds. TCLV 131 is that long-term secret, not the session
591
+ key, and reproducing the resolution means reading firmware that ships encrypted.
592
+ **TLS is the better answer in principle and is implemented here** --
593
+ `VisionectServer(certfile=..., keyfile=...)` sniffs the first six bytes of each
594
+ connection for a ClientHello and upgrades only that connection, so plaintext and
595
+ TLS signs share the one port exactly as the vendor's gateway arranges it. But
596
+ the device half depends on TCLV 145 (*"TLS mode: 0=disabled, 1=TLS 1.3"*), and
597
+ on the firmware this was developed against (7.4.4407) **the device does not
598
+ implement 145**: it refuses both a read and a write of it with the same code it
599
+ gives for a parameter id that does not exist. So on that firmware there is no
600
+ transport security available at all, and the control is network isolation. See
601
+ `OPEN-QUESTIONS.md` A4 for the wire evidence.
602
+
603
+ `pyvisionect.io.usb.encryption` holds all of this with its provenance, and
604
+ `pyvisionect-usb encryption` prints it. No setter in that module has ever been
605
+ executed.
606
+
607
+ ## Protocol notes worth knowing
608
+
609
+ ### The checksum is direction-dependent
610
+
611
+ The single most dangerous detail in this protocol. A symmetric CRC
612
+ implementation appears to work and then fails silently.
613
+
614
+ | direction | what is CRC'd |
615
+ |---|---|
616
+ | server -> device | `crc32_ieee(body)` — the whole body after compression |
617
+ | device -> server | `crc32_ieee(header[0:16])` — **it does not cover the payload at all** |
618
+
619
+ Proof of the device rule: two status packets ten minutes apart, with different
620
+ packet IDs and different battery and uptime values, carry the *identical*
621
+ checksum `0x198ceb01`, because their `(Version, Security, Compression, Length)`
622
+ prefix is identical.
623
+
624
+ `pyvisionect.wire.frame_checksum` takes a mandatory `Direction` and refuses
625
+ anything else. The decoder only *verifies* the inbound field in strict mode
626
+ (`ConnectionConfig(strict=True)`), off by default, because the real gateway never
627
+ validates it and a CRC that covers no payload bytes cannot detect corruption
628
+ anyway.
629
+
630
+ ### Framing
631
+
632
+ ```
633
+ ProtocolHeader 20 B LE Version=3 | Security | Compression | Length | Checksum
634
+ if Compression != 0: a chain of 24-B block records
635
+ BlockIndex(0-based) | BlocksMinusOne | PayloadLength | UncompressedLength
636
+ | Stored | Reserved
637
+ block plaintext = 4800 B (0x12C0)
638
+ Stored==1 -> payload verbatim; Stored==0 -> payload is a RAW LZ4 BLOCK
639
+ DataHeader 36 B LE Priority | DeviceID[16] | Type | ID | Length | Reserved
640
+ ```
641
+
642
+ - `Stored == 1` means **not** compressed. LZ4 is used only when it *strictly*
643
+ shrinks the block.
644
+ - `BlocksMinusOne` is an **index**, repeated identically in every block — 384 in
645
+ all 385 blocks of the captured image push — so a receiver knows the total from
646
+ the first header.
647
+ - The compressed payload is a **raw LZ4 block**: no frame magic, no content
648
+ checksum, no size prefix. `lz4.block`, not `lz4.frame`.
649
+ - The device never compresses; the gateway always does, even for an 8-byte ack.
650
+ - Maximum frame: 50 MiB (`0x3200000`).
651
+
652
+ ### IDs and acks
653
+
654
+ - Device packet IDs are a counter that **resets to 1 on every TCP connection**.
655
+ - Server packet IDs are a random uint32.
656
+ - The responder echoes the originator's ID. `ID == 0xFFFFFFFF` means "do not ack".
657
+ - Ack is `Control{Flags: 1}`; `Flags == 0` is a NACK; bit 25 is NACK-because-charging.
658
+ A device NACK carries a 4-byte error code — `0x00008a00` for the `@screen_N`
659
+ open that this hardware always refuses.
660
+
661
+ ### Packet type 2 (command): two of its 24 ids are captured, 22 are not
662
+
663
+ `sleep` (4) and `status request` (11) were provoked out of the vendor server on
664
+ 2026-10-05 and decoded off the wire by this library unmodified. So
665
+ `CommandPacket`'s 12-byte header is **real** and `Reserved` **is** emitted — the
666
+ param packet's struct-versus-wire mismatch (struct 12 bytes, wire header 8,
667
+ `Reserved` dropped) does not extend to type 2. The status-request frame proves
668
+ that on its own: `0b000000 00000000 00000000`, 12 bytes of header and no
669
+ payload. The device acks both with `Control{Flags: 1}`.
670
+
671
+ Also settled: **`CommandType` 0 is `echo` and 1 is `reboot`**, in both the v1 and
672
+ the v2 enum. An earlier revision of these notes had the two swapped, which would
673
+ have made `reboot()` send `echo` and an "echo" reboot the sign.
674
+
675
+ Every other id has still never been seen, and five have no emission site
676
+ anywhere in the vendor suite: `9` (LED window), `10` (LDRLED), `-1` (refresh),
677
+ `-2` (clear screen) and `-3` (keyboard). So: prefer a verified route where one
678
+ exists — an image push instead of `refresh`/`clear_screen`, a TCLV write instead
679
+ of `set_heartbeat` — and if you want a guarantee:
680
+
681
+ ```python
682
+ ConnectionConfig(allow_command_packets=False) # refuses to emit type 2 at all
683
+ ```
684
+
685
+ Two of 24 is not enough to take the other 22 on trust, so that opt-out is still
686
+ worth setting. What retires the caution for an id is what retired it for these
687
+ two: a frame on the wire plus the device's serial console saying what it did.
688
+ Meanwhile the effects are observable after the fact — a reboot shows up as the
689
+ device reconnecting with `ConnectReason == 1`, and the status answering a status
690
+ request carries `ConnectReason == 8` ("by server request"). Both are reported by
691
+ `status.connect_reason_name`.
692
+
693
+ ### There is no `list` opcode, and `@screen_N` is not about updates
694
+
695
+ A directory listing is a plain **read of `"."`** — a path of `"/"` or `""` is
696
+ rewritten to the one-byte string `"."`, and `Read(".", 10240)` returns an ASCII
697
+ blob:
698
+
699
+ ```python
700
+ conn.file_list() # open "." for reading
701
+ conn.read_file_range(FILE_LIST_LENGTH)
702
+ ...
703
+ parse_file_listing(reply) # {name: FileListEntry(size, checksum)}
704
+ ```
705
+
706
+ The columns are **`name checksum size`** — the useless one is in the middle, and
707
+ it reads `"0"` for every file on this firmware. The order is not a guess:
708
+ `/image0.pv2` lists as 134409 bytes and that file's own `ProtocolHeader.Length`
709
+ reads 134389, which is 134409 minus the 20-byte header.
710
+
711
+ Every reply the device sends — the listing, and every chunk of a file read —
712
+ arrives as `FileOperation.EVENT` (6), **not** `READ` (2). `read` is the request
713
+ direction only.
714
+
715
+ ### Reading a file back off the device
716
+
717
+ ```python
718
+ listing = await server.list_device_files(uuid) # one round trip, <1 s
719
+ raw = await server.read_device_file( # minutes; see below
720
+ uuid, "/image0.pv2", listing["/image0.pv2"].size,
721
+ progress=lambda done, total: print(done, total),
722
+ )
723
+ frame = parse_stored_frame(raw) # -> ImagePacket
724
+ canvas = decode_image_packet(frame.image, panel).canvas
725
+ ```
726
+
727
+ A `.pv2` is a stored protocol frame: `ProtocolHeader` (version **2**, not the
728
+ wire's 3) + LZ4 block chain + `DataHeader` + an ordinary type-5 image packet.
729
+ `parse_stored_frame_header()` reads the shape out of the first 44 bytes without
730
+ inflating anything. `decode_image_packet()` is the inverse of `encode_frame` and
731
+ is gated on the golden capture round-tripping bit for bit.
732
+
733
+ Three device facts shape the API rather than being hidden by it:
734
+
735
+ * **one reply carries at most 1024 bytes**, whatever you ask for (asking for
736
+ 32768 gets you 1024);
737
+ * **there is no seek** — `open` rewinds to zero and nothing else moves the
738
+ cursor, so a lost reply means restarting the whole transfer;
739
+ * **throughput is ~2.3 KiB/s**, about 420 ms per round trip, so this sign'''s
740
+ stored frames take **1–9 minutes each**.
741
+
742
+ `FileRead` in `pyvisionect.session.filetransfer` is the sans-io sequencer if you
743
+ are driving your own io.
744
+
745
+ **These files are not framebuffers.** On firmware 7.4.4407 `/image0.pv2` …
746
+ `/image5.pv2` are Visionect'''s shipped demo screens — a wayfinding board
747
+ ("Welcome to Nanotech inc."), a museum label ("Room 35 — Michelangelo and the
748
+ Florentines") and four more. Pushing a new frame changes none of them: not their
749
+ size, not their first bytes. They also carry `DataHeader.DeviceID == 0` and
750
+ `ImageHeader.Checksum == 0`, which no frame we send ever does
751
+ (`StoredFrame.looks_like_our_push` is that test). So there is **no device-side
752
+ readback of what the panel is currently showing**, and matching a stored
753
+ `ImageHeader.Checksum` against `DeviceState.pushed_checksum` cannot work — the
754
+ field is zero in all six. `DisplayStateCRC` remains the only way to ask the
755
+ device what it is displaying, and it is enough.
756
+
757
+ An earlier version of these docs said the gateway opens `@screen_<N>` "before
758
+ deciding how to update the screen", making the NACK "the mechanism behind
759
+ incremental updates". **That was wrong**, and it invented a constraint that does
760
+ not exist. The only reference to `"@screen_2"` in the whole gateway binary is a
761
+ hardcoded literal inside `main.(*grpcHandlers).handleLiveView` — not even a
762
+ `@screen_%d` format. The NACKs in the capture are replies to the `ac-device`
763
+ **live-view** request; the admin UI only offers that for `HardwareNameID` in
764
+ {11, 13, 24, 34, 42} and this sign is 8. The file protocol is not entangled with
765
+ image pushes at all.
766
+
767
+ (Partial updates are still never sent to this sign by the *vendor* server, for an unrelated
768
+ reason: `getRectangleSupport` returns false unconditionally for `HardwareNameID == 8`. This
769
+ library can send them anyway — see "Screen-space partial updates" above.)
770
+
771
+ ### Running without the LZ4 codec
772
+
773
+ ```python
774
+ ConnectionConfig(compressor=STORED_ONLY) # every block Stored=1
775
+ ```
776
+
777
+ The LZ4 codec is imported lazily and is only needed to compress outbound frames (the
778
+ default) or to inflate an inbound compressed one — which a device never sends:
779
+ every device→server frame in the capture carries `Compression = 0`.
780
+ `STORED_ONLY` keeps the ordinary block-chain framing and marks every block
781
+ `Stored=1`, which is a path the device demonstrably handles (60 of the captured
782
+ push's 385 blocks were stored anyway). The trade is roughly 4% more bytes for
783
+ zero C extensions beyond numpy/Pillow, and the captured push shows LZ4 buying
784
+ almost nothing on dithered halftone data (mean ratio 0.956).
785
+
786
+ Setting `Compression.NONE` on the **outbound** path is a different thing and is
787
+ **unverified** — the gateway was never observed sending an uncompressed frame to
788
+ a device, so whether the firmware accepts one is unknown. Do not reach for it.
789
+
790
+ ### Reconnects
791
+
792
+ A reconnect is a **full IP-stack re-initialisation**, not a socket retry:
793
+
794
+ ```
795
+ 802.2 XID -> DHCP DISCOVER (from 0.0.0.0) -> DHCP REQUEST
796
+ -> ARP who-has gateway -> ARP who-has server -> TCP SYN :11113
797
+ -> status with the ID counter reset to 1
798
+ ```
799
+
800
+ So **never key session state on the source port or the packet counter.** Only the
801
+ UUID is stable. `DeviceStateStore` does exactly that, and one of those
802
+ connections was observed opening and closing without carrying a single protocol
803
+ byte, so a silent connection must not evict anything.
804
+
805
+ ### Status packets are not CBOR
806
+
807
+ The payload is a flat list of 8-byte `(uint32 tag, uint32 value)` records,
808
+ terminated by tag `0xFFFFFFFF`. Absent fields are omitted entirely, so a status
809
+ is sparse — 62 records out of ~104 possible tags in the real capture.
810
+ Multi-word values occupy *consecutive* tags, which is why the numbering has gaps.
811
+
812
+ `StatusPacket` keeps the raw record list in wire order, so re-encoding is exactly
813
+ the inverse of decoding; `.fields()` gives you the named, typed view.
814
+
815
+ Codecs that are easy to get wrong:
816
+
817
+ | field | encoding |
818
+ |---|---|
819
+ | `SignalStrength` (13) | dBm **magnitude with the sign dropped** — negate it |
820
+ | `DeviceUptime` (15), `NextStatus` (27) | **minutes**, not seconds |
821
+ | `AverageTemperature` and friends | signed **int8** in the low byte; `0xFF`/`0xFFFFFFFF` = no reading |
822
+ | `HardwareID` (2) | `ID<<24 \| Family<<16 \| PCB` |
823
+ | `GTIN` (50–53) | 4 ASCII chars per word, little-endian, NUL-terminated |
824
+ | `BSSID` (91–92) | 6 bytes over 2 tags, little-endian |
825
+ | `Features` (43) | a **10**-bit mask |
826
+ | `ErrorCode` (1) | the *reason the packet was sent*, not a fault (13 = deep-sleep request) |
827
+ | `0xFFFFFFFF` as a value | "field absent" |
828
+
829
+ `Features` deserves a note. The vendor's *legacy* parser loops
830
+ `for mask := 1; mask <= 0x100; mask <<= 1` and silently drops bit 9 (`WiFiOTA`,
831
+ 512), so the vendor's own admin UI and engine see the live sign's `585` as if it
832
+ were `73`. **We do not replicate that bug.**
833
+
834
+ ### Devices are data, not subclasses
835
+
836
+ `DisplayType` stays an **opaque uint32**. The live sign reports `0xC2050128`,
837
+ which is not in the vendor's enum at all (it falls through to
838
+ `DISPLAY_UNKNOWN`) and is nevertheless a perfectly valid key. So: look the raw
839
+ value up in a table with a default row, and take *capabilities* from the device's
840
+ own `PV2Features` advertisement, never from the model.
841
+
842
+ For the 32" sign the server models `4 x 1440x640` and then the `eink-flip`
843
+ driver's interlacing step emits **two** rectangles of `2880x640` with
844
+ `ScreenID` 0 and 1, horizontally mirrored. `imaging/` reproduces both.
845
+
846
+ `panel_for()` says whether it recognised the panel at all, so diagnostics can be
847
+ honest about it rather than silently using a guess:
848
+
849
+ ```python
850
+ >>> panel_for(0xC2050128).describe()
851
+ 'unrecognised panel, assuming 1440x2560 (4 x 1440x640, driver eink-flip)'
852
+ >>> panel_for(0xC2050128).is_default
853
+ True
854
+ ```
855
+
856
+ Delta updates are implemented in the vendor server but it **refuses to send them to
857
+ this hardware**: `getRectangleSupport` returns false unconditionally for
858
+ `HardwareNameID == 8`, before it even consults the device options. Hence
859
+ `DeviceState.supports_rectangles`, which defaults to `False` until the device has
860
+ told us what it is.
861
+
862
+ That is server policy, not a panel limit. The 31.2" sign **does** accept partial
863
+ rectangles. What it cannot take is a rectangle in *canvas* coordinates, which would have
864
+ to survive the interlaced fold; one addressed in *screen* coordinates bypasses the fold.
865
+ `DeviceState.accepts_screen_rectangles` is the other half of the idea — False and True
866
+ respectively for this sign — and `pyvisionect.imaging.partial` is the encoder.
867
+
868
+ ### Screen-space partial updates — opt-in, one device, not vendor-sanctioned
869
+
870
+ ```python
871
+ from pyvisionect.imaging import DirtyTracker, PartialPolicy, Dithering
872
+
873
+ tracker = DirtyTracker(panel=conn.state.panel, encoding=4,
874
+ dithering=Dithering.BLUE_NOISE,
875
+ policy=PartialPolicy(max_consecutive_partials=10))
876
+
877
+ frame = tracker.update(img) # first frame: a full screen
878
+ frame = tracker.update(img2) # after that: only what changed
879
+ if frame.rectangles: # empty means the panel already shows this
880
+ conn.send_image(frame)
881
+ ```
882
+
883
+ Everything is still a pure function of the tracker's state plus the image — no clock, no
884
+ I/O — and it is still **CPU-bound**, so keep it off the event loop. It is a good deal
885
+ cheaper than a full push, though: on the real 1440 × 2560 dashboard canvas with a
886
+ `300 × 120` change, 9 ms against 34 ms for a full blue-noise encode, and **1.6 ms** if you
887
+ pass `rects=` because you already know what you redrew. `encode_frame(...,
888
+ partial=True)` and `encode_partial_frame(...)` are the stateless forms;
889
+ `encode_frame` without `partial=` behaves exactly as it always has.
890
+
891
+ A realistic small change — a `200x100` canvas block — costs **342 bytes on the wire
892
+ against 83 729 for a full push**, measured from the firmware's own profiling line. The
893
+ 2x in there is unavoidable: one screen rectangle always covers two canvas bands, because
894
+ they are interleaved 4 pixels at a time, so a partial carries the partner band's
895
+ unchanged pixels alongside the changed ones. Do not read this as faster refreshes — the
896
+ panel still spends ~1.7 s on a partial and 2.9–5.3 s on a full one, and the policy makes
897
+ you take a full one periodically.
898
+
899
+ That periodic full push is the point, not an overhead: with the shipped
900
+ `RectangleFlags = 0` a full-screen update *asks for* the panel's inverse clearing
901
+ waveform, and e-ink under nothing but partial updates accumulates ghosting. Measured:
902
+ across eight partial pushes the firmware never once initiated a clearing refresh of its
903
+ own, so the policy is doing real work. It also does not always get what it asks for — the
904
+ device grants the clearing waveform on some full pushes and not others, for reasons we
905
+ have not pinned down — which is why `PartialPolicy` defaults to the vendor's conservative
906
+ `noFullUpdateMax = 10` rather than something larger.
907
+
908
+ The tracker falls back to a full push — and tells you why in
909
+ `EncodedFrame.fallback_reason` — when there is no previous state, when the encoding or
910
+ dithering changed, when an inverse update is requested, when the dirty area would cost
911
+ more than half a full push, when there are more dirty regions than merging can reduce,
912
+ when the panel has no screen-space addressing, and when the ghosting budget trips. If a
913
+ push *fails*, call `tracker.rollback()`: the tracker's state image is a claim about what
914
+ the glass shows, and a failed push makes it a lie.
915
+
916
+ Verified by hand on one device — `HardwareNameID 8`, the 31.2" Place&Play 32, firmware
917
+ 7.4.4407, hardware 1.1.0. The vendor's server never sends this hardware a partial, so
918
+ there is no vendor behaviour to match and no vendor support if it misbehaves. See
919
+ `OPEN-QUESTIONS.md` A10 and `docs/imaging.md`.
920
+
921
+ ## What is deliberately out of scope
922
+
923
+ - **Link encryption.** `Security != 0` needs a 16-byte session key that the
924
+ vendor's gateway escrows with a Visionect HTTPS service; that key material is
925
+ not in the server image, so a self-hosted deployment is plaintext by
926
+ construction. The decoder raises a clear error and the seam is there.
927
+ - **Firmware and bootloader push.** The payloads are AES-CBC (fixed, fleet-wide IV) under a key that
928
+ exists only on Visionect's servers. Relaying an opaque blob to a device that
929
+ will flash it is not something to ship untested.
930
+ - **Discovery.** There is none. Give Home Assistant an explicit address.
931
+ - **`packet.Type 12` (CBOR) payloads.** The framing is implemented; the CBOR body
932
+ is not parsed. That channel belongs to the newer "AC"/JS-app device generation
933
+ and firmware 7.4.4407 never uses it.
934
+
935
+ ## Tests
936
+
937
+ ```sh
938
+ pip install -e '.[test,imaging,usb]'
939
+ pytest
940
+ ```
941
+
942
+ The primary correctness gate is a **golden replay** of real traffic from the
943
+ user's sign (`tests/fixtures/golden.json.gz`, ~90 KB, extracted from a 1.9 MB
944
+ pcap with `tools/extract_pcap_fixture.py`). It asserts that every one of the 62
945
+ captured frames decodes in strict mode, and that **61 of 62 re-encode
946
+ byte-for-byte** — payload re-encoded through its own codec, re-framed, re-CRC'd,
947
+ and compared against the captured bytes.
948
+
949
+ Two honest caveats about that number:
950
+
951
+ 1. **The vendor's LZ4 compressor is not reproducible.** `vss/lz4.Lz4Compress`
952
+ produces different (equally valid) output from python-lz4 for the same input.
953
+ Measured over all 328 LZ4 blocks the gateway sent in the capture: **0 of 328**
954
+ match `lz4.block.compress` in its default or `fast` modes at any
955
+ acceleration, and only **3 of 328** match under `high_compression` (levels
956
+ 1–9) — and those three are the tiny 44-byte ack bodies, not the image data.
957
+ So for the gateway direction the replay test feeds the
958
+ encoder a compressor that hands back the capture's own per-block payloads.
959
+ Everything else — the block headers, the stored/LZ4 decision, the CRC, the
960
+ outer header — is reproduced exactly, and the chain is separately rebuilt
961
+ byte-for-byte from the decoded plaintext. Interoperability is unaffected (the
962
+ device decodes any valid LZ4 block); `encode_blocks(compressor=...)` is the
963
+ seam if you ever do reproduce it.
964
+ 2. **`tcpdump` dropped five 1460-byte segments inside the 1.84 MB image push.**
965
+ 4 of its 385 blocks are unrecoverable and `crc32(body)` for that one frame
966
+ cannot be recomputed, so it is the one frame excluded from the byte-exact
967
+ count. Everything else about it *is* checked: 383 of 385 block headers, the
968
+ 60-stored/325-LZ4 split, the `DataHeader`, the `ImageHeader` and both
969
+ `RectangleHeader`s, all byte-exact.
970
+
971
+ If the original pcap happens to be present, `tests/test_pcap_full_replay.py`
972
+ repeats the exercise against the raw capture instead of the fixture; it skips
973
+ cleanly when it is not.
974
+
975
+ Also covered: round-trip property tests on every codec, the direction-dependent
976
+ checksum against its captured constants, the 235-entry TCLV table, the session
977
+ state machine (acks, NACKs, reconnect-by-UUID, all three timers), the
978
+ pending-work queue (every coalescing rule, the connect ordering, ack/NACK
979
+ bookkeeping, persistence), `FrameState` and `DeviceState` serialisation, the listener over real loopback sockets
980
+ (bind errors, stats, flush), and an AST scan that fails the build if anything in
981
+ `wire/`, `packets/`, `session/` or `devices/` grows an I/O import or a clock
982
+ call.
983
+
984
+ The USB package has its own 274 tests in `tests/usb/`, run against a fake
985
+ transport that replays **real captured frames** from a live sign
986
+ (`pyvisionect.io.usb.fake`, scrubbed of identifiers and otherwise untouched).
987
+ That matters more than it sounds: a fixture written by hand from a parser's point
988
+ of view tests the parser against its own assumptions. Several parsers are shaped
989
+ the way they are only because of something visible in those captures and nowhere
990
+ in the vendor's documentation — the blank line before `uuid_get`'s payload, the
991
+ `rv: 0` that precedes `certs_config_get`'s body, the tab-separated `task_list`
992
+ columns, the one `status_get` key with a space in it.
993
+
994
+ The interleaving tests are the ones worth reading. The fake can splice the real
995
+ eight-line heartbeat burst into the middle of a reply, before the echo, or into
996
+ the buffer ahead of the write, and the tests assert that a parsed value comes out
997
+ identical either way. There is also a test that runs the async-log classifier
998
+ over **every line of every captured reply** and fails if it would swallow one,
999
+ because a false positive there silently eats an answer.
1000
+
1001
+ A further set of cross-checks compares two commands that report the same
1002
+ underlying value — `wifi_bssid_get` against `status_get`'s two BSSID words,
1003
+ `cc3100_rssi` against `SIGNAL_STRENGTH`, `fs_stats`' block count against
1004
+ `FS_TOTAL_SIZE`'s bytes. Those are what would catch a parser that is
1005
+ self-consistently wrong, and all of them were re-run against the live sign.
1006
+
1007
+ One of those is a regression test for a **hang** rather than a wrong answer:
1008
+ `test_close_does_not_hang_with_a_client_still_connected` opens a client, leaves
1009
+ it open as a real sign does, and asserts `close()` returns. Remove the
1010
+ `close_clients()` call and it times out, along with the test that the port is
1011
+ released for a reload. Worth knowing because `close_clients` appears zero times
1012
+ in all of Home Assistant core — no core integration hosts a listener for devices
1013
+ that hold connections open indefinitely, so there was no precedent to copy.
1014
+
1015
+ ## Provenance
1016
+
1017
+ Every non-obvious constant in this package carries a docstring citing where it
1018
+ came from: a Go symbol and source line from the unstripped `bin/gateway`
1019
+ (`proto/v2` v2.1.5, `proto` v1.2.23), a byte offset in the captured traffic, or
1020
+ the vendor's published CLI reference. A handful of things are marked `[INFERRED]`
1021
+ or `[GAP]` because they were not provable from the material available — notably
1022
+ `packet.Priority`'s value space, the meaning of the status sentinel's value and
1023
+ the `GPS` coordinate string framing. Those are flagged in place rather than
1024
+ smoothed over. The `sleep` command's payload layout and the inverse-update
1025
+ option bit were on that list until 2026-10-05; both are now verified on
1026
+ hardware.
1027
+
1028
+ ## Licence
1029
+
1030
+ MIT.