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,202 @@
|
|
|
1
|
+
"""The remaining payload types: command, touch, button, GPS, CBOR.
|
|
2
|
+
|
|
3
|
+
All little-endian, all small. ``command`` (2) is server-to-device only; the
|
|
4
|
+
others are device-to-server.
|
|
5
|
+
|
|
6
|
+
.. note::
|
|
7
|
+
**Packet type 2 (``command``) is captured for 2 of its 24 command ids.**
|
|
8
|
+
|
|
9
|
+
``sleep`` (4) and ``status request`` (11) were provoked out of the vendor
|
|
10
|
+
server on 2026-10-05 and decoded off the wire by :class:`CommandPacket`
|
|
11
|
+
unmodified::
|
|
12
|
+
|
|
13
|
+
sleep 04000000 04000000 00000000 8e030000
|
|
14
|
+
status request 0b000000 00000000 00000000
|
|
15
|
+
|
|
16
|
+
So the 12-byte ``CommandHeader`` (``Type`` / ``PayloadLength`` /
|
|
17
|
+
``Reserved``) is **real**, and ``Reserved`` is emitted. The precedent that
|
|
18
|
+
made it suspect no longer applies: ``proto.Command``'s struct is 12 bytes
|
|
19
|
+
and the param packet's on-wire header is **8**, because ``Reserved`` is
|
|
20
|
+
simply dropped there -- but type 2 emits it. The zero-payload status
|
|
21
|
+
request settles that on its own: 12 bytes of header, nothing after. The
|
|
22
|
+
device acks both frames with ``Control{Flags: 1}``, and the status that
|
|
23
|
+
answers a status request carries ``ConnectReason == 8`` ("by server
|
|
24
|
+
request").
|
|
25
|
+
|
|
26
|
+
**Every other command id has never been observed on the wire**, in either
|
|
27
|
+
direction, so the payload and effect of the remaining 22 are code-read
|
|
28
|
+
only. Five of them have **no emission site anywhere in the vendor
|
|
29
|
+
server**: ``9`` (LED window), ``10`` (LDRLED), ``-1`` (refresh), ``-2``
|
|
30
|
+
(clear screen) and ``-3`` (keyboard). ``-4`` ("beep") does have one, built
|
|
31
|
+
inline in ``webkit.generateCommand``; and ``15`` is emitted by
|
|
32
|
+
``stdcmd.DisplayID.Done`` even though both ``String()`` chains print
|
|
33
|
+
``unknown`` for it.
|
|
34
|
+
|
|
35
|
+
Consequences for a consumer:
|
|
36
|
+
|
|
37
|
+
* prefer a verified route wherever one exists -- an image push instead of
|
|
38
|
+
``refresh``/``clear_screen``, a TCLV write instead of ``set_heartbeat``;
|
|
39
|
+
* ``ConnectionConfig(allow_command_packets=False)`` refuses to emit type 2
|
|
40
|
+
at all, so an integration can ship a "safe mode" and a test suite can
|
|
41
|
+
assert that nothing slipped through. Two ids out of 24 is not enough to
|
|
42
|
+
take the other 22 on trust;
|
|
43
|
+
* a reboot *is* observable after the fact: the device reconnects with
|
|
44
|
+
``ConnectReason == 1``, which
|
|
45
|
+
:attr:`~pyvisionect.packets.StatusPacket.connect_reason_name` reports.
|
|
46
|
+
"""
|
|
47
|
+
|
|
48
|
+
from __future__ import annotations
|
|
49
|
+
|
|
50
|
+
import struct
|
|
51
|
+
from dataclasses import dataclass
|
|
52
|
+
|
|
53
|
+
from ..devices.enums import CommandType, PacketType
|
|
54
|
+
from ..wire.errors import PayloadError
|
|
55
|
+
|
|
56
|
+
__all__ = [
|
|
57
|
+
"CommandPacket",
|
|
58
|
+
"TouchPacket",
|
|
59
|
+
"ButtonPacket",
|
|
60
|
+
"GpsPacket",
|
|
61
|
+
"CborPacket",
|
|
62
|
+
]
|
|
63
|
+
|
|
64
|
+
_CMD = struct.Struct("<iII")
|
|
65
|
+
_TOUCH = struct.Struct("<5I")
|
|
66
|
+
_BUTTON = struct.Struct("<2I")
|
|
67
|
+
_CBOR = struct.Struct("<3I")
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
@dataclass(slots=True)
|
|
71
|
+
class CommandPacket:
|
|
72
|
+
"""``packet.CommandHeader`` + payload (12 + N bytes).
|
|
73
|
+
|
|
74
|
+
The 12-byte header is confirmed on the wire, ``Reserved`` included: this
|
|
75
|
+
codec decoded both captured type-2 frames with no change (see the module
|
|
76
|
+
note).
|
|
77
|
+
|
|
78
|
+
``Type`` is a signed int32: ``-1`` refresh, ``-2`` clear screen,
|
|
79
|
+
``-3`` keyboard, ``-4`` beep are all real values. ``0`` is **echo** and
|
|
80
|
+
``1`` is **reboot**, in both the v1 and the v2 enum.
|
|
81
|
+
"""
|
|
82
|
+
|
|
83
|
+
type: int
|
|
84
|
+
payload: bytes = b""
|
|
85
|
+
reserved: int = 0
|
|
86
|
+
|
|
87
|
+
TYPE = PacketType.COMMAND
|
|
88
|
+
|
|
89
|
+
@property
|
|
90
|
+
def type_name(self) -> str:
|
|
91
|
+
return CommandType.NAMES.get(self.type, "unknown")
|
|
92
|
+
|
|
93
|
+
@classmethod
|
|
94
|
+
def decode(cls, payload: bytes) -> "CommandPacket":
|
|
95
|
+
if len(payload) < 12:
|
|
96
|
+
raise PayloadError(f"command payload is {len(payload)} bytes, need >= 12")
|
|
97
|
+
type_, length, reserved = _CMD.unpack_from(payload, 0)
|
|
98
|
+
return cls(type=type_, payload=payload[12 : 12 + length], reserved=reserved)
|
|
99
|
+
|
|
100
|
+
def encode(self) -> bytes:
|
|
101
|
+
return _CMD.pack(self.type, len(self.payload), self.reserved) + self.payload
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
@dataclass(frozen=True, slots=True)
|
|
105
|
+
class TouchPacket:
|
|
106
|
+
"""``packet.Touch`` -- five uint32s, 20 bytes."""
|
|
107
|
+
|
|
108
|
+
display_crc: int
|
|
109
|
+
display_id: int
|
|
110
|
+
finger_num: int
|
|
111
|
+
x: int
|
|
112
|
+
y: int
|
|
113
|
+
|
|
114
|
+
TYPE = PacketType.TOUCH
|
|
115
|
+
|
|
116
|
+
@classmethod
|
|
117
|
+
def decode(cls, payload: bytes) -> "TouchPacket":
|
|
118
|
+
if len(payload) < 20:
|
|
119
|
+
raise PayloadError(f"touch payload is {len(payload)} bytes, need 20")
|
|
120
|
+
return cls(*_TOUCH.unpack_from(payload, 0))
|
|
121
|
+
|
|
122
|
+
def encode(self) -> bytes:
|
|
123
|
+
return _TOUCH.pack(
|
|
124
|
+
self.display_crc, self.display_id, self.finger_num, self.x, self.y
|
|
125
|
+
)
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
@dataclass(frozen=True, slots=True)
|
|
129
|
+
class ButtonPacket:
|
|
130
|
+
"""``packet.Button`` -- ``Active``, ``State``; 8 bytes."""
|
|
131
|
+
|
|
132
|
+
active: int
|
|
133
|
+
state: int
|
|
134
|
+
|
|
135
|
+
TYPE = PacketType.BUTTON
|
|
136
|
+
|
|
137
|
+
@classmethod
|
|
138
|
+
def decode(cls, payload: bytes) -> "ButtonPacket":
|
|
139
|
+
if len(payload) < 8:
|
|
140
|
+
raise PayloadError(f"button payload is {len(payload)} bytes, need 8")
|
|
141
|
+
return cls(*_BUTTON.unpack_from(payload, 0))
|
|
142
|
+
|
|
143
|
+
def encode(self) -> bytes:
|
|
144
|
+
return _BUTTON.pack(self.active, self.state)
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
@dataclass(frozen=True, slots=True)
|
|
148
|
+
class GpsPacket:
|
|
149
|
+
"""``packet.GPS`` -- ``PowerState uint32`` then a coordinate string.
|
|
150
|
+
|
|
151
|
+
The Go struct holds a ``string``; the on-wire framing of that string was not
|
|
152
|
+
recovered (no GPS device was available), so the remainder is kept as bytes
|
|
153
|
+
and exposed as NUL-trimmed ASCII. [GAP]
|
|
154
|
+
"""
|
|
155
|
+
|
|
156
|
+
power_state: int
|
|
157
|
+
raw: bytes = b""
|
|
158
|
+
|
|
159
|
+
TYPE = PacketType.GPS
|
|
160
|
+
|
|
161
|
+
@property
|
|
162
|
+
def coordinates(self) -> str:
|
|
163
|
+
return self.raw.split(b"\x00")[0].decode("ascii", errors="replace")
|
|
164
|
+
|
|
165
|
+
@classmethod
|
|
166
|
+
def decode(cls, payload: bytes) -> "GpsPacket":
|
|
167
|
+
if len(payload) < 4:
|
|
168
|
+
raise PayloadError(f"gps payload is {len(payload)} bytes, need >= 4")
|
|
169
|
+
(power,) = struct.unpack_from("<I", payload, 0)
|
|
170
|
+
return cls(power_state=power, raw=payload[4:])
|
|
171
|
+
|
|
172
|
+
def encode(self) -> bytes:
|
|
173
|
+
return struct.pack("<I", self.power_state) + self.raw
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
@dataclass(slots=True)
|
|
177
|
+
class CborPacket:
|
|
178
|
+
"""``packet.CBORHeader`` + CBOR bytes (``packet/cbor.go:18-46``).
|
|
179
|
+
|
|
180
|
+
The "AC" (JS-app) device generation's channel. Firmware 7.4.4407 never
|
|
181
|
+
emits it, so this codec is framing-only: the CBOR body is not parsed.
|
|
182
|
+
"""
|
|
183
|
+
|
|
184
|
+
user_data: int = 0
|
|
185
|
+
data: bytes = b""
|
|
186
|
+
reserved: int = 0
|
|
187
|
+
|
|
188
|
+
TYPE = PacketType.CBOR
|
|
189
|
+
|
|
190
|
+
@classmethod
|
|
191
|
+
def decode(cls, payload: bytes) -> "CborPacket":
|
|
192
|
+
if len(payload) < 12:
|
|
193
|
+
raise PayloadError(f"cbor payload is {len(payload)} bytes, need >= 12")
|
|
194
|
+
user_data, reserved, length = _CBOR.unpack_from(payload, 0)
|
|
195
|
+
if len(payload) < 12 + length:
|
|
196
|
+
raise PayloadError(
|
|
197
|
+
f"cbor declares {length} bytes, only {len(payload) - 12} remain"
|
|
198
|
+
)
|
|
199
|
+
return cls(user_data=user_data, data=payload[12 : 12 + length], reserved=reserved)
|
|
200
|
+
|
|
201
|
+
def encode(self) -> bytes:
|
|
202
|
+
return _CBOR.pack(self.user_data, self.reserved, len(self.data)) + self.data
|
|
@@ -0,0 +1,284 @@
|
|
|
1
|
+
"""Parameter packets (type 8) -- the TCLV configuration channel.
|
|
2
|
+
|
|
3
|
+
Wire format (``packet.(*Param).MarshalBinaryTo``, ``packet/param.go:21-47``)::
|
|
4
|
+
|
|
5
|
+
ParamHeader (8 bytes)
|
|
6
|
+
0 4 Reserved uint32 LE
|
|
7
|
+
4 4 PayloadLength uint32 LE = sum over items of (4 + len(Value))
|
|
8
|
+
|
|
9
|
+
then, repeated:
|
|
10
|
+
ParamPayload
|
|
11
|
+
+0 2 Type uint16 LE (the TCLV parameter id)
|
|
12
|
+
+2 1 Control uint8 (0 read, 1 write, 2 read error, 3 write error)
|
|
13
|
+
+3 1 Length uint8 (= len(Value); a value is at most 255 bytes)
|
|
14
|
+
+4 N Value Length bytes
|
|
15
|
+
|
|
16
|
+
Note the header is **8 bytes**, not the 12 of ``proto.Command`` -- ``Reserved``
|
|
17
|
+
is the first word and ``PayloadLength`` the second, and nothing else is emitted.
|
|
18
|
+
Counted off the capture: a 32-byte read request carried 24 bytes of items.
|
|
19
|
+
|
|
20
|
+
A **read request** carries no TLVs at all: it is 8 header bytes followed by a
|
|
21
|
+
bare ``uint32`` per requested id. That is not a separate struct -- the gateway's
|
|
22
|
+
captured request was::
|
|
23
|
+
|
|
24
|
+
00 00 00 00 Reserved = 0
|
|
25
|
+
18 00 00 00 PayloadLength = 24
|
|
26
|
+
1d 00 00 00 -> id 29, Control 0 (read), Length 0
|
|
27
|
+
12 00 00 00 -> id 18, Control 0, Length 0
|
|
28
|
+
...
|
|
29
|
+
|
|
30
|
+
i.e. six zero-value ``ParamPayload`` records, which is exactly what this codec
|
|
31
|
+
produces for ``ParamItem(29, READ, b"")``.
|
|
32
|
+
|
|
33
|
+
Values are **untyped bytes**: a uint32 for numeric keys, a uint16 for the port,
|
|
34
|
+
bare ASCII with no NUL for strings. The library does not guess; use
|
|
35
|
+
:func:`encode_value` / :func:`decode_value` when you want a typed view.
|
|
36
|
+
"""
|
|
37
|
+
|
|
38
|
+
from __future__ import annotations
|
|
39
|
+
|
|
40
|
+
import struct
|
|
41
|
+
from dataclasses import dataclass, field
|
|
42
|
+
|
|
43
|
+
from ..devices.enums import PacketType, ParamControl
|
|
44
|
+
from ..devices.tclv import (
|
|
45
|
+
DEFAULT_VALUE_WIDTH,
|
|
46
|
+
check_writable,
|
|
47
|
+
name_of,
|
|
48
|
+
width_of,
|
|
49
|
+
)
|
|
50
|
+
from ..wire.errors import PayloadError
|
|
51
|
+
|
|
52
|
+
__all__ = [
|
|
53
|
+
"ParamItem",
|
|
54
|
+
"ParamPacket",
|
|
55
|
+
"encode_value",
|
|
56
|
+
"decode_value",
|
|
57
|
+
"PARAM_ERROR_NO_SUCH_PARAMETER",
|
|
58
|
+
"PARAM_ERROR_BAD_VALUE",
|
|
59
|
+
"PARAM_ERROR_NAMES",
|
|
60
|
+
]
|
|
61
|
+
|
|
62
|
+
PARAM_ERROR_NO_SUCH_PARAMETER = 0x00580000
|
|
63
|
+
"""Error value for a parameter this firmware does not implement.
|
|
64
|
+
|
|
65
|
+
Measured: reading 145 (``TLS mode``), 146 (``EPD count``), 147..151, 158..160
|
|
66
|
+
and the deliberately invented id 250 all came back ``control=2``, ``Length=4``,
|
|
67
|
+
``value=00 00 58 00`` -- byte for byte identical.
|
|
68
|
+
|
|
69
|
+
What makes this a *reading* rather than a guess is that other refusals in the
|
|
70
|
+
same sweep came back **different**. Sweeping 130..160 on firmware 7.4.4407
|
|
71
|
+
produced four distinct error values, and the ones that are not ``0x58`` land on
|
|
72
|
+
parameters the device demonstrably has:
|
|
73
|
+
|
|
74
|
+
=========== ===============================================================
|
|
75
|
+
error value ids
|
|
76
|
+
=========== ===============================================================
|
|
77
|
+
``0x58`` 133-137, 141, 142, 145-151, 158-160, and the invented 250
|
|
78
|
+
``0x5d`` 138 (BLE MAC), 143 (WiFi module upgrade), 157 (format filesystem)
|
|
79
|
+
``0x8d`` 139 (performs WiFi scan)
|
|
80
|
+
``0x60`` 140 (BLE advertising data)
|
|
81
|
+
=========== ===============================================================
|
|
82
|
+
|
|
83
|
+
BLE is on (155 reads 1), the filesystem exists, the WiFi module exists -- and
|
|
84
|
+
those ids answer with something *other* than ``0x58``. So ``0x58`` is the
|
|
85
|
+
firmware saying it has no such parameter, not a blanket "no". The other three
|
|
86
|
+
values have no interpretation here; three of their four ids are command-shaped,
|
|
87
|
+
which is suggestive and nothing more.
|
|
88
|
+
"""
|
|
89
|
+
|
|
90
|
+
PARAM_ERROR_BAD_VALUE = 0x005A0000
|
|
91
|
+
"""Error value for a parameter that exists but whose value was unacceptable.
|
|
92
|
+
|
|
93
|
+
Measured: a **one-byte** write to 29 (``Heart beat interval``, a uint32) came
|
|
94
|
+
back ``control=3``, ``value=00 00 5a 00``. The same id read back cleanly in the
|
|
95
|
+
same session, so this is not "no such parameter" -- it is the width.
|
|
96
|
+
|
|
97
|
+
That these two differ is what makes the parameter channel diagnosable at all:
|
|
98
|
+
without it, "this firmware has no such setting" and "this library encoded the
|
|
99
|
+
value wrongly" are the same symptom.
|
|
100
|
+
"""
|
|
101
|
+
|
|
102
|
+
PARAM_ERROR_NAMES: dict[int, str] = {
|
|
103
|
+
PARAM_ERROR_NO_SUCH_PARAMETER: "no such parameter on this firmware",
|
|
104
|
+
PARAM_ERROR_BAD_VALUE: "parameter exists, value rejected (wrong width?)",
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
_HDR = struct.Struct("<II")
|
|
108
|
+
_ITEM = struct.Struct("<HBB")
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
@dataclass(frozen=True, slots=True)
|
|
112
|
+
class ParamItem:
|
|
113
|
+
"""One ``packet.ParamPayload`` record."""
|
|
114
|
+
|
|
115
|
+
id: int
|
|
116
|
+
control: int = ParamControl.READ
|
|
117
|
+
value: bytes = b""
|
|
118
|
+
|
|
119
|
+
def __post_init__(self) -> None:
|
|
120
|
+
if len(self.value) > 255:
|
|
121
|
+
raise ValueError(
|
|
122
|
+
f"TCLV value for id {self.id} is {len(self.value)} bytes; "
|
|
123
|
+
"the Length field is a uint8"
|
|
124
|
+
)
|
|
125
|
+
|
|
126
|
+
@property
|
|
127
|
+
def name(self) -> str:
|
|
128
|
+
return name_of(self.id)
|
|
129
|
+
|
|
130
|
+
@property
|
|
131
|
+
def is_error(self) -> bool:
|
|
132
|
+
return self.control in (ParamControl.READ_ERROR, ParamControl.WRITE_ERROR)
|
|
133
|
+
|
|
134
|
+
@property
|
|
135
|
+
def error_code(self) -> int | None:
|
|
136
|
+
"""The device's reason code on an error reply, else None.
|
|
137
|
+
|
|
138
|
+
Compare against :data:`PARAM_ERROR_NO_SUCH_PARAMETER` and
|
|
139
|
+
:data:`PARAM_ERROR_BAD_VALUE`. An unrecognised value is returned as-is
|
|
140
|
+
rather than mapped to anything: only two have been observed and there
|
|
141
|
+
is no table for the rest.
|
|
142
|
+
"""
|
|
143
|
+
if not self.is_error:
|
|
144
|
+
return None
|
|
145
|
+
return self.as_int()
|
|
146
|
+
|
|
147
|
+
@property
|
|
148
|
+
def error_name(self) -> str | None:
|
|
149
|
+
""":attr:`error_code` as prose, or its hex if it is one we have not seen."""
|
|
150
|
+
code = self.error_code
|
|
151
|
+
if code is None:
|
|
152
|
+
return None
|
|
153
|
+
return PARAM_ERROR_NAMES.get(code, f"unknown reason 0x{code:08x}")
|
|
154
|
+
|
|
155
|
+
def encode(self) -> bytes:
|
|
156
|
+
return _ITEM.pack(self.id, self.control, len(self.value)) + self.value
|
|
157
|
+
|
|
158
|
+
def as_int(self) -> int:
|
|
159
|
+
"""Little-endian unsigned integer view of the value."""
|
|
160
|
+
return int.from_bytes(self.value, "little")
|
|
161
|
+
|
|
162
|
+
def as_str(self) -> str:
|
|
163
|
+
"""ASCII view, stripping a trailing NUL if the device sent one."""
|
|
164
|
+
return self.value.split(b"\x00")[0].decode("ascii", errors="replace")
|
|
165
|
+
|
|
166
|
+
def __str__(self) -> str:
|
|
167
|
+
ctl = ParamControl.NAMES.get(self.control, str(self.control))
|
|
168
|
+
return f"{self.id}({self.name!r}) {ctl} = {self.value!r}"
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def encode_value(value: int | str | bytes, *, width: int | None = None) -> bytes:
|
|
172
|
+
"""Value encoder.
|
|
173
|
+
|
|
174
|
+
Args:
|
|
175
|
+
value: ``bytes`` are passed through; ``str`` becomes bare ASCII with no
|
|
176
|
+
terminator (that is what the capture shows); ``int`` becomes a
|
|
177
|
+
little-endian unsigned integer of *width* bytes.
|
|
178
|
+
width: bytes for an integer. Defaults to
|
|
179
|
+
:data:`~pyvisionect.devices.tclv.DEFAULT_VALUE_WIDTH`; callers that
|
|
180
|
+
know the parameter should pass
|
|
181
|
+
:func:`~pyvisionect.devices.tclv.width_of`, which
|
|
182
|
+
:meth:`ParamPacket.write` does for them.
|
|
183
|
+
|
|
184
|
+
The default used to be "the narrowest of 1/2/4 that fits the value", which
|
|
185
|
+
is wrong and was wrong silently. Width is a property of the **parameter**,
|
|
186
|
+
not of the value: the heartbeat (29) is a uint32 whose normal value is 1,
|
|
187
|
+
and a one-byte write to it comes back as a write error. See
|
|
188
|
+
:data:`~pyvisionect.devices.tclv.VALUE_WIDTHS`.
|
|
189
|
+
"""
|
|
190
|
+
if isinstance(value, bytes):
|
|
191
|
+
return value
|
|
192
|
+
if isinstance(value, str):
|
|
193
|
+
return value.encode("ascii")
|
|
194
|
+
if isinstance(value, bool):
|
|
195
|
+
return bytes([int(value)])
|
|
196
|
+
if isinstance(value, int):
|
|
197
|
+
if width is None:
|
|
198
|
+
width = DEFAULT_VALUE_WIDTH
|
|
199
|
+
return int(value).to_bytes(width, "little")
|
|
200
|
+
raise TypeError(f"cannot encode {type(value).__name__} as a TCLV value")
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
def decode_value(raw: bytes) -> int | str:
|
|
204
|
+
"""Decode a value as an int if it looks numeric, else as ASCII.
|
|
205
|
+
|
|
206
|
+
A heuristic, offered for display only. The protocol carries no type tag.
|
|
207
|
+
"""
|
|
208
|
+
if len(raw) in (1, 2, 4) and not all(0x20 <= b < 0x7F for b in raw):
|
|
209
|
+
return int.from_bytes(raw, "little")
|
|
210
|
+
if raw and all(0x20 <= b < 0x7F or b == 0 for b in raw):
|
|
211
|
+
return raw.split(b"\x00")[0].decode("ascii")
|
|
212
|
+
return int.from_bytes(raw, "little")
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
@dataclass(slots=True)
|
|
216
|
+
class ParamPacket:
|
|
217
|
+
"""A ``packet.Param`` payload."""
|
|
218
|
+
|
|
219
|
+
items: list[ParamItem] = field(default_factory=list)
|
|
220
|
+
reserved: int = 0
|
|
221
|
+
|
|
222
|
+
TYPE = PacketType.PARAM
|
|
223
|
+
|
|
224
|
+
@classmethod
|
|
225
|
+
def read(cls, ids: list[int] | tuple[int, ...]) -> "ParamPacket":
|
|
226
|
+
"""Build a read request for *ids*."""
|
|
227
|
+
return cls(items=[ParamItem(i, ParamControl.READ, b"") for i in ids])
|
|
228
|
+
|
|
229
|
+
@classmethod
|
|
230
|
+
def write(
|
|
231
|
+
cls, values: dict[int, int | str | bytes], *, allow_read_only: bool = False
|
|
232
|
+
) -> "ParamPacket":
|
|
233
|
+
"""Build a write request.
|
|
234
|
+
|
|
235
|
+
Raises:
|
|
236
|
+
ReadOnlyParameter: for any id in the eight-strong network-read-only
|
|
237
|
+
set, unless *allow_read_only* is set. The error names the USB CLI
|
|
238
|
+
command that can set it.
|
|
239
|
+
"""
|
|
240
|
+
items = []
|
|
241
|
+
for pid, value in values.items():
|
|
242
|
+
if not allow_read_only:
|
|
243
|
+
check_writable(pid)
|
|
244
|
+
items.append(
|
|
245
|
+
ParamItem(
|
|
246
|
+
pid,
|
|
247
|
+
ParamControl.WRITE,
|
|
248
|
+
encode_value(value, width=width_of(pid)),
|
|
249
|
+
)
|
|
250
|
+
)
|
|
251
|
+
return cls(items=items)
|
|
252
|
+
|
|
253
|
+
@classmethod
|
|
254
|
+
def decode(cls, payload: bytes) -> "ParamPacket":
|
|
255
|
+
if len(payload) < 8:
|
|
256
|
+
raise PayloadError(f"param payload is {len(payload)} bytes, need >= 8")
|
|
257
|
+
reserved, declared = _HDR.unpack_from(payload, 0)
|
|
258
|
+
body = payload[8 : 8 + declared] if declared else payload[8:]
|
|
259
|
+
items: list[ParamItem] = []
|
|
260
|
+
offset = 0
|
|
261
|
+
while offset + 4 <= len(body):
|
|
262
|
+
pid, control, length = _ITEM.unpack_from(body, offset)
|
|
263
|
+
offset += 4
|
|
264
|
+
if offset + length > len(body):
|
|
265
|
+
raise PayloadError(
|
|
266
|
+
f"param id {pid} declares {length} value bytes, only "
|
|
267
|
+
f"{len(body) - offset} remain"
|
|
268
|
+
)
|
|
269
|
+
items.append(ParamItem(pid, control, body[offset : offset + length]))
|
|
270
|
+
offset += length
|
|
271
|
+
return cls(items=items, reserved=reserved)
|
|
272
|
+
|
|
273
|
+
def encode(self) -> bytes:
|
|
274
|
+
body = b"".join(item.encode() for item in self.items)
|
|
275
|
+
return _HDR.pack(self.reserved, len(body)) + body
|
|
276
|
+
|
|
277
|
+
def by_id(self) -> dict[int, ParamItem]:
|
|
278
|
+
return {item.id: item for item in self.items}
|
|
279
|
+
|
|
280
|
+
def __iter__(self):
|
|
281
|
+
return iter(self.items)
|
|
282
|
+
|
|
283
|
+
def __len__(self) -> int:
|
|
284
|
+
return len(self.items)
|