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.0A 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.
pip install libusb1import usb1import usb1
# Create USB context and enumerate devices
with usb1.USBContext() as context:
# List all USB devices
for device in context.getDeviceIterator(skip_on_error=True):
print(f'ID {device.getVendorID():04x}:{device.getProductID():04x}')
print(f'Bus {device.getBusNumber():03d} Device {device.getDeviceAddress():03d}')
# Find specific device by vendor/product ID
device = context.getByVendorIDAndProductID(0x1234, 0x5678)
if device:
# Open device for communication
with device.open() as handle:
# Claim interface for exclusive access
with handle.claimInterface(0):
# Perform synchronous control transfer
data = handle.controlRead(
request_type=usb1.TYPE_VENDOR | usb1.RECIPIENT_DEVICE | usb1.ENDPOINT_IN,
request=0x01,
value=0,
index=0,
length=64,
timeout=1000
)
print(f'Received: {data.hex()}')libusb1 follows a hierarchical object model that mirrors the USB specification:
The library provides both synchronous methods (blocking) for simple use cases and asynchronous transfers (non-blocking) for high-performance applications requiring concurrent USB operations.
Core USB context functionality for initializing the library, enumerating devices, and managing system resources with comprehensive device discovery and filtering capabilities.
class USBContext:
def __init__(self, log_level=None, use_usbdk=False, with_device_discovery=True, log_callback=None): ...
def __enter__(self): ...
def __exit__(self, exc_type, exc_val, exc_tb): ...
def getDeviceIterator(self, skip_on_error=False): ...
def getDeviceList(self, skip_on_access_error=False, skip_on_error=False): ...
def getByVendorIDAndProductID(self, vendor_id, product_id, skip_on_access_error=False, skip_on_error=False): ...
def openByVendorIDAndProductID(self, vendor_id, product_id, skip_on_access_error=False, skip_on_error=False): ...USB device representation and handle management for accessing device properties, opening communication channels, claiming interfaces, and configuring device settings.
class USBDevice:
def open(self): ...
def getBusNumber(self): ...
def getDeviceAddress(self): ...
def getVendorID(self): ...
def getProductID(self): ...
def getDeviceSpeed(self): ...
class USBDeviceHandle:
def close(self): ...
def claimInterface(self, interface): ...
def releaseInterface(self, interface): ...
def setConfiguration(self, configuration): ...
def getConfiguration(self): ...Device Access and Configuration
Blocking USB transfer operations for control, bulk, and interrupt endpoints with timeout support and error handling, suitable for simple request-response communication patterns.
class USBDeviceHandle:
def controlRead(self, request_type, request, value, index, length, timeout=0): ...
def controlWrite(self, request_type, request, value, index, data, timeout=0): ...
def bulkRead(self, endpoint, length, timeout=0): ...
def bulkWrite(self, endpoint, data, timeout=0): ...
def interruptRead(self, endpoint, length, timeout=0): ...
def interruptWrite(self, endpoint, data, timeout=0): ...Non-blocking USB transfer operations using event-driven callbacks for high-performance applications requiring concurrent transfers and integration with event loops.
class USBTransfer:
def setControl(self, request_type, request, value, index, buffer_or_len, callback=None, user_data=None, timeout=0): ...
def setBulk(self, endpoint, buffer_or_len, callback=None, user_data=None, timeout=0): ...
def setIsochronous(self, endpoint, buffer_or_len, callback=None, user_data=None, timeout=0, iso_transfer_length_list=None): ...
def submit(self): ...
def cancel(self): ...
class USBTransferHelper:
def setEventCallback(self, event, callback): ...
def setDefaultCallback(self, callback): ...USB descriptor object wrappers providing structured access to device configuration data including configurations, interfaces, alternate settings, and endpoints.
class USBConfiguration:
def getNumInterfaces(self): ...
def getConfigurationValue(self): ...
def getMaxPower(self): ...
class USBInterface:
def getNumSettings(self): ...
class USBInterfaceSetting:
def getNumber(self): ...
def getClass(self): ...
def getSubClass(self): ...
def getProtocol(self): ...
def getNumEndpoints(self): ...
class USBEndpoint:
def getAddress(self): ...
def getAttributes(self): ...
def getMaxPacketSize(self): ...def getVersion():
"""
Get libusb version information.
Returns:
Version: Named tuple with major, minor, micro, nano, rc, describe fields
"""
def hasCapability(capability):
"""
Test libusb capability support.
Args:
capability: Capability constant (CAP_HAS_CAPABILITY, CAP_HAS_HOTPLUG, etc.)
Returns:
bool: True if capability is supported
"""
def setLogCallback(callback):
"""
Set global log callback function.
Args:
callback: Function accepting (context, level, message) or None to disable
"""
def setLocale(locale):
"""
Set locale for translatable libusb messages.
Args:
locale (str): 2-letter ISO 639-1 code
"""
def loadLibrary(libusb=None):
"""
Load libusb library from custom path.
Args:
libusb (str, optional): Path to libusb library file, or None to use default lookup
Note:
Must be called before creating any USB contexts. Allows applications to
customize library loading for specific libusb versions or locations.
"""class USBError(Exception):
"""Base class for USB-related errors."""
class USBErrorIO(USBError):
"""I/O error."""
class USBErrorInvalidParam(USBError):
"""Invalid parameter."""
class USBErrorAccess(USBError):
"""Access denied (insufficient permissions)."""
class USBErrorNoDevice(USBError):
"""No such device (disconnected)."""
class USBErrorNotFound(USBError):
"""Entity not found."""
class USBErrorBusy(USBError):
"""Resource busy."""
class USBErrorTimeout(USBError):
"""Operation timed out."""
# Has .transferred or .received property with partial data
class USBErrorOverflow(USBError):
"""Overflow."""
class USBErrorPipe(USBError):
"""Pipe error."""
class USBErrorInterrupted(USBError):
"""System call interrupted."""
class USBErrorNoMem(USBError):
"""Insufficient memory."""
class USBErrorNotSupported(USBError):
"""Operation not supported or unimplemented."""
class USBErrorOther(USBError):
"""Other error."""
class DoomedTransferError(Exception):
"""Exception raised when operating on a doomed transfer."""TRANSFER_TYPE_CONTROL = 0
TRANSFER_TYPE_ISOCHRONOUS = 1
TRANSFER_TYPE_BULK = 2
TRANSFER_TYPE_INTERRUPT = 3TRANSFER_COMPLETED = 0
TRANSFER_ERROR = 1
TRANSFER_TIMED_OUT = 2
TRANSFER_CANCELLED = 3
TRANSFER_STALL = 4
TRANSFER_NO_DEVICE = 5
TRANSFER_OVERFLOW = 6ENDPOINT_IN = 0x80
ENDPOINT_OUT = 0x00
ENDPOINT_DIR_MASK = 0x80TYPE_STANDARD = 0x00
TYPE_CLASS = 0x20
TYPE_VENDOR = 0x40
RECIPIENT_DEVICE = 0x00
RECIPIENT_INTERFACE = 0x01
RECIPIENT_ENDPOINT = 0x02
RECIPIENT_OTHER = 0x03SPEED_UNKNOWN = 0
SPEED_LOW = 1
SPEED_FULL = 2
SPEED_HIGH = 3
SPEED_SUPER = 4
SPEED_SUPER_PLUS = 5LOG_LEVEL_NONE = 0
LOG_LEVEL_ERROR = 1
LOG_LEVEL_WARNING = 2
LOG_LEVEL_INFO = 3
LOG_LEVEL_DEBUG = 4CAP_HAS_CAPABILITY = 0x0000
CAP_HAS_HOTPLUG = 0x0001
CAP_HAS_HID_ACCESS = 0x0100
CAP_SUPPORTS_DETACH_KERNEL_DRIVER = 0x0101HOTPLUG_EVENT_DEVICE_ARRIVED = 0x01
HOTPLUG_EVENT_DEVICE_LEFT = 0x02
HOTPLUG_ENUMERATE = 0x01
HOTPLUG_MATCH_ANY = -1CLASS_PER_INTERFACE = 0
CLASS_AUDIO = 1
CLASS_COMM = 2
CLASS_HID = 3
CLASS_PHYSICAL = 5
CLASS_IMAGE = 6
CLASS_PRINTER = 7
CLASS_MASS_STORAGE = 8
CLASS_HUB = 9
CLASS_DATA = 10
CLASS_SMART_CARD = 11
CLASS_CONTENT_SECURITY = 13
CLASS_VIDEO = 14
CLASS_PERSONAL_HEALTHCARE = 15
CLASS_DIAGNOSTIC_DEVICE = 220
CLASS_WIRELESS = 224
CLASS_APPLICATION = 254
CLASS_VENDOR_SPEC = 255REQUEST_GET_STATUS = 0x00
REQUEST_CLEAR_FEATURE = 0x01
REQUEST_SET_FEATURE = 0x03
REQUEST_SET_ADDRESS = 0x05
REQUEST_GET_DESCRIPTOR = 0x06
REQUEST_SET_DESCRIPTOR = 0x07
REQUEST_GET_CONFIGURATION = 0x08
REQUEST_SET_CONFIGURATION = 0x09
REQUEST_GET_INTERFACE = 0x0A
REQUEST_SET_INTERFACE = 0x0B
REQUEST_SYNCH_FRAME = 0x0C
REQUEST_SET_SEL = 0x30
REQUEST_SET_ISOCH_DELAY = 0x31