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,518 @@
1
+ """Status packets (type 3) -- the device's heartbeat and the only packet it must send.
2
+
3
+ The payload is **not CBOR**. It is a flat sequence of 8-byte records::
4
+
5
+ +-------------------------------+
6
+ | Tag (uint32 LE) |
7
+ +-------------------------------+
8
+ | Value (uint32 LE) |
9
+ +-------------------------------+
10
+ ... one record per *present* field ...
11
+ | Tag = 0xFFFFFFFF | <- sentinel, always last
12
+ | Value = <changes with the payload>
13
+ +-------------------------------+
14
+
15
+ ``status.(*Encoder).write`` (``status/encoder.go:348-356``) returns early on a nil
16
+ pointer, so **absent fields are omitted entirely** and a status is a sparse list.
17
+ In the captured heartbeat 62 of the ~104 possible tags are present.
18
+
19
+ Multi-word values occupy **consecutive** tags
20
+ (``status.(*Encoder).writeMultiValue``, ``encoder.go:371-382``), which is exactly
21
+ why the tag numbering has gaps.
22
+
23
+ Tag table provenance
24
+ --------------------
25
+
26
+ Two sources agree and are reconciled here:
27
+
28
+ * the **v2** ``status.Status`` struct's ``cbor:"N,keyasint"`` numbers, read out of
29
+ the Go runtime type metadata. The flat wire payload reuses those numbers as
30
+ its uint32 keys, so the CBOR tags are directly authoritative even though this
31
+ firmware never sends CBOR.
32
+ * the **v1** ``proto.statusStringMap`` (103 entries + sentinel), which is what the
33
+ REST API surfaces.
34
+
35
+ Where they disagree, **v2 wins** and the v1 name is kept as an alias:
36
+
37
+ === ========================== ==========================
38
+ tag v2 (authoritative) v1 (REST name)
39
+ === ========================== ==========================
40
+ 2 ``HardwareID`` ``BootloaderVersion``
41
+ 3 ``FirmwareID`` ``ApplicationVersion``
42
+ 8 ``DisplayType`` ``DisplayIds``
43
+ 46 ``FLButtonCount`` ``ButtonCount``
44
+ === ========================== ==========================
45
+
46
+ Every tag present in v1 but absent from the v2 struct turned out to be a
47
+ *continuation* tag of a multi-word v2 field (``GTIN2..4``, ``FirmwareMinor``,
48
+ ``BSSID2``, ...), so the two tables are consistent once multi-word fields are
49
+ expanded. Tags 91/92 (``BSSID``) exist only in v2.
50
+
51
+ Scalar encodings that are easy to get wrong
52
+ -------------------------------------------
53
+
54
+ * ``SignalStrength`` (13) is a **dBm magnitude with the sign dropped** -- negate it.
55
+ The captured 44 means -44 dBm.
56
+ * ``DeviceUptime`` (15) and ``NextStatus`` (27) are in **minutes**, not seconds.
57
+ The captured 35793 is ~24.9 days.
58
+ * ``Temperature`` is a signed **int8** in the low byte, no scaling. ``0xFFFFFFFF``
59
+ (and ``0xFF``) means "no reading".
60
+ * ``HardwareID`` packs ``ID<<24 | Family<<16 | PCB``.
61
+ * ``String`` is 4 ASCII chars per word, **little-endian**, NUL-terminated.
62
+ * ``BSSID`` is 6 bytes over 2 tags, LE.
63
+ * ``Features`` (43) is a **10**-bit mask. We do not reproduce the vendor's
64
+ bit-9-dropping legacy parser.
65
+ * ``ErrorCode`` (1) is the *reason the packet was sent*, not a fault.
66
+ * ``0xFFFFFFFF`` as a value means "field absent" for the fields whose
67
+ ``UnmarshalUint32`` treats it as a no-op (``HardwareID``, ``MobileModuleID``,
68
+ ``MobileLinkType``, ``ProximityThreshold``, ...).
69
+ """
70
+
71
+ from __future__ import annotations
72
+
73
+ import enum
74
+ import struct
75
+ from dataclasses import dataclass, field
76
+ from typing import Any, Iterator
77
+
78
+ from ..devices import enums as devenums
79
+ from ..wire.errors import PayloadError
80
+
81
+ __all__ = [
82
+ "SENTINEL_TAG",
83
+ "ABSENT",
84
+ "StatusCodec",
85
+ "StatusTag",
86
+ "STATUS_TAGS",
87
+ "STATUS_TAG_NAMES",
88
+ "StatusPacket",
89
+ "decode_status_fields",
90
+ ]
91
+
92
+ SENTINEL_TAG = 0xFFFFFFFF
93
+ """The record that terminates the list. v1 calls the tag ``LastStatus``.
94
+
95
+ Its *value* is **the CRC-32/ISO-HDLC of every record byte that precedes it** --
96
+ the ordinary zlib/PNG CRC-32, i.e. ``zlib.crc32(payload[:-8])``. Confirmed on
97
+ 16 of 16 live status frames (2026-10-05), across three TCP connections and three
98
+ connect reasons.
99
+
100
+ We still carry it verbatim and never enforce it, for one concrete reason: the
101
+ committed golden fixture **fails** the check, by a constant ``0xe63fe9a0``,
102
+ because the fixture is scrubbed and ``BSSID`` lives inside the CRC'd region.
103
+ Substituting the same bytes into every frame of a fixed-length region shifts
104
+ every CRC by the same amount, which is exactly what is observed. So anything
105
+ that validated this would reject our own test data, and any future scrub has to
106
+ recompute it.
107
+ """
108
+
109
+ ABSENT = 0xFFFFFFFF
110
+ """The "field not present" sentinel *value*."""
111
+
112
+ _REC = struct.Struct("<II")
113
+
114
+
115
+ class StatusCodec(enum.Enum):
116
+ """How to turn a tag's raw uint32 word(s) into a Python value."""
117
+
118
+ U32 = "u32"
119
+ BOOL = "bool"
120
+ I32 = "i32"
121
+ TEMPERATURE = "temperature"
122
+ HARDWARE_ID = "hardware_id"
123
+ VERSION = "version"
124
+ TOUCH_VERSION = "touch_version"
125
+ FEATURES = "features"
126
+ SCPU_SENSORS = "scpu_sensors"
127
+ BSSID = "bssid"
128
+ STRING = "string"
129
+ RSSI = "rssi"
130
+ MINUTES = "minutes"
131
+ ENUM = "enum"
132
+
133
+
134
+ @dataclass(frozen=True, slots=True)
135
+ class StatusTag:
136
+ """One row of the status tag table."""
137
+
138
+ tag: int
139
+ name: str
140
+ codec: StatusCodec = StatusCodec.U32
141
+ words: int = 1
142
+ """How many consecutive tags the value occupies."""
143
+ v1_name: str | None = None
144
+ """The v1/REST name, when it differs from *name*."""
145
+ enum_table: dict[int, str] | None = None
146
+ unit: str | None = None
147
+
148
+ @property
149
+ def tags(self) -> range:
150
+ return range(self.tag, self.tag + self.words)
151
+
152
+
153
+ def _t(tag, name, codec=StatusCodec.U32, words=1, v1=None, table=None, unit=None):
154
+ return StatusTag(tag, name, codec, words, v1, table, unit)
155
+
156
+
157
+ STATUS_TAGS: tuple[StatusTag, ...] = (
158
+ _t(0, "ConnectReason", StatusCodec.ENUM, table=devenums.CONNECT_REASON),
159
+ _t(1, "ErrorCode", StatusCodec.ENUM, table=devenums.ERROR_CODE),
160
+ _t(2, "HardwareID", StatusCodec.HARDWARE_ID, v1="BootloaderVersion"),
161
+ _t(3, "FirmwareID", StatusCodec.U32, v1="ApplicationVersion"),
162
+ _t(4, "WiFiModuleID", StatusCodec.U32, v1="WiFiModuleId"),
163
+ _t(5, "MobileModuleID", StatusCodec.U32, v1="MobileModuleId"),
164
+ _t(6, "ConnectivityUsed", StatusCodec.ENUM, table=devenums.CONNECTIVITY_USED),
165
+ _t(7, "NumberOfSupportedDisplays", StatusCodec.U32, v1="NumSupportedDisplays"),
166
+ _t(8, "DisplayType", StatusCodec.U32, v1="DisplayIds"),
167
+ _t(9, "DisplayStateCRC", StatusCodec.U32),
168
+ _t(10, "BatteryLevel", StatusCodec.U32, v1="Battery", unit="%"),
169
+ _t(11, "ChargingStatus", StatusCodec.ENUM, v1="Charger", table=devenums.CHARGING_STATUS),
170
+ _t(12, "AverageTemperature", StatusCodec.TEMPERATURE, v1="Temperature", unit="degC"),
171
+ _t(13, "SignalStrength", StatusCodec.RSSI, v1="RSSI", unit="dBm"),
172
+ _t(14, "ExternalBattery", StatusCodec.U32),
173
+ _t(15, "DeviceUptime", StatusCodec.MINUTES, v1="Uptime", unit="min"),
174
+ _t(16, "Firmware", StatusCodec.VERSION, words=3),
175
+ _t(19, "Bootloader", StatusCodec.VERSION, words=3),
176
+ _t(22, "HardwareNameID", StatusCodec.U32),
177
+ _t(23, "Hardware", StatusCodec.VERSION, words=3),
178
+ _t(26, "HardwareFirmwareInterface", StatusCodec.U32, v1="HardwareFirmwareIface"),
179
+ _t(27, "NextStatus", StatusCodec.MINUTES, unit="min"),
180
+ _t(28, "ExternalTemperatureSensor", StatusCodec.TEMPERATURE,
181
+ v1="ExternalTempSensor", unit="degC"),
182
+ _t(29, "TouchType", StatusCodec.ENUM, table=devenums.TOUCH_TYPE),
183
+ _t(30, "TouchFirmware", StatusCodec.TOUCH_VERSION, words=2),
184
+ _t(32, "TouchEventCount", StatusCodec.U32),
185
+ _t(33, "AccelerometerEventCount", StatusCodec.U32, v1="AcceleromenterEventCount"),
186
+ _t(34, "BatteryVoltage", StatusCodec.U32, unit="mV"),
187
+ _t(35, "BatteryCurrent", StatusCodec.U32, unit="mA"),
188
+ _t(36, "EventQueueOverflow", StatusCodec.U32, v1="EventQueueOverFlow"),
189
+ _t(37, "GPSState", StatusCodec.U32, v1="PV2GPSState"),
190
+ _t(38, "DisplayWidth", StatusCodec.U32, unit="px"),
191
+ _t(39, "DisplayHeight", StatusCodec.U32, unit="px"),
192
+ _t(40, "ProtocolVersion", StatusCodec.U32),
193
+ _t(41, "HumiditySensor", StatusCodec.U32),
194
+ _t(42, "PressureSensor", StatusCodec.U32),
195
+ _t(43, "Features", StatusCodec.FEATURES, v1="PV2Features"),
196
+ _t(44, "SCPUSensorStatus", StatusCodec.SCPU_SENSORS),
197
+ _t(45, "EPDTemperatureSensor", StatusCodec.TEMPERATURE, v1="EPDTempSensor", unit="degC"),
198
+ _t(46, "FLButtonCount", StatusCodec.U32, v1="ButtonCount"),
199
+ _t(47, "MobileLinkType", StatusCodec.U32),
200
+ _t(48, "FlSensorValue", StatusCodec.U32, v1="PV2FLSensorValue"),
201
+ _t(49, "VMSensorValue", StatusCodec.U32, v1="SCPUVMSensorValue"),
202
+ _t(50, "GTIN", StatusCodec.STRING, words=4),
203
+ _t(54, "ImagePushAllowed", StatusCodec.BOOL),
204
+ _t(55, "RTCGMTEpoch", StatusCodec.U32, v1="RtcGmtEpoch"),
205
+ _t(56, "MobileSecurity", StatusCodec.U32, v1="MobSecurity"),
206
+ _t(57, "JSAPIVersion", StatusCodec.VERSION, words=3),
207
+ _t(60, "FSTotalSize", StatusCodec.U32, v1="FsTotalSize", unit="bytes"),
208
+ _t(61, "FSFreeSize", StatusCodec.U32, v1="FsFreeSize", unit="bytes"),
209
+ _t(62, "JSEStatus", StatusCodec.U32, v1="JseStatus"),
210
+ _t(63, "ProximityCalibration", StatusCodec.U32, v1="ProximityCal"),
211
+ _t(64, "HitDetector", StatusCodec.U32),
212
+ _t(65, "Button1Count", StatusCodec.U32),
213
+ _t(66, "Button2Count", StatusCodec.U32),
214
+ _t(67, "Button3Count", StatusCodec.U32),
215
+ _t(68, "Button4Count", StatusCodec.U32),
216
+ _t(69, "BLEState", StatusCodec.U32),
217
+ _t(70, "ProximityCount", StatusCodec.U32),
218
+ _t(71, "NetworkErrCount", StatusCodec.U32, v1="NetworkErrorCount"),
219
+ _t(72, "JSAppVersion", StatusCodec.VERSION, words=3),
220
+ _t(75, "WallMountCount", StatusCodec.U32),
221
+ _t(76, "JSAppID", StatusCodec.STRING, words=10),
222
+ _t(86, "JSAppType", StatusCodec.ENUM, table=devenums.JS_APP_TYPE),
223
+ _t(87, "MCUAwakeCount", StatusCodec.U32, v1="McuAwakeCount"),
224
+ _t(88, "DCMState", StatusCodec.ENUM, v1="DcmState", table=devenums.DCM_STATE),
225
+ _t(89, "WiFiDTIM", StatusCodec.U32, v1="WiFiDtim"),
226
+ _t(90, "ProximityThreshold", StatusCodec.U32),
227
+ _t(91, "BSSID", StatusCodec.BSSID, words=2),
228
+ _t(93, "BatterySOC1Voltage", StatusCodec.U32, unit="mV"),
229
+ _t(94, "BatterySOC1Current", StatusCodec.I32, unit="mA"),
230
+ _t(95, "BatterySOC1Percent", StatusCodec.U32, unit="%"),
231
+ _t(96, "BatterySOC2Voltage", StatusCodec.U32, unit="mV"),
232
+ _t(97, "BatterySOC2Current", StatusCodec.I32, unit="mA"),
233
+ _t(98, "BatterySOC2Percent", StatusCodec.U32, unit="%"),
234
+ _t(99, "DisplayUpdateCount", StatusCodec.U32),
235
+ _t(100, "ConnectivityVersion", StatusCodec.VERSION, words=3),
236
+ _t(103, "QSPIFlashID", StatusCodec.ENUM, table=devenums.QSPI_FLASH_ID),
237
+ )
238
+
239
+ STATUS_TAG_BY_BASE: dict[int, StatusTag] = {t.tag: t for t in STATUS_TAGS}
240
+
241
+ STATUS_TAG_NAMES: dict[int, str] = {}
242
+ for _tag in STATUS_TAGS:
243
+ for _i, _n in enumerate(_tag.tags):
244
+ STATUS_TAG_NAMES[_n] = _tag.name if _i == 0 else f"{_tag.name}+{_i}"
245
+ STATUS_TAG_NAMES[SENTINEL_TAG] = "LastStatus"
246
+ del _tag, _i, _n
247
+
248
+
249
+ # ------------------------------------------------------------------ codecs
250
+
251
+ def _decode_string(words: list[int]) -> str:
252
+ """4 ASCII chars per word, little-endian, NUL-terminated.
253
+
254
+ GTIN spans tags 50..53 and the captured frame's last word is ``0xffff0032``,
255
+ i.e. ``"2\\0"`` followed by 0xff padding -- so the NUL ends the string and
256
+ whatever follows in that word is ignored.
257
+ """
258
+ out = bytearray()
259
+ for w in words:
260
+ chunk = w.to_bytes(4, "little")
261
+ if b"\x00" in chunk:
262
+ out += chunk[: chunk.index(b"\x00")]
263
+ break
264
+ out += chunk
265
+ return out.decode("ascii", errors="replace")
266
+
267
+
268
+ def _encode_string(value: str, words: int) -> list[int]:
269
+ """Inverse of :func:`_decode_string`, padding the final word with NULs."""
270
+ raw = value.encode("ascii")
271
+ if len(raw) >= words * 4:
272
+ raise ValueError(f"{value!r} does not fit in {words} words with a NUL")
273
+ raw += b"\x00"
274
+ raw += b"\x00" * (-len(raw) % 4)
275
+ return [int.from_bytes(raw[i : i + 4], "little") for i in range(0, len(raw), 4)]
276
+
277
+
278
+ def _decode_bssid(words: list[int]) -> str | None:
279
+ """6 bytes over 2 tags, LE: tag+0 = bytes 0..3, tag+1 = bytes 4..5."""
280
+ if not words or words[0] == ABSENT:
281
+ return None
282
+ raw = words[0].to_bytes(4, "little") + (
283
+ words[1].to_bytes(4, "little")[:2] if len(words) > 1 else b""
284
+ )
285
+ return ":".join(f"{b:02X}" for b in raw[:6])
286
+
287
+
288
+ def _decode_temperature(word: int) -> int | None:
289
+ """Signed int8 in the low byte, degrees C, no scaling."""
290
+ if word == ABSENT:
291
+ return None
292
+ low = word & 0xFF
293
+ if low == 0xFF:
294
+ return None
295
+ return low - 256 if low >= 0x80 else low
296
+
297
+
298
+ def _decode_hardware_id(word: int) -> dict[str, Any] | None:
299
+ """``bits 31..24 = ID``, ``23..16 = Family``, ``15..0 = PCB``."""
300
+ if word == ABSENT:
301
+ return None
302
+ hw_id = (word >> 24) & 0xFF
303
+ family = (word >> 16) & 0xFF
304
+ return {
305
+ "id": hw_id,
306
+ "family": family,
307
+ "family_name": devenums.HARDWARE_FAMILY.get(family, "n/a"),
308
+ "pcb": word & 0xFFFF,
309
+ }
310
+
311
+
312
+ def _decode_bits(word: int, names: tuple[str, ...]) -> dict[str, bool]:
313
+ return {name: bool(word >> i & 1) for i, name in enumerate(names)}
314
+
315
+
316
+ def _decode_value(tag: StatusTag, words: list[int]) -> Any:
317
+ codec = tag.codec
318
+ first = words[0]
319
+ if codec is StatusCodec.U32:
320
+ return None if first == ABSENT else first
321
+ if codec is StatusCodec.BOOL:
322
+ return bool(first)
323
+ if codec is StatusCodec.I32:
324
+ return first - (1 << 32) if first >= (1 << 31) else first
325
+ if codec is StatusCodec.ENUM:
326
+ table = tag.enum_table or {}
327
+ return {"value": first, "name": devenums.describe(table, first)}
328
+ if codec is StatusCodec.TEMPERATURE:
329
+ return _decode_temperature(first)
330
+ if codec is StatusCodec.HARDWARE_ID:
331
+ return _decode_hardware_id(first)
332
+ if codec is StatusCodec.VERSION:
333
+ return {
334
+ "major": words[0] if len(words) > 0 else None,
335
+ "minor": words[1] if len(words) > 1 else None,
336
+ "revision": words[2] if len(words) > 2 else None,
337
+ }
338
+ if codec is StatusCodec.TOUCH_VERSION:
339
+ return {
340
+ "major": words[0] if len(words) > 0 else None,
341
+ "minor": words[1] if len(words) > 1 else None,
342
+ }
343
+ if codec is StatusCodec.FEATURES:
344
+ out = _decode_bits(first, devenums.PV2_FEATURE_BITS)
345
+ out["_mask"] = first
346
+ return out
347
+ if codec is StatusCodec.SCPU_SENSORS:
348
+ return _decode_bits(first, devenums.SCPU_SENSOR_BITS)
349
+ if codec is StatusCodec.BSSID:
350
+ return _decode_bssid(words)
351
+ if codec is StatusCodec.STRING:
352
+ return _decode_string(words)
353
+ if codec is StatusCodec.RSSI:
354
+ # dBm magnitude with the sign dropped: 44 on the wire means -44 dBm.
355
+ return None if first == ABSENT else -first
356
+ if codec is StatusCodec.MINUTES:
357
+ return None if first == ABSENT else first
358
+ raise AssertionError(f"unhandled codec {codec}")
359
+
360
+
361
+ def decode_status_fields(raw: dict[int, int]) -> dict[str, Any]:
362
+ """Turn a ``{tag: word}`` map into a ``{name: value}`` map.
363
+
364
+ Tags not in :data:`STATUS_TAGS` are collected under ``"Unknown"`` as a
365
+ ``{tag: word}`` dict, mirroring ``status.Status.Unknown``.
366
+ """
367
+ out: dict[str, Any] = {}
368
+ consumed: set[int] = set()
369
+ for tag in STATUS_TAGS:
370
+ if tag.tag not in raw:
371
+ continue
372
+ words = [raw[n] for n in tag.tags if n in raw]
373
+ consumed.update(n for n in tag.tags if n in raw)
374
+ out[tag.name] = _decode_value(tag, words)
375
+ unknown = {t: v for t, v in raw.items() if t not in consumed and t != SENTINEL_TAG}
376
+ if unknown:
377
+ out["Unknown"] = unknown
378
+ return out
379
+
380
+
381
+ # ------------------------------------------------------------------ packet
382
+
383
+ @dataclass(slots=True)
384
+ class StatusPacket:
385
+ """A status payload, held as the **ordered raw record list**.
386
+
387
+ Keeping the records in wire order (rather than only the decoded field map) is
388
+ what makes byte-exact re-encoding provable: :meth:`encode` is the exact
389
+ inverse of :meth:`decode` for every captured frame.
390
+
391
+ Attributes:
392
+ records: ``(tag, value)`` in wire order, excluding the sentinel.
393
+ sentinel: the sentinel record's *value*. Carried verbatim; its meaning is
394
+ unconfirmed.
395
+ trailing: any bytes after the sentinel (always empty in practice).
396
+ """
397
+
398
+ records: list[tuple[int, int]] = field(default_factory=list)
399
+ sentinel: int | None = None
400
+ trailing: bytes = b""
401
+
402
+ TYPE = devenums.PacketType.STATUS
403
+
404
+ @classmethod
405
+ def decode(cls, payload: bytes) -> "StatusPacket":
406
+ if len(payload) % 8:
407
+ raise PayloadError(
408
+ f"status payload is {len(payload)} bytes, not a multiple of 8"
409
+ )
410
+ records: list[tuple[int, int]] = []
411
+ sentinel: int | None = None
412
+ offset = 0
413
+ while offset + 8 <= len(payload):
414
+ tag, value = _REC.unpack_from(payload, offset)
415
+ offset += 8
416
+ if tag == SENTINEL_TAG:
417
+ sentinel = value
418
+ break
419
+ records.append((tag, value))
420
+ return cls(records=records, sentinel=sentinel, trailing=payload[offset:])
421
+
422
+ def encode(self) -> bytes:
423
+ out = bytearray()
424
+ for tag, value in self.records:
425
+ out += _REC.pack(tag, value)
426
+ if self.sentinel is not None:
427
+ out += _REC.pack(SENTINEL_TAG, self.sentinel)
428
+ out += self.trailing
429
+ return bytes(out)
430
+
431
+ # -- views -----------------------------------------------------------
432
+
433
+ @property
434
+ def raw(self) -> dict[int, int]:
435
+ """``{tag: value}``. Later duplicates win, as in the Go decoder."""
436
+ return dict(self.records)
437
+
438
+ def fields(self) -> dict[str, Any]:
439
+ """The decoded, named field map."""
440
+ return decode_status_fields(self.raw)
441
+
442
+ def get(self, name: str, default: Any = None) -> Any:
443
+ return self.fields().get(name, default)
444
+
445
+ def __iter__(self) -> Iterator[tuple[int, int]]:
446
+ return iter(self.records)
447
+
448
+ def __len__(self) -> int:
449
+ return len(self.records)
450
+
451
+ # -- convenience accessors used by the session layer -----------------
452
+
453
+ @property
454
+ def connect_reason(self) -> int | None:
455
+ """Status tag 0, raw."""
456
+ return self.raw.get(0)
457
+
458
+ @property
459
+ def connect_reason_name(self) -> str:
460
+ """Status tag 0, named: ``"reboot"``, ``"wakeup"``, ``"heartbeat"``, ...
461
+
462
+ The cheapest confirmation available that a type-2 command landed: a
463
+ reboot command that worked shows up as the device reconnecting with
464
+ reason ``1`` (``"reboot"``), and a server-requested status as ``8``
465
+ (``"by server request"``) -- ``8`` **confirmed live** 2026-10-05, as the
466
+ answer to a captured ``status request`` command, and ``2`` (``"wakeup"``)
467
+ as the answer to an ``app_wakeup`` out of deep sleep. Unknown values
468
+ render ``"n/a"``, as the vendor's own ``String()`` does.
469
+ """
470
+ reason = self.connect_reason
471
+ if reason is None:
472
+ return "n/a"
473
+ return devenums.describe(devenums.CONNECT_REASON, reason)
474
+
475
+ @property
476
+ def error_code(self) -> int | None:
477
+ return self.raw.get(1)
478
+
479
+ @property
480
+ def display_type(self) -> int | None:
481
+ """Raw uint32 ``DisplayType`` (tag 8). Deliberately not an enum."""
482
+ return self.raw.get(8)
483
+
484
+ @property
485
+ def display_state_crc(self) -> int | None:
486
+ """Tag 9: the XXHash32 the device computed over its own 8-bit state image.
487
+
488
+ Compare it against ``EncodedFrame.state_checksum`` to decide whether a
489
+ push is needed. Note this is **not** a CRC despite the vendor's name.
490
+ """
491
+ return self.raw.get(9)
492
+
493
+ @property
494
+ def hardware_name_id(self) -> int | None:
495
+ return self.raw.get(22)
496
+
497
+ @property
498
+ def next_status_minutes(self) -> int | None:
499
+ return self.raw.get(27)
500
+
501
+ @property
502
+ def firmware_version(self) -> tuple[int, int, int] | None:
503
+ r = self.raw
504
+ if 16 not in r:
505
+ return None
506
+ return (r.get(16, 0), r.get(17, 0), r.get(18, 0))
507
+
508
+ @property
509
+ def features_mask(self) -> int | None:
510
+ return self.raw.get(43)
511
+
512
+ @property
513
+ def image_push_allowed(self) -> bool:
514
+ return bool(self.raw.get(54, 0))
515
+
516
+ @property
517
+ def protocol_version(self) -> int | None:
518
+ return self.raw.get(40)