Skip to main content

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