Skip to main content

usb_stack/class/hid/
device.rs

1//! [`HidDevice`] — what a HID function has to provide.
2
3use crate::bus::UsbBus;
4use crate::class::hid::{hid_protocol, hid_subclass};
5use crate::endpoint::EndpointIn;
6
7// ─── Report type ─────────────────────────────────────────────────────────────
8
9/// Kind of report, as selected by the `wValue` high byte of `Get Report` and
10/// `Set Report`.
11#[derive(Clone, Copy, PartialEq, Eq, Debug)]
12#[cfg_attr(feature = "defmt", derive(defmt::Format))]
13pub enum ReportType {
14    /// Input report: device → host.
15    Input,
16    /// Output report: host → device.
17    Output,
18    /// Feature report: readable and writable configuration.
19    Feature,
20}
21
22impl ReportType {
23    /// Decode the `wValue` high byte of a `Get Report` / `Set Report` request.
24    pub(crate) fn from_w_value(value: u16) -> Option<Self> {
25        match (value >> 8) as u8 {
26            1 => Some(Self::Input),
27            2 => Some(Self::Output),
28            3 => Some(Self::Feature),
29            _ => None,
30        }
31    }
32}
33
34// ─── HidSpec ─────────────────────────────────────────────────────────────────
35
36/// Static description of a HID function.
37///
38/// Everything a [`HidClass`](super::HidClass) needs to allocate its endpoints
39/// and write its descriptors, plus the two facts about the reports that cannot
40/// be derived from the report descriptor itself (its size and whether it
41/// declares report IDs).
42///
43/// ```ignore
44/// use my_hal_usb::class::hid::{HidSpec, hid_protocol, hid_subclass};
45///
46/// static MY_DESCRIPTOR: &[u8] = &[0x05, 0x01, 0x09, 0x06, 0xA1, 0x01, 0xC0];
47///
48/// const SPEC: HidSpec = HidSpec::new(MY_DESCRIPTOR, 8)
49///     .subclass(hid_subclass::BOOT)
50///     .protocol(hid_protocol::KEYBOARD)
51///     .out_report_size(1)
52///     .poll_interval_ms(8);
53/// ```
54#[derive(Clone, Copy, PartialEq, Eq, Debug)]
55pub struct HidSpec {
56    /// Report descriptor, served for `Get Descriptor (HID Report)`.
57    pub report_descriptor: &'static [u8],
58    /// Size of the interrupt IN endpoint — at least the largest input report,
59    /// including its report ID byte when report IDs are used.
60    pub in_report_size: u16,
61    /// Size of the interrupt OUT endpoint, or `0` for a function without one.
62    pub out_report_size: u16,
63    /// HID subclass: `0` (none) or [`hid_subclass::BOOT`].
64    pub subclass: u8,
65    /// HID protocol: `0` (none) or a boot protocol.
66    pub protocol: u8,
67    /// Interrupt endpoint polling interval, in milliseconds.
68    pub poll_interval_ms: u8,
69    /// `true` when the report descriptor declares report IDs.
70    ///
71    /// Output reports on the interrupt OUT endpoint then carry the report ID as
72    /// their first byte (HID 1.11 §7.2.2), whereas `Set Report` passes it in
73    /// `wValue` and leaves it out of the data.
74    pub report_ids: bool,
75}
76
77impl HidSpec {
78    /// A spec with no subclass, no protocol, no OUT endpoint, a 10 ms poll
79    /// interval and no report IDs.
80    pub const fn new(report_descriptor: &'static [u8], in_report_size: u16) -> Self {
81        Self {
82            report_descriptor,
83            in_report_size,
84            out_report_size: 0,
85            subclass: hid_subclass::NONE,
86            protocol: hid_protocol::NONE,
87            poll_interval_ms: 10,
88            report_ids: false,
89        }
90    }
91
92    /// Set the HID subclass (and, for boot devices, the protocol).
93    pub const fn subclass(mut self, subclass: u8) -> Self {
94        self.subclass = subclass;
95        self
96    }
97
98    /// Set the HID protocol reported in the interface descriptor.
99    pub const fn protocol(mut self, protocol: u8) -> Self {
100        self.protocol = protocol;
101        self
102    }
103
104    /// Allocate an interrupt OUT endpoint of `size` bytes.
105    pub const fn out_report_size(mut self, size: u16) -> Self {
106        self.out_report_size = size;
107        self
108    }
109
110    /// Set the interrupt endpoint polling interval, in milliseconds.
111    pub const fn poll_interval_ms(mut self, interval: u8) -> Self {
112        self.poll_interval_ms = interval;
113        self
114    }
115
116    /// Declare that the report descriptor uses report IDs.
117    pub const fn report_ids(mut self, report_ids: bool) -> Self {
118        self.report_ids = report_ids;
119        self
120    }
121}
122
123// ─── HidDevice ───────────────────────────────────────────────────────────────
124
125/// A HID function: a report descriptor plus the reports it exchanges with the
126/// host.
127///
128/// Implement it to build a custom HID device, or use one of the ready-made ones:
129/// [`Keyboard`](super::keyboard::Keyboard), [`Mouse`](super::mouse::Mouse),
130/// [`CustomHid`](super::custom::CustomHid).
131///
132/// Wrap the implementation in a [`HidClass`](super::HidClass), which owns the
133/// endpoints and handles the USB side:
134///
135/// ```ignore
136/// let mut hid = HidClass::new(&alloc, MyHidDevice::new());
137/// loop {
138///     usb_dev.poll(&mut [&mut hid]);
139///     hid.device_mut().update(...);
140/// }
141/// ```
142///
143/// All methods except [`spec`](Self::spec) have default implementations, so a
144/// device only writes what it actually supports.
145pub trait HidDevice<B: UsbBus> {
146    // ── Description ───────────────────────────────────────────────────────────
147
148    /// Report descriptor, endpoint sizes and interface class/protocol.
149    fn spec(&self) -> HidSpec;
150
151    // ── Control requests ──────────────────────────────────────────────────────
152
153    /// `Get Report` — copy the report selected by `report_type` and `report_id`
154    /// into `buf` and return its length, including the report ID byte when the
155    /// spec declares report IDs.
156    ///
157    /// Return `None` to stall the request.
158    fn get_report(
159        &mut self,
160        _report_type: ReportType,
161        _report_id: u8,
162        _buf: &mut [u8],
163    ) -> Option<usize> {
164        None
165    }
166
167    /// `Set Report` — handle a report written by the host.
168    ///
169    /// `data` starts at the first report byte; the report ID is passed in
170    /// `report_id`, not included in `data` (HID 1.11 §7.2.1).  Return `false` to
171    /// stall the request.
172    fn set_report(&mut self, _report_type: ReportType, _report_id: u8, _data: &[u8]) -> bool {
173        false
174    }
175
176    /// Output report received on the interrupt OUT endpoint.
177    ///
178    /// The class splits the packet for you: with `report_ids` set, the first
179    /// byte is passed as `report_id` and `data` holds the rest; otherwise
180    /// `report_id` is `0` and `data` is the whole packet.
181    fn output_report(&mut self, _report_id: u8, _data: &[u8]) {}
182
183    // ── Lifecycle ─────────────────────────────────────────────────────────────
184
185    /// Called after a USB bus reset.
186    fn reset(&mut self) {}
187
188    /// Called when the host configures the device.
189    ///
190    /// Devices that push input reports should mark everything as pending here so
191    /// the host gets a snapshot of the current state.
192    fn configure(&mut self) {}
193
194    /// Called when the host de-configures the device.
195    fn deconfigure(&mut self) {}
196
197    /// Called on every device poll while configured.
198    ///
199    /// Push input reports with `input`; a report that cannot be sent yet
200    /// ([`WouldBlock`](crate::error::UsbError::WouldBlock)) stays the device's
201    /// responsibility to retry on the next call.
202    fn poll(&mut self, _input: &EndpointIn<'_, B>) {}
203}