Skip to main content

capsules_extra/usb/
keyboard_hid.rs

1// Licensed under the Apache License, Version 2.0 or the MIT License.
2// SPDX-License-Identifier: Apache-2.0 OR MIT
3// Copyright Tock Contributors 2023.
4
5//! Keyboard USB HID device
6
7use super::descriptors;
8use super::descriptors::Buffer64;
9use super::descriptors::DescriptorType;
10use super::descriptors::EndpointAddress;
11use super::descriptors::EndpointDescriptor;
12use super::descriptors::HIDCountryCode;
13use super::descriptors::HIDDescriptor;
14use super::descriptors::HIDSubordinateDescriptor;
15use super::descriptors::InterfaceDescriptor;
16use super::descriptors::ReportDescriptor;
17use super::descriptors::TransferDirection;
18use super::usbc_client_ctrl::ClientCtrl;
19
20use kernel::ErrorCode;
21use kernel::hil;
22use kernel::hil::usb::TransferType;
23use kernel::utilities::cells::OptionalCell;
24use kernel::utilities::cells::TakeCell;
25use tock_registers_v0::interfaces::Writeable;
26
27/// Use 1 Interrupt transfer IN/OUT endpoint
28const ENDPOINT_NUM: usize = 1;
29
30const IN_BUFFER: usize = 0;
31
32static LANGUAGES: &[u16; 1] = &[
33    0x0409, // English (United States)
34];
35/// Max packet size specified by spec
36pub const MAX_CTRL_PACKET_SIZE: u8 = 64;
37
38const N_ENDPOINTS: usize = 1;
39
40/// The HID report descriptor for keyboard from
41/// <https://www.usb.org/sites/default/files/hid1_11.pdf>.
42static REPORT_DESCRIPTOR: &[u8] = &[
43    0x05, 0x01, // Usage Page (Generic Desktop),
44    0x09, 0x06, // Usage (Keyboard),
45    0xA1, 0x01, // Collection (Application),
46    0x75, 0x01, // Report Size (1),
47    0x95, 0x08, // Report Count (8),
48    0x05, 0x07, // Usage Page (Key Codes),
49    0x19, 0xE0, // Usage Minimum (224),
50    0x29, 0xE7, // Usage Maximum (231),
51    0x15, 0x00, // Logical Minimum (0),
52    0x25, 0x01, // Logical Maximum (1),
53    0x81, 0x02, // Input (Data, Variable, Absolute),
54    // ;Modifier byte
55    0x95, 0x01, // Report Count (1),
56    0x75, 0x08, // Report Size (8),
57    0x81, 0x03, // Input (Constant),
58    // ;Reserved byte
59    0x95, 0x05, // Report Count (5),
60    0x75, 0x01, // Report Size (1),
61    0x05, 0x08, // Usage Page (LEDs),
62    0x19, 0x01, // Usage Minimum (1),
63    0x29, 0x05, // Usage Maximum (5),
64    0x91, 0x02, // Output (Data, Variable, Absolute),
65    // ;LED report
66    0x95, 0x01, // Report Count (1),
67    0x75, 0x03, // Report Size (3),
68    0x91, 0x03, // Output (Constant), ;LED report
69    // padding
70    0x95, 0x06, //................// Report Count (6),
71    0x75, 0x08, // Report Size (8),
72    0x15, 0x00, // Logical Minimum (0),
73    0x25, 0x68, // Logical Maximum(104),
74    0x05, 0x07, // Usage Page (Key Codes),
75    0x19, 0x00, // Usage Minimum (0),
76    0x29, 0x68, // Usage Maximum (104),
77    0x81, 0x00, // Input (Data, Array),
78    0xc0, // End Collection
79];
80
81static REPORT: ReportDescriptor<'static> = ReportDescriptor {
82    desc: REPORT_DESCRIPTOR,
83};
84
85static SUB_HID_DESCRIPTOR: &[HIDSubordinateDescriptor] = &[HIDSubordinateDescriptor {
86    typ: DescriptorType::Report,
87    len: REPORT_DESCRIPTOR.len() as u16,
88}];
89
90static HID_DESCRIPTOR: HIDDescriptor<'static> = HIDDescriptor {
91    hid_class: 0x0111,
92    country_code: HIDCountryCode::NotSupported,
93    sub_descriptors: SUB_HID_DESCRIPTOR,
94};
95
96/// Implementation of the CTAP HID (Human Interface Device)
97pub struct KeyboardHid<'a, U: 'a> {
98    /// Helper USB client library for handling many USB operations.
99    client_ctrl: ClientCtrl<'a, 'static, U>,
100
101    /// 64 byte buffers for each endpoint.
102    buffers: [Buffer64; N_ENDPOINTS],
103
104    client: OptionalCell<&'a dyn hil::usb_hid::Client<'a, [u8; 64]>>,
105
106    /// A buffer to hold the data we want to send
107    send_buffer: TakeCell<'static, [u8; 64]>,
108}
109
110impl<'a, U: hil::usb::UsbController<'a>> KeyboardHid<'a, U> {
111    pub fn new(
112        controller: &'a U,
113        vendor_id: u16,
114        product_id: u16,
115        strings: &'static [&'static str; 3],
116    ) -> Self {
117        let interfaces: &mut [InterfaceDescriptor] = &mut [InterfaceDescriptor {
118            interface_number: 0,
119            interface_class: 0x03,    // HID
120            interface_subclass: 0x01, // Boot subclass
121            interface_protocol: 0x01, // Keyboard
122            ..InterfaceDescriptor::default()
123        }];
124
125        let endpoints: &[&[EndpointDescriptor]] = &[&[EndpointDescriptor {
126            endpoint_address: EndpointAddress::new_const(
127                ENDPOINT_NUM,
128                TransferDirection::DeviceToHost,
129            ),
130            transfer_type: TransferType::Interrupt,
131            max_packet_size: 8,
132            interval: 10,
133        }]];
134
135        let (device_descriptor_buffer, other_descriptor_buffer) =
136            descriptors::create_descriptor_buffers(
137                descriptors::DeviceDescriptor {
138                    vendor_id,
139                    product_id,
140                    manufacturer_string: 1,
141                    product_string: 2,
142                    serial_number_string: 3,
143                    max_packet_size_ep0: MAX_CTRL_PACKET_SIZE,
144                    ..descriptors::DeviceDescriptor::default()
145                },
146                descriptors::ConfigurationDescriptor {
147                    attributes: descriptors::ConfigurationAttributes::new(true, true),
148                    max_power: 0x32,
149                    ..descriptors::ConfigurationDescriptor::default()
150                },
151                interfaces,
152                endpoints,
153                Some(&HID_DESCRIPTOR),
154                None,
155            );
156
157        KeyboardHid {
158            client_ctrl: ClientCtrl::new(
159                controller,
160                device_descriptor_buffer,
161                other_descriptor_buffer,
162                Some(&HID_DESCRIPTOR),
163                Some(&REPORT),
164                LANGUAGES,
165                strings,
166            ),
167            buffers: [Buffer64::default()],
168            client: OptionalCell::empty(),
169            send_buffer: TakeCell::empty(),
170        }
171    }
172
173    #[inline]
174    fn controller(&self) -> &'a U {
175        self.client_ctrl.controller()
176    }
177
178    pub fn set_client(&'a self, client: &'a dyn hil::usb_hid::Client<'a, [u8; 64]>) {
179        self.client.set(client);
180    }
181}
182
183impl<'a, U: hil::usb::UsbController<'a>> hil::usb_hid::UsbHid<'a, [u8; 64]> for KeyboardHid<'a, U> {
184    fn send_buffer(
185        &'a self,
186        send: &'static mut [u8; 64],
187    ) -> Result<usize, (ErrorCode, &'static mut [u8; 64])> {
188        let len = send.len();
189
190        self.send_buffer.replace(send);
191        self.controller().endpoint_resume_in(ENDPOINT_NUM);
192
193        Ok(len)
194    }
195
196    fn send_cancel(&'a self) -> Result<&'static mut [u8; 64], ErrorCode> {
197        match self.send_buffer.take() {
198            Some(buf) => Ok(buf),
199            None => Err(ErrorCode::BUSY),
200        }
201    }
202
203    // Keyboard doesn't use receive so this is unimplemented.
204    fn receive_buffer(
205        &'a self,
206        _recv: &'static mut [u8; 64],
207    ) -> Result<(), (ErrorCode, &'static mut [u8; 64])> {
208        Ok(())
209    }
210
211    // Keyboard doesn't use receive so this is unimplemented.
212    fn receive_cancel(&'a self) -> Result<&'static mut [u8; 64], ErrorCode> {
213        Err(ErrorCode::BUSY)
214    }
215}
216
217impl<'a, U: hil::usb::UsbController<'a>> hil::usb::Client<'a> for KeyboardHid<'a, U> {
218    fn enable(&'a self) {
219        // Set up the default control endpoint
220        self.client_ctrl.enable();
221
222        // Setup buffers for IN data transfer.
223        self.controller()
224            .endpoint_set_in_buffer(ENDPOINT_NUM, &self.buffers[IN_BUFFER].buf);
225        self.controller()
226            .endpoint_in_out_enable(TransferType::Interrupt, ENDPOINT_NUM);
227    }
228
229    fn attach(&'a self) {
230        self.client_ctrl.attach();
231    }
232
233    fn bus_reset(&'a self) {}
234
235    /// Handle a Control Setup transaction.
236    fn ctrl_setup(&'a self, endpoint: usize) -> hil::usb::CtrlSetupResult {
237        self.client_ctrl.ctrl_setup(endpoint)
238    }
239
240    /// Handle a Control In transaction
241    fn ctrl_in(&'a self, endpoint: usize) -> hil::usb::CtrlInResult {
242        self.client_ctrl.ctrl_in(endpoint)
243    }
244
245    /// Handle a Control Out transaction
246    fn ctrl_out(&'a self, _endpoint: usize, _packet_bytes: u32) -> hil::usb::CtrlOutResult {
247        // self.client_ctrl.ctrl_out(endpoint, packet_bytes)
248        hil::usb::CtrlOutResult::Ok
249    }
250
251    fn ctrl_status(&'a self, endpoint: usize) {
252        self.client_ctrl.ctrl_status(endpoint)
253    }
254
255    /// Handle the completion of a Control transfer
256    fn ctrl_status_complete(&'a self, endpoint: usize) {
257        self.client_ctrl.ctrl_status_complete(endpoint)
258    }
259
260    /// Handle a Bulk/Interrupt IN transaction.
261    ///
262    /// This is called when we can send data to the host. It should get called
263    /// when we tell the controller we want to resume the IN endpoint (meaning
264    /// we know we have data to send) and afterwards until we return
265    /// `hil::usb::InResult::Delay` from this function. That means we can use
266    /// this as a callback to mean that the transmission finished by waiting
267    /// until this function is called when we don't have anything left to send.
268    fn packet_in(&'a self, transfer_type: TransferType, _endpoint: usize) -> hil::usb::InResult {
269        match transfer_type {
270            TransferType::Interrupt => {
271                self.send_buffer
272                    .take()
273                    .map_or(hil::usb::InResult::Delay, |buf| {
274                        // Get packet that we have shared with the underlying
275                        // USB stack to copy the tx into.
276                        let packet = &self.buffers[IN_BUFFER].buf;
277
278                        // Copy from the TX buffer to the outgoing USB packet.
279                        // Our endpoint supports exactly 8 bytes so we use that
280                        // length.
281                        for i in 0..8 {
282                            packet[i].set(buf[i]);
283                        }
284
285                        // Put the TX buffer back so we can keep sending from
286                        // it.
287                        self.send_buffer.replace(buf);
288
289                        // Return that we have data to send.
290                        hil::usb::InResult::Packet(8)
291                    })
292            }
293            TransferType::Bulk | TransferType::Control | TransferType::Isochronous => {
294                hil::usb::InResult::Error
295            }
296        }
297    }
298
299    /// Handle a Bulk/Interrupt OUT transaction
300    ///
301    /// Unused for keyboard.
302    fn packet_out(
303        &'a self,
304        transfer_type: TransferType,
305        _endpoint: usize,
306        _packet_bytes: u32,
307    ) -> hil::usb::OutResult {
308        match transfer_type {
309            TransferType::Interrupt => hil::usb::OutResult::Ok,
310
311            TransferType::Bulk | TransferType::Control | TransferType::Isochronous => {
312                hil::usb::OutResult::Error
313            }
314        }
315    }
316
317    fn packet_transmitted(&'a self, endpoint: usize) {
318        self.send_buffer.take().map(|buf| {
319            self.client.map(move |client| {
320                client.packet_transmitted(Ok(()), buf, endpoint);
321            });
322        });
323    }
324}