Debian Codegraph @

src/nitrokey/trussed/_bootloader/lpc55_upload/utils/interfaces/device/usb_device.py

raw
1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
3 #
4 # Copyright 2023 NXP
5 #
6 # SPDX-License-Identifier: BSD-3-Clause
7
8 """Low level Hid device."""
9
10 import logging
11 import warnings
12 from typing import TYPE_CHECKING, List, Optional
13
14 from ....exceptions import SPSDKConnectionError, SPSDKError
15 from ....utils.exceptions import SPSDKTimeoutError
16 from ....utils.interfaces.device.base import DeviceBase
17
18 if TYPE_CHECKING:
19 import hid
20
21 logger = logging.getLogger(__name__)
22
23
24 class UsbDevice(DeviceBase):
25 """USB device class."""
26
27 def __init__(
28 self,
29 vid: int,
30 pid: int,
31 path: bytes,
32 vendor_name: str,
33 product_name: str,
34 interface_number: int,
35 ) -> None:
36 """Initialize the USB interface object."""
37 self._opened = False
38 self.vid = vid
39 self.pid = pid
40 self.path = path
41 self.vendor_name = vendor_name
42 self.product_name = product_name
43 self.interface_number = interface_number
44 self._timeout = 2000
45 self._device: Optional["hid.device"] = None
46
47 @property
48 def timeout(self) -> int:
49 """Timeout property."""
50 return self._timeout
51
52 @timeout.setter
53 def timeout(self, value: int) -> None:
54 """Timeout property setter."""
55 self._timeout = value
56
57 @property
58 def is_opened(self) -> bool:
59 """Indicates whether device is open.
60
61 :return: True if device is open, False othervise.
62 """
63 return self._device is not None
64
65 def open(self) -> None:
66 """Open the interface.
67
68 :raises SPSDKError: if device is already opened
69 :raises SPSDKConnectionError: if the device can not be opened
70 """
71 import hid
72
73 logger.debug(f"Opening the Interface: {str(self)}")
74 if self.is_opened:
75 # This would get HID_DEVICE into broken state
76 raise SPSDKError("Can't open already opened device")
77 try:
78 self._device = hid.device()
79 self._device.open_path(self.path)
80 except Exception as error:
81 self._device = None
82 raise SPSDKConnectionError(f"Unable to open device '{str(self)}'") from error
83
84 def close(self) -> None:
85 """Close the interface.
86
87 :raises SPSDKConnectionError: if no device is available
88 :raises SPSDKConnectionError: if the device can not be opened
89 """
90 logger.debug(f"Closing the Interface: {str(self)}")
91 if self._device is not None:
92 try:
93 self._device.close()
94 self._device = None
95 except Exception as error:
96 raise SPSDKConnectionError(f"Unable to close device '{str(self)}'") from error
97
98 def read(self, length: int, timeout: Optional[int] = None) -> bytes:
99 """Read data on the IN endpoint associated to the HID interface.
100
101 :return: Return CmdResponse object.
102 :raises SPSDKConnectionError: Raises an error if device is not opened for reading
103 :raises SPSDKConnectionError: Raises if device is not available
104 :raises SPSDKConnectionError: Raises if reading fails
105 :raises SPSDKTimeoutError: Time-out
106 """
107 timeout = timeout or self.timeout
108 if self._device is None:
109 raise SPSDKConnectionError("Device is not opened for reading")
110 try:
111 data = self._device.read(length, timeout_ms=timeout)
112 except Exception as e:
113 raise SPSDKConnectionError(str(e)) from e
114 if not data:
115 logger.error("Cannot read from HID device")
116 raise SPSDKTimeoutError()
117 return bytes(data)
118
119 def write(self, data: bytes, timeout: Optional[int] = None) -> None:
120 """Send data to device.
121
122 :param data: Data to send
123 :param timeout: Timeout to be used
124 :raises SPSDKConnectionError: Sending data to device failure
125 """
126 timeout = timeout or self.timeout
127 if self._device is None:
128 raise SPSDKConnectionError("Device is not opened for writing")
129 try:
130 bytes_written = self._device.write(data)
131 except Exception as e:
132 raise SPSDKConnectionError(str(e)) from e
133 if bytes_written < 0 or bytes_written < len(data):
134 raise SPSDKConnectionError(
135 f"Invalid size of written bytes has been detected: {bytes_written} != {len(data)}"
136 )
137
138 def __str__(self) -> str:
139 """Return information about the USB interface."""
140 return f"{self.product_name:s} (0x{self.vid:04X}, 0x{self.pid:04X})path={self.path!r}"
141
142 def __hash__(self) -> int:
143 return hash(self.path)
144
145 @classmethod
146 def enumerate(
147 cls, vid: Optional[int] = None, pid: Optional[int] = None, path: Optional[str] = None
148 ) -> List["UsbDevice"]:
149 """Get list of all connected devices which matches device_id."""
150 try:
151 import hid
152 except ImportError as err:
153 logger.warning("Failed to import hid module", exc_info=True)
154 warnings.warn( # noqa: B028
155 f"Failed to list LPC55 bootloaders due to a missing library: {err}",
156 category=RuntimeWarning,
157 )
158 return []
159
160 devices = []
161
162 # iterate on all devices found
163 for dev in hid.enumerate(vendor_id=vid or 0, product_id=pid or 0):
164 if path is None or dev["path"] == path.encode():
165 new_device = cls(
166 vid=dev["vendor_id"],
167 pid=dev["product_id"],
168 path=dev["path"],
169 vendor_name=dev["manufacturer_string"],
170 product_name=dev["product_string"],
171 interface_number=dev["interface_number"],
172 )
173 devices.append(new_device)
174 return devices