usb-stack 0.3.0

MCU-independent USB device and host stack core: bus traits, control transfers, enumeration, classes (CDC-ACM, HID, GS_USB, i2c-tiny-usb, UAC 1.0) and a HID host
Documentation
//! Host-side USB stack.
//!
//! The host stack is split the same way as the device stack: everything below
//! the controller is hardware independent, and a peripheral driver implements
//! [`HostController`].
//!
//! ```text
//!   application                  class::hid::Keyboard, class::hub::Hub, your own driver
//!   ────────────────────────
//!   Device                       enumeration, control transfers
//!   Pipe                         bulk and interrupt transfers
//!   ────────────────────────
//!   HostController               trait: port, channels, transactions
//!   ────────────────────────
//!   (a peripheral driver)        implements HostController
//! ```
//!
//! Transfers are expressed at transaction level and driven synchronously: a
//! call blocks until the controller halts the channel, so no interrupts, no DMA
//! and no `async` are involved. Enumeration is a fixed sequence of control
//! transfers ([`Host::enumerate`] runs it), and everything a device offers
//! afterwards is reachable through [`Device::control`] and [`Pipe`].
//!
//! ## What is covered
//!
//! - Root port and hubs: [`class::hub::Hub`] powers the downstream ports,
//!   resets them and enumerates what is attached; a hub found behind a hub can
//!   be opened the same way, so cascades work
//! - Control, bulk and interrupt transfers at low, full and high speed
//! - Device, configuration, interface, endpoint and string descriptors
//! - Classes: HID boot keyboards ([`class::hid::Keyboard`]) and hubs
//!   ([`class::hub::Hub`])
//!
//! Isochronous transfers are not implemented. Split transactions (the
//! transaction translator of a high-speed hub) are described by
//! [`HubRoute::translator`] but no controller in this workspace implements
//! them yet, so a FS/LS device behind a high-speed hub reports
//! [`HostError::Unsupported`]. Put the hub
//! on a full-speed host, or configure a high-speed host as FS/LS-only, and the
//! same devices enumerate without split transactions.
//!
//! ## Example
//!
//! ```ignore
//! use usb_stack::host::{Host, class::hid::Keyboard};
//!
//! let bus = Host::new(&my_controller);
//!
//! loop {
//!     let device = match bus.enumerate() {
//!         Ok(device) => device,
//!         Err(error) => continue, // nothing attached, or a device that misbehaves
//!     };
//!     if let Ok(keyboard) = Keyboard::open(&device) {
//!         let mut previous = Default::default();
//!         while let Ok(report) = keyboard.read() {
//!             for key in report.new_keys(&previous) {
//!                 defmt::info!("key {}", key);
//!             }
//!             previous = report;
//!         }
//!     }
//! }
//! ```

pub mod class;
pub mod controller;
pub mod descriptor;
pub mod device;
pub mod error;
pub mod pipe;

pub use crate::request::Request;
pub use controller::{
    Channel, DeviceAddress, EndpointConfig, HostController, HubRoute, PortStatus, Speed, Toggle,
    Translator,
};
pub use descriptor::{
    Configuration, Descriptor, Descriptors, DeviceDescriptor, EndpointDescriptor, Endpoints,
    Interface, Interfaces,
};
pub use device::{CONFIG_MAX, Device};
pub use error::{HostError, HostResult};
pub use pipe::Pipe;

/// The root port of a host controller.
///
/// This is the entry point of the stack: it reports the port, resets it and
/// enumerates what is attached. Everything else hangs off the [`Device`] that
/// [`enumerate`](Self::enumerate) returns.
pub struct Host<'d, C: HostController> {
    controller: &'d C,
}

impl<'d, C: HostController> Host<'d, C> {
    /// Wrap a controller. The controller must be powered up already.
    #[inline]
    pub const fn new(controller: &'d C) -> Self {
        Self { controller }
    }

    /// Read the root port without changing anything.
    #[inline]
    pub fn port(&self) -> PortStatus {
        self.controller.port_status()
    }

    /// Power the port, drive a bus reset and report the negotiated speed.
    ///
    /// A device has to be attached; this is what enumeration starts with.
    #[inline]
    pub fn reset(&self) -> HostResult<PortStatus> {
        self.controller.reset_port()
    }

    /// Wait up to a second for a device to be attached.
    pub fn wait_for_device(&self) -> HostResult<PortStatus> {
        for _ in 0..1000 {
            let status = self.controller.port_status();
            if status.connected {
                return Ok(status);
            }
            self.controller.wait_millis(1);
        }
        Err(HostError::Timeout)
    }

    /// Reset the port and enumerate the attached device at the first free
    /// address.
    pub fn enumerate(&self) -> HostResult<Device<'d, C>> {
        self.enumerate_at(DeviceAddress::FIRST)
    }

    /// Reset the port and enumerate the attached device at `address`.
    pub fn enumerate_at(&self, address: DeviceAddress) -> HostResult<Device<'d, C>> {
        let status = self.controller.reset_port()?;
        if !status.enabled {
            return Err(HostError::Disconnected);
        }
        Device::enumerate(self.controller, address, status.speed)
    }
}

/// The addresses handed out to enumerated devices.
///
/// Address zero is reserved for enumeration and never handed out; the pool
/// tracks 1 through 126. A root-port device and every device behind a hub need
/// an address of their own, so a host that supports hubs keeps one of these
/// and hands each [`Device`] the address it was enumerated at.
pub struct AddressPool {
    used: [bool; 127],
}

impl AddressPool {
    /// An empty pool.
    pub const fn new() -> Self {
        Self { used: [false; 127] }
    }

    /// Take the lowest free address, or `None` when all 126 are in use.
    pub fn take(&mut self) -> Option<DeviceAddress> {
        for value in DeviceAddress::FIRST.raw()..127 {
            if !self.used[value as usize] {
                self.used[value as usize] = true;
                return Some(DeviceAddress::new(value));
            }
        }
        None
    }

    /// Mark `address` as used, for a device that was enumerated by the
    /// application rather than taken from this pool.
    pub fn reserve(&mut self, address: DeviceAddress) {
        self.used[address.raw() as usize] = true;
    }

    /// Give `address` back when the device is unplugged.
    pub fn release(&mut self, address: DeviceAddress) {
        self.used[address.raw() as usize] = false;
    }

    /// Whether `address` has been taken or reserved.
    pub fn is_used(&self, address: DeviceAddress) -> bool {
        self.used[address.raw() as usize]
    }
}

impl Default for AddressPool {
    fn default() -> Self {
        Self::new()
    }
}