uwscli 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.
- uwscli/__init__.py +11 -0
- uwscli/cli.py +416 -0
- uwscli/lcd.py +594 -0
- uwscli/logging_utils.py +34 -0
- uwscli/structs.py +108 -0
- uwscli/system_usb.py +160 -0
- uwscli/usbutil.py +207 -0
- uwscli/wireless.py +362 -0
- uwscli-0.1.0.dist-info/METADATA +169 -0
- uwscli-0.1.0.dist-info/RECORD +14 -0
- uwscli-0.1.0.dist-info/WHEEL +5 -0
- uwscli-0.1.0.dist-info/entry_points.txt +2 -0
- uwscli-0.1.0.dist-info/licenses/LICENSE +21 -0
- uwscli-0.1.0.dist-info/top_level.txt +1 -0
uwscli/lcd.py
ADDED
|
@@ -0,0 +1,594 @@
|
|
|
1
|
+
"""Uni Fan LCD (TL) HID device access helpers."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import contextlib
|
|
6
|
+
import dataclasses
|
|
7
|
+
import datetime
|
|
8
|
+
import enum
|
|
9
|
+
import time
|
|
10
|
+
from typing import Dict, Iterator, List, Optional
|
|
11
|
+
|
|
12
|
+
import hid
|
|
13
|
+
|
|
14
|
+
try: # Prefer the namespace-safe module
|
|
15
|
+
from Cryptodome.Cipher import DES # type: ignore[import]
|
|
16
|
+
from Cryptodome.Util import Padding # type: ignore[import]
|
|
17
|
+
except ImportError: # pragma: no cover - fallback for alternative install
|
|
18
|
+
try:
|
|
19
|
+
from Crypto.Cipher import DES # type: ignore[import]
|
|
20
|
+
from Crypto.Util import Padding # type: ignore[import]
|
|
21
|
+
except ImportError: # pragma: no cover - handled at runtime
|
|
22
|
+
DES = None # type: ignore[assignment]
|
|
23
|
+
Padding = None # type: ignore[assignment]
|
|
24
|
+
|
|
25
|
+
from .structs import LCDControlMode, LCDControlSetting, ScreenRotation
|
|
26
|
+
from .system_usb import find_devices_by_vid_pid
|
|
27
|
+
from .usbutil import USBEndpointDevice, USBError
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
LCD_REPORT_ID = 0x02
|
|
31
|
+
OUTPUT_PACKET_SIZE = 512
|
|
32
|
+
INPUT_PACKET_SIZE = 64
|
|
33
|
+
USB_INPUT_PACKET_SIZE = OUTPUT_PACKET_SIZE
|
|
34
|
+
MAX_CHUNK = 501
|
|
35
|
+
|
|
36
|
+
# Known Uni Fan LCD VID/PID combinations (original and TL V2 wireless hub)
|
|
37
|
+
KNOWN_LCD_IDS = (
|
|
38
|
+
(0x04FC, 0x7393),
|
|
39
|
+
(0x1CBE, 0x0006),
|
|
40
|
+
)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class LCDDeviceError(RuntimeError):
|
|
44
|
+
"""Raised when HID operations fail."""
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
@dataclasses.dataclass
|
|
48
|
+
class HidDeviceInfo:
|
|
49
|
+
path: str
|
|
50
|
+
vendor_id: int
|
|
51
|
+
product_id: int
|
|
52
|
+
serial_number: Optional[str]
|
|
53
|
+
manufacturer: Optional[str]
|
|
54
|
+
product: Optional[str]
|
|
55
|
+
source: str = "hid"
|
|
56
|
+
location_id: Optional[int] = None
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def enumerate_devices() -> List[HidDeviceInfo]:
|
|
60
|
+
devices: List[HidDeviceInfo] = []
|
|
61
|
+
for vendor_id, product_id in KNOWN_LCD_IDS:
|
|
62
|
+
found_for_pair = False
|
|
63
|
+
for entry in hid.enumerate(vendor_id, product_id):
|
|
64
|
+
devices.append(
|
|
65
|
+
HidDeviceInfo(
|
|
66
|
+
path=entry["path"],
|
|
67
|
+
vendor_id=entry["vendor_id"],
|
|
68
|
+
product_id=entry["product_id"],
|
|
69
|
+
serial_number=entry.get("serial_number"),
|
|
70
|
+
manufacturer=entry.get("manufacturer_string"),
|
|
71
|
+
product=entry.get("product_string"),
|
|
72
|
+
source="hid",
|
|
73
|
+
location_id=entry.get("location_id"),
|
|
74
|
+
),
|
|
75
|
+
)
|
|
76
|
+
found_for_pair = True
|
|
77
|
+
if not found_for_pair:
|
|
78
|
+
for record in find_devices_by_vid_pid(vendor_id, product_id):
|
|
79
|
+
source = "usb"
|
|
80
|
+
if (record.vendor_id, record.product_id) == (0x1CBE, 0x0006):
|
|
81
|
+
source = "wireless"
|
|
82
|
+
devices.append(
|
|
83
|
+
HidDeviceInfo(
|
|
84
|
+
path=f"usb:{record.vendor_id:04x}:{record.product_id:04x}:{record.location_id or 0}",
|
|
85
|
+
vendor_id=record.vendor_id,
|
|
86
|
+
product_id=record.product_id,
|
|
87
|
+
serial_number=record.serial,
|
|
88
|
+
manufacturer=record.vendor,
|
|
89
|
+
product=record.product,
|
|
90
|
+
source=source,
|
|
91
|
+
location_id=record.location_id,
|
|
92
|
+
),
|
|
93
|
+
)
|
|
94
|
+
unique: List[HidDeviceInfo] = []
|
|
95
|
+
seen = set()
|
|
96
|
+
for dev in devices:
|
|
97
|
+
key = (dev.path, dev.serial_number, dev.vendor_id, dev.product_id)
|
|
98
|
+
if key in seen:
|
|
99
|
+
continue
|
|
100
|
+
seen.add(key)
|
|
101
|
+
unique.append(dev)
|
|
102
|
+
return unique
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
class WirelessCommand(enum.IntEnum):
|
|
106
|
+
GET_VER = 10
|
|
107
|
+
REBOOT = 11
|
|
108
|
+
ROTATE = 13
|
|
109
|
+
BRIGHTNESS = 14
|
|
110
|
+
SET_FRAME_RATE = 15
|
|
111
|
+
UPDATE_FIRMWARE = 40
|
|
112
|
+
STOP_CLOCK = 41
|
|
113
|
+
PUSH_JPG = 101
|
|
114
|
+
START_PLAY = 121
|
|
115
|
+
QUERY_BLOCK = 122
|
|
116
|
+
STOP_PLAY = 123
|
|
117
|
+
GET_POS_INDEX = 201
|
|
118
|
+
FACTORY_H264_TEST = 253
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
class WirelessUSBTransport:
|
|
122
|
+
"""Implements the wireless hub WinUSB protocol used by Uni Fan LCD devices."""
|
|
123
|
+
|
|
124
|
+
_KEY = b"slv3tuzx"
|
|
125
|
+
_HEADER_SIZE = 512
|
|
126
|
+
_PAYLOAD_BUFFER = 102400
|
|
127
|
+
|
|
128
|
+
def __init__(
|
|
129
|
+
self,
|
|
130
|
+
vendor_id: int,
|
|
131
|
+
product_id: int,
|
|
132
|
+
timeout_ms: int = 5000,
|
|
133
|
+
*,
|
|
134
|
+
serial_number: Optional[str] = None,
|
|
135
|
+
location_id: Optional[int] = None,
|
|
136
|
+
) -> None:
|
|
137
|
+
self._vendor_id = vendor_id
|
|
138
|
+
self._product_id = product_id
|
|
139
|
+
self._timeout_ms = timeout_ms
|
|
140
|
+
self._serial_number = serial_number
|
|
141
|
+
self._location_id = location_id
|
|
142
|
+
self._device = USBEndpointDevice(
|
|
143
|
+
vendor_id,
|
|
144
|
+
product_id,
|
|
145
|
+
write_endpoint=0x01,
|
|
146
|
+
read_endpoint=0x81,
|
|
147
|
+
interface=0,
|
|
148
|
+
configuration=None,
|
|
149
|
+
timeout_ms=timeout_ms,
|
|
150
|
+
serial_number=serial_number,
|
|
151
|
+
location_id=location_id,
|
|
152
|
+
)
|
|
153
|
+
utc_midnight = datetime.datetime.utcnow().replace(hour=0, minute=0, second=0, microsecond=0)
|
|
154
|
+
self._epoch = utc_midnight - datetime.timedelta(days=1)
|
|
155
|
+
self._last_handshake = 0.0
|
|
156
|
+
|
|
157
|
+
def close(self) -> None:
|
|
158
|
+
self._device.close()
|
|
159
|
+
self._last_handshake = 0.0
|
|
160
|
+
|
|
161
|
+
def handshake(self) -> Dict[str, int]:
|
|
162
|
+
response = self._send_command(WirelessCommand.GET_POS_INDEX, expect_reply=True)
|
|
163
|
+
for _ in range(4):
|
|
164
|
+
if response:
|
|
165
|
+
command = response[0]
|
|
166
|
+
if command == WirelessCommand.GET_POS_INDEX:
|
|
167
|
+
mode = response[8] if len(response) > 8 else 0
|
|
168
|
+
frame_index = response[9] if len(response) > 9 else 0
|
|
169
|
+
self._last_handshake = time.monotonic()
|
|
170
|
+
return {"mode": mode, "frame_index": frame_index}
|
|
171
|
+
if command == WirelessCommand.GET_VER:
|
|
172
|
+
self._parse_version(response)
|
|
173
|
+
self._last_handshake = time.monotonic()
|
|
174
|
+
return {"mode": 0, "frame_index": 0}
|
|
175
|
+
response = self._read_next()
|
|
176
|
+
raise LCDDeviceError("No valid handshake response from wireless LCD")
|
|
177
|
+
|
|
178
|
+
def firmware_version(self) -> Dict[str, str]:
|
|
179
|
+
response = self._send_command(WirelessCommand.GET_VER, expect_reply=True)
|
|
180
|
+
for _ in range(4):
|
|
181
|
+
if response and response[0] == WirelessCommand.GET_VER:
|
|
182
|
+
version = self._parse_version(response)
|
|
183
|
+
self._last_handshake = time.monotonic()
|
|
184
|
+
return {"version": version or "unknown", "build": ""}
|
|
185
|
+
response = self._read_next()
|
|
186
|
+
raise LCDDeviceError("Firmware request did not return expected data")
|
|
187
|
+
|
|
188
|
+
def _ensure_awake(self) -> None:
|
|
189
|
+
now = time.monotonic()
|
|
190
|
+
if self._last_handshake and now - self._last_handshake <= 2.0:
|
|
191
|
+
return
|
|
192
|
+
self.handshake()
|
|
193
|
+
|
|
194
|
+
def control(self, setting: LCDControlSetting) -> None:
|
|
195
|
+
self._ensure_awake()
|
|
196
|
+
brightness = max(0, min(100, setting.brightness))
|
|
197
|
+
self._send_command(
|
|
198
|
+
WirelessCommand.BRIGHTNESS,
|
|
199
|
+
single_byte=brightness,
|
|
200
|
+
drain_response=True,
|
|
201
|
+
)
|
|
202
|
+
self._send_command(
|
|
203
|
+
WirelessCommand.ROTATE,
|
|
204
|
+
single_byte=setting.rotation.value,
|
|
205
|
+
drain_response=True,
|
|
206
|
+
)
|
|
207
|
+
|
|
208
|
+
def send_jpg(self, payload: bytes) -> None:
|
|
209
|
+
self._ensure_awake()
|
|
210
|
+
self._send_command(
|
|
211
|
+
WirelessCommand.PUSH_JPG,
|
|
212
|
+
payload=payload,
|
|
213
|
+
expect_reply=False,
|
|
214
|
+
drain_response=True,
|
|
215
|
+
)
|
|
216
|
+
|
|
217
|
+
def send_sync_jpg(self, payload: bytes) -> None:
|
|
218
|
+
self.send_jpg(payload)
|
|
219
|
+
|
|
220
|
+
def send_boot_jpg(self, payload: bytes) -> None:
|
|
221
|
+
self.send_jpg(payload)
|
|
222
|
+
|
|
223
|
+
def send_boot_video(self, payload: bytes) -> None:
|
|
224
|
+
raise LCDDeviceError("Boot video upload is not supported for wireless LCD devices")
|
|
225
|
+
|
|
226
|
+
def send_avi(self, payload: bytes) -> None:
|
|
227
|
+
raise LCDDeviceError("AVI streaming is not supported for wireless LCD devices")
|
|
228
|
+
|
|
229
|
+
def reboot(self) -> None:
|
|
230
|
+
self._ensure_awake()
|
|
231
|
+
self._send_command(WirelessCommand.REBOOT, expect_reply=False, drain_response=True)
|
|
232
|
+
|
|
233
|
+
def _timestamp_ms(self) -> int:
|
|
234
|
+
delta = datetime.datetime.utcnow() - self._epoch
|
|
235
|
+
return int(delta.total_seconds() * 1000) & 0xFFFFFFFF
|
|
236
|
+
|
|
237
|
+
def _send_command(
|
|
238
|
+
self,
|
|
239
|
+
command: WirelessCommand,
|
|
240
|
+
*,
|
|
241
|
+
payload: Optional[bytes] = None,
|
|
242
|
+
single_byte: Optional[int] = None,
|
|
243
|
+
expect_reply: bool = False,
|
|
244
|
+
drain_response: bool = False,
|
|
245
|
+
) -> bytes:
|
|
246
|
+
packet = self._build_packet(command, payload=payload, single_byte=single_byte)
|
|
247
|
+
written = self._write_with_recovery(packet)
|
|
248
|
+
if written != len(packet):
|
|
249
|
+
raise LCDDeviceError(f"Incomplete wireless USB write ({written}/{len(packet)})")
|
|
250
|
+
if expect_reply:
|
|
251
|
+
return self._device.read(self._HEADER_SIZE)
|
|
252
|
+
if drain_response:
|
|
253
|
+
self._drain_optional_response()
|
|
254
|
+
return b""
|
|
255
|
+
|
|
256
|
+
def _write_with_recovery(self, packet: bytes) -> int:
|
|
257
|
+
try:
|
|
258
|
+
return self._device.write(packet)
|
|
259
|
+
except USBError as exc:
|
|
260
|
+
if not self._should_retry(exc):
|
|
261
|
+
raise
|
|
262
|
+
self._reset_connection()
|
|
263
|
+
return self._device.write(packet)
|
|
264
|
+
|
|
265
|
+
def _should_retry(self, exc: USBError) -> bool:
|
|
266
|
+
message = str(exc).lower()
|
|
267
|
+
if "timeout" in message or "timed out" in message:
|
|
268
|
+
return True
|
|
269
|
+
cause = exc.__cause__
|
|
270
|
+
errno = getattr(cause, "errno", None)
|
|
271
|
+
return errno == 110
|
|
272
|
+
|
|
273
|
+
def _reset_connection(self) -> None:
|
|
274
|
+
with contextlib.suppress(Exception):
|
|
275
|
+
self._device.close()
|
|
276
|
+
self._device = USBEndpointDevice(
|
|
277
|
+
self._vendor_id,
|
|
278
|
+
self._product_id,
|
|
279
|
+
write_endpoint=0x01,
|
|
280
|
+
read_endpoint=0x81,
|
|
281
|
+
interface=0,
|
|
282
|
+
configuration=None,
|
|
283
|
+
timeout_ms=self._timeout_ms,
|
|
284
|
+
serial_number=self._serial_number,
|
|
285
|
+
location_id=self._location_id,
|
|
286
|
+
)
|
|
287
|
+
self._last_handshake = 0.0
|
|
288
|
+
time.sleep(0.05)
|
|
289
|
+
|
|
290
|
+
def _build_packet(
|
|
291
|
+
self,
|
|
292
|
+
command: WirelessCommand,
|
|
293
|
+
*,
|
|
294
|
+
payload: Optional[bytes],
|
|
295
|
+
single_byte: Optional[int],
|
|
296
|
+
) -> bytes:
|
|
297
|
+
header = bytearray(504)
|
|
298
|
+
header[0] = command & 0xFF
|
|
299
|
+
header[2] = 26
|
|
300
|
+
header[3] = 109
|
|
301
|
+
header[4:8] = self._timestamp_ms().to_bytes(4, "little", signed=False)
|
|
302
|
+
if payload is not None:
|
|
303
|
+
if len(payload) > self._PAYLOAD_BUFFER - self._HEADER_SIZE:
|
|
304
|
+
raise LCDDeviceError("Payload too large for wireless LCD transfer")
|
|
305
|
+
header[8:12] = len(payload).to_bytes(4, "big", signed=False)
|
|
306
|
+
elif single_byte is not None:
|
|
307
|
+
header[8] = single_byte & 0xFF
|
|
308
|
+
encrypted_header = self._encrypt(bytes(header))
|
|
309
|
+
if payload is None:
|
|
310
|
+
packet = bytearray(self._HEADER_SIZE)
|
|
311
|
+
packet[: len(encrypted_header)] = encrypted_header
|
|
312
|
+
return bytes(packet)
|
|
313
|
+
|
|
314
|
+
packet_length = max(self._PAYLOAD_BUFFER, self._HEADER_SIZE + len(payload))
|
|
315
|
+
packet = bytearray(packet_length)
|
|
316
|
+
packet[: len(encrypted_header)] = encrypted_header
|
|
317
|
+
packet[self._HEADER_SIZE : self._HEADER_SIZE + len(payload)] = payload
|
|
318
|
+
return bytes(packet)
|
|
319
|
+
|
|
320
|
+
def _encrypt(self, data: bytes) -> bytes:
|
|
321
|
+
if DES is None or Padding is None: # pragma: no cover - dependency missing
|
|
322
|
+
raise LCDDeviceError(
|
|
323
|
+
"PyCryptodome is required for wireless LCD support. Install with 'pip install pycryptodomex'.",
|
|
324
|
+
)
|
|
325
|
+
padded = Padding.pad(data, 8, style="pkcs7")
|
|
326
|
+
cipher = DES.new(self._KEY, DES.MODE_CBC, iv=self._KEY)
|
|
327
|
+
return cipher.encrypt(padded)
|
|
328
|
+
|
|
329
|
+
def _parse_version(self, packet: bytes) -> str:
|
|
330
|
+
raw = packet[8 : 8 + 32]
|
|
331
|
+
value = raw.split(b"\x00", 1)[0].decode("utf-8", errors="ignore").strip()
|
|
332
|
+
return value
|
|
333
|
+
|
|
334
|
+
def _drain_optional_response(self, timeout_ms: int = 200) -> None:
|
|
335
|
+
try:
|
|
336
|
+
self._device.read(self._HEADER_SIZE, timeout_ms=timeout_ms)
|
|
337
|
+
except USBError:
|
|
338
|
+
# Some operations do not produce an acknowledgement; ignore timeouts.
|
|
339
|
+
return
|
|
340
|
+
|
|
341
|
+
def _read_next(self) -> bytes:
|
|
342
|
+
try:
|
|
343
|
+
return self._device.read(self._HEADER_SIZE)
|
|
344
|
+
except USBError:
|
|
345
|
+
return b""
|
|
346
|
+
|
|
347
|
+
class TLLCDDevice:
|
|
348
|
+
"""Control a TL LCD panel resolved by its USB serial number."""
|
|
349
|
+
|
|
350
|
+
def __init__(self, serial: str) -> None:
|
|
351
|
+
self._backend = "hid"
|
|
352
|
+
self._hid: Optional[hid.Device] = None
|
|
353
|
+
self._usb: Optional[USBEndpointDevice] = None
|
|
354
|
+
self._wireless: Optional[WirelessUSBTransport] = None
|
|
355
|
+
normalized = serial.strip()
|
|
356
|
+
if not normalized:
|
|
357
|
+
raise LCDDeviceError("Serial selector cannot be empty")
|
|
358
|
+
if normalized.startswith("serial:"):
|
|
359
|
+
normalized = normalized.split(":", 1)[1].strip()
|
|
360
|
+
if not normalized:
|
|
361
|
+
raise LCDDeviceError("Serial selector cannot be empty")
|
|
362
|
+
|
|
363
|
+
matches = [dev for dev in enumerate_devices() if dev.serial_number == normalized]
|
|
364
|
+
if not matches:
|
|
365
|
+
raise LCDDeviceError(f"No LCD device found with serial {normalized}")
|
|
366
|
+
if len(matches) > 1:
|
|
367
|
+
raise LCDDeviceError(
|
|
368
|
+
f"Multiple LCD devices share serial {normalized}; specify a unique serial",
|
|
369
|
+
)
|
|
370
|
+
|
|
371
|
+
resolved = matches[0]
|
|
372
|
+
if resolved.source == "hid":
|
|
373
|
+
try:
|
|
374
|
+
self._hid = hid.Device(path=resolved.path)
|
|
375
|
+
except OSError as exc:
|
|
376
|
+
raise LCDDeviceError(f"Unable to open HID device: {exc}") from exc
|
|
377
|
+
self._hid.nonblocking = False
|
|
378
|
+
return
|
|
379
|
+
|
|
380
|
+
if resolved.location_id is None:
|
|
381
|
+
raise LCDDeviceError(
|
|
382
|
+
f"Device serial {normalized} is missing a location id; replug the device and try again",
|
|
383
|
+
)
|
|
384
|
+
|
|
385
|
+
try:
|
|
386
|
+
if (resolved.vendor_id, resolved.product_id) == (0x1CBE, 0x0006):
|
|
387
|
+
self._backend = "wireless"
|
|
388
|
+
self._wireless = WirelessUSBTransport(
|
|
389
|
+
resolved.vendor_id,
|
|
390
|
+
resolved.product_id,
|
|
391
|
+
timeout_ms=5000,
|
|
392
|
+
location_id=resolved.location_id,
|
|
393
|
+
)
|
|
394
|
+
else:
|
|
395
|
+
self._backend = "usb"
|
|
396
|
+
self._usb = USBEndpointDevice(
|
|
397
|
+
resolved.vendor_id,
|
|
398
|
+
resolved.product_id,
|
|
399
|
+
write_endpoint=None,
|
|
400
|
+
read_endpoint=None,
|
|
401
|
+
interface=None,
|
|
402
|
+
timeout_ms=5000,
|
|
403
|
+
location_id=resolved.location_id,
|
|
404
|
+
)
|
|
405
|
+
except USBError as exc:
|
|
406
|
+
raise LCDDeviceError(str(exc)) from exc
|
|
407
|
+
|
|
408
|
+
def close(self) -> None:
|
|
409
|
+
if self._backend == "hid" and self._hid is not None:
|
|
410
|
+
with contextlib.suppress(Exception):
|
|
411
|
+
self._hid.close()
|
|
412
|
+
self._hid = None
|
|
413
|
+
elif self._backend == "usb" and self._usb is not None:
|
|
414
|
+
self._usb.close()
|
|
415
|
+
self._usb = None
|
|
416
|
+
elif self._backend == "wireless" and self._wireless is not None:
|
|
417
|
+
self._wireless.close()
|
|
418
|
+
self._wireless = None
|
|
419
|
+
|
|
420
|
+
def __enter__(self) -> "TLLCDDevice":
|
|
421
|
+
return self
|
|
422
|
+
|
|
423
|
+
def __exit__(self, exc_type, exc, tb) -> None:
|
|
424
|
+
self.close()
|
|
425
|
+
|
|
426
|
+
def _build_packets(self, command: int, data: bytes) -> Iterator[bytes]:
|
|
427
|
+
data_length = len(data)
|
|
428
|
+
if data_length == 0:
|
|
429
|
+
packet = bytearray(OUTPUT_PACKET_SIZE)
|
|
430
|
+
packet[0] = LCD_REPORT_ID
|
|
431
|
+
packet[1] = command
|
|
432
|
+
return iter([bytes(packet)])
|
|
433
|
+
packets: List[bytes] = []
|
|
434
|
+
packet_number = 0
|
|
435
|
+
offset = 0
|
|
436
|
+
while offset < data_length:
|
|
437
|
+
chunk = data[offset : offset + MAX_CHUNK]
|
|
438
|
+
packet = bytearray(OUTPUT_PACKET_SIZE)
|
|
439
|
+
packet[0] = LCD_REPORT_ID
|
|
440
|
+
packet[1] = command
|
|
441
|
+
packet[2:6] = data_length.to_bytes(4, "big")
|
|
442
|
+
packet[6:9] = packet_number.to_bytes(3, "big")
|
|
443
|
+
packet[9:11] = len(chunk).to_bytes(2, "big")
|
|
444
|
+
packet[11 : 11 + len(chunk)] = chunk
|
|
445
|
+
packets.append(bytes(packet))
|
|
446
|
+
offset += len(chunk)
|
|
447
|
+
packet_number += 1
|
|
448
|
+
return iter(packets)
|
|
449
|
+
|
|
450
|
+
def _write(self, command: int, data: bytes, expect_reply: bool) -> List[bytes]:
|
|
451
|
+
if self._backend == "wireless":
|
|
452
|
+
raise LCDDeviceError("Wireless LCD backend does not support HID framing")
|
|
453
|
+
responses: List[bytes] = []
|
|
454
|
+
packets = list(self._build_packets(command, data))
|
|
455
|
+
if not packets:
|
|
456
|
+
packets = [bytes(bytearray([LCD_REPORT_ID, command] + [0] * (OUTPUT_PACKET_SIZE - 2)))]
|
|
457
|
+
for packet in packets:
|
|
458
|
+
written = self._write_packet(packet)
|
|
459
|
+
if written != len(packet):
|
|
460
|
+
raise LCDDeviceError(
|
|
461
|
+
f"Incomplete HID write ({written}/{len(packet)})",
|
|
462
|
+
)
|
|
463
|
+
if expect_reply:
|
|
464
|
+
response = self._read_packet()
|
|
465
|
+
if not response:
|
|
466
|
+
raise LCDDeviceError("Timeout waiting for LCD response")
|
|
467
|
+
if response[1] != command:
|
|
468
|
+
raise LCDDeviceError(
|
|
469
|
+
f"Unexpected response command 0x{response[1]:02x} for 0x{command:02x}",
|
|
470
|
+
)
|
|
471
|
+
responses.append(bytes(response))
|
|
472
|
+
return responses
|
|
473
|
+
|
|
474
|
+
def _write_packet(self, packet: bytes) -> int:
|
|
475
|
+
if self._backend == "hid" and self._hid is not None:
|
|
476
|
+
return self._hid.write(packet)
|
|
477
|
+
if self._backend == "usb" and self._usb is not None:
|
|
478
|
+
try:
|
|
479
|
+
return self._usb.write(packet)
|
|
480
|
+
except USBError as exc:
|
|
481
|
+
raise LCDDeviceError(f"USB write failed: {exc}") from exc
|
|
482
|
+
if self._backend == "wireless":
|
|
483
|
+
raise LCDDeviceError("Wireless LCD backend does not support HID packet writes")
|
|
484
|
+
raise LCDDeviceError("LCD device is not open")
|
|
485
|
+
|
|
486
|
+
def _read_packet(self) -> bytes:
|
|
487
|
+
if self._backend == "hid" and self._hid is not None:
|
|
488
|
+
return bytes(self._hid.read(INPUT_PACKET_SIZE, timeout=1000))
|
|
489
|
+
if self._backend == "usb" and self._usb is not None:
|
|
490
|
+
try:
|
|
491
|
+
return self._usb.read(USB_INPUT_PACKET_SIZE)
|
|
492
|
+
except USBError as exc:
|
|
493
|
+
raise LCDDeviceError(f"USB read failed: {exc}") from exc
|
|
494
|
+
if self._backend == "wireless":
|
|
495
|
+
raise LCDDeviceError("Wireless LCD backend does not support HID packet reads")
|
|
496
|
+
raise LCDDeviceError("LCD device is not open")
|
|
497
|
+
|
|
498
|
+
def handshake(self) -> Dict[str, int]:
|
|
499
|
+
if self._backend == "wireless":
|
|
500
|
+
if not self._wireless:
|
|
501
|
+
raise LCDDeviceError("Wireless transport is unavailable")
|
|
502
|
+
return self._wireless.handshake()
|
|
503
|
+
response = self._write(0x3C, b"", expect_reply=True)
|
|
504
|
+
if not response:
|
|
505
|
+
raise LCDDeviceError("No handshake response")
|
|
506
|
+
payload = _extract_payload(response[0])
|
|
507
|
+
if len(payload) < 3:
|
|
508
|
+
raise LCDDeviceError("Handshake payload too short")
|
|
509
|
+
mode = payload[0]
|
|
510
|
+
frame_index = (payload[1] << 8) | payload[2]
|
|
511
|
+
return {"mode": mode, "frame_index": frame_index}
|
|
512
|
+
|
|
513
|
+
def firmware_version(self) -> Dict[str, str]:
|
|
514
|
+
if self._backend == "wireless":
|
|
515
|
+
if not self._wireless:
|
|
516
|
+
raise LCDDeviceError("Wireless transport is unavailable")
|
|
517
|
+
return self._wireless.firmware_version()
|
|
518
|
+
responses = self._write(0x3D, b"", expect_reply=True)
|
|
519
|
+
if len(responses) < 2:
|
|
520
|
+
raise LCDDeviceError("Firmware request did not return two packets")
|
|
521
|
+
version = _extract_payload(responses[0]).split(b"\x00", 1)[0].decode("ascii", errors="ignore")
|
|
522
|
+
build_date = _extract_payload(responses[1]).split(b"\x00", 1)[0].decode("ascii", errors="ignore")
|
|
523
|
+
return {"version": version, "build": build_date}
|
|
524
|
+
|
|
525
|
+
def control(self, setting: LCDControlSetting) -> None:
|
|
526
|
+
if self._backend == "wireless":
|
|
527
|
+
if not self._wireless:
|
|
528
|
+
raise LCDDeviceError("Wireless transport is unavailable")
|
|
529
|
+
self._wireless.control(setting)
|
|
530
|
+
return
|
|
531
|
+
self._write(0x40, setting.to_bytes(), expect_reply=True)
|
|
532
|
+
|
|
533
|
+
def send_jpg(self, payload: bytes) -> None:
|
|
534
|
+
if self._backend == "wireless":
|
|
535
|
+
if not self._wireless:
|
|
536
|
+
raise LCDDeviceError("Wireless transport is unavailable")
|
|
537
|
+
self._wireless.send_jpg(payload)
|
|
538
|
+
return
|
|
539
|
+
self._write(0x41, payload, expect_reply=True)
|
|
540
|
+
|
|
541
|
+
def send_avi(self, payload: bytes) -> None:
|
|
542
|
+
if self._backend == "wireless":
|
|
543
|
+
if not self._wireless:
|
|
544
|
+
raise LCDDeviceError("Wireless transport is unavailable")
|
|
545
|
+
self._wireless.send_avi(payload)
|
|
546
|
+
return
|
|
547
|
+
self._write(0x45, payload, expect_reply=True)
|
|
548
|
+
|
|
549
|
+
def send_sync_jpg(self, payload: bytes) -> None:
|
|
550
|
+
if self._backend == "wireless":
|
|
551
|
+
if not self._wireless:
|
|
552
|
+
raise LCDDeviceError("Wireless transport is unavailable")
|
|
553
|
+
self._wireless.send_sync_jpg(payload)
|
|
554
|
+
return
|
|
555
|
+
self._write(0x46, payload, expect_reply=False)
|
|
556
|
+
|
|
557
|
+
def send_boot_jpg(self, payload: bytes) -> None:
|
|
558
|
+
if self._backend == "wireless":
|
|
559
|
+
if not self._wireless:
|
|
560
|
+
raise LCDDeviceError("Wireless transport is unavailable")
|
|
561
|
+
self._wireless.send_boot_jpg(payload)
|
|
562
|
+
return
|
|
563
|
+
self._write(0x48, payload, expect_reply=True)
|
|
564
|
+
|
|
565
|
+
def send_boot_video(self, payload: bytes) -> None:
|
|
566
|
+
if self._backend == "wireless":
|
|
567
|
+
if not self._wireless:
|
|
568
|
+
raise LCDDeviceError("Wireless transport is unavailable")
|
|
569
|
+
self._wireless.send_boot_video(payload)
|
|
570
|
+
return
|
|
571
|
+
self._write(0x47, payload, expect_reply=True)
|
|
572
|
+
|
|
573
|
+
|
|
574
|
+
def rotation_from_arg(value: int) -> ScreenRotation:
|
|
575
|
+
return ScreenRotation.from_degrees(value)
|
|
576
|
+
|
|
577
|
+
|
|
578
|
+
def mode_from_arg(value: str) -> LCDControlMode:
|
|
579
|
+
value_upper = value.upper().replace("-", "_")
|
|
580
|
+
try:
|
|
581
|
+
return LCDControlMode[value_upper]
|
|
582
|
+
except KeyError as exc:
|
|
583
|
+
raise ValueError(
|
|
584
|
+
f"Invalid LCD control mode '{value}'. Valid modes: "
|
|
585
|
+
+ ", ".join(m.name.lower() for m in LCDControlMode),
|
|
586
|
+
) from exc
|
|
587
|
+
|
|
588
|
+
|
|
589
|
+
def _extract_payload(packet: bytes) -> bytes:
|
|
590
|
+
if len(packet) < 11 or packet[0] != LCD_REPORT_ID:
|
|
591
|
+
raise LCDDeviceError("Malformed LCD input packet")
|
|
592
|
+
length = (packet[9] << 8) | packet[10]
|
|
593
|
+
length = min(length, max(0, len(packet) - 11))
|
|
594
|
+
return bytes(packet[11 : 11 + length])
|
uwscli/logging_utils.py
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
"""Helpers for consistent logging configuration across the CLI."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import logging
|
|
6
|
+
|
|
7
|
+
_LOG_FORMAT = "%(asctime)s %(levelname)s %(name)s: %(message)s"
|
|
8
|
+
_DATE_FORMAT = "%H:%M:%S"
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def configure_logging(verbosity: int) -> None:
|
|
12
|
+
"""Configure the root logger based on the requested verbosity.
|
|
13
|
+
|
|
14
|
+
The CLI treats no flag as WARNING, "-v" as INFO, and "-vv" (or more)
|
|
15
|
+
as DEBUG. Repeated invocations only adjust levels to avoid duplicating
|
|
16
|
+
handlers when the CLI is imported in tests.
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
if verbosity >= 2:
|
|
20
|
+
level = logging.DEBUG
|
|
21
|
+
elif verbosity == 1:
|
|
22
|
+
level = logging.INFO
|
|
23
|
+
else:
|
|
24
|
+
level = logging.WARNING
|
|
25
|
+
|
|
26
|
+
root = logging.getLogger()
|
|
27
|
+
if root.handlers:
|
|
28
|
+
root.setLevel(level)
|
|
29
|
+
for handler in root.handlers:
|
|
30
|
+
handler.setLevel(level)
|
|
31
|
+
else:
|
|
32
|
+
logging.basicConfig(level=level, format=_LOG_FORMAT, datefmt=_DATE_FORMAT)
|
|
33
|
+
|
|
34
|
+
logging.captureWarnings(True)
|