machine.USBDevice — USB device driver
Note
machine.USBDevice currently only supports the esp32, rp2 and samd ports. Native USB support is also required, and not all boards support native USB.
USBDevice provides a low-level Python API for implementing USB device functionality using Python code.
Warning
This low-level API assumes you are familiar with the USB standards. There are high-level usb driver modules in micropython-lib, which provide a simpler interface and more built-in functionality.
Terminology
A “runtime” USB device interface or driver is one defined using this Python API after MicroPython has initially started. A “builtin” USB device interface or driver is one compiled into the MicroPython firmware and always available. For example, the USB-CDC (serial port) that is usually enabled by default. The builtin USB-MSC (mass storage) is an option on some ports.
Lifecycle
Managing runtime USB interfaces can be tricky, especially if you communicate with MicroPython over a builtin USB-CDC serial port that is part of the same USB device.
A MicroPython soft reset will always clear all runtime USB interfaces, which causes the entire USB device to disconnect from the host. If MicroPython also provides a builtin USB-CDC serial port, it will reappear after the soft reset.
This means that some functions targeting the USB-CDC serial port (such as mpremote run) will fail immediately if a runtime USB interface is active, because the port disappears when mpremote triggers a soft reset. The operation should succeed on the second attempt, because there are no longer any runtime USB interfaces after the soft reset.
To configure the runtime USB device at every boot, it is recommended to place the configuration code in a boot.py file on the device VFS. At each reset, this file is executed before the USB subsystem is initialized (before main.py), so it allows the board to start the runtime USB device immediately.
For development or debugging, it can be convenient to connect a hardware serial REPL and completely disable the builtin USB-CDC serial port. Not all ports support this (currently only rp2). Custom builds should be configured with #define MICROPY_HW_USB_CDC (0) and #define MICROPY_HW_ENABLE_UART_REPL (1).
- class machine.USBDevice
Construct a USBDevice object.
Note
This object is a singleton; each call to this constructor returns the same object reference.
- config(desc_dev, desc_cfg, desc_strs=None, open_itf_cb=None, reset_cb=None, control_xfer_cb=None, xfer_cb=None)
Configure the USBDevice singleton object, setting the USB runtime device state and callback functions:
desc_dev - A bytes-like object containing the new USB device descriptor.
desc_cfg - A bytes-like object containing the new USB configuration descriptor.
desc_strs - An optional string or bytes object containing the USB string descriptor values. It can be a list, dict, or any object that supports subscript indexing with integer keys (USB string descriptor indices). Strings are an optional USB feature; this parameter can be left unset (the default) if no strings are referenced in the device and configuration descriptors, or if only builtin strings should be used. Except for index 0, all string values should be plain ASCII. Index 0 is the special “language” USB descriptor, represented by a bytes object in a custom format defined in the USB standard. To use the default “English” language descriptor, None can be returned at index 0. To fall back to providing the builtin string value for a given index, the subscript lookup can return None, raise KeyError, or raise IndexError.
open_itf_cb - This callback is called once for each interface or interface association descriptor in response to the USB host’s Set Configuration request (the last stage before the USB device becomes available to the host). The callback takes one argument, which is a memoryview of the interface or IAD descriptor accepted by the host (including all associated descriptors). It is a view of the same desc_cfg object provided to this function as a separate argument. The memoryview is only valid until the callback function returns.
reset_cb - This callback is called when the USB host performs a bus reset. The callback takes no arguments. Any transfers in progress will not complete. The USB host will most likely re-enumerate the USB device by calling the descriptor callbacks and then open_itf_cb().
control_xfer_cb - This callback is called one or more times for each USB control transfer (device endpoint 0). It takes two arguments. The first argument is the control transfer stage. It is one of the following: 1 for the SETUP stage. 2 for the DATA stage. 3 for the ACK stage. The second argument is a memoryview for reading the USB control request data for this stage. The memoryview is only valid until the callback function returns. The data in this memoryview remains the same across the three stages of a single transfer. A successful transfer consists of this callback being called for the three stages in order. In general, if the device wants to do something in response to a control request, it is best to wait until the ACK stage to confirm that the host controller has completed the transfer as expected. The callback should return one of the following values: False to stall the endpoint and reject the transfer. It will not continue to any remaining stages. True to continue the transfer to the next stage. A buffer object can be returned in the SETUP stage when the transfer will send or receive additional data. This is usually the case when the wLength field in the request has a non-zero value. For OUT direction transfers, this should be a writable buffer; for IN direction transfers, this should be a readable buffer with the data.
xfer_cb - This callback is called whenever a non-control transfer submitted by calling USBDevice.submit_xfer() completes. The callback has three arguments: The endpoint number of the completed transfer. The result value: True if the transfer succeeded, otherwise False. The number of bytes successfully transferred. In the case of a “short” transfer, the result is True and xferred_bytes will be less than the length of the buffer submitted for the transfer.
Note
If a bus reset occurs (see USBDevice.reset()), xfer_cb will not be called for any transfers that have not yet completed.
- active([value])
Return the current active state of this runtime USB device as a boolean. The runtime USB device is “active” when it is available to interact with the host; this does not mean that a USB host is actually present. If the optional value argument is set to a true value, the USB device will be activated. If the optional value argument is set to a false value, the USB device is deactivated. When the USB device is deactivated, the USB host will not detect it. To simulate disconnecting and reconnecting the USB device, call active(False) and then active(True). This may be necessary if the runtime device configuration has changed, so that the host sees the new device.
- builtin_driver
This attribute holds the current builtin driver configuration and must be set to one of the USBDevice.BUILTIN_ named constants defined on this object. By default, it holds the value USBDevice.BUILTIN_NONE. When setting this field, the runtime USB device must be inactive. Call the USBDevice.active() function if necessary to deactivate it before setting (and activate it again after setting). If this value is set to anything other than USBDevice.BUILTIN_NONE, the following restrictions apply to the USBDevice.config() arguments:
desc_cfg should begin with the builtin USB interface descriptor data accessible via the USBDevice.builtin_driver attribute desc_cfg.
Descriptors appended after the builtin configuration descriptor should use interface, string and endpoint numbers starting from the maximum builtin values defined in the USBDevice.builtin_driver attributes itf_max, str_max and ep_max.
If any new interfaces are appended to the end of desc_cfg, the bNumInterfaces field in the builtin configuration descriptor also needs to be updated.
desc_strs should be None or a list/dict in which index values less than USBDevice.builtin_driver.str_max are missing or have a value of None. This reserves those string indices for the builtin driver. Placing a different string at any of these indices will override that string in the builtin driver.
- remote_wakeup()
Wake the host if we are in suspend mode and the host has enabled the REMOTE_WAKEUP feature. This must be enabled in the USB attributes and enabled on the host. Returns True if remote wakeup is enabled and active and the host has been woken.
- submit_xfer(ep, buffer)
Submit a USB transfer on endpoint number ep. buffer must be an object implementing the buffer interface, with read access for IN endpoints and write access for OUT endpoints.
Note
ep cannot be the control endpoint number 0. Control transfers are built up by successive calls to control_xfer_cb, see above.
Returns True if successful, or False if the transfer could not be queued (because the USB device is not configured by the host, or because another transfer is already queued on this endpoint). When the USB host completes the transfer, the xfer_cb callback is called (see above). If the USB device is not active, an OSError is raised with the reason MP_EINVAL.
- stall(ep[, stall])
Call this function to get or set the STALL state of a device endpoint. ep is the endpoint number. If the optional stall argument is set, it is a boolean flag for the STALL state. The return value is the current stall state of the endpoint (before any changes made by this function). An endpoint set to STALL may remain stalled until this function is called again, or the STALL may be automatically cleared by the USB host. If the USB device is not active, an OSError is raised with the reason MP_EINVAL.
- BUILTIN_NONE
- BUILTIN_DEFAULT
- BUILTIN_CDC
- BUILTIN_MSC
- BUILTIN_CDC_MSC
These constant objects hold the builtin descriptor data compiled into the MicroPython firmware. USBDevice.BUILTIN_NONE and USBDevice.BUILTIN_DEFAULT always exist. Depending on the firmware build configuration and the actual builtin driver, other objects may exist.
Note
Currently, at most one of USBDevice.BUILTIN_CDC, USBDevice.BUILTIN_MSC and USBDevice.BUILTIN_CDC_MSC is defined, and it will be the same object as USBDevice.BUILTIN_DEFAULT. These constants are defined to allow runtime detection of the builtin driver (if any). Support for selecting one of multiple builtin driver configurations may be added in the future.
These values are assigned to USBDevice.builtin_driver to get/set the builtin configuration. Each object contains the following read-only fields:
itf_max - One greater than the highest bInterfaceNumber value used in the builtin configuration descriptor.
ep_max - One greater than the highest bEndpointAddress value used in the builtin configuration descriptor. Does not include any IN flag bit (0x80).
str_max - One greater than the highest string descriptor index value used by any builtin descriptor.
desc_dev - A bytes object containing the builtin USB device descriptor.
desc_cfg - A bytes object containing the complete builtin USB configuration descriptor.