1Pure-python wrapper for libusb-1.0
2
3Supports all transfer types, both in synchronous and asynchronous mode.
4
5Home: http://github.com/vpelletier/python-libusb1
6
7PyPI: http://pypi.python.org/pypi/libusb1
8
9.. role:: c_code(code)
10  :language: c
11
12.. role:: python_code(code)
13  :language: python
14
15Dependencies
16============
17
18- CPython_ 2.7+ or 3.4+, pypy_ 2.0+. Older versions may work, but are not
19  recommended as there is no automated regression testing set up for them.
20
21- libusb-1.0_
22
23Supported OSes
24==============
25
26python-libusb1 can be expected to work on:
27
28- GNU/Linux
29
30- Windows [#]_ native dll or via Cygwin_
31
32- OSX [#]_ via MacPorts_, Fink_ or Homebrew_
33
34- FreeBSD (including Debian GNU/kFreeBSD)
35
36- OpenBSD
37
38.. [#] Beware of libusb-win32, which implements 0.1 API, not 1.0 .
39
40.. [#] Beware of possible lack of select.poll if you want to use asynchronous
41       API.
42
43Installation
44============
45
46Releases from PyPI, with name *libusb1*. Installing from command line::
47
48    $ pip install libusb1
49
50or::
51
52    $ easy_install libusb1
53
54Latest version from source tree::
55
56    $ git clone https://github.com/vpelletier/python-libusb1.git
57    $ cd python-libusb1
58    $ python setup.py install
59
60Usage
61=====
62
63Finding a device and gaining exclusive access:
64
65.. code:: python
66
67    import usb1
68    with usb1.USBContext() as context:
69        handle = context.openByVendorIDAndProductID(
70            VENDOR_ID,
71            PRODUCT_ID,
72            skip_on_error=True,
73        )
74        if handle is None:
75            # Device not present, or user is not allowed to access device.
76        with handle.claimInterface(INTERFACE):
77            # Do stuff with endpoints on claimed interface.
78
79Synchronous I/O:
80
81.. code:: python
82
83    while True:
84        data = handle.bulkRead(ENDPOINT, BUFFER_SIZE)
85        # Process data...
86
87Asynchronous I/O, with more error handling:
88
89.. code:: python
90
91    def processReceivedData(transfer):
92        if transfer.getStatus() != usb1.TRANSFER_COMPLETED:
93            # Transfer did not complete successfully, there is no data to read.
94            # This example does not resubmit transfers on errors. You may want
95            # to resubmit in some cases (timeout, ...).
96            return
97        data = transfer.getBuffer()[:transfer.getActualLength()]
98        # Process data...
99        # Resubmit transfer once data is processed.
100        transfer.submit()
101
102    # Build a list of transfer objects and submit them to prime the pump.
103    transfer_list = []
104    for _ in range(TRANSFER_COUNT):
105        transfer = handle.getTransfer()
106        transfer.setBulk(
107            usb1.ENDPOINT_IN | ENDPOINT,
108            BUFFER_SIZE,
109            callback=processReceivedData,
110        )
111        transfer.submit()
112        transfer_list.append(transfer)
113    # Loop as long as there is at least one submitted transfer.
114    while any(x.isSubmitted() for x in transfer_list):
115        try:
116            context.handleEvents()
117        except usb1.USBErrorInterrupted:
118            pass
119
120For more, see the ``example`` directory.
121
122Documentation
123=============
124
125python-libusb1 main documentation is accessible with python's standard
126``pydoc`` command.
127
128python-libusb1 follows libusb-1.0 documentation as closely as possible, without
129taking decisions for you. Thanks to this, python-libusb1 does not need to
130duplicate the nice existing `libusb1.0 documentation`_.
131
132Some description is needed though on how to jump from libusb-1.0 documentation
133to python-libusb1, and vice-versa:
134
135``usb1`` module groups libusb-1.0 functions as class methods. The first
136parameter (when it's a ``libusb_...`` pointer) defined the class the fonction
137belongs to. For example:
138
139- :c_code:`int libusb_init (libusb_context **context)` becomes USBContext class
140  constructor, :python_code:`USBContext.__init__(self)`
141
142- :c_code:`ssize_t libusb_get_device_list (libusb_context *ctx,
143  libusb_device ***list)` becomes an USBContext method, returning a
144  list of USBDevice instances, :python_code:`USBDevice.getDeviceList(self)`
145
146- :c_code:`uint8_t libusb_get_bus_number (libusb_device *dev)` becomes an
147  USBDevice method, :python_code:`USBDevice.getBusNumber(self)`
148
149Error statuses are converted into :python_code:`usb1.USBError` exceptions, with
150status as ``value`` instance property.
151
152``usb1`` module also defines a few more functions and classes, which are
153otherwise not so convenient to call from Python: the event handling API needed
154by async API.
155
156History
157=======
158
1590.0.1
160-----
161
162Initial release
163
1640.1.1
165-----
166
167Massive rework of usb1.py, making it more python-ish and fixing some
168memory leaks.
169
1700.1.2
171-----
172
173Deprecate "transfer" constructor parameter to allow instance reuse.
174
1750.1.3
176-----
177
178Some work on isochronous "in" transfers. They don't raise exceptions anymore,
179but data validity and python-induced latency impact weren't properly checked.
180
1810.2.0
182-----
183
184Fix asynchronous configuration transfers.
185
186Stand-alone polling thread for multi-threaded apps.
187
188More libusb methods exposed on objects, including ones not yet part of
189released libusb versions (up to their commit 4630fc2).
190
1912to3 friendly.
192
193Drop deprecated USBDevice.reprConfigurations method.
194
1950.2.1
196-----
197
198Add FreeBSD support.
199
2000.2.2
201-----
202
203Add Cygwin support.
204
205OpenBSD support checked (no change).
206
2070.2.3
208-----
209
210Add fink and homebrew support on OSX.
211
212Drop PATH_MAX definition.
213
214Try harder when looking for libusb.
215
2161.0.0
217-----
218
219Fix FreeBSD ABI compatibility.
220
221Easier to list connected devices.
222
223Easier to terminate all async transfers for clean exit.
224
225Fix few segfault causes.
226
227pypy support.
228
2291.1.0
230-----
231
232Descriptor walk API documented.
233
234Version and capability APIs exposed.
235
236Some portability fixes (OSes, python versions).
237
238Isochronous transfer refuses to round transfer size.
239
240Better exception handling in enumeration.
241
242Add examples.
243
244Better documentation.
245
2461.2.0
247-----
248
249Wrap hotplug API.
250
251Wrap port number API.
252
253Wrap kernel auto-detach API.
254
255Drop wrapper for libusb_strerror, with compatibility place-holder.
256
257Add a few new upstream enum values.
258
2591.3.0
260-----
261
262**Backward-incompatible change**: Enum class now affects caller's local scope,
263not its global scope. This should not be of much importance, as:
264
265- This class is probably very little used outside libusb1.py
266
267- This class is probably mostly used at module level, where locals == globals.
268
269  It is possible to get former behaviour by providing the new ``scope_dict``
270  parameter to ``Enum`` constructor::
271
272    SOME_ENUM = libusb1.Enum({...}, scope_dict=globals())
273
274Improve start-up time on CPython by not importing standard ``inspect`` module.
275
276Fix some more USBTransfer memory leaks.
277
278Add Transfer.iterISO for more efficient isochronous reception.
279
2801.3.1
281-----
282
283Fixed USBContext.waitForEvent.
284
285Fix typo in USBInterfaceSetting.getClassTuple method name. Backward
286compatibility preserved.
287
288Remove globals accesses from USBDeviceHandle destructor.
289
290Assorted documentation improvements.
291
2921.3.2
293-----
294
295Made USBDevice instances hashable.
296
297Relaxed licensing by moving from GPL v2+ to LGPL v2.1+, for consistency with
298libusb1.
299
3001.4.0
301-----
302
303Reduce (remove ?) the need to import libusb1 module by exposing USBError and
304constants in usb1 module.
305
306Fix libusb1.LIBUSB_ENDPOINT_ENDPOINT_MASK and
307libusb1.LIBUSB_ENDPOINT_DIR_MASK naming.
308
309Fix pydoc appearance of several USBContext methods.
310
311Define exception classes for each error values.
312
3131.4.1
314-----
315
316Fix wheel generation (``python3 setup.py bdist_wheel``).
317
3181.5.0
319-----
320
321controlWrite, bulkWrite and interruptWrite now reject (with TypeError) numeric
322values for ``data`` parameter.
323
324Fix libusb1.REQUEST_TYPE_* names (were TYPE_*). Preserve backward
325compatibility.
326
327Add USBContext.getDeviceIterator method.
328
329Rename USBContext.exit as USBContext.close for consistency with other USB*
330classes. Preserve backward compatibility.
331
332Make USBDeviceHandle.claimInterface a context manager, for easier interface
333releasing.
334
3351.5.1
336-----
337
338Introduce USBPollerThread.stop .
339
340Fix USBDeviceHandle.getSupportedLanguageList bug when running under python 3.
341While fixing this bug it was realised that this method returned ctypes objects.
342This was not intended, and it now returns regular integers.
343
3441.5.2
345-----
346
347Make USBTransfer.cancel raise specific error instances.
348
3491.5.3
350-----
351
352Fix USBTransfer.cancel exception raising introduced in 1.5.2: it was
353accidentally becomming a bound method, preventing the raise to actually
354happen (in at least CPython 2.x) or raising type conversion errors (in at least
355CPython 3.5.2).
356
3571.6
358---
359
360Improve asynchronous transfer performance: (very) suboptimal code was used to
361initialise asynchronous transfer buffer. As a consequence, usb1 now exposes
362``bytearrays`` where it used to expose ``bytes`` or ``str`` objects.
363
364Deprecate libusb1 module import, which should not be needed since all (?)
365needed constants were re-bound to usb1 module.
366
367Move testUSB1 module inside usb1, to eventually only expose usb1 as top-level
368module.
369
3701.6.1
371-----
372
373Fix getSupportedLanguageList.
374
375Fix and extend get{,ASCII}StringDescriptor .
376
377Fix iterISO and getISOBufferList.
378
3791.6.2
380-----
381
382Fix getASCIIStringDescriptor: unlike getStringDescriptor, this returns only the
383payload of the string descriptor, without its header.
384
3851.6.3
386-----
387
388Deprecate USBPollerThread . It is mileading users for which the simple version
389(a thread calling ``USBContext.handleEvents``) would be enough. And for more
390advanced uses (ie, actually needing to poll non-libusb file descriptors), this
391class only works reliably with epoll: kqueue (which should tehcnically work)
392has a different API on python level, and poll (which has the same API as epoll
393on python level) lacks the critical ability to change the set of monitored file
394descriptors while a poll is already running, causing long pauses - if not
395deadlocks.
396
3971.6.4
398-----
399
400Fix asynchronous control transfers.
401
4021.6.5
403-----
404
405Document hotplug handler limitations.
406
407Run 2to3 when running setup.py with python3, and reduce differences with
408python3.
409
410Properly cast libusb_set_pollfd_notifiers arguments.
411Fix null pointer value: POINTER(None) is the type of a pointer which may be a
412null pointer, which falls back to c_void_p. But c_void_p() is an actual null
413pointer.
414
4151.6.6
416-----
417
418Expose bare string descriptors (aka string indexes) on USBDevice.
419
4201.6.7
421-----
422
423get{,ASCII}StringDescriptor now return None for descriptor 0 instead of raising
424UnicodeDecodeError. Use getSupportedLanguageList to access it.
425Moved getManufacturer, getProduct and getSerialNumber to USBDeviceHandle. Kept
426shortcuts for these on USBDevice.
427
4281.7
429---
430
431get{,ASCII}StringDescriptor now return None for descriptor 0, use
432getSupportedLanguageList to get its content.
433getManufacturer, getProduct and getSerialNumber are now on USBDeviceHandle,
434with backward-compatibility aliases on their original location.
435Synchronous bulk and interrupt API exposes number of bytes sent and received
436bytes even when a timeout occurs.
437
4381.7.1
439-----
440
441usb1.__version__ is now present, managed by versioneer.
442Fix an occasional segfault when closing a transfer from inside its callback
443function.
444
4451.8
446---
447
448Fix getExtra and libusb1.libusb_control_transfer_get_data .
449Fix getMaxPower unit on SuperSpeed devices.
450
4511.8.1
452-----
453
454Release process rework:
455
456- embed libusb1 dll for easier deployment on Windows
457- cryptographically signed releases
458
459Use libusb_free_pollfds whenever available (libusb1>=1.0.20).
460Fix hotplug callback destruction at context teardown.
461Drop remnants of python 2.6 support code.
462
4631.9
464---
465
466Drop USBPollerThread and deprecate libusb-lock-related USBContext API.
467
4681.9.1
469-----
470
471Fix installation from pypi source tarball, broken in 1.8.1 .
472
4731.9.2
474-----
475
476Windows wheels: Update bundled libusb to 1.0.24 .
477Fix soure-only build when wheel is not available.
478
4791.9.3
480-----
481
482Add support for pyinstaller.
483Improve the way the windows dlls are embedded in wheels.
484Fix support for python 3.10 .
485Add support for homebrew on Apple M1.
486
487.. _CPython: http://www.python.org/
488
489.. _pypy: http://pypy.org/
490
491.. _Cygwin: https://www.cygwin.com/
492
493.. _MacPorts: https://www.macports.org/
494
495.. _Fink: http://www.finkproject.org/
496
497.. _Homebrew: http://brew.sh/
498
499.. _libusb-1.0: https://github.com/libusb/libusb/wiki/
500
501.. _libusb1.0 documentation: http://libusb.sourceforge.net/api-1.0/
502