usb_stack/class/hid/mod.rs
1//! USB HID (Human Interface Device) class.
2//!
3//! The module is split in two halves:
4//!
5//! * [`HidClass`] — the USB side. It owns the interface and the interrupt
6//! endpoints, writes the interface/HID/endpoint descriptors, serves the report
7//! descriptor, answers the HID class requests (`Get/Set Report`,
8//! `Get/Set Idle`, `Get/Set Protocol`) and forwards reports to the device.
9//! * [`HidDevice`] — the HID side. A report descriptor, endpoint sizes and the
10//! reports the function exchanges with the host.
11//!
12//! Ready-made functions live in the submodules:
13//!
14//! | Function | Reports |
15//! |----------|---------|
16//! | [`keyboard::Keyboard`] | boot keyboard: 8-byte input, 1-byte LED output |
17//! | [`mouse::Mouse`] | boot mouse: 4-byte input |
18//! | [`custom::CustomHid`] | caller-supplied report descriptor |
19//! | [`power::PowerDevice`] | HID Power Device: status, measurements, battery, configuration, controls |
20//!
21//! # Example
22//!
23//! ```ignore
24//! use my_hal_usb::{UsbBusAllocator, UsbDeviceBuilder};
25//! use my_hal_usb::class::hid::{HidClass, keyboard::{Keyboard, KeyboardReport}};
26//! use my_hal_usb::MyBus;
27//!
28//! let alloc = UsbBusAllocator::new(MyBus::new(/* peripheral */));
29//! let mut kbd = HidClass::new(&alloc, Keyboard::new());
30//! let mut dev = UsbDeviceBuilder::new(&alloc, 0x2E8A, 0x000B)
31//! .product("Pico HID Keyboard")
32//! .build();
33//!
34//! loop {
35//! dev.poll(&mut [&mut kbd]);
36//!
37//! let report = KeyboardReport::default();
38//! let _ = kbd.send_input(&report.to_bytes());
39//! }
40//! ```
41//!
42//! # Reaching the device
43//!
44//! The class owns the device, so applications drive it through
45//! [`HidClass::device_mut`].
46
47pub mod custom;
48pub mod device;
49pub mod keyboard;
50pub mod mouse;
51pub mod power;
52
53pub use device::{HidDevice, HidSpec, ReportType};
54
55use crate::bus::{InterfaceNumber, UsbBus, UsbBusAllocator};
56use crate::class::UsbClass;
57use crate::control::{ControlIn, ControlOut, Recipient, RequestType, StandardRequest};
58use crate::descriptor::{DescriptorWriter, class_code};
59use crate::endpoint::{EndpointAddress, EndpointIn, EndpointOut, In, Out};
60use crate::error::{UsbError, UsbResult};
61
62// ─── HID constants ───────────────────────────────────────────────────────────
63
64/// HID subclass (`bInterfaceSubClass`).
65pub mod hid_subclass {
66 /// No subclass — report protocol only.
67 pub const NONE: u8 = 0x00;
68 /// Boot interface subclass — the device also implements a boot protocol.
69 pub const BOOT: u8 = 0x01;
70}
71
72/// HID protocol (`bInterfaceProtocol`), only meaningful for boot devices.
73pub mod hid_protocol {
74 /// No protocol.
75 pub const NONE: u8 = 0x00;
76 /// Keyboard boot protocol.
77 pub const KEYBOARD: u8 = 0x01;
78 /// Mouse boot protocol.
79 pub const MOUSE: u8 = 0x02;
80}
81
82/// Values exchanged by `Get Protocol` / `Set Protocol` (HID 1.11 §7.2.5).
83///
84/// Not to be confused with the interface descriptor's protocol field
85/// ([`hid_protocol`]), which says *which* boot protocol a device implements.
86pub mod hid_protocol_mode {
87 /// Boot protocol — reports use the fixed boot format.
88 pub const BOOT: u8 = 0x00;
89 /// Report protocol — reports follow the report descriptor.
90 pub const REPORT: u8 = 0x01;
91}
92
93/// HID class descriptor types.
94pub mod hid_descriptor_type {
95 /// HID descriptor (`0x21`), written by [`HidClass`](super::HidClass).
96 pub const HID: u8 = 0x21;
97 /// Report descriptor (`0x22`), served for `Get Descriptor`.
98 pub const REPORT: u8 = 0x22;
99 /// Physical descriptor (`0x23`), rarely used.
100 pub const PHYSICAL: u8 = 0x23;
101}
102
103/// HID class-specific request codes (`bRequest`).
104pub mod hid_request {
105 /// `Get Report` — read a report from the device.
106 pub const GET_REPORT: u8 = 0x01;
107 /// `Get Idle` — current idle rate, in 4 ms units.
108 pub const GET_IDLE: u8 = 0x02;
109 /// `Get Protocol` — `0` = boot protocol, `1` = report protocol.
110 pub const GET_PROTOCOL: u8 = 0x03;
111 /// `Set Report` — write a report to the device.
112 pub const SET_REPORT: u8 = 0x09;
113 /// `Set Idle` — set the idle rate.
114 pub const SET_IDLE: u8 = 0x0A;
115 /// `Set Protocol`.
116 pub const SET_PROTOCOL: u8 = 0x0B;
117}
118
119/// `bcdHID` value written to the HID descriptor (HID 1.11).
120const BCD_HID: u16 = 0x0111;
121
122/// Buffer for one interrupt OUT packet — the full-speed maximum packet size.
123const OUT_PACKET_MAX: usize = 64;
124
125// ─── HidClass ────────────────────────────────────────────────────────────────
126
127/// USB HID class — the transport for a [`HidDevice`].
128///
129/// Allocates one interface, an interrupt IN endpoint for input reports and, if
130/// the device's [`HidSpec`] asks for one, an interrupt OUT endpoint. The
131/// endpoint sizes and the interface class/protocol come from the device's spec.
132pub struct HidClass<'a, B: UsbBus, D> {
133 interface: InterfaceNumber,
134 int_in: EndpointIn<'a, B>,
135 int_out: Option<EndpointOut<'a, B>>,
136 idle_rate: u8,
137 protocol: u8,
138 configured: bool,
139 device: D,
140}
141
142impl<'a, B: UsbBus, D: HidDevice<B>> HidClass<'a, B, D> {
143 /// Create a HID class for `device`, allocating its interface and endpoints.
144 ///
145 /// Must be called before the [`UsbBusAllocator`] is frozen by building the
146 /// device.
147 pub fn new(alloc: &'a UsbBusAllocator<B>, device: D) -> Self {
148 let spec = device.spec();
149 let interface = alloc.interface();
150 let int_in = alloc.interrupt::<In>(spec.in_report_size, spec.poll_interval_ms);
151 let int_out = if spec.out_report_size == 0 {
152 None
153 } else {
154 Some(alloc.interrupt::<Out>(spec.out_report_size, spec.poll_interval_ms))
155 };
156 Self {
157 interface,
158 int_in,
159 int_out,
160 idle_rate: 0,
161 // Report protocol: devices here always send descriptor-format
162 // reports, and boot devices' descriptors match the boot format.
163 protocol: hid_protocol_mode::REPORT,
164 configured: false,
165 device,
166 }
167 }
168
169 // ── Device access ─────────────────────────────────────────────────────────
170
171 /// The wrapped HID function.
172 pub fn device(&self) -> &D {
173 &self.device
174 }
175
176 /// The wrapped HID function, to update its state from the main loop.
177 pub fn device_mut(&mut self) -> &mut D {
178 &mut self.device
179 }
180
181 // ── State ─────────────────────────────────────────────────────────────────
182
183 /// `true` once the host has configured the device.
184 pub fn is_configured(&self) -> bool {
185 self.configured
186 }
187
188 /// Interface number allocated for this function.
189 pub fn interface(&self) -> InterfaceNumber {
190 self.interface
191 }
192
193 /// Report descriptor served to the host.
194 pub fn report_descriptor(&self) -> &'static [u8] {
195 self.device.spec().report_descriptor
196 }
197
198 // ── Input reports ─────────────────────────────────────────────────────────
199
200 /// Send an input report to the host.
201 ///
202 /// `report` is the raw report, including the report ID byte when the
203 /// descriptor uses report IDs. Returns
204 /// [`WouldBlock`](UsbError::WouldBlock) when the previous report has not
205 /// been collected yet — the caller retries later.
206 pub fn send_input(&self, report: &[u8]) -> UsbResult<()> {
207 if !self.configured {
208 return Err(UsbError::InvalidState);
209 }
210 self.int_in.write(report).map(|_| ())
211 }
212
213 /// Let the device send the input reports it queued.
214 ///
215 /// Called automatically from every [`UsbClass::poll`], so calling it is only
216 /// useful to shorten the latency by one loop iteration.
217 pub fn flush(&mut self) {
218 if self.configured {
219 self.device.poll(&self.int_in);
220 }
221 }
222
223 // ── Helpers ───────────────────────────────────────────────────────────────
224
225 /// `true` if the request is a class/standard request addressed at this
226 /// function's interface.
227 fn is_our_interface(&self, request: &crate::control::Request) -> bool {
228 request.recipient == Recipient::Interface && request.index as u8 == u8::from(self.interface)
229 }
230
231 /// `true` if the device implements the boot protocol.
232 fn is_boot_device(&self) -> bool {
233 self.device.spec().subclass == hid_subclass::BOOT
234 }
235}
236
237// ─── UsbClass<B> implementation ───────────────────────────────────────────────
238
239impl<B: UsbBus, D: HidDevice<B>> UsbClass<B> for HidClass<'_, B, D> {
240 fn configuration_descriptors(&self, w: &mut DescriptorWriter) -> UsbResult<()> {
241 let spec = self.device.spec();
242 let num_endpoints = 1 + self.int_out.is_some() as u8;
243 w.interface(
244 self.interface,
245 num_endpoints,
246 class_code::HID,
247 spec.subclass,
248 spec.protocol,
249 )?;
250
251 // HID descriptor: one class descriptor follows, the report descriptor.
252 let report_len = spec.report_descriptor.len() as u16;
253 w.write(
254 hid_descriptor_type::HID,
255 &[
256 (BCD_HID >> 8) as u8,
257 BCD_HID as u8,
258 0x00, // bCountryCode — not localised
259 0x01, // bNumDescriptors
260 hid_descriptor_type::REPORT,
261 report_len as u8,
262 (report_len >> 8) as u8,
263 ],
264 )?;
265
266 w.endpoint(
267 self.int_in.address(),
268 self.int_in.ep_type(),
269 self.int_in.max_packet_size(),
270 spec.poll_interval_ms,
271 )?;
272
273 if let Some(ref ep) = self.int_out {
274 w.endpoint(
275 ep.address(),
276 ep.ep_type(),
277 ep.max_packet_size(),
278 spec.poll_interval_ms,
279 )?;
280 }
281
282 Ok(())
283 }
284
285 fn control_in(&mut self, xfer: ControlIn<'_, B>) {
286 let req = *xfer.request();
287
288 if !self.is_our_interface(&req) {
289 return;
290 }
291
292 match req.request_type {
293 // Get Descriptor (HID Report) — hand out the report descriptor.
294 RequestType::Standard if req.request == StandardRequest::GET_DESCRIPTOR => {
295 let (desc_type, _) = req.descriptor_type_index();
296 if desc_type == hid_descriptor_type::REPORT {
297 let _ = xfer.accept_with_static(self.device.spec().report_descriptor);
298 }
299 }
300 RequestType::Class => match req.request {
301 hid_request::GET_REPORT => {
302 let Some(report_type) = ReportType::from_w_value(req.value) else {
303 let _ = xfer.reject();
304 return;
305 };
306 let report_id = req.value as u8;
307 // The closure fills the control buffer from device state; an
308 // error leaves the request unanswered and the device layer
309 // stalls EP0.
310 let _ = xfer.accept(|buf| {
311 self.device
312 .get_report(report_type, report_id, buf)
313 .ok_or(UsbError::InvalidState)
314 });
315 }
316 // Idle rate is transport state: report it back, remember writes,
317 // and ignore its value (input reports are sent on change).
318 hid_request::GET_IDLE => {
319 let _ = xfer.accept_with(&[self.idle_rate]);
320 }
321 // Report protocol is always supported; a non-boot device has
322 // nothing else to offer, but answering is friendlier than
323 // stalling a host that asks anyway.
324 hid_request::GET_PROTOCOL => {
325 let _ = xfer.accept_with(&[self.protocol]);
326 }
327 _ => {
328 let _ = xfer.reject();
329 }
330 },
331 _ => {}
332 }
333 }
334
335 fn control_out(&mut self, xfer: ControlOut<'_, B>) {
336 let req = *xfer.request();
337
338 if !self.is_our_interface(&req) {
339 return;
340 }
341
342 if req.request_type != RequestType::Class {
343 return;
344 }
345
346 match req.request {
347 hid_request::SET_REPORT => {
348 let Some(report_type) = ReportType::from_w_value(req.value) else {
349 let _ = xfer.reject();
350 return;
351 };
352 let report_id = req.value as u8;
353 if self.device.set_report(report_type, report_id, xfer.data()) {
354 let _ = xfer.accept();
355 } else {
356 let _ = xfer.reject();
357 }
358 }
359 hid_request::SET_IDLE => {
360 self.idle_rate = (req.value >> 8) as u8;
361 let _ = xfer.accept();
362 }
363 // Only a boot device can be asked to switch protocols; the reports
364 // of the ready-made boot devices are already boot-format.
365 hid_request::SET_PROTOCOL if self.is_boot_device() => {
366 self.protocol = req.value as u8;
367 let _ = xfer.accept();
368 }
369 _ => {
370 let _ = xfer.reject();
371 }
372 }
373 }
374
375 fn endpoint_out(&mut self, addr: EndpointAddress) {
376 let mut packet = [0u8; OUT_PACKET_MAX];
377
378 let Self {
379 int_out, device, ..
380 } = self;
381 let Some(ep) = int_out else { return };
382 if ep.address() != addr {
383 return;
384 }
385 let Ok(len) = ep.read(&mut packet) else {
386 return;
387 };
388 if len == 0 {
389 return;
390 }
391
392 // Interrupt OUT reports carry their report ID as the first byte when the
393 // descriptor uses report IDs (HID 1.11 §7.2.2); without them the whole
394 // packet is report data.
395 if device.spec().report_ids {
396 device.output_report(packet[0], &packet[1..len]);
397 } else {
398 device.output_report(0, &packet[..len]);
399 }
400 }
401
402 fn configure(&mut self) {
403 self.configured = true;
404 self.device.configure();
405 }
406
407 fn deconfigure(&mut self) {
408 self.configured = false;
409 self.device.deconfigure();
410 }
411
412 fn reset(&mut self) {
413 self.configured = false;
414 self.idle_rate = 0;
415 self.protocol = hid_protocol_mode::REPORT;
416 self.device.reset();
417 }
418
419 fn poll(&mut self) {
420 self.flush();
421 }
422}