1==========================
2Programming with PyUSB 1.0
3==========================
4
5Let me introduce myself
6=======================
7
8PyUSB 1.0 is a Python_ library allowing easy USB_ access. PyUSB provides
9several features:
10
11100% written in Python:
12    Unlike the 0.x version, which is written in C, 1.0 version is written in
13    Python. This allows Python programmers with no background in C to
14    understand better how PyUSB works.
15Platform neutrality:
16    1.0 version implements a frontend-backend scheme. This isolates the API
17    from system specific implementation details. The glue between the two
18    layers is the ``IBackend`` interface. PyUSB comes with builtin backends for
19    libusb 0.1, libusb 1.0 and OpenUSB.  You can write your own backend if you
20    desire to.
21Portability:
22    PyUSB should run on any platform with Python >= 2.4, ctypes_ and at least
23    one of the supported builtin backends.
24Easiness:
25    Communicating with an USB_ device has never been so easy! USB is a complex
26    protocol, but PyUSB has good defaults for most common configurations.
27Support for isochronous transfers:
28    PyUSB supports isochronous transfers if the underlying backend supports it.
29
30Although PyUSB makes USB programming less painful, it is assumed in this
31tutorial that you have a minimal USB protocol background. If you don't know
32anything about USB, I recommend you the excellent Jan Axelson's book **USB
33Complete**.
34
35Enough talk, let's code!
36========================
37
38Who's who
39---------
40
41First of all, let's give an overview on the PyUSB modules. PyUSB modules are
42under the ``usb`` package, with the following modules:
43
44======= ===========
45Content Description
46------- -----------
47core    The main USB module.
48util    Utility functions.
49control Standard control requests.
50legacy  The 0.x compatibility layer.
51backend A subpackage containing the builtin backends.
52======= ===========
53
54For example, to import the ``core`` module, type the following::
55
56    >>> import usb.core
57    >>> dev = usb.core.find()
58
59Let's get it started
60--------------------
61
62Following is a simplistic program that sends the 'test' string to the first OUT
63endpoint found:
64
65.. code-block:: python
66
67    import usb.core
68    import usb.util
69
70    # find our device
71    dev = usb.core.find(idVendor=0xfffe, idProduct=0x0001)
72
73    # was it found?
74    if dev is None:
75        raise ValueError('Device not found')
76
77    # set the active configuration. With no arguments, the first
78    # configuration will be the active one
79    dev.set_configuration()
80
81    # get an endpoint instance
82    cfg = dev.get_active_configuration()
83    intf = cfg[(0,0)]
84
85    ep = usb.util.find_descriptor(
86        intf,
87        # match the first OUT endpoint
88        custom_match = \
89        lambda e: \
90            usb.util.endpoint_direction(e.bEndpointAddress) == \
91            usb.util.ENDPOINT_OUT)
92
93    assert ep is not None
94
95    # write the data
96    ep.write('test')
97
98The first two lines import PyUSB package modules. ``usb.core`` is the main
99module, and ``usb.util`` contains utility functions. The next command searches
100for our device and returns an instance object if it is found. If not, ``None``
101is returned.  After, we set the configuration to use. Note that no argument
102indicating what configuration we want was supplied. As you will see, many PyUSB
103functions have defaults for most common devices. In this case, the
104configuration set is the first one found.
105
106Then, we look for the endpoint we are interested. We search for it inside the
107first interface we have. After finding the endpoint, we send the data to it.
108
109If we know the endpoint address in advance, we could just call the ``write``
110function from the device object:
111
112.. code-block:: python
113
114    dev.write(1, 'test')
115
116Here we write the string 'test' at the endpoint address *1*.
117All these functions will be detailed in the following sections.
118
119What's wrong?
120-------------
121
122Every function in PyUSB raises an exception in case of an error. Besides the
123`Python standard exceptions
124<http://docs.python.org/library/exceptions.html>`__, PyUSB defines the
125``usb.core.USBError`` for USB related errors.
126
127You can also use the PyUSB log functionality. It uses the `logging
128<http://docs.python.org/library/logging.html>`__ module. To enable it, define
129the environment variable ``PYUSB_DEBUG`` with one of the following level
130names: ``critical``, ``error``, ``warning``, ``info`` or ``debug``.
131
132By default the messages are sent to `sys.stderr
133<http://docs.python.org/library/sys.html>`__.  If you want to, you can redirect
134log messages to a file by defining the ``PYUSB_LOG_FILENAME`` environment
135variable. If its value is a valid file path, messages will be written to it,
136otherwise it will be sent to ``sys.stderr``.
137
138Where are you?
139--------------
140
141The ``find()`` function in the ``core`` module is used to find and enumerate
142devices connected to the system. For example, let's say that our device has a
143vendor ID equal to `0xfffe` and product ID equals to `0x0001`. If we would like
144to find it, we proceed in this way:
145
146.. code-block:: python
147
148    import usb.core
149
150    dev = usb.core.find(idVendor=0xfffe, idProduct=0x0001)
151    if dev is None:
152        raise ValueError('Our device is not connected')
153
154That's it, the function will return an ``usb.core.Device`` object representing
155our device. If the device is not found, it returns ``None``. Actually, you can
156use any field of the Device Descriptor_ you desire. For example, what if we
157would like to discover if there is a USB printer connected to the system?  This
158is very easy:
159
160.. code-block:: python
161
162    # actually this is not the whole history, keep reading
163    if usb.core.find(bDeviceClass=7) is None:
164        raise ValueError('No printer found')
165
166The 7 is the code for the printer class according to the USB spec.
167Hey, wait, what if I want to enumerate all printers present? No problem:
168
169.. code-block:: python
170
171    # this is not the whole history yet...
172    printers = usb.core.find(find_all=True, bDeviceClass=7)
173
174    # Python 2, Python 3, to be or not to be
175    import sys
176    sys.stdout.write('There are ' + len(printers) + ' in the system\n.')
177
178What happened? Well, it is time for a little explanation... ``find`` has a
179parameter called ``find_all`` that defaults to False. When it is false [#]_,
180``find`` will return the first device found that matches the specified criteria
181(more on that soon). If you give it a *true* value, ``find`` will instead
182return a list with all devices matching the criteria.  That's it! Simple, isn't
183it?
184
185Finished? No! I have not told you the whole history: many devices actually put
186their class information in the Interface Descriptor_ instead of the Device
187Descriptor_. So, to really find all printers connected to the system, we would
188need to transverse all configurations, and then all interfaces and check if one
189of the interfaces has its `bInterfaceClass` field equal to 7. If you are a
190`programmer <http://en.wikipedia.org/wiki/Laziness>`__ like me, you might be
191wondering if there is an easier way to do that. The answer is yes, there is.
192First, let's give a look on the final code to find all printers connected:
193
194.. code-block:: python
195
196    import usb.core
197    import usb.util
198    import sys
199
200    class find_class(object):
201        def __init__(self, class_):
202            self._class = class_
203        def __call__(self, device):
204            # first, let's check the device
205            if device.bDeviceClass == self._class:
206                return True
207            # ok, transverse all devices to find an
208            # interface that matches our class
209            for cfg in device:
210                # find_descriptor: what's it?
211                intf = usb.util.find_descriptor(
212                                            cfg,
213                                            bInterfaceClass=self._class
214                                    )
215                if intf is not None:
216                    return True
217
218            return False
219
220    printers = usb.core.find(find_all=1, custom_match=find_class(7))
221
222The ``custom_match`` parameter accepts any callable object that receives the
223device object. It must return true for a matching device, and false for a
224non-matching device. You can also combine ``custom_match`` with device fields
225if you want:
226
227.. code-block:: python
228
229    # find all printers that belongs to our vendor:
230    printers = usb.core.find(find_all=1, custom_match=find_class(7), idVendor=0xfffe)
231
232Here we are only interested in the printers of the `0xfffe` vendor.
233
234Describe yourself
235-----------------
236
237Ok, we've found our device, but before talking to it, we would like to know
238more about it, you know, configurations, interfaces, endpoints, transfer
239types...
240
241If you have a device, you can access any device descriptor fields as object
242properties:
243
244.. code-block:: python
245
246    >>> dev.bLength
247    >>> dev.bNumConfigurations
248    >>> dev.bDeviceClass
249    >>> # ...
250
251To access the configurations available in the device, you can iterate over the
252device:
253
254.. code-block:: python
255
256    for cfg in dev:
257        sys.stdout.write(str(cfg.bConfigurationValue) + '\n')
258
259In the same way, you can iterate over a configuration to access the interfaces,
260and iterate over the interfaces to access their endpoints. Each kind of object
261has as attributes the fields of the respective descriptor. Let's see an
262example:
263
264.. code-block:: python
265
266    for cfg in dev:
267        sys.stdout.write(str(cfg.bConfigurationValue) + '\n')
268        for intf in cfg:
269            sys.stdout.write('\t' + \
270                             str(intf.bInterfaceNumber) + \
271                             ',' + \
272                             str(intf.bAlternateSetting) + \
273                             '\n')
274            for ep in intf:
275                sys.stdout.write('\t\t' + \
276                                 str(ep.bEndpointAddress) + \
277                                 '\n')
278
279You can also use the subscript operator to access the descriptors randomly,
280like this:
281
282.. code-block:: python
283
284    >>> # access the second configuration
285    >>> cfg = dev[1]
286    >>> # access the first interface
287    >>> intf = cfg[(0,0)]
288    >>> # third endpoint
289    >>> ep = intf[2]
290
291As you can see, the index is zero-based. But wait! There is something weird in
292the way I access an interface... Yes, you are right, the subscript operator in
293the Configuration accepts a sequence of two items, with the first one being the
294index of the Interface and the second one, the alternate setting. So, to access
295the first interface, but its second alternate setting, we write ``cfg[(0,1)]``.
296
297Now it's time to we learn a powerful way to find descriptors, the
298``find_descriptor`` utility function. We have already seen it in the printer
299finding example.  ``find_descriptor`` works in almost the same way as ``find``,
300with two exceptions:
301
302* ``find_descriptor`` receives as its first parameter the parent descriptor
303  that you will search on.
304* There is no ``backend`` [#]_ parameter.
305
306For example, if we have a configuration descriptor ``cfg`` and want to find all
307alternate settings of the interface 1, we do so:
308
309.. code-block:: python
310
311    import usb.util
312    alt = usb.util.find_descriptor(cfg, find_all=True, bInterfaceNumber=1)
313
314Notice that ``find_descriptor`` is in the ``usb.util`` module. It also accepts
315the early described ``custom_match`` parameter.
316
317Dealing with multiple identical devices
318***************************************
319
320Sometimes you may have two identical devices connected to the computer. How can
321you differentiate them? ``Device`` objects come with two additional attributes
322which are not part of the USB Spec, but are very useful: ``bus`` and
323``address`` attributes. First of all, it is worth it to say that these
324attributes come from the backend and a backend is free to not support them, in
325which case they are set to ``None``. That said, these attributes represent the
326bus number and bus address of the device and, as you might already have
327imagined, can be used to differentiate two devices with the same ``idVendor``
328and ``idProduct`` attributes.
329
330How am I supposed to work?
331--------------------------
332
333USB devices after connection must be configured through a few standard
334requests.  When I started to study USB_ spec, I found myself confused with
335descriptors, configurations, interfaces, alternate settings, transfer types and
336all this stuff... And worst, you cannot simply ignore them, a device does not
337work without setting a configuration, even if it has just one! PyUSB tries to
338make your life as easy as possible. For example, after getting your device
339object, one of the first things you need to do before communicating with it is
340issuing a ``set_configuration`` request. The parameter for this request is the
341``bConfigurationValue`` of the configuration you are interested on.  Most
342devices have no more than one configuration, and tracking the configuration
343value to use is annoying (although most code I have seen simply hardcodes it).
344Therefore, in PyUSB, you can just issue a ``set_configuration`` call with no
345arguments. In this case, it will set the first configuration found (if your
346device has just one, you don't need to worry about the configuration value at
347all). For example, let's imagine you have a device with one configuration
348descriptor with its `bConfigurationValue` field equals to 5 [#]_, the following
349calls below will work equally:
350
351.. code-block:: python
352
353    >>> dev.set_configuration(5)
354    # or
355    >>> dev.set_configuration() # we assume the configuration 5 is the first one
356    # or
357    >>> cfg = util.find_descriptor(dev, bConfigurationValue=5)
358    >>> cfg.set()
359    # or
360    >>> cfg = util.find_descriptor(dev, bConfigurationValue=5)
361    >>> dev.set_configuration(cfg)
362
363Wow! You can use a ``Configuration`` object as a parameter to
364``set_configuration``!  Yes, and also it has a ``set`` method to configure
365itself as the current configuration.
366
367The other setting you might or might not have to configure is the interface
368alternate setting. Each device can have only one activated configuration at a
369time, and each configuration may have more than one interface, and you can use
370all interfaces at the same time. You better understand this concept if you
371think of an interface as a logical device. For example, let's imagine a
372multifunction printer, which is at the same time a printer and a scanner. To
373keep things simple (or at least as simple as we can), let's consider that it
374has just one configuration. As we have a printer and a scanner, the
375configuration has two interfaces, one for the printer and one for the scanner.
376A device with more than one interface is called a composite device. When you
377connect your multifunction printer to your computer, the Operating System would
378load two different drivers: one for each "logical" peripheral you have [#]_.
379
380What about the alternate setting? Good you asked. An interface has one or more
381alternate settings. An interface with just one alternate setting is considered
382to not having an alternate setting [#]_. Alternate settings are for interfaces
383what configurations are for devices, i.e, for each interface, you can have only
384one alternate setting active. For example, USB spec says that a device cannot
385have an isochronous endpoint in its primary alternate setting [#]_, so a
386streaming device must have at least two alternate settings, with the second one
387having the isochronous endpoint(s). But as opposed to configurations,
388interfaces with just one alternate setting don't need to be set [#]_. You
389select an interface alternate setting through the ``set_interface_altsetting``
390function:
391
392.. code-block:: python
393
394    >>> dev.set_interface_altsetting(interface = 0, alternate_setting = 0)
395
396.. warning::
397    The USB spec says that a device is allowed to return an error in case it
398    receives a SET_INTERFACE request for an interface that has no additional
399    alternate settings. So, if you are not sure if either the interface has more
400    than one alternate setting or it accepts a SET_INTERFACE request,
401    the safest way is to call ``set_interface_altsetting`` inside an
402    try-except block, like this:
403
404    .. code-block:: python
405
406        try:
407            dev.set_interface_altsetting(...)
408        except USBError:
409            pass
410
411You can also use an ``Interface`` object as parameter to the function, the
412``interface`` and ``alternate_setting`` parameters are automatically inferred
413from ``bInterfaceNumber`` and ``bAlternateSetting`` fields. Example:
414
415.. code-block:: python
416
417    >>> intf = find_descriptor(...)
418    >>> dev.set_interface_altsetting(intf)
419    >>> intf.set_altsetting() # wow! Interface also has a method for it
420
421.. warning::
422    The ``Interface`` object must belong to the active configuration descriptor.
423
424Talk to me, honey
425-----------------
426
427Now it's time for us to learn how to communicate with USB devices. USB has four
428flavors of transfers: bulk, interrupt, isochronous and control. I don't intend
429to explain the purpose of each transfer and the differences among them.
430Therefore, I assume you know at least the basics of the USB transfers.
431
432Control transfer is the only transfer that has structured data described in the
433spec, the others just send and receive raw data from USB point of view. Because
434of it, you have a different function to deal with control transfers, all the
435other transfers are managed by the same functions.
436
437You issue a control transfer through the ``ctrl_transfer`` method. It is used
438both for OUT and IN transfers. The transfer direction is determined from the
439``bmRequestType`` parameter.
440
441The ``ctrl_transfer`` parameters are almost equal to the control request
442structure. Following is a example of how to do a control transfer [#]_:
443
444.. code-block:: python
445
446    >>> msg = 'test'
447    >>> assert dev.ctrl_transfer(0x40, CTRL_LOOPBACK_WRITE, 0, 0, msg) == len(msg)
448    >>> ret = dev.ctrl_transfer(0xC0, CTRL_LOOPBACK_READ, 0, 0, len(msg))
449    >>> sret = ''.join([chr(x) for x in ret])
450    >>> assert sret == msg
451
452In this example, it is assumed that our device implements two custom control
453requests that act as a loopback pipe. What you write with the
454``CTRL_LOOPBACK_WRITE`` message, you can read with the ``CTRL_LOOPBACK_READ``
455message.
456
457The first four parameters are the ``bmRequestType``, ``bmRequest``, ``wValue``
458and ``wIndex`` fields of the standard control transfer structure. The fifth
459parameter is either the data payload for an OUT transfer or the number of bytes
460to read in an IN transfer.  The data payload can be any sequence type that can
461be used as a parameter for the array_ ``__init__`` method.  If there is no data
462payload, the parameter should be ``None`` (or 0 in case of an IN transfer).
463There is one last optional parameter specifying the timeout of the operation.
464If you don't supply it, a default timeout will be used (more on that later). In
465an OUT transfer, the return value is the number of bytes really sent to the
466device. In an IN transfer, the return value is an array_ object with the data
467read.
468
469For the other transfers, you use the methods ``write`` and ``read``,
470respectively, to write and read data. You don't need to worry about the
471transfer type, it is automatically determined from the endpoint address. Here
472is our loopback example assuming the we have a loopback pipe in the endpoint
4731:
474
475.. code-block:: python
476
477    >>> msg = 'test'
478    >>> assert len(dev.write(1, msg, 100)) == len(msg)
479    >>> ret = dev.read(0x81, len(msg), 100)
480    >>> sret = ''.join([chr(x) for x in ret])
481    >>> assert sret == msg
482
483The first and third parameters are equal for both methods, they are the
484endpoint address and timeout, respectively. The second parameter is the data
485payload (write) or the number of bytes to read (read). The returned data if
486either an instance of the array_ object for the ``read`` method or the number
487of bytes written for the ``write`` method.
488
489Since beta 2 version, instead of the number of bytes, you can also pass to
490``read`` and ``ctrl_transfer`` an array_ object in which the data will be
491read into. In this case, the number of bytes to read will be the length of
492the array times the ``array.itemsize`` value.
493
494As in ``ctrl_transfer``, the ``timeout`` parameter is optional. When the
495``timeout`` is omitted, it is used the ``Device.default_timeout`` property
496as the operation timeout.
497
498Control yourself
499----------------
500
501Besides the transfers functions, the module ``usb.control`` offers functions
502which implement the standard USB control requests and the ``usb.util`` module
503has the convenience function ``get_string`` specifically to return string
504descriptors.
505
506Additional Topics
507=================
508
509Behind every great abstraction, there's a great implementation
510--------------------------------------------------------------
511
512In the early days, there was only libusb_. Then came libusb 1.0, and we had
513libusb 0.1 and 1.0.  After, they created OpenUSB_, and now we live at the
514`Tower of Babel <http://en.wikipedia.org/wiki/Tower_of_Babel>`__ of the USB
515libraries [#]_.  How does PyUSB deal with it? Well, PyUSB is a democratic
516library, you may choose whichever library you want. Actually, you can write
517your own USB library from scratch and tell PyUSB to use it.
518
519The ``find`` function has one more parameter that I haven't told you. It is the
520``backend`` parameter. If you don't supply it, it will be used one of the
521builtin backends. A backend is an object inherited from
522``usb.backend.IBackend``, responsible to implement the operating system
523specific USB stuff. As you might guess, the builtins are libusb 0.1, libusb 1.0
524and OpenUSB backends.
525
526You can create your own backend and use it. Just inherit from ``IBackend`` and
527implement the methods necessary. You might want to take a look at the
528``usb.backend`` package documentation to learn how to do that.
529
530Don't be selfish
531----------------
532
533Python has what we call *automatic memory management*. This means that the
534virtual machine will decide when to release objects from the memory. Under the
535hood, PyUSB manages all low level resources it needs to work (interface
536claiming, device handles, etc.) and most of the users don't need to worry about
537that. But, because of the nondeterministic nature of automatic object
538destruction of Python, users cannot predict when the resources allocated will
539be released. Some applications need to allocate and free the resources
540deterministically.  For these kind of applications, the ``usb.util`` module has
541a set of functions to deal with resource management.
542
543If you want to claim and release interfaces manually, you may use the
544``claim_interface`` and ``release_interface`` functions. ``claim_interface``
545will claim the specified interface if the device has not done it yet. If the
546device already claimed the interface, it does nothing.  In a similar way,
547``release_interface`` will release the specified interface if it is claimed.
548If the interface is not claimed, it does nothing. You can use manual interface
549claim to solve the `configuration selection problem
550<http://libusb.sourceforge.net/api-1.0/caveats.html>`__ described in the
551libusb_ documentation.
552
553If you want to free all resources allocated by the device object (including
554interfaces claimed), you can use the ``dispose_resources`` function. It
555releases all resources allocated and puts the device object (but not the device
556hardware itself) in the state it was at the time when the ``find`` function
557returned.
558
559Specifying libraries by hand
560----------------------------
561
562In general, a backend is an wrapper on a shared library which implements the
563USB access API.  By default, the backend uses the `find_library()
564<http://docs.python.org/3/library/ctypes.html#finding-shared-libraries>`_
565ctypes_ function. On Linux and other Unix like Operating Systems,
566``find_library`` tries to run external programs (like */sbin/ldconfig*, *gcc*
567and *objdump*) to find the library file.
568
569On systems where these programs are missing and/or the library cache is
570disabled, this function cannot be used. To overcome this limitation, PyUSB
571allows you to supply a custom `find_library()` function to the backend.
572
573An example for such scenario would be:
574
575.. code-block:: python
576
577    >>> import usb.core
578    >>> import usb.backend.libusb1
579    >>>
580    >>> backend = usb.backend.libusb1.get_backend(find_library=lambda x: "/usr/lib/libusb-1.0.so")
581    >>> dev     = usb.core.find(..., backend=backend)
582
583Notice the `find_library` argument for the `get_backend()` function, in which
584you supply a function that is responsible to find the correct library for the
585backend.
586
587Old school rules
588----------------
589
590If you wrote an application using the old PyUSB API (0.whatever), you may be
591asking yourself if you need to update your code to use the new API. Well, you
592should, but you don't need to. PyUSB 1.0 comes with the ``usb.legacy``
593compatibility module. It implements the older API above the new API. "So, do I
594have just to replace my ``import usb`` statement with ``import usb.legacy as
595usb`` to get my application working?", you ask. The answer is yes, it will
596work, but you don't have to. If you run your application untouched it will just
597work, because the ``import usb`` statement will import all public symbols from
598``usb.legacy``. If you face a problem, probably you found a bug.
599
600Help me, please
601---------------
602
603If you need help, **do not email me**, the mailing list is there for this.
604Subscribe instructions can be found at the PyUSB_ website.
605
606.. [#] When I say True or False (capitalized), I mean the respective values of
607       the Python language. And when I say true and false, I mean any
608       expression in Python which evals to true or false.
609
610.. [#] See backend specific documentation.
611
612.. [#] USB spec does not impose any sequential value to the configuration
613       value. The same is true for interface and alternate setting numbers.
614
615.. [#] Actually things are a little more complex, but this simple explanation
616       is enough for us.
617
618.. [#] I know it sounds weird.
619
620.. [#] This is because if there is no bandwidth for isochronous transfer at the
621       device configuration time, the device can be successfully enumerated.
622
623.. [#] This does not happen for configurations because a device is allowed to
624       be in an unconfigured state.
625
626.. [#] In PyUSB, control transfers are only issued in the endpoint 0. It's very
627       very very rare a device having an alternate control endpoint (I've never
628       seem such device).
629
630.. [#] It's just a joke, don't take it seriously. Many choices is better than
631       no choice.
632
633.. _libusb: http://www.libusb.org
634.. _OpenUSB: http://sourceforge.net/p/openusb/wiki/Home/
635.. _USB: http://www.usb.org
636.. _PyUSB: http://pyusb.wiki.sourceforge.net
637.. _Python: http://www.python.org
638.. _ctypes: http://docs.python.org/library/ctypes.html
639.. _Descriptor: http://www.beyondlogic.org/usbnutshell/usb5.htm
640.. _array: http://docs.python.org/library/array.html
641