Pure-python wrapper for libusb-1.0 providing comprehensive USB device access with support for all transfer types
npx @tessl/cli install tessl/pypi-libusb1@3.3.00
# libusb1
1
2
A pure-Python wrapper for libusb-1.0 providing comprehensive USB device access functionality. libusb1 enables developers to build cross-platform USB communication applications entirely in Python, supporting all USB transfer types (control, bulk, interrupt, isochronous) in both synchronous and asynchronous modes with robust error handling and event-driven programming patterns.
3
4
## Package Information
5
6
- **Package Name**: libusb1
7
- **Language**: Python
8
- **Installation**: `pip install libusb1`
9
- **Dependencies**: libusb-1.0 system library
10
- **Supported Platforms**: GNU/Linux, Windows, macOS, FreeBSD, OpenBSD
11
12
## Core Imports
13
14
```python
15
import usb1
16
```
17
18
## Basic Usage
19
20
```python
21
import usb1
22
23
# Create USB context and enumerate devices
24
with usb1.USBContext() as context:
25
# List all USB devices
26
for device in context.getDeviceIterator(skip_on_error=True):
27
print(f'ID {device.getVendorID():04x}:{device.getProductID():04x}')
28
print(f'Bus {device.getBusNumber():03d} Device {device.getDeviceAddress():03d}')
29
30
# Find specific device by vendor/product ID
31
device = context.getByVendorIDAndProductID(0x1234, 0x5678)
32
if device:
33
# Open device for communication
34
with device.open() as handle:
35
# Claim interface for exclusive access
36
with handle.claimInterface(0):
37
# Perform synchronous control transfer
38
data = handle.controlRead(
39
request_type=usb1.TYPE_VENDOR | usb1.RECIPIENT_DEVICE | usb1.ENDPOINT_IN,
40
request=0x01,
41
value=0,
42
index=0,
43
length=64,
44
timeout=1000
45
)
46
print(f'Received: {data.hex()}')
47
```
48
49
## Architecture
50
51
libusb1 follows a hierarchical object model that mirrors the USB specification:
52
53
- **USBContext**: Top-level USB context managing system resources and device enumeration
54
- **USBDevice**: Represents a USB device with access to descriptors (no communication)
55
- **USBDeviceHandle**: Handle for opened device enabling data transfer and configuration
56
- **USBTransfer**: Asynchronous transfer objects for non-blocking I/O operations
57
- **Descriptor Objects**: Configuration, interface, and endpoint descriptor wrappers
58
59
The library provides both synchronous methods (blocking) for simple use cases and asynchronous transfers (non-blocking) for high-performance applications requiring concurrent USB operations.
60
61
## Capabilities
62
63
### USB Context Management
64
65
Core USB context functionality for initializing the library, enumerating devices, and managing system resources with comprehensive device discovery and filtering capabilities.
66
67
```python { .api }
68
class USBContext:
69
def __init__(self, log_level=None, use_usbdk=False, with_device_discovery=True, log_callback=None): ...
70
def __enter__(self): ...
71
def __exit__(self, exc_type, exc_val, exc_tb): ...
72
def getDeviceIterator(self, skip_on_error=False): ...
73
def getDeviceList(self, skip_on_access_error=False, skip_on_error=False): ...
74
def getByVendorIDAndProductID(self, vendor_id, product_id, skip_on_access_error=False, skip_on_error=False): ...
75
def openByVendorIDAndProductID(self, vendor_id, product_id, skip_on_access_error=False, skip_on_error=False): ...
76
```
77
78
[USB Context Management](./usb-context.md)
79
80
### Device Access and Configuration
81
82
USB device representation and handle management for accessing device properties, opening communication channels, claiming interfaces, and configuring device settings.
83
84
```python { .api }
85
class USBDevice:
86
def open(self): ...
87
def getBusNumber(self): ...
88
def getDeviceAddress(self): ...
89
def getVendorID(self): ...
90
def getProductID(self): ...
91
def getDeviceSpeed(self): ...
92
93
class USBDeviceHandle:
94
def close(self): ...
95
def claimInterface(self, interface): ...
96
def releaseInterface(self, interface): ...
97
def setConfiguration(self, configuration): ...
98
def getConfiguration(self): ...
99
```
100
101
[Device Access and Configuration](./device-access.md)
102
103
### Synchronous USB Transfers
104
105
Blocking USB transfer operations for control, bulk, and interrupt endpoints with timeout support and error handling, suitable for simple request-response communication patterns.
106
107
```python { .api }
108
class USBDeviceHandle:
109
def controlRead(self, request_type, request, value, index, length, timeout=0): ...
110
def controlWrite(self, request_type, request, value, index, data, timeout=0): ...
111
def bulkRead(self, endpoint, length, timeout=0): ...
112
def bulkWrite(self, endpoint, data, timeout=0): ...
113
def interruptRead(self, endpoint, length, timeout=0): ...
114
def interruptWrite(self, endpoint, data, timeout=0): ...
115
```
116
117
[Synchronous USB Transfers](./sync-transfers.md)
118
119
### Asynchronous USB Transfers
120
121
Non-blocking USB transfer operations using event-driven callbacks for high-performance applications requiring concurrent transfers and integration with event loops.
122
123
```python { .api }
124
class USBTransfer:
125
def setControl(self, request_type, request, value, index, buffer_or_len, callback=None, user_data=None, timeout=0): ...
126
def setBulk(self, endpoint, buffer_or_len, callback=None, user_data=None, timeout=0): ...
127
def setIsochronous(self, endpoint, buffer_or_len, callback=None, user_data=None, timeout=0, iso_transfer_length_list=None): ...
128
def submit(self): ...
129
def cancel(self): ...
130
131
class USBTransferHelper:
132
def setEventCallback(self, event, callback): ...
133
def setDefaultCallback(self, callback): ...
134
```
135
136
[Asynchronous USB Transfers](./async-transfers.md)
137
138
### USB Descriptors
139
140
USB descriptor object wrappers providing structured access to device configuration data including configurations, interfaces, alternate settings, and endpoints.
141
142
```python { .api }
143
class USBConfiguration:
144
def getNumInterfaces(self): ...
145
def getConfigurationValue(self): ...
146
def getMaxPower(self): ...
147
148
class USBInterface:
149
def getNumSettings(self): ...
150
151
class USBInterfaceSetting:
152
def getNumber(self): ...
153
def getClass(self): ...
154
def getSubClass(self): ...
155
def getProtocol(self): ...
156
def getNumEndpoints(self): ...
157
158
class USBEndpoint:
159
def getAddress(self): ...
160
def getAttributes(self): ...
161
def getMaxPacketSize(self): ...
162
```
163
164
[USB Descriptors](./descriptors.md)
165
166
## Global Functions
167
168
```python { .api }
169
def getVersion():
170
"""
171
Get libusb version information.
172
173
Returns:
174
Version: Named tuple with major, minor, micro, nano, rc, describe fields
175
"""
176
177
def hasCapability(capability):
178
"""
179
Test libusb capability support.
180
181
Args:
182
capability: Capability constant (CAP_HAS_CAPABILITY, CAP_HAS_HOTPLUG, etc.)
183
184
Returns:
185
bool: True if capability is supported
186
"""
187
188
def setLogCallback(callback):
189
"""
190
Set global log callback function.
191
192
Args:
193
callback: Function accepting (context, level, message) or None to disable
194
"""
195
196
def setLocale(locale):
197
"""
198
Set locale for translatable libusb messages.
199
200
Args:
201
locale (str): 2-letter ISO 639-1 code
202
"""
203
204
def loadLibrary(libusb=None):
205
"""
206
Load libusb library from custom path.
207
208
Args:
209
libusb (str, optional): Path to libusb library file, or None to use default lookup
210
211
Note:
212
Must be called before creating any USB contexts. Allows applications to
213
customize library loading for specific libusb versions or locations.
214
"""
215
```
216
217
## Exception Classes
218
219
```python { .api }
220
class USBError(Exception):
221
"""Base class for USB-related errors."""
222
223
class USBErrorIO(USBError):
224
"""I/O error."""
225
226
class USBErrorInvalidParam(USBError):
227
"""Invalid parameter."""
228
229
class USBErrorAccess(USBError):
230
"""Access denied (insufficient permissions)."""
231
232
class USBErrorNoDevice(USBError):
233
"""No such device (disconnected)."""
234
235
class USBErrorNotFound(USBError):
236
"""Entity not found."""
237
238
class USBErrorBusy(USBError):
239
"""Resource busy."""
240
241
class USBErrorTimeout(USBError):
242
"""Operation timed out."""
243
# Has .transferred or .received property with partial data
244
245
class USBErrorOverflow(USBError):
246
"""Overflow."""
247
248
class USBErrorPipe(USBError):
249
"""Pipe error."""
250
251
class USBErrorInterrupted(USBError):
252
"""System call interrupted."""
253
254
class USBErrorNoMem(USBError):
255
"""Insufficient memory."""
256
257
class USBErrorNotSupported(USBError):
258
"""Operation not supported or unimplemented."""
259
260
class USBErrorOther(USBError):
261
"""Other error."""
262
263
class DoomedTransferError(Exception):
264
"""Exception raised when operating on a doomed transfer."""
265
```
266
267
## Constants
268
269
### Transfer Types
270
```python { .api }
271
TRANSFER_TYPE_CONTROL = 0
272
TRANSFER_TYPE_ISOCHRONOUS = 1
273
TRANSFER_TYPE_BULK = 2
274
TRANSFER_TYPE_INTERRUPT = 3
275
```
276
277
### Transfer Status
278
```python { .api }
279
TRANSFER_COMPLETED = 0
280
TRANSFER_ERROR = 1
281
TRANSFER_TIMED_OUT = 2
282
TRANSFER_CANCELLED = 3
283
TRANSFER_STALL = 4
284
TRANSFER_NO_DEVICE = 5
285
TRANSFER_OVERFLOW = 6
286
```
287
288
### Endpoint Directions
289
```python { .api }
290
ENDPOINT_IN = 0x80
291
ENDPOINT_OUT = 0x00
292
ENDPOINT_DIR_MASK = 0x80
293
```
294
295
### Request Types
296
```python { .api }
297
TYPE_STANDARD = 0x00
298
TYPE_CLASS = 0x20
299
TYPE_VENDOR = 0x40
300
301
RECIPIENT_DEVICE = 0x00
302
RECIPIENT_INTERFACE = 0x01
303
RECIPIENT_ENDPOINT = 0x02
304
RECIPIENT_OTHER = 0x03
305
```
306
307
### Device Speeds
308
```python { .api }
309
SPEED_UNKNOWN = 0
310
SPEED_LOW = 1
311
SPEED_FULL = 2
312
SPEED_HIGH = 3
313
SPEED_SUPER = 4
314
SPEED_SUPER_PLUS = 5
315
```
316
317
### Log Levels
318
```python { .api }
319
LOG_LEVEL_NONE = 0
320
LOG_LEVEL_ERROR = 1
321
LOG_LEVEL_WARNING = 2
322
LOG_LEVEL_INFO = 3
323
LOG_LEVEL_DEBUG = 4
324
```
325
326
### Capabilities
327
```python { .api }
328
CAP_HAS_CAPABILITY = 0x0000
329
CAP_HAS_HOTPLUG = 0x0001
330
CAP_HAS_HID_ACCESS = 0x0100
331
CAP_SUPPORTS_DETACH_KERNEL_DRIVER = 0x0101
332
```
333
334
### Hotplug Events
335
```python { .api }
336
HOTPLUG_EVENT_DEVICE_ARRIVED = 0x01
337
HOTPLUG_EVENT_DEVICE_LEFT = 0x02
338
HOTPLUG_ENUMERATE = 0x01
339
HOTPLUG_MATCH_ANY = -1
340
```
341
342
### USB Interface Classes
343
```python { .api }
344
CLASS_PER_INTERFACE = 0
345
CLASS_AUDIO = 1
346
CLASS_COMM = 2
347
CLASS_HID = 3
348
CLASS_PHYSICAL = 5
349
CLASS_IMAGE = 6
350
CLASS_PRINTER = 7
351
CLASS_MASS_STORAGE = 8
352
CLASS_HUB = 9
353
CLASS_DATA = 10
354
CLASS_SMART_CARD = 11
355
CLASS_CONTENT_SECURITY = 13
356
CLASS_VIDEO = 14
357
CLASS_PERSONAL_HEALTHCARE = 15
358
CLASS_DIAGNOSTIC_DEVICE = 220
359
CLASS_WIRELESS = 224
360
CLASS_APPLICATION = 254
361
CLASS_VENDOR_SPEC = 255
362
```
363
364
### Standard USB Requests
365
```python { .api }
366
REQUEST_GET_STATUS = 0x00
367
REQUEST_CLEAR_FEATURE = 0x01
368
REQUEST_SET_FEATURE = 0x03
369
REQUEST_SET_ADDRESS = 0x05
370
REQUEST_GET_DESCRIPTOR = 0x06
371
REQUEST_SET_DESCRIPTOR = 0x07
372
REQUEST_GET_CONFIGURATION = 0x08
373
REQUEST_SET_CONFIGURATION = 0x09
374
REQUEST_GET_INTERFACE = 0x0A
375
REQUEST_SET_INTERFACE = 0x0B
376
REQUEST_SYNCH_FRAME = 0x0C
377
REQUEST_SET_SEL = 0x30
378
REQUEST_SET_ISOCH_DELAY = 0x31
379
```