or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

backends.mdcontrol-requests.mddevice-communication.mddevice-discovery.mdindex.mdlegacy-api.mdutilities.md

index.mddocs/

0

# PyUSB

1

2

A comprehensive Python library that provides easy access to Universal Serial Bus (USB) devices for Python applications. PyUSB offers a backend-neutral, API-rich interface that abstracts the complexities of USB communication while supporting multiple USB backends including libusb 1.0, libusb 0.1, and OpenUSB.

3

4

## Package Information

5

6

- **Package Name**: pyusb

7

- **Language**: Python

8

- **Installation**: `pip install pyusb`

9

- **Python Versions**: Python >= 3.9

10

- **Platforms**: Linux, Windows, macOS, BSD

11

12

## Core Imports

13

14

```python

15

import usb.core

16

import usb.util

17

```

18

19

For device discovery and basic operations:

20

21

```python

22

import usb.core

23

24

# Find devices

25

device = usb.core.find(idVendor=0x1234, idProduct=0x5678)

26

```

27

28

For control requests:

29

30

```python

31

import usb.control

32

```

33

34

Legacy compatibility (0.x version):

35

36

```python

37

import usb # Imports legacy API automatically

38

```

39

40

## Basic Usage

41

42

```python

43

import usb.core

44

import usb.util

45

46

# Find USB device by vendor and product ID

47

device = usb.core.find(idVendor=0x1234, idProduct=0x5678)

48

49

if device is None:

50

raise ValueError('Device not found')

51

52

# Set device configuration (usually needed)

53

device.set_configuration()

54

55

# Get device configuration

56

config = device.get_active_configuration()

57

58

# Find the first interface and its first endpoint

59

interface = config.interfaces()[0]

60

endpoint = interface.endpoints()[0]

61

62

# Read data from endpoint

63

try:

64

data = device.read(endpoint.bEndpointAddress, 64, timeout=1000)

65

print(f"Read {len(data)} bytes: {data}")

66

except usb.core.USBTimeoutError:

67

print("Read timeout")

68

69

# Write data to endpoint (if it's an OUT endpoint)

70

if usb.util.endpoint_direction(endpoint.bEndpointAddress) == usb.util.ENDPOINT_OUT:

71

bytes_written = device.write(endpoint.bEndpointAddress, b'Hello USB!', timeout=1000)

72

print(f"Wrote {bytes_written} bytes")

73

```

74

75

## Architecture

76

77

PyUSB is organized around several key components:

78

79

- **Core API (`usb.core`)**: Modern, recommended interface for USB operations centered around the Device class

80

- **Legacy API (`usb.legacy`)**: Backward compatibility with PyUSB 0.x versions

81

- **Backend System**: Pluggable backends supporting multiple USB libraries (libusb 1.0, libusb 0.1, OpenUSB)

82

- **Utility Functions (`usb.util`)**: Helper functions for endpoint handling, interface management, and device operations

83

- **Control Requests (`usb.control`)**: Standard USB control transfer functions

84

85

The Device class serves as the primary interface, providing methods for configuration, communication, and resource management while abstracting backend-specific details.

86

87

## Capabilities

88

89

### Device Discovery and Management

90

91

Find and enumerate USB devices using flexible filtering criteria, with support for device iteration and backend selection.

92

93

```python { .api }

94

def find(find_all=False, backend=None, custom_match=None, **args):

95

"""

96

Find USB devices matching criteria.

97

98

Parameters:

99

- find_all: bool, return all matches instead of first match

100

- backend: USB backend to use

101

- custom_match: callable for custom matching logic

102

- **args: device descriptor fields to match (idVendor, idProduct, etc.)

103

104

Returns:

105

Device or list of devices

106

"""

107

108

def show_devices(verbose=False, **kwargs):

109

"""Display information about available USB devices."""

110

```

111

112

[Device Discovery](./device-discovery.md)

113

114

### Device Communication

115

116

Core device operations including configuration, data transfer, and endpoint communication with comprehensive error handling.

117

118

```python { .api }

119

class Device:

120

# Communication methods

121

def read(self, endpoint, size_or_buffer, timeout=None):

122

"""Read data from endpoint."""

123

124

def write(self, endpoint, data, timeout=None):

125

"""Write data to endpoint."""

126

127

def ctrl_transfer(self, bmRequestType, bRequest, wValue=0, wIndex=0, data_or_wLength=None, timeout=None):

128

"""Perform control transfer."""

129

130

# Configuration methods

131

def set_configuration(self, configuration=None):

132

"""Set device configuration."""

133

134

def get_active_configuration(self):

135

"""Get current active configuration."""

136

137

def set_interface_altsetting(self, interface=None, alternate_setting=None):

138

"""Set alternate setting for interface."""

139

140

# Device information properties

141

@property

142

def langids(self):

143

"""Get supported language ID codes."""

144

145

@property

146

def serial_number(self):

147

"""Get device serial number string."""

148

149

@property

150

def product(self):

151

"""Get device product string."""

152

153

@property

154

def manufacturer(self):

155

"""Get device manufacturer string."""

156

157

@property

158

def parent(self):

159

"""Get parent device."""

160

161

@property

162

def backend(self):

163

"""Get backend being used."""

164

165

# Device management

166

def configurations(self):

167

"""Get tuple of device configurations."""

168

169

def clear_halt(self, ep):

170

"""Clear halt/stall condition for endpoint."""

171

172

def reset(self):

173

"""Reset device."""

174

175

# Kernel driver management

176

def is_kernel_driver_active(self, interface):

177

"""Check if kernel driver is active on interface."""

178

179

def detach_kernel_driver(self, interface):

180

"""Detach kernel driver from interface."""

181

182

def attach_kernel_driver(self, interface):

183

"""Re-attach kernel driver to interface."""

184

```

