0
# Device Communication
1
2
Core device operations for USB communication including configuration, data transfer, and endpoint operations. The Device class provides the primary interface for all USB device interactions in PyUSB's modern API.
3
4
## Capabilities
5
6
### Device Configuration
7
8
Configure USB devices by setting active configurations and managing device state.
9
10
```python { .api }
11
class Device:
12
def set_configuration(self, configuration=None):
13
"""
14
Set device configuration.
15
16
Parameters:
17
- configuration: int or Configuration object, configuration to set (default: first configuration)
18
19
Raises:
20
- USBError: Configuration failed
21
"""
22
23
def get_active_configuration(self):
24
"""
25
Get active configuration.
26
27
Returns:
28
Configuration object representing active configuration
29
30
Raises:
31
- USBError: Unable to get configuration
32
"""
33
34
def set_interface_altsetting(self, interface=None, alternate_setting=None):
35
"""
36
Set alternate setting for an interface.
37
38
Parameters:
39
- interface: int or Interface object, interface to modify
40
- alternate_setting: int, alternate setting to select
41
42
Raises:
43
- USBError: Interface setting failed
44
"""
45
46
def configurations(self):
47
"""
48
Get tuple of all device configurations.
49
50
Returns:
51
tuple: Configuration objects for device
52
"""
53
```
54
55
### Data Transfer Operations
56
57
Read and write data to USB endpoints with configurable timeouts and error handling.
58
59
```python { .api }
60
class Device:
61
def read(self, endpoint, size_or_buffer, timeout=None):
62
"""
63
Read data from endpoint.
64
65
Parameters:
66
- endpoint: int, endpoint address to read from
67
- size_or_buffer: int or array-like, size to read or buffer to fill
68
- timeout: int, timeout in milliseconds (None for no timeout)
69
70
Returns:
71
array.array of bytes read
72
73
Raises:
74
- USBTimeoutError: Read operation timed out
75
- USBError: Read operation failed
76
"""
77
78
def write(self, endpoint, data, timeout=None):
79
"""
80
Write data to endpoint.
81
82
Parameters:
83
- endpoint: int, endpoint address to write to
84
- data: bytes or array-like, data to write
85
- timeout: int, timeout in milliseconds (None for no timeout)
86
87
Returns:
88
int: number of bytes written
89
90
Raises:
91
- USBTimeoutError: Write operation timed out
92
- USBError: Write operation failed
93
"""
94
```
95
96
### Control Transfers
97
98
Perform USB control transfers for device-specific operations and standard requests.
99
100
```python { .api }
101
class Device:
102
def ctrl_transfer(self, bmRequestType, bRequest, wValue=0, wIndex=0, data_or_wLength=None, timeout=None):
103
"""
104
Perform control transfer.
105
106
Parameters:
107
- bmRequestType: int, request type and direction
108
- bRequest: int, specific request
109
- wValue: int, request-specific value
110
- wIndex: int, request-specific index
111
- data_or_wLength: bytes/int, data to send or length to read
112
- timeout: int, timeout in milliseconds
113
114
Returns:
115
array.array for IN transfers, int (bytes transferred) for OUT transfers
116
117
Raises:
118
- USBTimeoutError: Control transfer timed out
119
- USBError: Control transfer failed
120
"""
121
```
122
123
### Device Reset and Recovery
124
125
Reset devices and manage device state for error recovery.
126
127
```python { .api }
128
class Device:
129
def reset(self):
130
"""
131
Reset the device.
132
133
Raises:
134
- USBError: Reset operation failed
135
"""
136
137
def clear_halt(self, endpoint):
138
"""
139
Clear halt/stall condition for endpoint.
140
141
Parameters:
142
- endpoint: int or Endpoint object, endpoint to clear
143
144
Raises:
145
- USBError: Clear operation failed
146
"""
147
```
148
149
### Kernel Driver Management
150
151
Manage kernel driver attachment for proper device access on Linux systems.
152
153
```python { .api }
154
class Device:
155
def detach_kernel_driver(self, interface):
156
"""
157
Detach kernel driver from interface.
158
159
Parameters:
160
- interface: int, interface number
161
162
Raises:
163
- USBError: Detach operation failed
164
"""
165
166
def attach_kernel_driver(self, interface):
167
"""
168
Attach kernel driver to interface.
169
170
Parameters:
171
- interface: int, interface number
172
173
Raises:
174
- USBError: Attach operation failed
175
"""
176
177
def is_kernel_driver_active(self, interface):
178
"""
179
Check if kernel driver is active on interface.
180
181
Parameters:
182
- interface: int, interface number
183
184
Returns:
185
bool: True if kernel driver is active
186
187
Raises:
188
- USBError: Check operation failed
189
"""
190
```
191
192
### Device Properties
193
194
Access device descriptor information and attributes.
195
196
```python { .api }
197
class Device:
198
# Device descriptor fields
199
idVendor: int # Vendor ID
200
idProduct: int # Product ID
201
bcdDevice: int # Device release number
202
iManufacturer: int # Manufacturer string index
203
iProduct: int # Product string index
204
iSerialNumber: int # Serial number string index
205
bNumConfigurations: int # Number of configurations
206
207
# USB specification fields
208
bcdUSB: int # USB specification version
209
bDeviceClass: int # Device class code
210
bDeviceSubClass: int # Device sub-class code
211
bDeviceProtocol: int # Device protocol code
212
bMaxPacketSize0: int # Maximum packet size for endpoint 0
213
214
# Property accessors for string descriptors
215
@property
216
def langids(self):
217
"""Get list of supported language ID codes."""
218
219
@property
220
def serial_number(self):
221
"""Get device serial number string descriptor."""
222
223
@property
224
def product(self):
225
"""Get device product string descriptor."""
226
227
@property
228
def manufacturer(self):
229
"""Get device manufacturer string descriptor."""
230
231
@property
232
def parent(self):
233
"""Get parent device (for composite devices)."""
234
235
@property
236
def backend(self):
237
"""Get backend object being used by this device."""
238
```
239
240
## Usage Examples
241
242
### Basic Device Communication
243
244
```python
245
import usb.core
246
import usb.util
247
248
# Find and configure device
249
device = usb.core.find(idVendor=0x1234, idProduct=0x5678)
250
device.set_configuration()
251
252
# Get endpoint for communication
253
config = device.get_active_configuration()
254
interface = config.interfaces()[0]
255
endpoint = interface.endpoints()[0]
256
257
# Read data
258
try:
259
data = device.read(endpoint.bEndpointAddress, 64, timeout=1000)
260
print(f"Received: {data}")
261
except usb.core.USBTimeoutError:
262
print("Read timeout")
263
264
# Write data (if endpoint supports output)
265
if usb.util.endpoint_direction(endpoint.bEndpointAddress) == usb.util.ENDPOINT_OUT:
266
written = device.write(endpoint.bEndpointAddress, b'Hello Device!', timeout=1000)
267
print(f"Sent {written} bytes")
268
```
269
270
### Control Transfer Example
271
272
```python
273
import usb.core
274
import usb.util
275
276
device = usb.core.find(idVendor=0x1234, idProduct=0x5678)
277
278
# Device-specific control request
279
result = device.ctrl_transfer(
280
bmRequestType=usb.util.build_request_type(
281
usb.util.CTRL_IN,
282
usb.util.CTRL_TYPE_VENDOR,
283
usb.util.CTRL_RECIPIENT_DEVICE
284
),
285
bRequest=0x01, # Custom request
286
wValue=0x0000,
287
wIndex=0x0000,
288
data_or_wLength=64
289
)
290
print(f"Control transfer result: {result}")
291
```
292
293
### Kernel Driver Management
294
295
```python
296
import usb.core
297
298
device = usb.core.find(idVendor=0x1234, idProduct=0x5678)
299
interface_num = 0
300
301
# Check and detach kernel driver if active
302
if device.is_kernel_driver_active(interface_num):
303
print("Detaching kernel driver")
304
device.detach_kernel_driver(interface_num)
305
306
try:
307
# Perform device operations
308
device.set_configuration()
309
# ... device communication ...
310
311
finally:
312
# Reattach kernel driver
313
device.attach_kernel_driver(interface_num)
314
```