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,334 @@
1
+ """``ProtocolHeader`` / ``DataHeader`` framing and the incremental frame decoder.
2
+
3
+ Three nested fixed-width little-endian headers::
4
+
5
+ ProtocolHeader 20 B Version | Security | Compression | Length | Checksum
6
+ +-- if Compression != 0: a chain of 24-B block records (see wire.blocks)
7
+ +-- DataHeader 36 B Priority | DeviceID[16] | Type | ID | Length | Reserved
8
+ +-- payload (per packet type)
9
+
10
+ It is not CBOR. ``packet.Type 12 = CBOR`` is a real enum member with a real
11
+ handler, but it is the newer "AC"/JS-app device generation's channel; firmware
12
+ 7.4.4407 never emits it.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import struct
18
+ from dataclasses import dataclass, field
19
+ from typing import Callable, Iterator
20
+
21
+ from .blocks import encode_blocks, decode_blocks, lz4_compress_block
22
+ from .checksum import Direction, frame_checksum, verify_checksum
23
+ from .errors import (
24
+ ChecksumMismatch,
25
+ FrameTooLarge,
26
+ ShortBuffer,
27
+ UnsupportedCompression,
28
+ UnsupportedSecurity,
29
+ UnsupportedVersion,
30
+ )
31
+
32
+ __all__ = [
33
+ "PROTOCOL_VERSION",
34
+ "PROTOCOL_HEADER_SIZE",
35
+ "DATA_HEADER_SIZE",
36
+ "MAX_FRAME_LENGTH",
37
+ "Compression",
38
+ "Security",
39
+ "ProtocolHeader",
40
+ "DataHeader",
41
+ "Frame",
42
+ "FrameDecoder",
43
+ "encode_frame",
44
+ ]
45
+
46
+ PROTOCOL_VERSION = 3
47
+ """Hardcoded by ``encoder.go:323`` and required by ``decoder.go:80``."""
48
+
49
+ PROTOCOL_HEADER_SIZE = 20
50
+ DATA_HEADER_SIZE = 36
51
+
52
+ MAX_FRAME_LENGTH = 0x3200000
53
+ """52,428,800 bytes = 50 MiB. ``decoder.go:84``: ``"packet too large: %d"``."""
54
+
55
+ _PROTO = struct.Struct("<5I")
56
+ _DATA = struct.Struct("<I16sIIII")
57
+
58
+
59
+ class Compression:
60
+ """``proto.CompressionType``."""
61
+
62
+ NONE = 0
63
+ LZ4 = 1
64
+
65
+
66
+ class Security:
67
+ """``proto.SecurityType``.
68
+
69
+ Only ``NONE`` is implemented. ``2``/``3`` are AES-128-CBC under a session key
70
+ the gateway escrows with a Visionect HTTPS service; that key material is not
71
+ in the server image, so a self-hosted deployment is plaintext by construction.
72
+ ``1`` is the firmware-container variant, not a TCP mode.
73
+ """
74
+
75
+ NONE = 0
76
+ SESSION = 2
77
+ SECURITY_PACKET = 3
78
+
79
+
80
+ @dataclass(frozen=True, slots=True)
81
+ class ProtocolHeader:
82
+ """The outer 20-byte frame header."""
83
+
84
+ version: int = PROTOCOL_VERSION
85
+ security: int = Security.NONE
86
+ compression: int = Compression.NONE
87
+ length: int = 0
88
+ checksum: int = 0
89
+
90
+ def pack(self) -> bytes:
91
+ return _PROTO.pack(
92
+ self.version, self.security, self.compression, self.length, self.checksum
93
+ )
94
+
95
+ def pack_prefix(self) -> bytes:
96
+ """The first 16 bytes, i.e. everything the device's CRC covers."""
97
+ return struct.pack(
98
+ "<4I", self.version, self.security, self.compression, self.length
99
+ )
100
+
101
+ @classmethod
102
+ def unpack_from(cls, buf: bytes, offset: int = 0) -> "ProtocolHeader":
103
+ if len(buf) - offset < PROTOCOL_HEADER_SIZE:
104
+ raise ShortBuffer(
105
+ f"need {PROTOCOL_HEADER_SIZE} bytes for a ProtocolHeader, "
106
+ f"have {len(buf) - offset}"
107
+ )
108
+ return cls(*_PROTO.unpack_from(buf, offset))
109
+
110
+
111
+ @dataclass(frozen=True, slots=True)
112
+ class DataHeader:
113
+ """The inner 36-byte ``packet.DataHeader``.
114
+
115
+ ``device_id`` is literally the 16 UUID bytes; there is no hashing, no
116
+ encoding. ``priority`` is 0 in every observed frame in both directions and
117
+ the gateway never writes it.
118
+ """
119
+
120
+ device_id: bytes
121
+ type: int
122
+ id: int
123
+ length: int
124
+ priority: int = 0
125
+ reserved: int = 0
126
+
127
+ def pack(self) -> bytes:
128
+ if len(self.device_id) != 16:
129
+ raise ValueError(f"device_id must be 16 bytes, got {len(self.device_id)}")
130
+ return _DATA.pack(
131
+ self.priority,
132
+ self.device_id,
133
+ self.type,
134
+ self.id,
135
+ self.length,
136
+ self.reserved,
137
+ )
138
+
139
+ @classmethod
140
+ def unpack_from(cls, buf: bytes, offset: int = 0) -> "DataHeader":
141
+ if len(buf) - offset < DATA_HEADER_SIZE:
142
+ raise ShortBuffer(
143
+ f"need {DATA_HEADER_SIZE} bytes for a DataHeader, have {len(buf) - offset}"
144
+ )
145
+ priority, device_id, type_, id_, length, reserved = _DATA.unpack_from(buf, offset)
146
+ return cls(
147
+ device_id=device_id,
148
+ type=type_,
149
+ id=id_,
150
+ length=length,
151
+ priority=priority,
152
+ reserved=reserved,
153
+ )
154
+
155
+
156
+ @dataclass(frozen=True, slots=True)
157
+ class Frame:
158
+ """One decoded frame: outer header, inner header, raw payload bytes.
159
+
160
+ ``raw_body`` is kept so a test can re-emit a captured frame byte-for-byte
161
+ without having to reproduce the vendor's LZ4 compressor.
162
+ """
163
+
164
+ header: ProtocolHeader
165
+ data: DataHeader
166
+ payload: bytes
167
+ raw_body: bytes = field(repr=False, default=b"")
168
+ plaintext: bytes = field(repr=False, default=b"")
169
+ """``DataHeader`` + payload, after block decoding."""
170
+
171
+ @property
172
+ def device_id(self) -> bytes:
173
+ return self.data.device_id
174
+
175
+ @property
176
+ def type(self) -> int:
177
+ return self.data.type
178
+
179
+ @property
180
+ def id(self) -> int:
181
+ return self.data.id
182
+
183
+
184
+ def encode_frame(
185
+ data: DataHeader,
186
+ payload: bytes,
187
+ *,
188
+ direction: Direction,
189
+ compression: int = Compression.LZ4,
190
+ compressor: Callable[[bytes], bytes] = lz4_compress_block,
191
+ raw_body: bytes | None = None,
192
+ ) -> bytes:
193
+ """Marshal one frame.
194
+
195
+ The order of operations is the vendor's, from ``encoder.go:214-339``:
196
+ marshal -> compress -> CRC-32 -> (encrypt) -> header. The CRC therefore
197
+ covers the *compressed* body, and ``Length`` is the final body length.
198
+
199
+ Args:
200
+ data: the inner header. Its ``length`` field is overwritten with
201
+ ``len(payload)``.
202
+ payload: the type-specific payload bytes.
203
+ direction: who is sending. Decides the checksum rule; see
204
+ :mod:`pyvisionect.wire.checksum`.
205
+ compression: ``Compression.LZ4`` (what the gateway always does, even for
206
+ an 8-byte ack) or ``Compression.NONE`` (what the device always does).
207
+ compressor: raw-LZ4-block compressor, for byte-exact replay experiments.
208
+ raw_body: if given, used verbatim as the body instead of re-marshalling.
209
+ Only for replay tests.
210
+
211
+ Returns:
212
+ The complete frame, ready to put on the wire.
213
+ """
214
+ if raw_body is not None:
215
+ body = raw_body
216
+ else:
217
+ plain = (
218
+ DataHeader(
219
+ device_id=data.device_id,
220
+ type=data.type,
221
+ id=data.id,
222
+ length=len(payload),
223
+ priority=data.priority,
224
+ reserved=data.reserved,
225
+ ).pack()
226
+ + payload
227
+ )
228
+ body = encode_blocks(plain, compressor=compressor) if compression else plain
229
+
230
+ if len(body) > MAX_FRAME_LENGTH:
231
+ raise FrameTooLarge(f"body is {len(body)} bytes, limit is {MAX_FRAME_LENGTH}")
232
+
233
+ header = ProtocolHeader(
234
+ version=PROTOCOL_VERSION,
235
+ security=Security.NONE,
236
+ compression=compression,
237
+ length=len(body),
238
+ )
239
+ checksum = frame_checksum(
240
+ direction, header16=header.pack_prefix(), body=body
241
+ )
242
+ return ProtocolHeader(
243
+ version=header.version,
244
+ security=header.security,
245
+ compression=header.compression,
246
+ length=header.length,
247
+ checksum=checksum,
248
+ ).pack() + body
249
+
250
+
251
+ class FrameDecoder:
252
+ """Incremental, pure frame decoder. Feed it bytes, pull out frames.
253
+
254
+ Sans-io: no sockets, no clock, no buffering policy beyond "keep the
255
+ remainder". A partial frame simply stays in the buffer.
256
+
257
+ Args:
258
+ direction: the direction of the stream being decoded. As a server this
259
+ is ``DEVICE_TO_SERVER``.
260
+ strict: verify the inbound checksum and the block-chain invariants.
261
+ **Off by default**: the real gateway validates neither, and the
262
+ device's checksum covers no payload bytes.
263
+ """
264
+
265
+ def __init__(
266
+ self, direction: Direction = Direction.DEVICE_TO_SERVER, *, strict: bool = False
267
+ ) -> None:
268
+ self.direction = direction
269
+ self.strict = strict
270
+ self._buf = bytearray()
271
+
272
+ @property
273
+ def buffered(self) -> int:
274
+ """Bytes held back because they are a partial frame."""
275
+ return len(self._buf)
276
+
277
+ def feed(self, data: bytes) -> list[Frame]:
278
+ """Append *data* and return every frame that is now complete."""
279
+ self._buf += data
280
+ return list(self._drain_frames())
281
+
282
+ def _drain_frames(self) -> Iterator[Frame]:
283
+ while True:
284
+ buf = self._buf
285
+ if len(buf) < PROTOCOL_HEADER_SIZE:
286
+ return
287
+ header = ProtocolHeader.unpack_from(buf)
288
+ if header.version != PROTOCOL_VERSION:
289
+ raise UnsupportedVersion(
290
+ f"unsupported protocol version {header.version}"
291
+ )
292
+ if header.length > MAX_FRAME_LENGTH:
293
+ raise FrameTooLarge(f"packet too large: {header.length}")
294
+ total = PROTOCOL_HEADER_SIZE + header.length
295
+ if len(buf) < total:
296
+ return
297
+ body = bytes(buf[PROTOCOL_HEADER_SIZE:total])
298
+ del self._buf[:total]
299
+ yield self._finish(header, body)
300
+
301
+ def _finish(self, header: ProtocolHeader, body: bytes) -> Frame:
302
+ if self.strict and not verify_checksum(
303
+ self.direction,
304
+ header16=header.pack_prefix(),
305
+ body=body,
306
+ checksum=header.checksum,
307
+ ):
308
+ raise ChecksumMismatch(
309
+ f"checksum 0x{header.checksum:08x} does not match the "
310
+ f"{self.direction.value} rule"
311
+ )
312
+ if header.security != Security.NONE:
313
+ raise UnsupportedSecurity(
314
+ f"ProtocolHeader.Security = {header.security}; link encryption is "
315
+ "not implemented (the session key is escrowed off-box)"
316
+ )
317
+ if header.compression == Compression.NONE:
318
+ plain = body
319
+ elif header.compression == Compression.LZ4:
320
+ plain = decode_blocks(body, strict=self.strict)
321
+ else:
322
+ raise UnsupportedCompression(
323
+ f"unsupported compression {header.compression}"
324
+ )
325
+
326
+ data = DataHeader.unpack_from(plain)
327
+ payload = plain[DATA_HEADER_SIZE : DATA_HEADER_SIZE + data.length]
328
+ return Frame(
329
+ header=header,
330
+ data=data,
331
+ payload=payload,
332
+ raw_body=body,
333
+ plaintext=plain,
334
+ )