185

186

[Device Communication](./device-communication.md)

187

188

### USB Control Requests

189

190

Standard USB control transfer operations for device configuration and status management.

191

192

```python { .api }

193

def get_status(dev, recipient, index=0):

194

"""Get recipient status."""

195

196

def clear_feature(dev, feature, recipient, index=0):

197

"""Clear a recipient feature."""

198

199

def set_feature(dev, feature, recipient, index=0):

200

"""Set a recipient feature."""

201

202

def get_descriptor(dev, desc_size, desc_type, desc_index=0, langid=None):

203

"""Get a device descriptor."""

204

205

def set_configuration(dev, config):

206

"""Set device configuration."""

207

```

208

209

[Control Requests](./control-requests.md)

210

211

### Utility Functions

212

213

Helper functions for endpoint handling, interface management, descriptor parsing, and resource cleanup.

214

215

```python { .api }

216

def endpoint_address(address):

217

"""Return endpoint absolute address."""

218

219

def endpoint_direction(address):

220

"""Return endpoint transfer direction."""

221

222

def find_descriptor(desc, find_all=False, custom_match=None, **args):

223

"""Find inner descriptor."""

224

225

def claim_interface(device, interface):

226

"""Explicitly claim an interface."""

227

228

def get_string(dev, index, langid=None):

229

"""Retrieve string descriptor from device."""

230

```

231

232

[Utilities](./utilities.md)

233

234

### Backend System

235

236

Pluggable backend architecture supporting multiple USB libraries with automatic backend detection and configuration.

237

238

```python { .api }

239

class IBackend:

240

"""Abstract backend interface."""

241

242

def get_backend():

243

"""Get backend instance, automatically selecting libusb1, libusb0, or openusb."""

244

```

245

246

[Backends](./backends.md)

247

248

### Legacy Compatibility API

249

250

Backward-compatible API matching PyUSB 0.x interface patterns with extensive USB constants and legacy device handling.

251

252

```python { .api }

253

def busses():

254

"""Return list of buses (legacy API)."""

255

256

class Device:

257

"""Legacy device representation."""

258

259

class DeviceHandle:

260

"""Legacy device handle."""

261

```

262

263

[Legacy API](./legacy-api.md)

264

265

## Types

266

267

```python { .api }

268

class USBError(IOError):

269

"""Base exception for USB operations."""

270

271

class USBTimeoutError(USBError):

272

"""USB operation timeout error."""

273

274

class NoBackendError(ValueError):

275

"""No USB backend available error."""

276

277

class Configuration:

278

"""USB configuration descriptor."""

279

bConfigurationValue: int

280

iConfiguration: int

281

bmAttributes: int

282

bMaxPower: int

283

284

class Interface:

285

"""USB interface descriptor."""

286

bInterfaceNumber: int

287

bAlternateSetting: int

288

bNumEndpoints: int

289

bInterfaceClass: int

290

bInterfaceSubClass: int

291

bInterfaceProtocol: int

292

iInterface: int

293

294

class Endpoint:

295

"""USB endpoint descriptor."""

296

bEndpointAddress: int

297

bmAttributes: int

298

wMaxPacketSize: int

299

bInterval: int

300

```

301

302

## Constants

303

304

```python { .api }

305

# USB Speed Constants

306

SPEED_UNKNOWN = 0

307

SPEED_LOW = 1

308

SPEED_FULL = 2

309

SPEED_HIGH = 3

310

SPEED_SUPER = 4

311

312

# Descriptor Type Constants

313

DESC_TYPE_DEVICE = 0x01

314

DESC_TYPE_CONFIG = 0x02

315

DESC_TYPE_STRING = 0x03

316

DESC_TYPE_INTERFACE = 0x04

317

DESC_TYPE_ENDPOINT = 0x05

318

319

# Endpoint Direction Constants

320

ENDPOINT_IN = 0x80

321

ENDPOINT_OUT = 0x00

322

323

# Endpoint Type Constants

324

ENDPOINT_TYPE_CTRL = 0x00

325

ENDPOINT_TYPE_ISO = 0x01

326

ENDPOINT_TYPE_BULK = 0x02

327

ENDPOINT_TYPE_INTR = 0x03

328

329

# Control Transfer Constants

330

CTRL_OUT = 0x00

331

CTRL_IN = 0x80

332

333

CTRL_TYPE_STANDARD = 0x00

334

CTRL_TYPE_CLASS = 0x20

335

CTRL_TYPE_VENDOR = 0x40

336

CTRL_TYPE_RESERVED = 0x60

337

338

CTRL_RECIPIENT_DEVICE = 0

339

CTRL_RECIPIENT_INTERFACE = 1

340

CTRL_RECIPIENT_ENDPOINT = 2

341

CTRL_RECIPIENT_OTHER = 3

342

```