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.
- pyvisionect/__init__.py +120 -0
- pyvisionect/devices/__init__.py +92 -0
- pyvisionect/devices/enums.py +403 -0
- pyvisionect/devices/panels.py +242 -0
- pyvisionect/devices/tclv.py +460 -0
- pyvisionect/imaging/README.md +175 -0
- pyvisionect/imaging/__init__.py +181 -0
- pyvisionect/imaging/checksum.py +114 -0
- pyvisionect/imaging/constants.py +131 -0
- pyvisionect/imaging/data/blue_noise_64.npy +0 -0
- pyvisionect/imaging/decode.py +172 -0
- pyvisionect/imaging/dither.py +357 -0
- pyvisionect/imaging/encoder.py +594 -0
- pyvisionect/imaging/geometry.py +129 -0
- pyvisionect/imaging/grey.py +104 -0
- pyvisionect/imaging/interlace.py +244 -0
- pyvisionect/imaging/pack.py +142 -0
- pyvisionect/imaging/panel.py +339 -0
- pyvisionect/imaging/partial.py +931 -0
- pyvisionect/imaging/rects.py +466 -0
- pyvisionect/io/__init__.py +33 -0
- pyvisionect/io/tcp.py +795 -0
- pyvisionect/io/usb/__init__.py +237 -0
- pyvisionect/io/usb/cli.py +278 -0
- pyvisionect/io/usb/commands.py +781 -0
- pyvisionect/io/usb/console.py +730 -0
- pyvisionect/io/usb/device.py +914 -0
- pyvisionect/io/usb/discovery.py +260 -0
- pyvisionect/io/usb/encryption.py +262 -0
- pyvisionect/io/usb/errors.py +175 -0
- pyvisionect/io/usb/fake.py +292 -0
- pyvisionect/io/usb/parsers.py +1464 -0
- pyvisionect/io/usb/provisioning.py +502 -0
- pyvisionect/packets/__init__.py +135 -0
- pyvisionect/packets/control.py +95 -0
- pyvisionect/packets/file.py +325 -0
- pyvisionect/packets/image.py +234 -0
- pyvisionect/packets/misc.py +202 -0
- pyvisionect/packets/param.py +284 -0
- pyvisionect/packets/status.py +518 -0
- pyvisionect/packets/stored.py +217 -0
- pyvisionect/py.typed +0 -0
- pyvisionect/session/__init__.py +100 -0
- pyvisionect/session/connection.py +1043 -0
- pyvisionect/session/device.py +587 -0
- pyvisionect/session/events.py +196 -0
- pyvisionect/session/filetransfer.py +251 -0
- pyvisionect/session/pending.py +425 -0
- pyvisionect/wire/__init__.py +91 -0
- pyvisionect/wire/blocks.py +350 -0
- pyvisionect/wire/checksum.py +115 -0
- pyvisionect/wire/errors.py +176 -0
- pyvisionect/wire/framing.py +334 -0
- pyvisionect-0.1.0.dist-info/METADATA +1030 -0
- pyvisionect-0.1.0.dist-info/RECORD +58 -0
- pyvisionect-0.1.0.dist-info/WHEEL +4 -0
- pyvisionect-0.1.0.dist-info/entry_points.txt +3 -0
- pyvisionect-0.1.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,350 @@
|
|
|
1
|
+
"""The LZ4 block chain used when ``ProtocolHeader.Compression == 1``.
|
|
2
|
+
|
|
3
|
+
Layout of one block record (24-byte header, 6 x uint32 LE, then the payload).
|
|
4
|
+
Recovered from ``proto/v2`` ``encoder.go:51-56`` (marshal) and
|
|
5
|
+
``encoder.go:62-69`` (unmarshal)::
|
|
6
|
+
|
|
7
|
+
offset size field notes
|
|
8
|
+
0 4 BlockIndex 0-based index of this block
|
|
9
|
+
4 4 BlocksMinusOne total blocks - 1; the SAME value in every header
|
|
10
|
+
8 4 PayloadLength bytes of block payload that follow
|
|
11
|
+
12 4 UncompressedLength 4800 (0x12C0) except the last block
|
|
12
|
+
16 4 Stored 1 = payload verbatim, 0 = payload is a raw LZ4 block
|
|
13
|
+
20 4 Reserved always 0
|
|
14
|
+
24 ... payload PayloadLength bytes
|
|
15
|
+
|
|
16
|
+
Two things bite here:
|
|
17
|
+
|
|
18
|
+
1. **The polarity of ``Stored`` is inverted from what the name suggests on a
|
|
19
|
+
first read.** ``1`` means *not* compressed. ``encoder.go:374-380``::
|
|
20
|
+
|
|
21
|
+
CMPL 0x34(SP) /*UncompressedLength*/, BX /*lz4 output size*/
|
|
22
|
+
JBE -> stored branch: Stored = 1 ; PayloadLength = UncompressedLength
|
|
23
|
+
fallthrough -> lz4: Stored = 0 ; PayloadLength = lz4 size
|
|
24
|
+
|
|
25
|
+
so LZ4 is used only when it *strictly* shrinks the block.
|
|
26
|
+
|
|
27
|
+
2. **``BlocksMinusOne`` is an index, not a count or a flag.** On the captured
|
|
28
|
+
1.84 MB image push it is ``384`` in all 385 blocks, so a receiver knows the
|
|
29
|
+
total block count from the first header alone.
|
|
30
|
+
|
|
31
|
+
The compressed payload is a **raw LZ4 block** -- no frame magic, no content
|
|
32
|
+
checksum, no size prefix. That is ``lz4.block`` in python-lz4, with
|
|
33
|
+
``store_size=False``, and emphatically *not* ``lz4.frame``.
|
|
34
|
+
"""
|
|
35
|
+
|
|
36
|
+
from __future__ import annotations
|
|
37
|
+
|
|
38
|
+
import struct
|
|
39
|
+
from dataclasses import dataclass
|
|
40
|
+
from typing import Callable, Iterable
|
|
41
|
+
|
|
42
|
+
from .errors import BlockError, MissingLz4
|
|
43
|
+
|
|
44
|
+
__all__ = [
|
|
45
|
+
"BLOCK_HEADER_SIZE",
|
|
46
|
+
"BLOCK_PLAINTEXT_SIZE",
|
|
47
|
+
"STORED_ONLY",
|
|
48
|
+
"BlockHeader",
|
|
49
|
+
"decode_blocks",
|
|
50
|
+
"encode_blocks",
|
|
51
|
+
"codec_name",
|
|
52
|
+
"have_lz4",
|
|
53
|
+
"iter_block_headers",
|
|
54
|
+
"lz4_compress_block",
|
|
55
|
+
"lz4_decompress_block",
|
|
56
|
+
"stored_only",
|
|
57
|
+
]
|
|
58
|
+
|
|
59
|
+
BLOCK_HEADER_SIZE = 24
|
|
60
|
+
BLOCK_PLAINTEXT_SIZE = 0x12C0
|
|
61
|
+
"""4800 bytes. ``encoder.go:353`` ``MOVL $0x12c0, 0x34(SP)``."""
|
|
62
|
+
|
|
63
|
+
MAX_TOTAL = 0x3200000
|
|
64
|
+
"""50 MiB. ``decoder.go:234``: ``"blocks too large: %d"``."""
|
|
65
|
+
|
|
66
|
+
_BLOCK = struct.Struct("<6I")
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
_BACKEND: tuple[str, object, object] | None = None
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def _load_backend():
|
|
73
|
+
"""Resolve an LZ4 block codec, preferring ``cramjam``.
|
|
74
|
+
|
|
75
|
+
Two implementations are accepted and they produce the *same wire bytes*;
|
|
76
|
+
they differ only in Python-side convention, which this function hides:
|
|
77
|
+
|
|
78
|
+
* ``cramjam`` -- Rust, and the **only** one that publishes musllinux
|
|
79
|
+
wheels, so it is the one that installs in Home Assistant's Alpine
|
|
80
|
+
container. Its ``compress_block`` prepends a 4-byte little-endian
|
|
81
|
+
uncompressed size, which is *not* part of a raw block and is stripped
|
|
82
|
+
here. Its ``decompress_block`` wants that length as ``output_len``.
|
|
83
|
+
* ``lz4`` (python-lz4) -- the C binding, kept as a fast path when it is
|
|
84
|
+
already installed. ``store_size=False`` is the raw form.
|
|
85
|
+
|
|
86
|
+
Imported lazily so a deployment that neither compresses outbound frames
|
|
87
|
+
(``ConnectionConfig(compressor=STORED_ONLY)``) nor receives a compressed
|
|
88
|
+
one can run with neither installed. That is a real configuration: every
|
|
89
|
+
device->server frame in the capture carries ``Compression = 0``, so a pure
|
|
90
|
+
server needs a codec only for its own outbound traffic.
|
|
91
|
+
"""
|
|
92
|
+
global _BACKEND
|
|
93
|
+
if _BACKEND is not None:
|
|
94
|
+
return _BACKEND
|
|
95
|
+
try:
|
|
96
|
+
import cramjam
|
|
97
|
+
|
|
98
|
+
def _c(plain: bytes) -> bytes:
|
|
99
|
+
# strip the 4-byte LE size cramjam prepends; the wire wants a bare block
|
|
100
|
+
return bytes(cramjam.lz4.compress_block(plain))[4:]
|
|
101
|
+
|
|
102
|
+
def _d(payload: bytes, n: int) -> bytes:
|
|
103
|
+
return bytes(cramjam.lz4.decompress_block(payload, output_len=n))
|
|
104
|
+
|
|
105
|
+
_BACKEND = ("cramjam", _c, _d)
|
|
106
|
+
return _BACKEND
|
|
107
|
+
except ImportError:
|
|
108
|
+
pass
|
|
109
|
+
try:
|
|
110
|
+
import lz4.block as _m
|
|
111
|
+
|
|
112
|
+
def _c(plain: bytes) -> bytes:
|
|
113
|
+
return _m.compress(plain, store_size=False)
|
|
114
|
+
|
|
115
|
+
def _d(payload: bytes, n: int) -> bytes:
|
|
116
|
+
return _m.decompress(payload, uncompressed_size=n)
|
|
117
|
+
|
|
118
|
+
_BACKEND = ("lz4", _c, _d)
|
|
119
|
+
return _BACKEND
|
|
120
|
+
except ImportError:
|
|
121
|
+
pass
|
|
122
|
+
raise MissingLz4(
|
|
123
|
+
"this frame needs an LZ4 block codec and neither 'cramjam' nor 'lz4' "
|
|
124
|
+
"is installed. Install one (pip install cramjam -- it is the one with "
|
|
125
|
+
"musllinux wheels, so it works in the official Home Assistant "
|
|
126
|
+
"container) or, if you only act as a server, pass "
|
|
127
|
+
"ConnectionConfig(compressor=STORED_ONLY) to emit every block "
|
|
128
|
+
"uncompressed -- the device never compresses, so inbound frames need "
|
|
129
|
+
"no codec at all."
|
|
130
|
+
)
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def codec_name() -> str | None:
|
|
134
|
+
"""Which LZ4 backend is in use, or ``None`` if neither is installed."""
|
|
135
|
+
try:
|
|
136
|
+
return _load_backend()[0]
|
|
137
|
+
except MissingLz4:
|
|
138
|
+
return None
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def have_lz4() -> bool:
|
|
142
|
+
"""Whether an LZ4 block codec is importable (either backend)."""
|
|
143
|
+
return codec_name() is not None
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
@dataclass(frozen=True, slots=True)
|
|
147
|
+
class BlockHeader:
|
|
148
|
+
"""One 24-byte block record header."""
|
|
149
|
+
|
|
150
|
+
index: int
|
|
151
|
+
blocks_minus_one: int
|
|
152
|
+
payload_length: int
|
|
153
|
+
uncompressed_length: int
|
|
154
|
+
stored: int
|
|
155
|
+
reserved: int = 0
|
|
156
|
+
|
|
157
|
+
@property
|
|
158
|
+
def block_count(self) -> int:
|
|
159
|
+
"""Total number of blocks in the chain (``BlocksMinusOne + 1``)."""
|
|
160
|
+
return self.blocks_minus_one + 1
|
|
161
|
+
|
|
162
|
+
@property
|
|
163
|
+
def is_stored(self) -> bool:
|
|
164
|
+
"""True when the payload is verbatim rather than an LZ4 block."""
|
|
165
|
+
return self.stored == 1
|
|
166
|
+
|
|
167
|
+
def pack(self) -> bytes:
|
|
168
|
+
return _BLOCK.pack(
|
|
169
|
+
self.index,
|
|
170
|
+
self.blocks_minus_one,
|
|
171
|
+
self.payload_length,
|
|
172
|
+
self.uncompressed_length,
|
|
173
|
+
self.stored,
|
|
174
|
+
self.reserved,
|
|
175
|
+
)
|
|
176
|
+
|
|
177
|
+
@classmethod
|
|
178
|
+
def unpack_from(cls, buf: bytes, offset: int = 0) -> "BlockHeader":
|
|
179
|
+
if len(buf) - offset < BLOCK_HEADER_SIZE:
|
|
180
|
+
raise BlockError(
|
|
181
|
+
f"need {BLOCK_HEADER_SIZE} bytes for a block header, have {len(buf) - offset}"
|
|
182
|
+
)
|
|
183
|
+
return cls(*_BLOCK.unpack_from(buf, offset))
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def lz4_decompress_block(payload: bytes, uncompressed_length: int) -> bytes:
|
|
187
|
+
"""Inflate a raw LZ4 block to exactly *uncompressed_length* bytes."""
|
|
188
|
+
try:
|
|
189
|
+
out = _load_backend()[2](payload, uncompressed_length)
|
|
190
|
+
except MissingLz4:
|
|
191
|
+
raise
|
|
192
|
+
except Exception as exc: # both backends raise their own bare errors
|
|
193
|
+
raise BlockError(f"raw LZ4 block did not inflate: {exc}") from exc
|
|
194
|
+
if len(out) != uncompressed_length:
|
|
195
|
+
raise BlockError(
|
|
196
|
+
f"LZ4 block inflated to {len(out)} bytes, header said {uncompressed_length}"
|
|
197
|
+
)
|
|
198
|
+
return out
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
def lz4_compress_block(plain: bytes) -> bytes:
|
|
202
|
+
"""Deflate *plain* to a raw LZ4 block (no size prefix, no frame header).
|
|
203
|
+
|
|
204
|
+
Note: this does **not** reproduce the vendor's ``vss/lz4.Lz4Compress`` output
|
|
205
|
+
byte-for-byte -- see ``README.md``. Any valid LZ4 block is decodable by the
|
|
206
|
+
device, so interoperability is unaffected; only byte-identical replay of a
|
|
207
|
+
captured server frame is.
|
|
208
|
+
"""
|
|
209
|
+
return _load_backend()[1](plain)
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
def stored_only(plain: bytes) -> bytes:
|
|
213
|
+
"""A "compressor" that never shrinks anything, so every block is ``Stored=1``.
|
|
214
|
+
|
|
215
|
+
Returns one byte more than it was given, which makes
|
|
216
|
+
:func:`encode_blocks` take the stored branch for every chunk -- the same
|
|
217
|
+
branch the vendor takes whenever LZ4 would not help. The result is a
|
|
218
|
+
perfectly ordinary, spec-conformant block chain that needs no LZ4 codec on
|
|
219
|
+
either side.
|
|
220
|
+
|
|
221
|
+
Worth considering because the captured 1.84 MB push shows LZ4 buying
|
|
222
|
+
essentially nothing on dithered halftone data: 60 of its 385 blocks were
|
|
223
|
+
stored anyway, and the 325 compressed ones averaged a 0.956 ratio. The
|
|
224
|
+
trade is ~4% more bytes on the wire for zero C extensions.
|
|
225
|
+
|
|
226
|
+
Note this keeps ``Compression = 1`` framing, which is what the device has
|
|
227
|
+
been observed receiving. Sending ``Compression = 0`` *to* a device is a
|
|
228
|
+
different thing and is **unverified** -- the gateway never does it.
|
|
229
|
+
"""
|
|
230
|
+
return plain + b"\x00"
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
STORED_ONLY = stored_only
|
|
234
|
+
"""Alias, for use as ``ConnectionConfig(compressor=STORED_ONLY)``."""
|
|
235
|
+
|
|
236
|
+
|
|
237
|
+
def decode_blocks(body: bytes, *, strict: bool = False) -> bytes:
|
|
238
|
+
"""Reassemble the plaintext from an LZ4 block chain.
|
|
239
|
+
|
|
240
|
+
Args:
|
|
241
|
+
body: the frame body, starting at the first block header.
|
|
242
|
+
strict: also validate ``BlockIndex`` ordering, the constancy of
|
|
243
|
+
``BlocksMinusOne``, ``Reserved == 0`` and that the chain consumes the
|
|
244
|
+
body exactly. The real gateway checks none of these.
|
|
245
|
+
|
|
246
|
+
Raises:
|
|
247
|
+
BlockError: on a malformed chain.
|
|
248
|
+
"""
|
|
249
|
+
out = bytearray()
|
|
250
|
+
offset = 0
|
|
251
|
+
index = 0
|
|
252
|
+
expected_count: int | None = None
|
|
253
|
+
|
|
254
|
+
while offset < len(body):
|
|
255
|
+
header = BlockHeader.unpack_from(body, offset)
|
|
256
|
+
if expected_count is None:
|
|
257
|
+
expected_count = header.block_count
|
|
258
|
+
# decoder.go:228-234
|
|
259
|
+
total = expected_count * BLOCK_PLAINTEXT_SIZE
|
|
260
|
+
if expected_count == 1:
|
|
261
|
+
total = header.uncompressed_length
|
|
262
|
+
if total > MAX_TOTAL:
|
|
263
|
+
raise BlockError(f"blocks too large: {total}")
|
|
264
|
+
elif strict and header.block_count != expected_count:
|
|
265
|
+
raise BlockError(
|
|
266
|
+
f"block {header.index}: BlocksMinusOne changed "
|
|
267
|
+
f"{expected_count - 1} -> {header.blocks_minus_one}"
|
|
268
|
+
)
|
|
269
|
+
if strict:
|
|
270
|
+
if header.index != index:
|
|
271
|
+
raise BlockError(f"block index out of order: want {index}, got {header.index}")
|
|
272
|
+
if header.reserved != 0:
|
|
273
|
+
raise BlockError(f"block {header.index}: Reserved = {header.reserved}, want 0")
|
|
274
|
+
if header.stored not in (0, 1):
|
|
275
|
+
raise BlockError(f"block {header.index}: Stored = {header.stored}, want 0 or 1")
|
|
276
|
+
|
|
277
|
+
start = offset + BLOCK_HEADER_SIZE
|
|
278
|
+
end = start + header.payload_length
|
|
279
|
+
if end > len(body):
|
|
280
|
+
raise BlockError(
|
|
281
|
+
f"block {header.index} payload runs past the body "
|
|
282
|
+
f"({end} > {len(body)})"
|
|
283
|
+
)
|
|
284
|
+
payload = body[start:end]
|
|
285
|
+
if header.is_stored:
|
|
286
|
+
if strict and header.payload_length != header.uncompressed_length:
|
|
287
|
+
raise BlockError(
|
|
288
|
+
f"block {header.index} is stored but PayloadLength "
|
|
289
|
+
f"{header.payload_length} != UncompressedLength {header.uncompressed_length}"
|
|
290
|
+
)
|
|
291
|
+
out += payload
|
|
292
|
+
else:
|
|
293
|
+
out += lz4_decompress_block(payload, header.uncompressed_length)
|
|
294
|
+
|
|
295
|
+
offset = end
|
|
296
|
+
index += 1
|
|
297
|
+
|
|
298
|
+
if expected_count is not None and strict and index != expected_count:
|
|
299
|
+
raise BlockError(f"chain has {index} blocks, first header said {expected_count}")
|
|
300
|
+
return bytes(out)
|
|
301
|
+
|
|
302
|
+
|
|
303
|
+
def iter_block_headers(body: bytes) -> Iterable[tuple[int, BlockHeader]]:
|
|
304
|
+
"""Yield ``(offset, header)`` for each block in *body* without inflating it."""
|
|
305
|
+
offset = 0
|
|
306
|
+
while offset < len(body):
|
|
307
|
+
header = BlockHeader.unpack_from(body, offset)
|
|
308
|
+
yield offset, header
|
|
309
|
+
offset += BLOCK_HEADER_SIZE + header.payload_length
|
|
310
|
+
|
|
311
|
+
|
|
312
|
+
def encode_blocks(
|
|
313
|
+
plain: bytes,
|
|
314
|
+
*,
|
|
315
|
+
compressor: Callable[[bytes], bytes] = lz4_compress_block,
|
|
316
|
+
block_size: int = BLOCK_PLAINTEXT_SIZE,
|
|
317
|
+
) -> bytes:
|
|
318
|
+
"""Split *plain* into ``block_size`` chunks and emit the block chain.
|
|
319
|
+
|
|
320
|
+
Follows the vendor's per-block decision exactly: compress the chunk, and use
|
|
321
|
+
the LZ4 payload only if it is **strictly** smaller than the chunk, otherwise
|
|
322
|
+
mark the block ``Stored = 1`` and emit the chunk verbatim.
|
|
323
|
+
|
|
324
|
+
Args:
|
|
325
|
+
plain: the marshalled packet (``DataHeader`` + payload, or raw body).
|
|
326
|
+
compressor: raw-LZ4-block compressor. Swappable so that a caller who has
|
|
327
|
+
reproduced ``vss/lz4.Lz4Compress`` can get byte-identical frames.
|
|
328
|
+
block_size: plaintext chunk size. Do not change; 4800 is what the device
|
|
329
|
+
expects.
|
|
330
|
+
|
|
331
|
+
Returns:
|
|
332
|
+
The frame body.
|
|
333
|
+
"""
|
|
334
|
+
if not plain:
|
|
335
|
+
# The vendor never emits a zero-length body; one empty stored block keeps
|
|
336
|
+
# the chain well-formed if a caller ever asks for it.
|
|
337
|
+
return BlockHeader(0, 0, 0, 0, 1).pack()
|
|
338
|
+
|
|
339
|
+
chunks = [plain[i : i + block_size] for i in range(0, len(plain), block_size)]
|
|
340
|
+
last = len(chunks) - 1
|
|
341
|
+
out = bytearray()
|
|
342
|
+
for i, chunk in enumerate(chunks):
|
|
343
|
+
squeezed = compressor(chunk)
|
|
344
|
+
if len(squeezed) < len(chunk):
|
|
345
|
+
payload, stored = squeezed, 0
|
|
346
|
+
else:
|
|
347
|
+
payload, stored = chunk, 1
|
|
348
|
+
out += BlockHeader(i, last, len(payload), len(chunk), stored).pack()
|
|
349
|
+
out += payload
|
|
350
|
+
return bytes(out)
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
"""The direction-dependent ``ProtocolHeader.Checksum``.
|
|
2
|
+
|
|
3
|
+
This is the single nastiest detail in the Visionect wire protocol, and the one
|
|
4
|
+
most likely to be implemented symmetrically and then fail silently. There is
|
|
5
|
+
exactly one function here, it takes an explicit :class:`Direction`, and nothing
|
|
6
|
+
else in the library is allowed to call :func:`crc32_ieee` on a frame directly.
|
|
7
|
+
|
|
8
|
+
What is actually CRC'd
|
|
9
|
+
----------------------
|
|
10
|
+
|
|
11
|
+
=================== ======================================== ==================================
|
|
12
|
+
direction covered bytes where this came from
|
|
13
|
+
=================== ======================================== ==================================
|
|
14
|
+
``SERVER_TO_DEVICE`` the whole body, after compression, ``encoder.go:314`` computes
|
|
15
|
+
before encryption ``crc32.ChecksumIEEE(body)`` on the
|
|
16
|
+
same slice later handed to
|
|
17
|
+
``encrypt``; stored at
|
|
18
|
+
``encoder.go:327``.
|
|
19
|
+
``DEVICE_TO_SERVER`` ``header[0:16]`` -- Version, Security, No code evidence (the firmware was
|
|
20
|
+
Compression, Length. **It does not not disassembled); 26/26 captured
|
|
21
|
+
cover the payload at all.** device frames match this rule and
|
|
22
|
+
nothing else.
|
|
23
|
+
=================== ======================================== ==================================
|
|
24
|
+
|
|
25
|
+
The proof that the device rule really is header-only: two status packets ten
|
|
26
|
+
minutes apart, with different packet IDs and different battery/uptime values,
|
|
27
|
+
carry the *identical* checksum ``0x198ceb01``, because their
|
|
28
|
+
``(Version=3, Security=0, Compression=0, Length=532)`` prefix is identical.
|
|
29
|
+
Conversely two server acks with identical headers ``(3, 0, 1, 68)`` carry
|
|
30
|
+
different checksums because their bodies differ.
|
|
31
|
+
|
|
32
|
+
Consequences for an implementation
|
|
33
|
+
----------------------------------
|
|
34
|
+
|
|
35
|
+
* As a **server** (which is what this library is), emit ``crc32(body)``.
|
|
36
|
+
* The inbound field is only verifiable in strict mode -- see
|
|
37
|
+
:func:`verify_checksum`. The real gateway never validates it: there is no
|
|
38
|
+
``crc32`` call anywhere in ``(*Decoder).DecodeWithTimeout``.
|
|
39
|
+
* As a **device emulator** (used by the test suite to re-encode captured device
|
|
40
|
+
frames byte-exactly), emit ``crc32(header[0:16])``.
|
|
41
|
+
"""
|
|
42
|
+
|
|
43
|
+
from __future__ import annotations
|
|
44
|
+
|
|
45
|
+
import enum
|
|
46
|
+
import zlib
|
|
47
|
+
|
|
48
|
+
__all__ = ["Direction", "crc32_ieee", "frame_checksum", "verify_checksum"]
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
class Direction(enum.Enum):
|
|
52
|
+
"""Which end of the link produced a frame.
|
|
53
|
+
|
|
54
|
+
There is no default and no "either": every call site must say which it is.
|
|
55
|
+
"""
|
|
56
|
+
|
|
57
|
+
SERVER_TO_DEVICE = "server->device"
|
|
58
|
+
"""We are the server. Checksum covers the body."""
|
|
59
|
+
|
|
60
|
+
DEVICE_TO_SERVER = "device->server"
|
|
61
|
+
"""The sign produced the frame. Checksum covers only ``header[0:16]``."""
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def crc32_ieee(data: bytes) -> int:
|
|
65
|
+
"""CRC-32/IEEE 802.3 (the ``zlib``/``crc32.ChecksumIEEE`` polynomial), as uint32."""
|
|
66
|
+
return zlib.crc32(data) & 0xFFFFFFFF
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def frame_checksum(direction: Direction, *, header16: bytes, body: bytes) -> int:
|
|
70
|
+
"""Compute ``ProtocolHeader.Checksum`` for *direction*.
|
|
71
|
+
|
|
72
|
+
Args:
|
|
73
|
+
direction: who is sending. Not optional, on purpose.
|
|
74
|
+
header16: the first 16 bytes of the 20-byte ``ProtocolHeader``, i.e.
|
|
75
|
+
``Version | Security | Compression | Length`` already packed. The
|
|
76
|
+
``Length`` field must already hold the final body length, because
|
|
77
|
+
the device's CRC covers it.
|
|
78
|
+
body: the frame body as it will appear on the wire (post-compression,
|
|
79
|
+
pre-encryption -- encryption is not implemented).
|
|
80
|
+
|
|
81
|
+
Returns:
|
|
82
|
+
The uint32 to store at offset 16 of the ``ProtocolHeader``.
|
|
83
|
+
|
|
84
|
+
Raises:
|
|
85
|
+
ValueError: if *header16* is not exactly 16 bytes, or *direction* is not
|
|
86
|
+
a :class:`Direction`.
|
|
87
|
+
"""
|
|
88
|
+
if not isinstance(direction, Direction):
|
|
89
|
+
raise ValueError(
|
|
90
|
+
f"direction must be a wire.Direction, not {type(direction).__name__}; "
|
|
91
|
+
"the checksum rule is not symmetric"
|
|
92
|
+
)
|
|
93
|
+
if len(header16) != 16:
|
|
94
|
+
raise ValueError(f"header16 must be exactly 16 bytes, got {len(header16)}")
|
|
95
|
+
|
|
96
|
+
if direction is Direction.SERVER_TO_DEVICE:
|
|
97
|
+
return crc32_ieee(body)
|
|
98
|
+
# DEVICE_TO_SERVER: header-only. Yes, really; see the module docstring.
|
|
99
|
+
return crc32_ieee(header16)
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def verify_checksum(
|
|
103
|
+
direction: Direction, *, header16: bytes, body: bytes, checksum: int
|
|
104
|
+
) -> bool:
|
|
105
|
+
"""Return whether *checksum* matches the rule for *direction*.
|
|
106
|
+
|
|
107
|
+
Used by the decoder only when ``strict=True``. It is off by default
|
|
108
|
+
because:
|
|
109
|
+
|
|
110
|
+
* the real gateway does not check it, so a correct-but-strict
|
|
111
|
+
reimplementation would reject frames the vendor server accepts; and
|
|
112
|
+
* the device rule covers no payload bytes, so the check cannot detect
|
|
113
|
+
payload corruption and buys nothing.
|
|
114
|
+
"""
|
|
115
|
+
return frame_checksum(direction, header16=header16, body=body) == checksum
|
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
"""Exceptions raised by the wire layer.
|
|
2
|
+
|
|
3
|
+
All of these are protocol-level faults: a frame that cannot be parsed, a checksum
|
|
4
|
+
that does not match in strict mode, or a frame that exceeds a limit the real
|
|
5
|
+
gateway enforces.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
__all__ = [
|
|
11
|
+
"VisionectError",
|
|
12
|
+
"ProtocolError",
|
|
13
|
+
"ShortBuffer",
|
|
14
|
+
"UnsupportedVersion",
|
|
15
|
+
"UnsupportedCompression",
|
|
16
|
+
"UnsupportedSecurity",
|
|
17
|
+
"FrameTooLarge",
|
|
18
|
+
"ChecksumMismatch",
|
|
19
|
+
"BlockError",
|
|
20
|
+
"PayloadError",
|
|
21
|
+
"ReadOnlyParameter",
|
|
22
|
+
"ListenError",
|
|
23
|
+
"CommandPacketsDisabled",
|
|
24
|
+
"MissingLz4",
|
|
25
|
+
]
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class VisionectError(Exception):
|
|
29
|
+
"""Base class for every error this library raises."""
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class ProtocolError(VisionectError):
|
|
33
|
+
"""A received byte stream does not conform to the protocol."""
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class ShortBuffer(ProtocolError):
|
|
37
|
+
"""A fixed-width header was handed fewer bytes than its size.
|
|
38
|
+
|
|
39
|
+
Mirrors ``io.ErrShortBuffer`` in ``proto/v2.(*ProtocolHeader).UnmarshalBinary``.
|
|
40
|
+
"""
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class UnsupportedVersion(ProtocolError):
|
|
44
|
+
"""``ProtocolHeader.Version != 3``.
|
|
45
|
+
|
|
46
|
+
The gateway's mux drops such a connection with
|
|
47
|
+
``"unsupported protocol version %d"`` (``decoder.go:81``).
|
|
48
|
+
"""
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
class UnsupportedCompression(ProtocolError):
|
|
52
|
+
"""``ProtocolHeader.Compression`` is neither 0 (none) nor 1 (LZ4 block list).
|
|
53
|
+
|
|
54
|
+
``decoder.go:127``: ``"unsupported compression %d"``.
|
|
55
|
+
"""
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
class UnsupportedSecurity(ProtocolError):
|
|
59
|
+
"""``ProtocolHeader.Security != 0``.
|
|
60
|
+
|
|
61
|
+
Link encryption is out of scope for v1: the session key is escrowed with a
|
|
62
|
+
Visionect HTTPS service and the key material is not present in the server
|
|
63
|
+
image, so a self-hosted deployment is plaintext by construction.
|
|
64
|
+
"""
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
class FrameTooLarge(ProtocolError):
|
|
68
|
+
"""``ProtocolHeader.Length`` exceeds ``MAX_FRAME_LENGTH`` (50 MiB).
|
|
69
|
+
|
|
70
|
+
``decoder.go:84``: ``hdr.Length > 0x3200000`` -> ``"packet too large: %d"``.
|
|
71
|
+
"""
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
class ChecksumMismatch(ProtocolError):
|
|
75
|
+
"""The CRC-32 in a received ``ProtocolHeader`` did not match.
|
|
76
|
+
|
|
77
|
+
Only raised in strict mode. The real gateway never validates the inbound
|
|
78
|
+
field at all, and a device CRC that covers only the header cannot detect
|
|
79
|
+
payload corruption anyway.
|
|
80
|
+
"""
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
class BlockError(ProtocolError):
|
|
84
|
+
"""The LZ4 block chain is malformed (bad length, bad index, bad LZ4 block)."""
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
class PayloadError(ProtocolError):
|
|
88
|
+
"""A per-type payload could not be decoded."""
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
class ReadOnlyParameter(VisionectError):
|
|
92
|
+
"""A write was attempted to a TCLV parameter the network cannot write.
|
|
93
|
+
|
|
94
|
+
Carries the id, the name and the USB CLI command that *can* set it.
|
|
95
|
+
"""
|
|
96
|
+
|
|
97
|
+
def __init__(self, param_id: int, name: str, usb_hint: str) -> None:
|
|
98
|
+
self.param_id = param_id
|
|
99
|
+
self.name = name
|
|
100
|
+
self.usb_hint = usb_hint
|
|
101
|
+
super().__init__(
|
|
102
|
+
f"TCLV parameter {param_id} ({name!r}) is read-only over the network "
|
|
103
|
+
f"(canWrite:false in the vendor's own descriptor table). "
|
|
104
|
+
f"Set it over the USB serial CLI instead: {usb_hint}, then `flash_save`, then `reboot`."
|
|
105
|
+
)
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
class ListenError(VisionectError):
|
|
109
|
+
"""Binding the device listener failed.
|
|
110
|
+
|
|
111
|
+
``asyncio.start_server`` raises a bare :class:`OSError`, which leaves a
|
|
112
|
+
caller string-matching ``errno`` to tell "the port is busy" from "I cannot
|
|
113
|
+
bind that address". Those need completely different advice, so the errno is
|
|
114
|
+
carried here as a field.
|
|
115
|
+
|
|
116
|
+
Attributes:
|
|
117
|
+
errno: the OS error number, **or None**. ``EADDRINUSE`` almost always
|
|
118
|
+
means the vendor's own server (or a previous, not-fully-closed
|
|
119
|
+
instance of this one) still holds port 11113; ``EACCES`` means a
|
|
120
|
+
privileged port or a sandbox; ``EADDRNOTAVAIL`` means the host
|
|
121
|
+
address does not exist on this machine.
|
|
122
|
+
|
|
123
|
+
``None`` happens and is not a bug here: when ``getaddrinfo``
|
|
124
|
+
resolves to several candidates and all of them fail, asyncio raises
|
|
125
|
+
a summary ``OSError("could not bind on any address out of ...")``
|
|
126
|
+
and **discards the per-address errno**, so there is nothing to
|
|
127
|
+
recover. Treat ``errno is None`` as "the address could not be
|
|
128
|
+
bound, reason not reported" and show :attr:`host` and :attr:`port`.
|
|
129
|
+
host: the address we tried to bind.
|
|
130
|
+
port: the port we tried to bind.
|
|
131
|
+
"""
|
|
132
|
+
|
|
133
|
+
def __init__(self, host: str, port: int, cause: OSError) -> None:
|
|
134
|
+
import errno as _errno
|
|
135
|
+
|
|
136
|
+
self.host = host
|
|
137
|
+
self.port = port
|
|
138
|
+
self.errno = cause.errno
|
|
139
|
+
self.__cause__ = cause
|
|
140
|
+
name = _errno.errorcode.get(cause.errno, "OSError") if cause.errno else "OSError"
|
|
141
|
+
hint = {
|
|
142
|
+
_errno.EADDRINUSE: (
|
|
143
|
+
"something already holds that port -- most likely the Visionect "
|
|
144
|
+
"server itself, which you cannot run alongside this listener, or "
|
|
145
|
+
"an earlier instance whose client connections were never closed "
|
|
146
|
+
"(see VisionectServer.close)"
|
|
147
|
+
),
|
|
148
|
+
_errno.EACCES: "no permission to bind that address or port",
|
|
149
|
+
_errno.EADDRNOTAVAIL: "that address does not exist on this host",
|
|
150
|
+
}.get(cause.errno or 0, str(cause))
|
|
151
|
+
if cause.errno is None:
|
|
152
|
+
hint = (
|
|
153
|
+
f"{cause}. asyncio does not report which errno applied to each "
|
|
154
|
+
"candidate address; check that the host address exists on this "
|
|
155
|
+
"machine and that nothing else holds the port"
|
|
156
|
+
)
|
|
157
|
+
super().__init__(f"cannot listen on {host}:{port} ({name}): {hint}")
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
class CommandPacketsDisabled(VisionectError):
|
|
161
|
+
"""A ``packet.Type 2`` (command) send was attempted with them disabled.
|
|
162
|
+
|
|
163
|
+
Only two of the 24 type-2 command ids have ever been observed on the wire
|
|
164
|
+
(``sleep`` and ``status request``, 2026-10-05); see the note at the
|
|
165
|
+
top of :mod:`pyvisionect.packets.misc`. ``ConnectionConfig(
|
|
166
|
+
allow_command_packets=False)`` lets a cautious consumer guarantee that none
|
|
167
|
+
are ever emitted.
|
|
168
|
+
"""
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
class MissingLz4(VisionectError):
|
|
172
|
+
"""An LZ4 block had to be produced or consumed but ``lz4`` is not installed.
|
|
173
|
+
|
|
174
|
+
The device never compresses, so a pure *server* can run without ``lz4`` by
|
|
175
|
+
setting ``ConnectionConfig(compressor=STORED_ONLY)``.
|
|
176
|
+
"""
|