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,587 @@
1
+ """Per-device durable state, keyed on the UUID and nothing else.
2
+
3
+ Why the UUID and nothing else
4
+ -----------------------------
5
+
6
+ A reconnect is a **full IP-stack re-initialisation**, not a socket retry. The
7
+ observed sequence is::
8
+
9
+ 802.2 XID -> DHCP DISCOVER (from 0.0.0.0, not a unicast renew) -> DHCP REQUEST
10
+ -> ARP who-has <gateway> -> ARP who-has <server> -> TCP SYN :11113
11
+ -> status with the packet ID counter reset to 1
12
+
13
+ So the source port changes, the packet counter restarts at 1, and the device may
14
+ even have a different IP. **Never key session state on the source port or the
15
+ packet counter.** The 16-byte UUID in the ``DataHeader`` is the only stable
16
+ identity, and the gateway treats registration as auto-create on first sight.
17
+
18
+ Two spontaneous reconnects were observed in a 22-minute window, and one of them
19
+ opened and closed carrying no protocol bytes at all, so a connection that
20
+ produces nothing is normal and must not evict the device's state.
21
+ """
22
+
23
+ from __future__ import annotations
24
+
25
+ from dataclasses import dataclass, field
26
+ from enum import Enum
27
+ from typing import Any
28
+
29
+ from ..devices.panels import Panel, panel_for
30
+ from ..packets.status import StatusPacket
31
+ from .pending import PendingWork
32
+
33
+ __all__ = [
34
+ "CONVERGENCE_CONTACTS",
35
+ "DEFAULT_CONTACT_INTERVAL",
36
+ "DRAW_ALLOWANCE",
37
+ "DeviceState",
38
+ "DeviceStateStore",
39
+ "RECTANGLE_UNSUPPORTED_HARDWARE",
40
+ "SCREEN_RECTANGLE_VERIFIED_HARDWARE",
41
+ "SyncStatus",
42
+ ]
43
+
44
+
45
+ class SyncStatus(str, Enum):
46
+ """What :attr:`DeviceState.in_sync` means *right now*, with the clock.
47
+
48
+ :attr:`DeviceState.in_sync` is a correct tri-state and a bad alarm. A push
49
+ legitimately leaves the device disagreeing with us for the whole of its
50
+ draw-and-report cycle -- measured at 48 s on the 31.2" sign with a
51
+ one-minute heartbeat -- so "checksums differ" raised immediately is a
52
+ problem indicator after **every normal update**.
53
+
54
+ This enum splits ``in_sync is False`` into the two cases that actually
55
+ differ:
56
+
57
+ * :attr:`CONVERGING` -- they differ, and the device has not yet had a fair
58
+ chance to tell us otherwise. Expected, transient, not a problem.
59
+ * :attr:`DIVERGED` -- they differ, and it has had its chance. The panel is
60
+ showing something other than what we sent.
61
+
62
+ "Had its chance" is :meth:`DeviceState.sync_status`; see there.
63
+ """
64
+
65
+ UNKNOWN = "unknown"
66
+ """Never pushed, or the device has not reported a ``DisplayStateCRC``."""
67
+
68
+ IN_SYNC = "in_sync"
69
+ """The device echoes the checksum of our last push."""
70
+
71
+ CONVERGING = "converging"
72
+ """Mismatched, but still inside the window the device is allowed."""
73
+
74
+ DIVERGED = "diverged"
75
+ """Mismatched after the device has had its say. A real problem."""
76
+
77
+
78
+ CONVERGENCE_CONTACTS = 2
79
+ """Status packets that must arrive after a push before a mismatch counts.
80
+
81
+ **Two, not one.** One is tempting and wrong: a push that lands a second before
82
+ a scheduled heartbeat is acked but not yet *drawn*, so the very next status
83
+ still carries the old ``DisplayStateCRC``.
84
+
85
+ The counter alone is not enough either, which is only visible on hardware: the
86
+ sign **bursts** status packets around a draw. Measured on the 31.2" sign on
87
+ 2026-10-05, with a one-minute announced heartbeat, the contacts arriving after
88
+ a push went 0 -> 9 in the first 55 s and then settled to roughly one a minute.
89
+ So "two contacts" can elapse in fifteen seconds, well before a 1.84 MB frame
90
+ has even finished transferring. That is why the counter is gated on
91
+ :data:`DRAW_ALLOWANCE` as well -- see :meth:`DeviceState.sync_status`.
92
+ """
93
+
94
+ DRAW_ALLOWANCE = 60.0
95
+ """Seconds for a frame to transfer and reach the glass, on top of one interval.
96
+
97
+ A full-screen push is ~1.84 MB to a CC3100 (acked at 3-7 s) and the panel needs
98
+ ~3 s of waveform. The measured gap from push to the device echoing the new
99
+ ``DisplayStateCRC`` is 10-48 s depending on where the push lands relative to the
100
+ heartbeat, so this is roughly 2x the worst observed case before it is even
101
+ added to an interval.
102
+ """
103
+
104
+ DEFAULT_CONTACT_INTERVAL = 60.0
105
+ """Seconds assumed between contacts when the device has not announced one.
106
+
107
+ ``NextStatus`` (status tag 27) is in minutes and is present on this hardware,
108
+ so this is only reached before the first status of a fresh install.
109
+ """
110
+
111
+ RECTANGLE_UNSUPPORTED_HARDWARE: frozenset[int] = frozenset({8})
112
+ """``HardwareNameID`` values for which the server's ``getRectangleSupport``
113
+ returns false **unconditionally** (``client.go:41``), before it even consults
114
+ ``MergeRegions`` / ``ForceRectangleSupport`` / the device option.
115
+
116
+ The live 32" sign reports ``HardwareNameID == 8``, so every push to it is
117
+ full-screen. Two further gates would stop partial updates anyway: the
118
+ interlacing step needs exactly four rectangles of exactly 1440x640 with equal
119
+ encoding, which small dirty rects can never satisfy, and ``noFullUpdateMax = 10``
120
+ caps consecutive partials regardless.
121
+
122
+ This set is about the **vendor server**. For what the device itself accepts,
123
+ see :data:`SCREEN_RECTANGLE_VERIFIED_HARDWARE`.
124
+ """
125
+
126
+ SCREEN_RECTANGLE_VERIFIED_HARDWARE: frozenset[int] = frozenset({8})
127
+ """``HardwareNameID`` values **measured** accepting a screen-space partial.
128
+
129
+ Note that this deliberately overlaps
130
+ :data:`RECTANGLE_UNSUPPORTED_HARDWARE` rather than complementing it: the two
131
+ sets answer different questions. ``HardwareNameID 8`` is in both because the
132
+ vendor's server would never send it a partial *and* the device takes one
133
+ happily.
134
+
135
+ Membership here means a physical device of that hardware class was driven with
136
+ screen-addressed partial rectangles and acked them, drew only the addressed
137
+ region, and echoed our state checksum back as ``DisplayStateCRC``. For id 8
138
+ that is the 31.2" Place&Play 32, firmware 7.4.4407, hardware revision 1.1.0,
139
+ on 2026-10-05: 17 pushes, 17 acks, zero NACKs (``OPEN-QUESTIONS.md`` A10).
140
+
141
+ It is a record of an experiment, not a capability advertisement. A device
142
+ does not tell us this about itself anywhere, so the only honest way to add an
143
+ id is to point one at :class:`pyvisionect.imaging.DirtyTracker` and watch the
144
+ glass.
145
+ """
146
+
147
+
148
+ @dataclass(slots=True)
149
+ class DeviceState:
150
+ """Everything we remember about one sign across reconnects.
151
+
152
+ Attributes:
153
+ device_id: the raw 16 UUID bytes.
154
+ last_status: the most recent status packet.
155
+ imaging_state: the opaque ``EncodedFrame.state`` from the last successful
156
+ push, to hand back to :func:`pyvisionect.imaging.encode_frame` as
157
+ ``prev_state``.
158
+ pushed_checksum: the ``ImageHeader.Checksum`` of our last push. Compare
159
+ against the device's reported ``DisplayStateCRC`` (status tag 9) to
160
+ tell whether the sign is in sync.
161
+ connections: how many TCP connections this UUID has opened.
162
+ """
163
+
164
+ device_id: bytes
165
+ last_status: StatusPacket | None = None
166
+ pending: PendingWork = field(default_factory=PendingWork)
167
+ """Durable, coalescing work for this device.
168
+
169
+ Queue here rather than on a connection: the device is absent most of the
170
+ time. See :mod:`pyvisionect.session.pending`.
171
+ """
172
+ imaging_state: Any = None
173
+ pushed_checksum: int | None = None
174
+ connections: int = 0
175
+ pushes: int = 0
176
+ """How many image packets we have queued for this device."""
177
+ statuses_seen: int = 0
178
+ """How many status packets this device has sent us, ever."""
179
+ statuses_at_push: int | None = None
180
+ """:attr:`statuses_seen` as it stood when the last push was queued.
181
+
182
+ The difference is :attr:`contacts_since_push`, which is the whole of "has
183
+ the device had a chance to report?" expressed without a clock.
184
+ """
185
+ last_push_at: float | None = None
186
+ """Caller-supplied clock value of the last push, or None.
187
+
188
+ Deliberately **not** persisted: it is whatever clock the caller passed
189
+ (``time.monotonic`` for the bundled listener), and a monotonic value means
190
+ nothing after a restart. A restored state therefore falls back to the
191
+ contact counter alone, which is the safe direction.
192
+ """
193
+ options: dict[str, str] = field(default_factory=dict)
194
+ """Server-side, string-keyed device options.
195
+
196
+ This is a *separate* namespace from the TCLV ids -- the vendor's
197
+ ``common.Device.Options`` map. Only ``"Secure"`` was traced end-to-end into
198
+ the protocol; a systematic Options -> TCLV mapping was not recovered. [GAP]
199
+
200
+ ``MergeRegions`` has the grammar ``"<bool>[,threshold=N][,thresholdStep=N]"``
201
+ and **N is a percentage of the display diagonal, not pixels** -- 5%/10% on a
202
+ 1440x640 display is 78.8/157.6 px.
203
+ """
204
+
205
+ @property
206
+ def uuid(self) -> str:
207
+ h = self.device_id.hex()
208
+ return f"{h[0:8]}-{h[8:12]}-{h[12:16]}-{h[16:20]}-{h[20:32]}"
209
+
210
+ @property
211
+ def display_type(self) -> int | None:
212
+ """The raw uint32 ``DisplayType`` the device last reported (status tag 8)."""
213
+ return self.last_status.display_type if self.last_status else None
214
+
215
+ @property
216
+ def panel(self) -> Panel:
217
+ """Modelled geometry, from the raw ``DisplayType`` with a default row."""
218
+ return panel_for(self.display_type if self.display_type is not None else -1)
219
+
220
+ @property
221
+ def hardware_name_id(self) -> int | None:
222
+ return self.last_status.hardware_name_id if self.last_status else None
223
+
224
+ @property
225
+ def supports_rectangles(self) -> bool:
226
+ """Whether the **vendor stack** would ever send this device a partial.
227
+
228
+ False for ``HardwareNameID == 8``, unconditionally. Defaults to False
229
+ when the hardware id is not yet known, so nothing depends on partials
230
+ before we have heard from the device.
231
+
232
+ .. warning::
233
+ This is a statement about ``getRectangleSupport``
234
+ (``vss/cmd/engine/client.go:41``), **not** about the panel. The
235
+ 31.2" sign was measured accepting partial rectangles on 2026-10-05:
236
+ it acks them, draws only the addressed region, and echoes back the
237
+ state checksum. What it will not take is a rectangle in *canvas*
238
+ coordinates, because those have to survive the interlaced fold; a
239
+ rectangle addressed in *screen* coordinates bypasses the fold
240
+ entirely. See ``OPEN-QUESTIONS.md`` A10. This property is left
241
+ False so that nothing silently starts emitting partials, but it is
242
+ the wrong question to ask of the hardware.
243
+ """
244
+ hw = self.hardware_name_id
245
+ if hw is None:
246
+ return False
247
+ return hw not in RECTANGLE_UNSUPPORTED_HARDWARE
248
+
249
+ @property
250
+ def accepts_screen_rectangles(self) -> bool:
251
+ """Whether **this device** was measured taking a partial rectangle.
252
+
253
+ The other half of the idea :attr:`supports_rectangles` used to carry
254
+ alone. ``supports_rectangles`` answers "would the vendor stack ever
255
+ send one"; this answers "does the hardware take one". For the 32"
256
+ sign the answers are **False and True** respectively, which is exactly
257
+ why they had to become two properties.
258
+
259
+ True for a ``HardwareNameID`` in
260
+ :data:`SCREEN_RECTANGLE_VERIFIED_HARDWARE`, and False until the device
261
+ has told us its hardware id -- the usual default, so nothing assumes a
262
+ capability before it has heard from the device.
263
+
264
+ What it unlocks is :mod:`pyvisionect.imaging.partial`: rectangles
265
+ addressed in **screen** coordinates, which never enter the interlaced
266
+ fold. Canvas-space rectangles remain impossible on this hardware, and
267
+ :attr:`pyvisionect.imaging.Panel.forces_full_screen` still says so.
268
+
269
+ .. warning::
270
+ This is hand-measured on one device, not vendor-sanctioned, and it
271
+ buys **bytes and encode time, not refresh latency** (the panel's
272
+ waveform floor is ~2.9 s whatever the area). Nothing in the
273
+ library turns partials on because of this property; it is here so a
274
+ caller can decide.
275
+ """
276
+ hw = self.hardware_name_id
277
+ if hw is None:
278
+ return False
279
+ return hw in SCREEN_RECTANGLE_VERIFIED_HARDWARE
280
+
281
+ @property
282
+ def features(self) -> dict[str, bool]:
283
+ """The device's own ``PV2Features`` advertisement (status tag 43).
284
+
285
+ Capabilities come from here, never from the model.
286
+ """
287
+ if not self.last_status:
288
+ return {}
289
+ fields = self.last_status.fields()
290
+ feats = fields.get("Features")
291
+ if not isinstance(feats, dict):
292
+ return {}
293
+ return {k: v for k, v in feats.items() if not k.startswith("_")}
294
+
295
+ @property
296
+ def has_pushed(self) -> bool:
297
+ """Whether we have ever pushed a frame to this device."""
298
+ return self.pushed_checksum is not None
299
+
300
+ @property
301
+ def in_sync(self) -> bool | None:
302
+ """Tri-state: in sync, out of sync, or **not known**.
303
+
304
+ * ``True`` -- the device's reported ``DisplayStateCRC`` equals the
305
+ ``ImageHeader.Checksum`` of our last push. It is showing what we sent.
306
+ * ``False`` -- they differ. A push is needed.
307
+ * ``None`` -- we have never pushed anything, or the device has not told
308
+ us its state yet. That is a fresh install, not a problem, and callers
309
+ should present it differently from ``False``.
310
+ """
311
+ if self.pushed_checksum is None or self.last_status is None:
312
+ return None
313
+ reported = self.last_status.display_state_crc
314
+ if reported is None:
315
+ return None
316
+ return reported == self.pushed_checksum
317
+
318
+ @property
319
+ def contacts_since_push(self) -> int:
320
+ """Status packets received since the last push was queued.
321
+
322
+ ``0`` when nothing has been pushed, so a fresh device never looks like
323
+ it has failed to converge.
324
+ """
325
+ if self.statuses_at_push is None:
326
+ return 0
327
+ return max(0, self.statuses_seen - self.statuses_at_push)
328
+
329
+ @property
330
+ def expected_contact_interval(self) -> float | None:
331
+ """Seconds until the device said it would next be in touch.
332
+
333
+ ``NextStatus`` (status tag 27) in **minutes**, converted. ``None``
334
+ before the first status packet. This is the device's own announcement
335
+ and is what "a chance to report" has to be measured against: a sign on
336
+ a one-hour heartbeat is not broken for the 59 minutes it is away.
337
+ """
338
+ if self.last_status is None:
339
+ return None
340
+ minutes = self.last_status.next_status_minutes
341
+ if not minutes:
342
+ return None
343
+ return float(minutes) * 60.0
344
+
345
+ def _interval(self, interval: float | None = None) -> float:
346
+ if interval is None:
347
+ interval = self.expected_contact_interval
348
+ if not interval or interval <= 0:
349
+ interval = DEFAULT_CONTACT_INTERVAL
350
+ return interval
351
+
352
+ def settle_time(self, *, interval: float | None = None) -> float:
353
+ """Seconds before the device could *possibly* have reported the push.
354
+
355
+ One full announced interval -- the worst case is a frame that finishes
356
+ drawing a moment after a status went out, so the news waits for the
357
+ next one -- plus :data:`DRAW_ALLOWANCE` for getting it onto the glass.
358
+
359
+ Nothing before this is evidence of anything, however many status
360
+ packets have arrived, because the sign emits a burst of them around a
361
+ draw.
362
+ """
363
+ return self._interval(interval) + DRAW_ALLOWANCE
364
+
365
+ def convergence_grace(
366
+ self,
367
+ *,
368
+ contacts: int = CONVERGENCE_CONTACTS,
369
+ interval: float | None = None,
370
+ ) -> float:
371
+ """Seconds a push is allowed before a mismatch is called a problem.
372
+
373
+ ``contacts * interval + DRAW_ALLOWANCE``, where *interval* defaults to
374
+ :attr:`expected_contact_interval` and then to
375
+ :data:`DEFAULT_CONTACT_INTERVAL`. It scales with the device's own
376
+ announced schedule rather than being a flat timeout, which is the
377
+ difference between "wait for the sign" and "wait long enough that the
378
+ alarm is useless".
379
+ """
380
+ return contacts * self._interval(interval) + DRAW_ALLOWANCE
381
+
382
+ def convergence_deadline(
383
+ self,
384
+ *,
385
+ contacts: int = CONVERGENCE_CONTACTS,
386
+ interval: float | None = None,
387
+ ) -> float | None:
388
+ """Clock value past which a mismatch counts, or None if unknown."""
389
+ if self.last_push_at is None:
390
+ return None
391
+ return self.last_push_at + self.convergence_grace(
392
+ contacts=contacts, interval=interval
393
+ )
394
+
395
+ def sync_status(
396
+ self,
397
+ now: float | None = None,
398
+ *,
399
+ contacts: int = CONVERGENCE_CONTACTS,
400
+ interval: float | None = None,
401
+ ) -> "SyncStatus":
402
+ """:attr:`in_sync`, but with "it has not answered yet" split out.
403
+
404
+ A mismatch becomes :attr:`SyncStatus.DIVERGED` when **either**:
405
+
406
+ * the device has been in touch :data:`CONVERGENCE_CONTACTS` times since
407
+ the push, **and** :meth:`settle_time` has passed so those contacts
408
+ could actually have carried the news -- it has had its say; or
409
+ * :meth:`convergence_grace` has passed -- it has stopped saying
410
+ anything, and a silent sign is not an excuse for a stale panel.
411
+
412
+ The second condition is the one that catches a device that went away.
413
+ The first is faster whenever the device is chatty, which matters for a
414
+ sign on a long heartbeat.
415
+
416
+ **The ``settle_time`` gate on the counter is not belt-and-braces.** The
417
+ 31.2" sign emits a burst of status packets around a draw -- nine in the
418
+ first 55 s after a push, then one a minute -- so the bare counter can
419
+ be satisfied in fifteen seconds, before a 1.84 MB frame has finished
420
+ transferring. Counting those as "chances to report" would reintroduce
421
+ the false alarm this method exists to remove.
422
+
423
+ Args:
424
+ now: a clock value on the same scale as the one passed to
425
+ :meth:`DeviceConnection.send_image`. Without it neither
426
+ deadline can be evaluated and the counter alone decides, which
427
+ is the right fallback for a state restored from disk: any push
428
+ it remembers is from before the restart and has long since had
429
+ its chance.
430
+ contacts: how many contacts count as "had its say".
431
+ interval: override the device's announced contact interval, in
432
+ seconds.
433
+ """
434
+ state = self.in_sync
435
+ if state is None:
436
+ return SyncStatus.UNKNOWN
437
+ if state:
438
+ return SyncStatus.IN_SYNC
439
+
440
+ enough_contacts = self.contacts_since_push >= contacts
441
+ if now is None or self.last_push_at is None:
442
+ return SyncStatus.DIVERGED if enough_contacts else SyncStatus.CONVERGING
443
+
444
+ elapsed = now - self.last_push_at
445
+ if enough_contacts and elapsed >= self.settle_time(interval=interval):
446
+ return SyncStatus.DIVERGED
447
+ if elapsed >= self.convergence_grace(contacts=contacts, interval=interval):
448
+ return SyncStatus.DIVERGED
449
+ return SyncStatus.CONVERGING
450
+
451
+ def note_push(self, checksum: int, *, now: float | None = None) -> None:
452
+ """Record that *checksum* was put on the wire.
453
+
454
+ Called for you by :meth:`DeviceConnection.send_image_packet`.
455
+ """
456
+ self.pushed_checksum = checksum
457
+ self.pushes += 1
458
+ self.statuses_at_push = self.statuses_seen
459
+ self.last_push_at = now
460
+
461
+ def apply_status(self, status: StatusPacket) -> None:
462
+ self.last_status = status
463
+ self.statuses_seen += 1
464
+
465
+ # ------------------------------------------------------- persistence
466
+
467
+ VERSION = 1
468
+
469
+ def to_dict(self) -> dict[str, Any]:
470
+ """A JSON-safe snapshot, so a consumer can persist the store wholesale.
471
+
472
+ ``imaging_state`` is **not** included: it is two numpy planes and has
473
+ its own, much better, binary format --
474
+ :meth:`pyvisionect.imaging.FrameState.to_bytes`. Persist that
475
+ separately and hand it back via :attr:`imaging_state`.
476
+ """
477
+ status = self.last_status
478
+ return {
479
+ "v": self.VERSION,
480
+ "device_id": self.device_id.hex(),
481
+ "pushed_checksum": self.pushed_checksum,
482
+ "connections": self.connections,
483
+ "pushes": self.pushes,
484
+ "statuses_seen": self.statuses_seen,
485
+ "statuses_at_push": self.statuses_at_push,
486
+ "options": dict(self.options),
487
+ "pending": self.pending.to_dict(),
488
+ "last_status": (
489
+ {
490
+ "records": [list(r) for r in status.records],
491
+ "sentinel": status.sentinel,
492
+ }
493
+ if status is not None
494
+ else None
495
+ ),
496
+ }
497
+
498
+ @classmethod
499
+ def from_dict(cls, raw: dict[str, Any]) -> "DeviceState":
500
+ """Restore from :meth:`to_dict`.
501
+
502
+ An unknown version raises rather than silently mis-restoring.
503
+ """
504
+ version = raw.get("v", 1)
505
+ if version != cls.VERSION:
506
+ raise ValueError(
507
+ f"DeviceState snapshot version {version} is not {cls.VERSION}; "
508
+ "discard it and let the device re-register instead of guessing"
509
+ )
510
+ status_raw = raw.get("last_status")
511
+ status = None
512
+ if status_raw:
513
+ status = StatusPacket(
514
+ records=[(int(t), int(v)) for t, v in status_raw["records"]],
515
+ sentinel=status_raw.get("sentinel"),
516
+ )
517
+ return cls(
518
+ device_id=bytes.fromhex(raw["device_id"]),
519
+ last_status=status,
520
+ pending=PendingWork.from_dict(raw["pending"]) if raw.get("pending") else PendingWork(),
521
+ pushed_checksum=raw.get("pushed_checksum"),
522
+ connections=int(raw.get("connections", 0)),
523
+ pushes=int(raw.get("pushes", 0)),
524
+ statuses_seen=int(raw.get("statuses_seen", 0)),
525
+ statuses_at_push=(
526
+ None
527
+ if raw.get("statuses_at_push") is None
528
+ else int(raw["statuses_at_push"])
529
+ ),
530
+ options=dict(raw.get("options") or {}),
531
+ )
532
+
533
+
534
+ class DeviceStateStore:
535
+ """A ``{uuid_bytes: DeviceState}`` map. Auto-creates on first sight.
536
+
537
+ Pure. Hold one of these for the lifetime of the listener, not per connection.
538
+ """
539
+
540
+ def __init__(self) -> None:
541
+ self._states: dict[bytes, DeviceState] = {}
542
+
543
+ def get(self, device_id: bytes) -> DeviceState:
544
+ state = self._states.get(device_id)
545
+ if state is None:
546
+ state = DeviceState(device_id=device_id)
547
+ self._states[device_id] = state
548
+ return state
549
+
550
+ def queue(self, device_id: bytes) -> PendingWork:
551
+ """The durable, coalescing work register for *device_id*.
552
+
553
+ Auto-creates, like :meth:`get`. Queue here whether or not the device is
554
+ currently connected -- :meth:`DeviceConnection.apply_pending` drains it
555
+ on the next connect, in the right order.
556
+ """
557
+ return self.get(device_id).pending
558
+
559
+ def restore(self, state: DeviceState) -> DeviceState:
560
+ """Insert a :class:`DeviceState` restored from :meth:`DeviceState.from_dict`."""
561
+ self._states[state.device_id] = state
562
+ return state
563
+
564
+ def to_dict(self) -> dict[str, Any]:
565
+ """Snapshot every known device, keyed on the hex UUID."""
566
+ return {
567
+ state.device_id.hex(): state.to_dict() for state in self._states.values()
568
+ }
569
+
570
+ @classmethod
571
+ def from_dict(cls, raw: dict[str, Any]) -> "DeviceStateStore":
572
+ store = cls()
573
+ for snapshot in raw.values():
574
+ store.restore(DeviceState.from_dict(snapshot))
575
+ return store
576
+
577
+ def __contains__(self, device_id: bytes) -> bool:
578
+ return device_id in self._states
579
+
580
+ def __len__(self) -> int:
581
+ return len(self._states)
582
+
583
+ def __iter__(self):
584
+ return iter(self._states.values())
585
+
586
+ def known(self) -> list[DeviceState]:
587
+ return list(self._states.values())