|
| 1 | +.. currentmodule:: machine |
| 2 | +.. _machine.USBDevice: |
| 3 | + |
| 4 | +class USBDevice -- USB Device driver |
| 5 | +==================================== |
| 6 | + |
| 7 | +.. note:: ``machine.USBDevice`` is currently only supported on the rp2 and samd |
| 8 | + ports. |
| 9 | + |
| 10 | +USBDevice provides a low-level Python API for implementing USB device functions using |
| 11 | +Python code. This low-level API assumes familiarity with the USB standard. It's |
| 12 | +not recommended to use this API directly, instead install the high-level usbd |
| 13 | +module from micropython-lib. |
| 14 | + |
| 15 | +.. warning:: This functionality is very new and the high-level usbd module is |
| 16 | + not yet merged into micropython-lib. It can be found `here on |
| 17 | + GitHub <https://github.com/micropython/micropython-lib/pull/558>`_. |
| 18 | + |
| 19 | +Terminology |
| 20 | +----------- |
| 21 | + |
| 22 | +- A "Runtime" USB device interface or driver is one which is defined using this |
| 23 | + Python API after MicroPython initially starts up. |
| 24 | + |
| 25 | +- A "Built-in" USB device interface or driver is one that is compiled into the |
| 26 | + MicroPython firmware, and is always available. Examples are USB-CDC (serial |
| 27 | + port) which is usually enabled by default. Built-in USB-MSC (Mass Storage) is an |
| 28 | + option on some ports. |
| 29 | + |
| 30 | +Lifecycle |
| 31 | +--------- |
| 32 | + |
| 33 | +Managing a runtime USB interface can be tricky, especially if you are communicating |
| 34 | +with MicroPython over a built-in USB-CDC serial port that's part of the same USB |
| 35 | +device. |
| 36 | + |
| 37 | +- A MicroPython soft reset will always clear all runtime USB interfaces, which |
| 38 | + results in the entire USB device disconnecting from the host. If MicroPython |
| 39 | + is also providing a built-in USB-CDC serial port then this will re-appear |
| 40 | + after the soft reset. |
| 41 | + |
| 42 | + This means some functions (like ``mpremote run``) that target the USB-CDC |
| 43 | + serial port will immediately fail if a runtime USB interface is active, |
| 44 | + because the port goes away when ``mpremote`` triggers a soft reset. The |
| 45 | + operation should succeed on the second try, as after the soft reset there is |
| 46 | + no more runtime USB interface. |
| 47 | + |
| 48 | +- To configure a runtime USB device on every boot, it's recommended to place the |
| 49 | + configuration code in the ``boot.py`` file on the :ref:`device VFS |
| 50 | + <filesystem>`. On each reset this file is executed before the USB subsystem is |
| 51 | + initialised (and before ``main.py``), so it allows the board to come up with the runtime |
| 52 | + USB device immediately. |
| 53 | + |
| 54 | +- For development or debugging, it may be convenient to connect a hardware |
| 55 | + serial REPL and disable the built-in USB-CDC serial port entirely. Not all ports |
| 56 | + support this (currently only ``rp2``). The custom build should be configured |
| 57 | + with ``#define MICROPY_HW_USB_CDC (0)`` and ``#define |
| 58 | + MICROPY_HW_ENABLE_UART_REPL (1)``. |
| 59 | + |
| 60 | +Constructors |
| 61 | +------------ |
| 62 | + |
| 63 | +.. class:: USBDevice() |
| 64 | + |
| 65 | + Construct a USBDevice object. |
| 66 | + |
| 67 | + .. note:: This object is a singleton, each call to this constructor |
| 68 | + returns the same object reference. |
| 69 | + |
| 70 | +Methods |
| 71 | +------- |
| 72 | + |
| 73 | +.. method:: USBDevice.config(desc_dev, desc_cfg, desc_strs=None, open_itf_cb=None, reset_cb=None, control_xfer_cb=None, xfer_cb=None) |
| 74 | + |
| 75 | + Configures the ``USBDevice`` singleton object with the USB runtime device |
| 76 | + state and callback functions: |
| 77 | + |
| 78 | + - ``desc_dev`` - A bytes-like object containing |
| 79 | + the new USB device descriptor. |
| 80 | + |
| 81 | + - ``desc_cfg`` - A bytes-like object containing the |
| 82 | + new USB configuration descriptor. |
| 83 | + |
| 84 | + - ``desc_strs`` - Optional object holding strings or bytes objects |
| 85 | + containing USB string descriptor values. Can be a list, a dict, or any |
| 86 | + object which supports subscript indexing with integer keys (USB string |
| 87 | + descriptor index). |
| 88 | + |
| 89 | + Strings are an optional USB feature, and this parameter can be unset |
| 90 | + (default) if no strings are referenced in the device and configuration |
| 91 | + descriptors, or if only built-in strings should be used. |
| 92 | + |
| 93 | + Apart from index 0, all the string values should be plain ASCII. Index 0 |
| 94 | + is the special "languages" USB descriptor, represented as a bytes object |
| 95 | + with a custom format defined in the USB standard. ``None`` can be |
| 96 | + returned at index 0 in order to use a default "English" language |
| 97 | + descriptor. |
| 98 | + |
| 99 | + To fall back to providing a built-in string value for a given index, a |
| 100 | + subscript lookup can return ``None``, raise ``KeyError``, or raise |
| 101 | + ``IndexError``. |
| 102 | + |
| 103 | + - ``open_itf_cb`` - This callback is called once for each interface |
| 104 | + or Interface Association Descriptor in response to a Set |
| 105 | + Configuration request from the USB Host (the final stage before |
| 106 | + the USB device is available to the host). |
| 107 | + |
| 108 | + The callback takes a single argument, which is a memoryview of the |
| 109 | + interface or IAD descriptor that the host is accepting (including |
| 110 | + all associated descriptors). It is a view into the same |
| 111 | + ``desc_cfg`` object that was provided as a separate |
| 112 | + argument to this function. The memoryview is only valid until the |
| 113 | + callback function returns. |
| 114 | + |
| 115 | + - ``reset_cb`` - This callback is called when the USB host performs |
| 116 | + a bus reset. The callback takes no arguments. Any in-progress |
| 117 | + transfers will never complete. The USB host will most likely |
| 118 | + proceed to re-enumerate the USB device by calling the descriptor |
| 119 | + callbacks and then ``open_itf_cb()``. |
| 120 | + |
| 121 | + - ``control_xfer_cb`` - This callback is called one or more times |
| 122 | + for each USB control transfer (device Endpoint 0). It takes two |
| 123 | + arguments. |
| 124 | + |
| 125 | + The first argument is the control transfer stage. It is one of: |
| 126 | + |
| 127 | + - ``1`` for SETUP stage. |
| 128 | + - ``2`` for DATA stage. |
| 129 | + - ``3`` for ACK stage. |
| 130 | + |
| 131 | + Second argument is a memoryview to read the USB control request |
| 132 | + data for this stage. The memoryview is only valid until the |
| 133 | + callback function returns. |
| 134 | + |
| 135 | + The callback should return one of the following values: |
| 136 | + |
| 137 | + - ``False`` to stall the endpoint and reject the transfer. |
| 138 | + - ``True`` to continue the transfer to the next stage. |
| 139 | + - A buffer object to provide data for this stage of the transfer. |
| 140 | + This should be a writable buffer for an ``OUT`` direction transfer, or a |
| 141 | + readable buffer with data for an ``IN`` direction transfer. |
| 142 | + |
| 143 | + - ``xfer_cb`` - This callback is called whenever a non-control |
| 144 | + transfer submitted by calling :func:`USBDevice.submit_xfer` completes. |
| 145 | + |
| 146 | + The callback has three arguments: |
| 147 | + |
| 148 | + 1. The Endpoint number for the completed transfer. |
| 149 | + 2. Result value: ``True`` if the transfer succeeded, ``False`` |
| 150 | + otherwise. |
| 151 | + 3. Number of bytes successfully transferred. In the case of a |
| 152 | + "short" transfer, The result is ``True`` and ``xferred_bytes`` |
| 153 | + will be smaller than the length of the buffer submitted for the |
| 154 | + transfer. |
| 155 | + |
| 156 | + .. note:: If a bus reset occurs (see :func:`USBDevice.reset`), |
| 157 | + ``xfer_cb`` is not called for any transfers that have not |
| 158 | + already completed. |
| 159 | + |
| 160 | +.. method:: USBDevice.active(self, [value] /) |
| 161 | + |
| 162 | + Returns the current active state of this runtime USB device as a |
| 163 | + boolean. The runtime USB device is "active" when it is available to |
| 164 | + interact with the host, it doesn't mean that a USB Host is actually |
| 165 | + present. |
| 166 | + |
| 167 | + If the optional ``value`` argument is set to a truthy value, then |
| 168 | + the USB device will be activated. |
| 169 | + |
| 170 | + If the optional ``value`` argument is set to a falsey value, then |
| 171 | + the USB device is deactivated. While the USB device is deactivated, |
| 172 | + it will not be detected by the USB Host. |
| 173 | + |
| 174 | + To simulate a disconnect and a reconnect of the USB device, call |
| 175 | + ``active(False)`` followed by ``active(True)``. This may be |
| 176 | + necessary if the runtime device configuration has changed, so that |
| 177 | + the host sees the new device. |
| 178 | + |
| 179 | +.. attribute:: USDBD.builtin_driver |
| 180 | + |
| 181 | + This attribute holds the current built-in driver configuration, and must be |
| 182 | + set to one of the ``USBDevice.BUILTIN_`` named constants defined on this object. |
| 183 | + |
| 184 | + By default it holds the value :data:`USBDevice.BUILTIN_NONE`. |
| 185 | + |
| 186 | + Runtime USB device must be inactive when setting this field. Call the |
| 187 | + :func:`USBDevice.active` function to deactivate before setting if necessary |
| 188 | + (and again to activate after setting). |
| 189 | + |
| 190 | + If this value is set to any value other than :data:`USBDevice.BUILTIN_NONE` then |
| 191 | + the following restrictions apply to the :func:`USBDevice.config` arguments: |
| 192 | + |
| 193 | + - ``desc_cfg`` should begin with the built-in USB interface descriptor data |
| 194 | + accessible via :data:`USBDevice.builtin_driver` attribute ``desc_cfg``. |
| 195 | + Descriptors appended after the built-in configuration descriptors should use |
| 196 | + interface, string and endpoint numbers starting from the max built-in values |
| 197 | + defined in :data:`USBDevice.builtin_driver` attributes ``itf_max``, ``str_max`` and |
| 198 | + ``ep_max``. |
| 199 | + |
| 200 | + - The ``bNumInterfaces`` field in the built-in configuration |
| 201 | + descriptor will also need to be updated if any new interfaces |
| 202 | + are appended to the end of ``desc_cfg``. |
| 203 | + |
| 204 | + - ``desc_strs`` should either be ``None`` or a list/dictionary where index |
| 205 | + values less than ``USBDevice.builtin_driver.str_max`` are missing or have |
| 206 | + value ``None``. This reserves those string indexes for the built-in |
| 207 | + drivers. Placing a different string at any of these indexes overrides that |
| 208 | + string in the built-in driver. |
| 209 | + |
| 210 | +.. method:: USBDevice.submit_xfer(self, ep, buffer /) |
| 211 | + |
| 212 | + Submit a USB transfer on endpoint number ``ep``. ``buffer`` must be |
| 213 | + an object implementing the buffer interface, with read access for |
| 214 | + ``IN`` endpoints and write access for ``OUT`` endpoints. |
| 215 | + |
| 216 | + .. note:: ``ep`` cannot be the control Endpoint number 0. Control |
| 217 | + transfers are built up through successive executions of |
| 218 | + ``control_xfer_cb``, see above. |
| 219 | + |
| 220 | + Returns ``True`` if successful, ``False`` if the transfer could not |
| 221 | + be queued (as USB device is not configured by host, or because |
| 222 | + another transfer is queued on this endpoint.) |
| 223 | + |
| 224 | + When the USB host completes the transfer, the ``xfer_cb`` callback |
| 225 | + is called (see above). |
| 226 | + |
| 227 | + Raises ``OSError`` with reason ``MP_EINVAL`` If the USB device is not |
| 228 | + active. |
| 229 | + |
| 230 | +.. method:: USBDevice.stall(self, ep, [stall] /) |
| 231 | + |
| 232 | + Calling this function gets or sets the STALL state of a device endpoint. |
| 233 | + |
| 234 | + ``ep`` is the number of the endpoint. |
| 235 | + |
| 236 | + If the optional ``stall`` parameter is set, this is a boolean flag |
| 237 | + for the STALL state. |
| 238 | + |
| 239 | + The return value is the current stall state of the endpoint (before |
| 240 | + any change made by this function). |
| 241 | + |
| 242 | + An endpoint that is set to STALL may remain stalled until this |
| 243 | + function is called again, or STALL may be cleared automatically by |
| 244 | + the USB host. |
| 245 | + |
| 246 | + Raises ``OSError`` with reason ``MP_EINVAL`` If the USB device is not |
| 247 | + active. |
| 248 | + |
| 249 | +Constants |
| 250 | +--------- |
| 251 | + |
| 252 | +.. data:: USBDevice.BUILTIN_NONE |
| 253 | +.. data:: USBDevice.BUILTIN_DEFAULT |
| 254 | +.. data:: USBDevice.BUILTIN_CDC |
| 255 | +.. data:: USBDevice.BUILTIN_MSC |
| 256 | +.. data:: USBDevice.BUILTIN_CDC_MSC |
| 257 | + |
| 258 | + These constant objects hold the built-in descriptor data which is |
| 259 | + compiled into the MicroPython firmware. ``USBDevice.BUILTIN_NONE`` and |
| 260 | + ``USBDevice.BUILTIN_DEFAULT`` are always present. Additional objects may be present |
| 261 | + depending on the firmware build configuration and the actual built-in drivers. |
| 262 | + |
| 263 | + .. note:: Currently at most one of ``USBDevice.BUILTIN_CDC``, |
| 264 | + ``USBDevice.BUILTIN_MSC`` and ``USBDevice.BUILTIN_CDC_MSC`` is defined |
| 265 | + and will be the same object as ``USBDevice.BUILTIN_DEFAULT``. |
| 266 | + These constants are defined to allow run-time detection of |
| 267 | + the built-in driver (if any). Support for selecting one of |
| 268 | + multiple built-in driver configurations may be added in the |
| 269 | + future. |
| 270 | + |
| 271 | + These values are assigned to :data:`USBDevice.builtin_driver` to get/set the |
| 272 | + built-in configuration. |
| 273 | + |
| 274 | + Each object contains the following read-only fields: |
| 275 | + |
| 276 | + - ``itf_max`` - One more than the highest bInterfaceNumber value used |
| 277 | + in the built-in configuration descriptor. |
| 278 | + - ``ep_max`` - One more than the highest bEndpointAddress value used |
| 279 | + in the built-in configuration descriptor. Does not include any |
| 280 | + ``IN`` flag bit (0x80). |
| 281 | + - ``str_max`` - One more than the highest string descriptor index |
| 282 | + value used by any built-in descriptor. |
| 283 | + - ``desc_dev`` - ``bytes`` object containing the built-in USB device |
| 284 | + descriptor. |
| 285 | + - ``desc_cfg`` - ``bytes`` object containing the complete built-in USB |
| 286 | + configuration descriptor. |
0 commit comments