usb_stack/host/mod.rs
1//! Host-side USB stack.
2//!
3//! The host stack is split the same way as the device stack: everything below
4//! the controller is hardware independent, and a peripheral driver implements
5//! [`HostController`].
6//!
7//! ```text
8//! application class::hid::Keyboard, class::hub::Hub, your own driver
9//! ────────────────────────
10//! Device enumeration, control transfers
11//! Pipe bulk and interrupt transfers
12//! ────────────────────────
13//! HostController trait: port, channels, transactions
14//! ────────────────────────
15//! (a peripheral driver) implements HostController
16//! ```
17//!
18//! Transfers are expressed at transaction level and driven synchronously: a
19//! call blocks until the controller halts the channel, so no interrupts, no DMA
20//! and no `async` are involved. Enumeration is a fixed sequence of control
21//! transfers ([`Host::enumerate`] runs it), and everything a device offers
22//! afterwards is reachable through [`Device::control`] and [`Pipe`].
23//!
24//! ## What is covered
25//!
26//! - Root port and hubs: [`class::hub::Hub`] powers the downstream ports,
27//! resets them and enumerates what is attached; a hub found behind a hub can
28//! be opened the same way, so cascades work
29//! - Control, bulk and interrupt transfers at low, full and high speed
30//! - Device, configuration, interface, endpoint and string descriptors
31//! - Classes: HID boot keyboards ([`class::hid::Keyboard`]) and hubs
32//! ([`class::hub::Hub`])
33//!
34//! Isochronous transfers are not implemented. Split transactions (the
35//! transaction translator of a high-speed hub) are described by
36//! [`HubRoute::translator`] but no controller in this workspace implements
37//! them yet, so a FS/LS device behind a high-speed hub reports
38//! [`HostError::Unsupported`]. Put the hub
39//! on a full-speed host, or configure a high-speed host as FS/LS-only, and the
40//! same devices enumerate without split transactions.
41//!
42//! ## Example
43//!
44//! ```ignore
45//! use usb_stack::host::{Host, class::hid::Keyboard};
46//!
47//! let bus = Host::new(&my_controller);
48//!
49//! loop {
50//! let device = match bus.enumerate() {
51//! Ok(device) => device,
52//! Err(error) => continue, // nothing attached, or a device that misbehaves
53//! };
54//! if let Ok(keyboard) = Keyboard::open(&device) {
55//! let mut previous = Default::default();
56//! while let Ok(report) = keyboard.read() {
57//! for key in report.new_keys(&previous) {
58//! defmt::info!("key {}", key);
59//! }
60//! previous = report;
61//! }
62//! }
63//! }
64//! ```
65
66pub mod class;
67pub mod controller;
68pub mod descriptor;
69pub mod device;
70pub mod error;
71pub mod pipe;
72
73pub use crate::request::Request;
74pub use controller::{
75 Channel, DeviceAddress, EndpointConfig, HostController, HubRoute, PortStatus, Speed, Toggle,
76 Translator,
77};
78pub use descriptor::{
79 Configuration, Descriptor, Descriptors, DeviceDescriptor, EndpointDescriptor, Endpoints,
80 Interface, Interfaces,
81};
82pub use device::{CONFIG_MAX, Device};
83pub use error::{HostError, HostResult};
84pub use pipe::Pipe;
85
86/// The root port of a host controller.
87///
88/// This is the entry point of the stack: it reports the port, resets it and
89/// enumerates what is attached. Everything else hangs off the [`Device`] that
90/// [`enumerate`](Self::enumerate) returns.
91pub struct Host<'d, C: HostController> {
92 controller: &'d C,
93}
94
95impl<'d, C: HostController> Host<'d, C> {
96 /// Wrap a controller. The controller must be powered up already.
97 #[inline]
98 pub const fn new(controller: &'d C) -> Self {
99 Self { controller }
100 }
101
102 /// Read the root port without changing anything.
103 #[inline]
104 pub fn port(&self) -> PortStatus {
105 self.controller.port_status()
106 }
107
108 /// Power the port, drive a bus reset and report the negotiated speed.
109 ///
110 /// A device has to be attached; this is what enumeration starts with.
111 #[inline]
112 pub fn reset(&self) -> HostResult<PortStatus> {
113 self.controller.reset_port()
114 }
115
116 /// Wait up to a second for a device to be attached.
117 pub fn wait_for_device(&self) -> HostResult<PortStatus> {
118 for _ in 0..1000 {
119 let status = self.controller.port_status();
120 if status.connected {
121 return Ok(status);
122 }
123 self.controller.wait_millis(1);
124 }
125 Err(HostError::Timeout)
126 }
127
128 /// Reset the port and enumerate the attached device at the first free
129 /// address.
130 pub fn enumerate(&self) -> HostResult<Device<'d, C>> {
131 self.enumerate_at(DeviceAddress::FIRST)
132 }
133
134 /// Reset the port and enumerate the attached device at `address`.
135 pub fn enumerate_at(&self, address: DeviceAddress) -> HostResult<Device<'d, C>> {
136 let status = self.controller.reset_port()?;
137 if !status.enabled {
138 return Err(HostError::Disconnected);
139 }
140 Device::enumerate(self.controller, address, status.speed)
141 }
142}
143
144/// The addresses handed out to enumerated devices.
145///
146/// Address zero is reserved for enumeration and never handed out; the pool
147/// tracks 1 through 126. A root-port device and every device behind a hub need
148/// an address of their own, so a host that supports hubs keeps one of these
149/// and hands each [`Device`] the address it was enumerated at.
150pub struct AddressPool {
151 used: [bool; 127],
152}
153
154impl AddressPool {
155 /// An empty pool.
156 pub const fn new() -> Self {
157 Self { used: [false; 127] }
158 }
159
160 /// Take the lowest free address, or `None` when all 126 are in use.
161 pub fn take(&mut self) -> Option<DeviceAddress> {
162 for value in DeviceAddress::FIRST.raw()..127 {
163 if !self.used[value as usize] {
164 self.used[value as usize] = true;
165 return Some(DeviceAddress::new(value));
166 }
167 }
168 None
169 }
170
171 /// Mark `address` as used, for a device that was enumerated by the
172 /// application rather than taken from this pool.
173 pub fn reserve(&mut self, address: DeviceAddress) {
174 self.used[address.raw() as usize] = true;
175 }
176
177 /// Give `address` back when the device is unplugged.
178 pub fn release(&mut self, address: DeviceAddress) {
179 self.used[address.raw() as usize] = false;
180 }
181
182 /// Whether `address` has been taken or reserved.
183 pub fn is_used(&self, address: DeviceAddress) -> bool {
184 self.used[address.raw() as usize]
185 }
186}
187
188impl Default for AddressPool {
189 fn default() -> Self {
190 Self::new()
191 }
192}