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/structs.py
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
"""Data structures shared across CLI commands."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
from enum import Enum
|
|
7
|
+
from typing import Iterable, Tuple
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class LCDControlMode(Enum):
|
|
11
|
+
RESERVER = 0
|
|
12
|
+
SHOW_JPG = 1
|
|
13
|
+
SHOW_AVI = 3
|
|
14
|
+
SHOW_APP_SYNC = 4
|
|
15
|
+
LCD_SETTING = 5
|
|
16
|
+
LCD_TEST = 6
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class ScreenRotation(Enum):
|
|
20
|
+
ROTATE_0 = 0
|
|
21
|
+
ROTATE_90 = 1
|
|
22
|
+
ROTATE_180 = 2
|
|
23
|
+
ROTATE_270 = 3
|
|
24
|
+
|
|
25
|
+
@staticmethod
|
|
26
|
+
def from_degrees(degrees: int) -> "ScreenRotation":
|
|
27
|
+
mapping = {
|
|
28
|
+
0: ScreenRotation.ROTATE_0,
|
|
29
|
+
90: ScreenRotation.ROTATE_90,
|
|
30
|
+
180: ScreenRotation.ROTATE_180,
|
|
31
|
+
270: ScreenRotation.ROTATE_270,
|
|
32
|
+
}
|
|
33
|
+
if degrees not in mapping:
|
|
34
|
+
raise ValueError("Rotation must be one of 0, 90, 180, 270 degrees")
|
|
35
|
+
return mapping[degrees]
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
@dataclass(frozen=True)
|
|
39
|
+
class LCDControlSetting:
|
|
40
|
+
mode: LCDControlMode = LCDControlMode.RESERVER
|
|
41
|
+
jpg_index: int = 0
|
|
42
|
+
brightness: int = 50
|
|
43
|
+
video_fps: int = 30
|
|
44
|
+
rotation: ScreenRotation = ScreenRotation.ROTATE_0
|
|
45
|
+
enable_test: bool = False
|
|
46
|
+
test_color: Tuple[int, int, int] = (0, 0, 0)
|
|
47
|
+
|
|
48
|
+
def to_bytes(self) -> bytes:
|
|
49
|
+
if not 0 <= self.jpg_index <= 0xFFFF:
|
|
50
|
+
raise ValueError("jpg_index must be within 0-65535")
|
|
51
|
+
if not 0 <= self.brightness <= 100:
|
|
52
|
+
raise ValueError("brightness must be within 0-100")
|
|
53
|
+
if not 0 <= self.video_fps <= 255:
|
|
54
|
+
raise ValueError("video_fps must fit in a byte")
|
|
55
|
+
for component in self.test_color:
|
|
56
|
+
if not 0 <= component <= 255:
|
|
57
|
+
raise ValueError("test_color components must be within 0-255")
|
|
58
|
+
payload = bytearray(11)
|
|
59
|
+
payload[0] = self.mode.value
|
|
60
|
+
payload[1] = (self.jpg_index >> 8) & 0xFF
|
|
61
|
+
payload[2] = self.jpg_index & 0xFF
|
|
62
|
+
payload[3] = 0
|
|
63
|
+
payload[4] = self.brightness & 0xFF
|
|
64
|
+
payload[5] = self.video_fps & 0xFF
|
|
65
|
+
payload[6] = self.rotation.value
|
|
66
|
+
payload[7] = 1 if self.enable_test else 0
|
|
67
|
+
payload[8] = self.test_color[0]
|
|
68
|
+
payload[9] = self.test_color[1]
|
|
69
|
+
payload[10] = self.test_color[2]
|
|
70
|
+
return bytes(payload)
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
@dataclass(frozen=True)
|
|
74
|
+
class WirelessDeviceInfo:
|
|
75
|
+
mac: str
|
|
76
|
+
master_mac: str
|
|
77
|
+
channel: int
|
|
78
|
+
rx_type: int
|
|
79
|
+
device_type: int
|
|
80
|
+
fan_count: int
|
|
81
|
+
pwm_values: Tuple[int, int, int, int]
|
|
82
|
+
fan_rpm: Tuple[int, int, int, int]
|
|
83
|
+
command_sequence: int
|
|
84
|
+
raw: bytes
|
|
85
|
+
|
|
86
|
+
@property
|
|
87
|
+
def is_bound(self) -> bool:
|
|
88
|
+
return any(part != "00" for part in self.master_mac.split(":"))
|
|
89
|
+
|
|
90
|
+
def pretty_rpm(self) -> str:
|
|
91
|
+
values = [rpm for rpm in self.fan_rpm if rpm > 0]
|
|
92
|
+
return ",".join(str(rpm) for rpm in values) if values else "-"
|
|
93
|
+
|
|
94
|
+
def pretty_pwm(self) -> str:
|
|
95
|
+
return ",".join(str(v) for v in self.pwm_values)
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def clamp_pwm_values(values: Iterable[int]) -> Tuple[int, int, int, int]:
|
|
99
|
+
result = []
|
|
100
|
+
for value in values:
|
|
101
|
+
if value < 0:
|
|
102
|
+
value = 0
|
|
103
|
+
elif value > 255:
|
|
104
|
+
value = 255
|
|
105
|
+
result.append(int(value))
|
|
106
|
+
while len(result) < 4:
|
|
107
|
+
result.append(result[-1] if result else 0)
|
|
108
|
+
return tuple(result[:4])
|
uwscli/system_usb.py
ADDED
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
"""Lightweight USB enumeration helpers for common POSIX targets."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
import re
|
|
7
|
+
import subprocess
|
|
8
|
+
import sys
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
from dataclasses import dataclass
|
|
11
|
+
from typing import Dict, List, Optional
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
@dataclass
|
|
15
|
+
class USBRecord:
|
|
16
|
+
vendor_id: int
|
|
17
|
+
product_id: int
|
|
18
|
+
product: Optional[str] = None
|
|
19
|
+
vendor: Optional[str] = None
|
|
20
|
+
serial: Optional[str] = None
|
|
21
|
+
location_id: Optional[int] = None
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
_VENDOR_RE = re.compile(r'"idVendor"\s*=\s*(\d+)')
|
|
25
|
+
_PRODUCT_RE = re.compile(r'"idProduct"\s*=\s*(\d+)')
|
|
26
|
+
_LOCATION_RE = re.compile(r'"locationID"\s*=\s*(\d+)')
|
|
27
|
+
_STRING_RE = re.compile(r'"(kUSBProductString|USB Product Name|kUSBVendorString|USB Vendor Name|USB Serial Number|kUSBSerialNumberString)"\s*=\s*"([^"]*)"')
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _read_text(path: Path) -> Optional[str]:
|
|
31
|
+
try:
|
|
32
|
+
return path.read_text().strip()
|
|
33
|
+
except (OSError, UnicodeDecodeError):
|
|
34
|
+
return None
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _parse_int(value: Optional[str], base: int = 10) -> Optional[int]:
|
|
38
|
+
if value is None:
|
|
39
|
+
return None
|
|
40
|
+
value = value.strip()
|
|
41
|
+
if not value:
|
|
42
|
+
return None
|
|
43
|
+
try:
|
|
44
|
+
return int(value, base)
|
|
45
|
+
except ValueError:
|
|
46
|
+
return None
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def _parse_ioreg(text: str) -> List[USBRecord]:
|
|
50
|
+
devices: List[USBRecord] = []
|
|
51
|
+
current: Dict[str, Optional[str] | int] | None = None
|
|
52
|
+
|
|
53
|
+
def flush() -> None:
|
|
54
|
+
nonlocal current
|
|
55
|
+
if not current:
|
|
56
|
+
return
|
|
57
|
+
vid = current.get("vendor_id")
|
|
58
|
+
pid = current.get("product_id")
|
|
59
|
+
if isinstance(vid, int) and isinstance(pid, int):
|
|
60
|
+
devices.append(
|
|
61
|
+
USBRecord(
|
|
62
|
+
vendor_id=vid,
|
|
63
|
+
product_id=pid,
|
|
64
|
+
product=current.get("product"),
|
|
65
|
+
vendor=current.get("vendor"),
|
|
66
|
+
serial=current.get("serial"),
|
|
67
|
+
location_id=current.get("location_id") if isinstance(current.get("location_id"), int) else None,
|
|
68
|
+
),
|
|
69
|
+
)
|
|
70
|
+
current = None
|
|
71
|
+
|
|
72
|
+
for raw_line in text.splitlines():
|
|
73
|
+
if "+-o " in raw_line:
|
|
74
|
+
flush()
|
|
75
|
+
current = {}
|
|
76
|
+
continue
|
|
77
|
+
if current is None:
|
|
78
|
+
continue
|
|
79
|
+
line = raw_line.strip()
|
|
80
|
+
match = _VENDOR_RE.search(line)
|
|
81
|
+
if match:
|
|
82
|
+
current["vendor_id"] = int(match.group(1))
|
|
83
|
+
continue
|
|
84
|
+
match = _PRODUCT_RE.search(line)
|
|
85
|
+
if match:
|
|
86
|
+
current["product_id"] = int(match.group(1))
|
|
87
|
+
continue
|
|
88
|
+
match = _LOCATION_RE.search(line)
|
|
89
|
+
if match:
|
|
90
|
+
current["location_id"] = int(match.group(1))
|
|
91
|
+
continue
|
|
92
|
+
match = _STRING_RE.search(line)
|
|
93
|
+
if match:
|
|
94
|
+
key, value = match.groups()
|
|
95
|
+
if "Product" in key:
|
|
96
|
+
current["product"] = value
|
|
97
|
+
elif "Vendor" in key:
|
|
98
|
+
current["vendor"] = value
|
|
99
|
+
elif "Serial" in key:
|
|
100
|
+
current["serial"] = value
|
|
101
|
+
flush()
|
|
102
|
+
return devices
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def _scan_linux_sysfs() -> List[USBRecord]:
|
|
106
|
+
root = Path("/sys/bus/usb/devices")
|
|
107
|
+
if not root.exists():
|
|
108
|
+
return []
|
|
109
|
+
devices: List[USBRecord] = []
|
|
110
|
+
for entry in root.iterdir():
|
|
111
|
+
if ":" in entry.name or not entry.is_dir():
|
|
112
|
+
continue
|
|
113
|
+
vid_str = _read_text(entry / "idVendor")
|
|
114
|
+
pid_str = _read_text(entry / "idProduct")
|
|
115
|
+
vendor_id = _parse_int(vid_str, base=16)
|
|
116
|
+
product_id = _parse_int(pid_str, base=16)
|
|
117
|
+
if vendor_id is None or product_id is None:
|
|
118
|
+
continue
|
|
119
|
+
product = _read_text(entry / "product")
|
|
120
|
+
vendor = _read_text(entry / "manufacturer")
|
|
121
|
+
serial = _read_text(entry / "serial")
|
|
122
|
+
busnum = _parse_int(_read_text(entry / "busnum"))
|
|
123
|
+
devnum = _parse_int(_read_text(entry / "devnum"))
|
|
124
|
+
location_id = None
|
|
125
|
+
if busnum is not None and devnum is not None:
|
|
126
|
+
location_id = (busnum << 8) | devnum
|
|
127
|
+
devices.append(
|
|
128
|
+
USBRecord(
|
|
129
|
+
vendor_id=vendor_id,
|
|
130
|
+
product_id=product_id,
|
|
131
|
+
product=product,
|
|
132
|
+
vendor=vendor,
|
|
133
|
+
serial=serial,
|
|
134
|
+
location_id=location_id,
|
|
135
|
+
),
|
|
136
|
+
)
|
|
137
|
+
return devices
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def scan_usb_devices() -> List[USBRecord]:
|
|
141
|
+
if os.name != "posix":
|
|
142
|
+
return []
|
|
143
|
+
if sys.platform.startswith("linux"):
|
|
144
|
+
return _scan_linux_sysfs()
|
|
145
|
+
try:
|
|
146
|
+
result = subprocess.run(
|
|
147
|
+
["ioreg", "-p", "IOUSB", "-l", "-w0"],
|
|
148
|
+
check=False,
|
|
149
|
+
capture_output=True,
|
|
150
|
+
text=True,
|
|
151
|
+
)
|
|
152
|
+
except FileNotFoundError:
|
|
153
|
+
return []
|
|
154
|
+
if result.returncode != 0:
|
|
155
|
+
return []
|
|
156
|
+
return _parse_ioreg(result.stdout)
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def find_devices_by_vid_pid(vendor_id: int, product_id: int) -> List[USBRecord]:
|
|
160
|
+
return [rec for rec in scan_usb_devices() if rec.vendor_id == vendor_id and rec.product_id == product_id]
|
uwscli/usbutil.py
ADDED
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
"""USB helper utilities built on top of PyUSB."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import contextlib
|
|
6
|
+
import time
|
|
7
|
+
from dataclasses import dataclass
|
|
8
|
+
from typing import Any, Optional
|
|
9
|
+
|
|
10
|
+
import usb.core
|
|
11
|
+
import usb.util
|
|
12
|
+
from usb.core import NoBackendError
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class USBError(RuntimeError):
|
|
16
|
+
"""Raised when the USB layer encounters a fatal condition."""
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def _is_resource_busy_error(exc: usb.core.USBError) -> bool:
|
|
20
|
+
"""Return True when libusb reports that an interface is still claimed."""
|
|
21
|
+
|
|
22
|
+
errno = getattr(exc, "errno", None)
|
|
23
|
+
if errno == 16:
|
|
24
|
+
return True
|
|
25
|
+
message = str(exc).lower()
|
|
26
|
+
return "resource busy" in message or "busy" in message
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
@dataclass
|
|
30
|
+
class USBEndpoints:
|
|
31
|
+
"""Holds the OUT and IN endpoints for a claimed USB interface."""
|
|
32
|
+
|
|
33
|
+
out: Any
|
|
34
|
+
inn: Any
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class USBEndpointDevice:
|
|
38
|
+
"""Convenience wrapper to claim a single-interface HID/WinUSB device."""
|
|
39
|
+
|
|
40
|
+
def __init__(
|
|
41
|
+
self,
|
|
42
|
+
vendor_id: int,
|
|
43
|
+
product_id: int,
|
|
44
|
+
*,
|
|
45
|
+
write_endpoint: Optional[int] = 0x01,
|
|
46
|
+
read_endpoint: Optional[int] = 0x81,
|
|
47
|
+
interface: Optional[int] = 0,
|
|
48
|
+
configuration: Optional[int] = None,
|
|
49
|
+
timeout_ms: int = 1000,
|
|
50
|
+
serial_number: Optional[str] = None,
|
|
51
|
+
location_id: Optional[int] = None,
|
|
52
|
+
) -> None:
|
|
53
|
+
self.vendor_id = vendor_id
|
|
54
|
+
self.product_id = product_id
|
|
55
|
+
self.timeout_ms = timeout_ms
|
|
56
|
+
self._serial_number = serial_number
|
|
57
|
+
self._location_id = location_id
|
|
58
|
+
self._device = self._open_device(configuration)
|
|
59
|
+
self._interface, self._endpoints = self._claim_interface(interface, write_endpoint, read_endpoint)
|
|
60
|
+
|
|
61
|
+
@property
|
|
62
|
+
def device(self) -> usb.core.Device:
|
|
63
|
+
return self._device
|
|
64
|
+
|
|
65
|
+
def _open_device(self, configuration: Optional[int]) -> usb.core.Device:
|
|
66
|
+
try:
|
|
67
|
+
if self._serial_number is not None or self._location_id is not None:
|
|
68
|
+
dev = usb.core.find(
|
|
69
|
+
idVendor=self.vendor_id,
|
|
70
|
+
idProduct=self.product_id,
|
|
71
|
+
custom_match=self._match_device,
|
|
72
|
+
)
|
|
73
|
+
else:
|
|
74
|
+
dev = usb.core.find(idVendor=self.vendor_id, idProduct=self.product_id)
|
|
75
|
+
except NoBackendError as exc:
|
|
76
|
+
raise USBError(
|
|
77
|
+
"PyUSB could not locate a usable libusb backend. Install libusb-1.0 and ensure it is discoverable.",
|
|
78
|
+
) from exc
|
|
79
|
+
if dev is None:
|
|
80
|
+
location_hint = ""
|
|
81
|
+
if self._location_id is not None:
|
|
82
|
+
location_hint = f" at location 0x{self._location_id:04x}"
|
|
83
|
+
raise USBError(
|
|
84
|
+
f"USB device {self.vendor_id:04x}:{self.product_id:04x} not found{location_hint}",
|
|
85
|
+
)
|
|
86
|
+
if configuration is not None:
|
|
87
|
+
dev.set_configuration(configuration)
|
|
88
|
+
else:
|
|
89
|
+
try:
|
|
90
|
+
dev.get_active_configuration()
|
|
91
|
+
except usb.core.USBError:
|
|
92
|
+
dev.set_configuration()
|
|
93
|
+
return dev
|
|
94
|
+
|
|
95
|
+
def _match_device(self, dev: usb.core.Device) -> bool:
|
|
96
|
+
if dev.idVendor != self.vendor_id or dev.idProduct != self.product_id:
|
|
97
|
+
return False
|
|
98
|
+
if self._location_id is not None:
|
|
99
|
+
bus = getattr(dev, "bus", None)
|
|
100
|
+
address = getattr(dev, "address", None)
|
|
101
|
+
if bus is None or address is None:
|
|
102
|
+
return False
|
|
103
|
+
if ((bus << 8) | address) != self._location_id:
|
|
104
|
+
return False
|
|
105
|
+
if self._serial_number is not None:
|
|
106
|
+
try:
|
|
107
|
+
serial = usb.util.get_string(dev, dev.iSerialNumber) if dev.iSerialNumber else None
|
|
108
|
+
except usb.core.USBError:
|
|
109
|
+
serial = None
|
|
110
|
+
if serial != self._serial_number:
|
|
111
|
+
return False
|
|
112
|
+
return True
|
|
113
|
+
|
|
114
|
+
def _claim_interface(
|
|
115
|
+
self,
|
|
116
|
+
interface: Optional[int],
|
|
117
|
+
write_ep: Optional[int],
|
|
118
|
+
read_ep: Optional[int],
|
|
119
|
+
) -> tuple[int, USBEndpoints]:
|
|
120
|
+
cfg = self._device.get_active_configuration()
|
|
121
|
+
candidates = []
|
|
122
|
+
if interface is not None:
|
|
123
|
+
candidates.append(interface)
|
|
124
|
+
else:
|
|
125
|
+
for intf in cfg:
|
|
126
|
+
if intf.bInterfaceClass in (0xFF, 0x03, 0):
|
|
127
|
+
candidates.append(intf.bInterfaceNumber)
|
|
128
|
+
for intf_num in candidates:
|
|
129
|
+
intf = cfg[(intf_num, 0)]
|
|
130
|
+
# Detach kernel driver if possible (Linux)
|
|
131
|
+
with contextlib.suppress(NotImplementedError, usb.core.USBError):
|
|
132
|
+
if self._device.is_kernel_driver_active(intf_num):
|
|
133
|
+
self._device.detach_kernel_driver(intf_num)
|
|
134
|
+
claimed = False
|
|
135
|
+
last_error: Optional[usb.core.USBError] = None
|
|
136
|
+
for attempt in range(5):
|
|
137
|
+
try:
|
|
138
|
+
usb.util.claim_interface(self._device, intf_num)
|
|
139
|
+
except usb.core.USBError as exc: # pragma: no branch - error handling path
|
|
140
|
+
last_error = exc
|
|
141
|
+
if not _is_resource_busy_error(exc) or attempt == 4:
|
|
142
|
+
if _is_resource_busy_error(exc):
|
|
143
|
+
raise USBError(
|
|
144
|
+
"USB interface is busy; ensure no other process is accessing the device.",
|
|
145
|
+
) from exc
|
|
146
|
+
raise
|
|
147
|
+
time.sleep(0.05 * (attempt + 1))
|
|
148
|
+
else:
|
|
149
|
+
claimed = True
|
|
150
|
+
break
|
|
151
|
+
if not claimed:
|
|
152
|
+
if last_error is not None:
|
|
153
|
+
raise last_error
|
|
154
|
+
continue
|
|
155
|
+
ep_out = None
|
|
156
|
+
ep_in = None
|
|
157
|
+
for ep in intf:
|
|
158
|
+
addr = ep.bEndpointAddress
|
|
159
|
+
if usb.util.endpoint_direction(addr) == usb.util.ENDPOINT_OUT:
|
|
160
|
+
if write_ep is None or addr == write_ep:
|
|
161
|
+
ep_out = ep
|
|
162
|
+
elif usb.util.endpoint_direction(addr) == usb.util.ENDPOINT_IN:
|
|
163
|
+
if read_ep is None or addr == read_ep:
|
|
164
|
+
ep_in = ep
|
|
165
|
+
if ep_out is None and write_ep is None:
|
|
166
|
+
ep_out = usb.util.find_descriptor(
|
|
167
|
+
intf,
|
|
168
|
+
custom_match=lambda e: usb.util.endpoint_direction(e.bEndpointAddress)
|
|
169
|
+
== usb.util.ENDPOINT_OUT,
|
|
170
|
+
)
|
|
171
|
+
if ep_in is None and read_ep is None:
|
|
172
|
+
ep_in = usb.util.find_descriptor(
|
|
173
|
+
intf,
|
|
174
|
+
custom_match=lambda e: usb.util.endpoint_direction(e.bEndpointAddress)
|
|
175
|
+
== usb.util.ENDPOINT_IN,
|
|
176
|
+
)
|
|
177
|
+
if ep_out is not None and ep_in is not None:
|
|
178
|
+
return intf_num, USBEndpoints(out=ep_out, inn=ep_in)
|
|
179
|
+
usb.util.release_interface(self._device, intf_num)
|
|
180
|
+
raise USBError("Could not locate suitable interface/endpoints for device")
|
|
181
|
+
|
|
182
|
+
def write(self, payload: bytes) -> int:
|
|
183
|
+
try:
|
|
184
|
+
return self._endpoints.out.write(payload, self.timeout_ms)
|
|
185
|
+
except usb.core.USBError as exc:
|
|
186
|
+
raise USBError(f"USB write failed: {exc}") from exc
|
|
187
|
+
|
|
188
|
+
def read(self, size: int, timeout_ms: Optional[int] = None) -> bytes:
|
|
189
|
+
try:
|
|
190
|
+
timeout = self.timeout_ms if timeout_ms is None else timeout_ms
|
|
191
|
+
data = self._endpoints.inn.read(size, timeout)
|
|
192
|
+
except usb.core.USBError as exc:
|
|
193
|
+
raise USBError(f"USB read failed: {exc}") from exc
|
|
194
|
+
return bytes(data)
|
|
195
|
+
|
|
196
|
+
def close(self) -> None:
|
|
197
|
+
with contextlib.suppress(Exception):
|
|
198
|
+
usb.util.release_interface(self._device, self._interface)
|
|
199
|
+
with contextlib.suppress(NotImplementedError, usb.core.USBError):
|
|
200
|
+
self._device.attach_kernel_driver(self._interface)
|
|
201
|
+
usb.util.dispose_resources(self._device)
|
|
202
|
+
|
|
203
|
+
def __enter__(self) -> "USBEndpointDevice":
|
|
204
|
+
return self
|
|
205
|
+
|
|
206
|
+
def __exit__(self, exc_type, exc, tb) -> None:
|
|
207
|
+
self.close()
|