usb_host_bulk – Continuous bulk transfers on USB host ports

This module keeps an endpoint busy in the background so that continuously-streaming devices, such as RTL2832U SDR dongles, never overflow. Devices are still found and configured with usb.core; usb_host manages the host ports themselves.

Available only on boards built with the PIO USB host and this feature enabled.

Available on these boards
  • Adafruit Fruit Jam

class usb_host_bulk.InStream(device: usb.core.Device, endpoint: int, *, buffer_size: int = 32768)

Continuously receive from a full-speed bulk IN endpoint in the background.

The USB host polls the endpoint every frame, independently of Python, and stores the payload in a ring of buffer_size bytes in internal SRAM.

Reads never block. To wait for data, wrap the stream with asyncio.StreamReader or poll in_waiting.

One stream per endpoint can run. They share the bandwidth of their host port.

Synchronous example:

import time
import usb.core
import usb_host_bulk

# Replace these with your device's vendor and product IDs.
device = usb.core.find(idVendor=0x0BDA, idProduct=0x2838)
if device is None:
    raise RuntimeError("USB device not found")
device.set_configuration()
# Many devices only start sending after device-specific setup, such as
# vendor requests made with device.ctrl_transfer(). Do that here.

buf = bytearray(8192)
received = 0
report_at = time.monotonic() + 1
with usb_host_bulk.InStream(device, 0x81) as stream:
    while True:
        n = stream.readinto(buf)  # None while nothing is waiting
        if n == 0:
            break  # the device stalled or was unplugged
        if n:
            received += n  # process buf[:n] here
        if time.monotonic() >= report_at:
            print("received", received, "bytes, lost packets:", stream.lost_packets)
            report_at += 1

asyncio example:

import asyncio
from asyncio import StreamReader
import usb.core
import usb_host_bulk

# Replace these with your device's vendor and product IDs.
device = usb.core.find(idVendor=0x0BDA, idProduct=0x2838)
if device is None:
    raise RuntimeError("USB device not found")
device.set_configuration()
# Many devices only start sending after device-specific setup, such as
# vendor requests made with device.ctrl_transfer(). Do that here.

received = 0

async def receive(stream):
    global received
    reader = StreamReader(stream)
    buf = bytearray(8192)
    while True:
        n = await reader.readinto(buf)
        if not n:
            break  # the device stalled or was unplugged
        received += n  # process buf[:n] here

async def report(stream):
    while True:
        await asyncio.sleep(1)
        print("received", received, "bytes, lost packets:", stream.lost_packets)

async def main():
    with usb_host_bulk.InStream(device, 0x81) as stream:
        reporter = asyncio.create_task(report(stream))
        await receive(stream)
        reporter.cancel()

asyncio.run(main())

asyncio.StreamReader(stream) is a CircuitPython and MicroPython idiom. Import StreamReader before starting the stream: asyncio loads it on first use, which can take long enough to overflow the ring. Use readinto rather than readexactly at high data rates, because readexactly allocates on every call.

Open endpoint on device and start capturing immediately.

Parameters:
  • device (usb.core.Device) – a configured device (call set_configuration() first)

  • endpoint (int) – bEndpointAddress of a bulk IN endpoint, 0x81 to 0x8F, with a maximum packet size of 64 bytes or less

  • buffer_size (int) – ring size in bytes, a power of two from 4096 to 65536

readinto(buf: circuitpython_typing.WriteableBuffer, nbytes: int | None = None) → int | None

Copy waiting bytes into buf, at most nbytes of them if given.

Capture ends when the stream is deinited, which drops any bytes not yet read. It also ends on its own when the device stalls the endpoint, is unplugged, or is reconfigured. Bytes captured before that can still be read.

Returns:

the number of bytes copied, None if nothing is waiting yet, or 0 once capture has ended and nothing is left to read

Return type:

int or None

read(nbytes: int | None = None) → bytes | None

Same as readinto, but allocates and returns bytes: None if nothing is waiting yet, b"" once capture has ended and nothing is left to read.

in_waiting: int

Bytes waiting to be read, including those left when capture ended on its own. (read-only)

lost_packets: int

Packets dropped because the ring was full, meaning reads were not frequent enough. Zero means the captured stream has no gaps. Readable after deinit. (read-only)

reset_input_buffer() → None

Discard every byte waiting in the ring. Raises ValueError once the stream is deinited, because no more data will come.

deinit() → None

Stop capture and free the ring, dropping any bytes not yet read.

__enter__() → InStream

No-op used by Context Managers.

__exit__() → None

Automatically deinitializes when exiting a context. See Lifetime and ContextManagers for more info.