Skip to main content

usb_stack/host/class/
hid.rs

1//! Boot-protocol keyboards.
2//!
3//! The HID boot protocol is what a BIOS speaks: an eight-byte report holding
4//! the modifier bitmap and up to six concurrently pressed keys. Devices that
5//! implement it are the ones that also work before an operating system has
6//! loaded a driver, which makes it the cheapest way to prove a host stack works.
7
8use crate::descriptor::class_code;
9use crate::endpoint::{Direction, EndpointAddress, EndpointType};
10use crate::host::controller::HostController;
11use crate::host::device::Device;
12use crate::host::error::{HostError, HostResult};
13use crate::host::pipe::Pipe;
14use crate::request::{Recipient, Request, RequestType};
15
16/// Bytes in a boot-protocol keyboard report.
17pub const REPORT_LEN: usize = 8;
18
19/// `SET_PROTOCOL` with the boot protocol.
20const HID_SET_PROTOCOL: u8 = 0x0b;
21/// `SET_IDLE` with an indefinite duration.
22const HID_SET_IDLE: u8 = 0x0a;
23
24/// Modifier bits of a keyboard report.
25#[allow(missing_docs)]
26pub mod modifier {
27    pub const LEFT_CTRL: u8 = 1 << 0;
28    pub const LEFT_SHIFT: u8 = 1 << 1;
29    pub const LEFT_ALT: u8 = 1 << 2;
30    pub const LEFT_GUI: u8 = 1 << 3;
31    pub const RIGHT_CTRL: u8 = 1 << 4;
32    pub const RIGHT_SHIFT: u8 = 1 << 5;
33    pub const RIGHT_ALT: u8 = 1 << 6;
34    pub const RIGHT_GUI: u8 = 1 << 7;
35}
36
37/// One boot-protocol keyboard report.
38#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
39#[cfg_attr(feature = "defmt", derive(defmt::Format))]
40pub struct Report {
41    /// Modifier bitmap, see [`modifier`].
42    pub modifiers: u8,
43    /// Usage codes of the pressed keys, zero for unused slots.
44    pub keys: [u8; 6],
45}
46
47impl Report {
48    /// Parse the bytes of a report; short reports are padded with zeroes.
49    pub fn parse(bytes: &[u8]) -> Self {
50        let mut report = Self::default();
51        if let Some((&modifiers, keys)) = bytes.split_first() {
52            report.modifiers = modifiers;
53            let count = keys.len().min(report.keys.len());
54            report.keys[..count].copy_from_slice(&keys[..count]);
55        }
56        report
57    }
58
59    /// No key and no modifier is held.
60    pub fn is_idle(&self) -> bool {
61        self.modifiers == 0 && self.keys.iter().all(|&key| key == 0)
62    }
63
64    /// Whether `key` is held down.
65    pub fn is_pressed(&self, key: u8) -> bool {
66        self.keys.contains(&key)
67    }
68
69    /// Whether any of the bits in `mask` of [`modifier`] is set.
70    pub fn has_modifier(&self, mask: u8) -> bool {
71        self.modifiers & mask != 0
72    }
73
74    /// The keys this report holds that `previous` did not.
75    pub fn new_keys<'a>(&'a self, previous: &'a Self) -> impl Iterator<Item = u8> + 'a {
76        self.keys
77            .iter()
78            .copied()
79            .filter(move |key| *key != 0 && !previous.keys.contains(key))
80    }
81}
82
83/// A keyboard driven through its boot-protocol interrupt endpoint.
84pub struct Keyboard<'d, C: HostController> {
85    pipe: Pipe<'d, C>,
86}
87
88impl<'d, C: HostController> Keyboard<'d, C> {
89    /// Find the boot keyboard interface of `device`, put it in boot protocol
90    /// mode and open its interrupt IN endpoint.
91    ///
92    /// The device has to be configured already
93    /// ([`Device::set_configuration`]), because the interface is only live
94    /// afterwards.
95    pub fn open(device: &Device<'d, C>) -> HostResult<Self> {
96        let endpoint = {
97            let configuration = device.configuration();
98            // Class 3, subclass 1, protocol 1 is a boot keyboard.
99            let interface = configuration
100                .find_interface(class_code::HID, 1, 1)
101                .ok_or(HostError::Unsupported)?;
102
103            let interface_number = interface.number() as u16;
104            let class_request = |request, value| {
105                Request::custom(
106                    Direction::Out,
107                    RequestType::Class,
108                    Recipient::Interface,
109                    request,
110                    value,
111                    interface_number,
112                    0,
113                )
114            };
115
116            // Boot protocol, and reports only when they change: the simplest
117            // configuration for a host that polls on demand.
118            device.control(&class_request(HID_SET_PROTOCOL, 0), &mut [])?;
119            device.control(&class_request(HID_SET_IDLE, 0), &mut [])?;
120
121            interface
122                .endpoints()
123                .find(|endpoint| {
124                    endpoint.address.is_in()
125                        && matches!(endpoint.transfer_type(), EndpointType::Interrupt)
126                })
127                .ok_or(HostError::Malformed)?
128        };
129
130        Ok(Self {
131            pipe: device.open(&endpoint)?,
132        })
133    }
134
135    /// Wait for the next report.
136    ///
137    /// The endpoint NAKs until something changed, so this blocks for up to the
138    /// NAK retry budget of the controller.
139    pub fn read(&self) -> HostResult<Report> {
140        let mut buffer = [0u8; REPORT_LEN];
141        let length = self.pipe.read(&mut buffer)?;
142        Ok(Report::parse(&buffer[..length]))
143    }
144
145    /// The interrupt IN endpoint the keyboard is read from.
146    #[inline]
147    pub fn endpoint(&self) -> EndpointAddress {
148        self.pipe.address()
149    }
150}