From 81772377e5d530f60ee47c36bc00952e72d634e5 Mon Sep 17 00:00:00 2001 From: Gianguido Sora Date: Thu, 28 Dec 2023 18:40:23 +0100 Subject: [PATCH] services/usb-device-xous: abstract AppHID state in a struct Simpler API, easier to understand and audit. The UsbDevice and UsbHidClass are stored in AppHID directly, so that callers have less things to worry about: just provide an UsbBusAllocator. This way we streamline the control flow within main_hw.rs, which is already pretty intricated. I still have to manage errors from usb-device-xous server to lib.rs, but that will come later. --- Cargo.lock | 1 + services/usb-device-xous/Cargo.toml | 1 + services/usb-device-xous/src/hid.rs | 169 ++++++++++++++++++++++-- services/usb-device-xous/src/main_hw.rs | 90 ++++--------- 4 files changed, 191 insertions(+), 70 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index cb9ec3ed9..42462bfb6 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5292,6 +5292,7 @@ version = "0.1.0" dependencies = [ "bitfield", "embedded-time", + "frunk_core", "fugit", "ghostfat", "keyboard", diff --git a/services/usb-device-xous/Cargo.toml b/services/usb-device-xous/Cargo.toml index bf45550bd..e2b5bcacd 100644 --- a/services/usb-device-xous/Cargo.toml +++ b/services/usb-device-xous/Cargo.toml @@ -40,6 +40,7 @@ usbd-serial = "0.1.1" ghostfat = "0.5.0" fugit = "0.3.7" +frunk_core = "0.4.2" [dependencies.usb-device] # see top level Cargo.toml for patch.crates-io directive to help with dev work diff --git a/services/usb-device-xous/src/hid.rs b/services/usb-device-xous/src/hid.rs index 78fa661a1..202502698 100644 --- a/services/usb-device-xous/src/hid.rs +++ b/services/usb-device-xous/src/hid.rs @@ -1,21 +1,32 @@ -use usb_device::class_prelude::{UsbBus, UsbBusAllocator}; +use crate::api::HIDReport; +use frunk_core::hlist::{HCons, HNil}; +use fugit::ExtU32; +use std::sync::Arc; +use std::{collections::VecDeque, sync::Mutex}; +use usb_device::device::UsbDeviceBuilder; +use usb_device::{ + class_prelude::{UsbBus, UsbBusAllocator}, + device::{UsbDevice, UsbVidPid}, + UsbError, +}; +use usb_device_xous::UsbDeviceState; use xous_usb_hid::{ device::DeviceClass, interface::{ HeapInterface, HeapInterfaceBuilder, HeapInterfaceConfig, InBytes64, OutBytes64, ReportSingle, UsbAllocatable, }, + usb_class::{UsbHidClass, UsbHidClassBuilder}, UsbHidError, }; -use crate::api::HIDReport; -use fugit::ExtU32; - -pub struct AppHID<'a, B: UsbBus> { +/// AppHIDDevice implements a UsbBus device whose internal USB interface allows for a heap-allocated +/// device report descriptor. +pub struct AppHIDDevice<'a, B: UsbBus> { interface: HeapInterface<'a, B, InBytes64, OutBytes64, ReportSingle>, } -impl<'a, B: UsbBus> AppHID<'a, B> { +impl<'a, B: UsbBus> AppHIDDevice<'a, B> { pub fn write_report(&mut self, report: &HIDReport) -> Result<(), UsbHidError> { self.interface .write_report(&report.0) @@ -39,7 +50,7 @@ impl<'a, B: UsbBus> AppHID<'a, B> { } } -impl<'a, B: UsbBus> DeviceClass<'a> for AppHID<'a, B> { +impl<'a, B: UsbBus> DeviceClass<'a> for AppHIDDevice<'a, B> { type I = HeapInterface<'a, B, InBytes64, OutBytes64, ReportSingle>; fn interface(&mut self) -> &mut Self::I { @@ -81,7 +92,7 @@ impl<'a> AppHIDConfig<'a> { } impl<'a, B: UsbBus + 'a> UsbAllocatable<'a, B> for AppHIDConfig<'a> { - type Allocated = AppHID<'a, B>; + type Allocated = AppHIDDevice<'a, B>; fn allocate(self, usb_alloc: &'a UsbBusAllocator) -> Self::Allocated { Self::Allocated { @@ -89,3 +100,145 @@ impl<'a, B: UsbBus + 'a> UsbAllocatable<'a, B> for AppHIDConfig<'a> { } } } + +#[derive(Debug)] +pub enum AppHIDError { + /// Returned when the maximum amount of packets allowed to stay in AppHID is reached, and the + /// oldest is dropped. + OldestReportDropped, + + /// No descriptor has been set on the AppHID, cannot poll. + NoDescriptorSet, + + /// Returned when there is an error coming from the USB bus. + UsbError(UsbError), +} + +/// AppHID wraps a USB HID device, and allows for dynamic reconfiguration of the HID device descriptor. +/// It buffers incoming HID reports in a queue until it is requested to return some. +/// Developers can set the maximum amount of HID reports to buffer, and AppHID will drop the oldest when a new +/// one is added, and threshold is met. +/// The buffer is heap-allocated: one HID report is 64 bytes, so depending on your configuration you might need +/// to increase the heap limits for your process. +pub struct AppHID<'a, B: UsbBus> { + max_stored_reports: usize, + incoming_reports: VecDeque, + device_descr_set: Arc>, + + class: UsbHidClass<'a, B, HCons, HNil>>, + device: UsbDevice<'a, B>, +} + +impl<'a, B: UsbBus> AppHID<'a, B> { + /// Creates a new USB device and HID class with the given parameters. + pub fn new( + vid_pid: UsbVidPid, + serial_number: &'a str, + alloc: &'a UsbBusAllocator, + config: AppHIDConfig<'a>, + max_stored_reports: usize, + ) -> Self { + let device = UsbDeviceBuilder::new(alloc, vid_pid) + .manufacturer("Kosagi") + .product("Precursor") + .serial_number(&serial_number) + .build(); + + let class = UsbHidClassBuilder::new().add_device(config).build(alloc); + + AppHID { + max_stored_reports, + incoming_reports: VecDeque::new(), + device_descr_set: Arc::new(Mutex::new(false)), + class, + device, + } + } + + /// Forces the reset of the underlying USB device. + /// Causes host to re-enumerate. + pub fn force_reset(&mut self) -> usb_device::Result<()> { + self.device.force_reset() + } + + /// Returns the current state of the underlying USB device. + pub fn state(&self) -> UsbDeviceState { + self.device.state() + } + + /// Polls for new reports on the bus, sent from the USB host. + pub fn poll(&mut self) -> Result<(), AppHIDError> { + if !self.device.poll(&mut [&mut self.class]) { + return Ok(()); + } + + if !self.descriptor_set() { + return Err(AppHIDError::NoDescriptorSet); + } + + let hidv2_device = self.class.device::, _>(); + match hidv2_device.read_report() { + Ok(report) => { + let result = { + let reports_stored = self.incoming_reports.len(); + if reports_stored <= self.max_stored_reports { + return Ok(()); + } + + self.incoming_reports.pop_back().unwrap(); + Err(AppHIDError::OldestReportDropped) + }; + + self.incoming_reports.push_back(report); + result + } + Err(err) => Err(AppHIDError::UsbError(err)), + } + } + + /// Sets the device descriptor report, which will be then sent to the host. + /// This method forces a device reset, hence re-enumeration from the host. + pub fn set_device_report(&mut self, descriptor: Vec) -> Result<(), AppHIDError> { + let hidv2_device = self.class.device::, _>(); + hidv2_device + .set_device_descriptor(descriptor) + .map_err(|e| AppHIDError::UsbError(e)) + .and_then(|_| { + Ok({ + *self.device_descr_set.lock().unwrap() = true; + self.device.force_reset().ok(); + }) + }) + } + + /// Resets the stored device descriptor report and drops all the stored incoming reports, if any. + /// This method forces a device reset, hence re-enumeration from the host. + pub fn reset_device_report(&mut self) -> Result<(), AppHIDError> { + self.incoming_reports.clear(); + self.set_device_report(vec![]).and_then(|_| { + Ok({ + *self.device_descr_set.lock().unwrap() = false; + }) + }) + } + + /// Returns true if there is a device descriptor set for the AppHID. + pub fn descriptor_set(&self) -> bool { + *self.device_descr_set.lock().unwrap() + } + + /// Returns the oldest HID report read from the USB bus. + pub fn read_report(&mut self) -> Option { + if !self.descriptor_set() { + return None; + } + + self.incoming_reports.pop_back() + } + + /// Writes a HID report on the USB bus. + pub fn write_report(&mut self, data: HIDReport) { + let hidv2_device = self.class.device::, _>(); + hidv2_device.write_report(&data).ok(); + } +} diff --git a/services/usb-device-xous/src/main_hw.rs b/services/usb-device-xous/src/main_hw.rs index 6478de611..b8045b362 100644 --- a/services/usb-device-xous/src/main_hw.rs +++ b/services/usb-device-xous/src/main_hw.rs @@ -1,5 +1,4 @@ use crate::*; -use crate::hid::AppHID; use crate::hid::AppHIDConfig; use num_traits::*; use usb_device_xous::KeyboardLedsReport; @@ -14,7 +13,6 @@ use xous_semver::SemVer; use core::num::NonZeroU8; use core::sync::atomic::{AtomicU32, AtomicBool, Ordering}; use std::sync::Arc; -use std::sync::Mutex; use utralib::generated::*; use usb_device::prelude::*; @@ -295,26 +293,17 @@ pub(crate) fn main_hw() -> ! { const TRNG_BACKOFF_MS: u32 = 1; const TRNG_BACKOFF_MAX_MS: u32 = 1000; // cap on how far we backoff the polling rate - // stores the descriptor that has been selected for the current HIDv2 view. - let selected_hidv2_descriptor = Arc::new(Mutex::new(None)); - let usb_hidv2_dev = SpinalUsbDevice::new(usbdev_sid, usb.clone(), csr.clone()); let hidv2_alloc = UsbBusAllocator::new(usb_hidv2_dev); + + let mut hidv2 = hid::AppHID::new( + UsbVidPid(0x1209, 0x3613), + &serial_number, + &hidv2_alloc, + AppHIDConfig::default(), + 10, + ); - let mut hidv2_class = UsbHidClassBuilder::new() - .add_device( - AppHIDConfig::default(), - ) - .build(&hidv2_alloc); - - - let mut hidv2_dev = UsbDeviceBuilder::new(&hidv2_alloc, UsbVidPid(0x1209, 0x3613)) - .manufacturer("Kosagi") - .product("Precursor") - .serial_number(&serial_number) - .build(); - - let mut hidv2_queue = VecDeque::::new(); let mut led_state: KeyboardLedsReport = KeyboardLedsReport::default(); let mut fido_listener: Option = None; @@ -471,7 +460,7 @@ pub(crate) fn main_hw() -> ! { serial_device.force_reset() }, Views::HIDv2 => { - hidv2_dev.force_reset() + hidv2.force_reset() } }.unwrap_or_else(|err| { log::warn!("USB reset for view {:?} on resume failed: {:?}", view, err) @@ -704,20 +693,9 @@ pub(crate) fn main_hw() -> ! { None }, Views::HIDv2 => { - if hidv2_dev.poll(&mut [&mut hidv2_class]) { - if selected_hidv2_descriptor.lock().unwrap().is_none() { - continue; - } - - let hidv2_device = hidv2_class.device::, _>(); - match hidv2_device.read_report(){ - Ok(report) => { - hidv2_queue.push_back(report); - log::info!("report pushed to vecdeque: {:?}", report); - } - Err(err) => log::debug!("hidv2 read report error: {:?}", err), - } - + match hidv2.poll() { + Ok(_) => (), + Err(error) => log::error!("hidv2 read report error: {:?}", error), } None @@ -752,7 +730,7 @@ pub(crate) fn main_hw() -> ! { #[cfg(feature="mass-storage")] Views::MassStorage => ums_device.state() == UsbDeviceState::Suspend, Views::Serial => serial_device.state() == UsbDeviceState::Suspend, - Views::HIDv2 => hidv2_dev.state() == UsbDeviceState::Suspend, + Views::HIDv2 => hidv2.state() == UsbDeviceState::Suspend, }; if is_suspend { log::info!("suspend detected"); @@ -1067,7 +1045,7 @@ pub(crate) fn main_hw() -> ! { #[cfg(feature="mass-storage")] Views::MassStorage => xous::return_scalar(msg.sender, ums_device.state() as usize).unwrap(), Views::Serial => xous::return_scalar(msg.sender, serial_device.state() as usize).unwrap(), - Views::HIDv2 => xous::return_scalar(msg.sender, hidv2_dev.state() as usize).unwrap(), + Views::HIDv2 => xous::return_scalar(msg.sender, hidv2.state() as usize).unwrap(), } }), Some(Opcode::SendKeyCode) => msg_blocking_scalar_unpack!(msg, code0, code1, code2, autoup, { @@ -1485,30 +1463,20 @@ pub(crate) fn main_hw() -> ! { }; let data = buffer.to_original::().unwrap(); - let mut selected_hidv2_descriptor = selected_hidv2_descriptor.lock().unwrap(); - *selected_hidv2_descriptor = Some(Vec::from(&data.descriptor[..data.len])); - - log::debug!("descriptor being set: {:?}", &selected_hidv2_descriptor.as_ref().unwrap()[..data.len]); - - let hidv2_device = hidv2_class.device::, _>(); - - match hidv2_device.set_device_descriptor(selected_hidv2_descriptor.as_ref().unwrap().clone()) { + // TODO(gsora): do something with the error + match hidv2.set_device_report(Vec::from(&data.descriptor[..data.len])) { Ok(_) => (), - Err(err) => { - log::error!("can't set hidv2 device descriptor: {:?}", err); - continue; + Err(error) => { + log::error!("cannot set hidv2 device report: {:?}", error); }, - }; - - log::debug!("successfully set new hidv2 descriptor"); - - hidv2_dev.force_reset().ok(); + } } Some(Opcode::HIDUnsetDescriptor) => { - *selected_hidv2_descriptor.lock().unwrap() = None; - hidv2_queue.clear(); - hidv2_dev.force_reset().ok(); - xous::return_scalar(msg.sender, 0).expect("cannot return hid app unset descriptor to sender") + // TODO(gsora): do something with the error + match hidv2.reset_device_report() { + Ok(_) => (), + Err(error) => log::error!("cannot reset hidv2 device report: {:?}", error), + } } Some(Opcode::HIDReadReport) => { let mut buffer = unsafe { @@ -1517,11 +1485,11 @@ pub(crate) fn main_hw() -> ! { let mut data = buffer.to_original::().unwrap(); - if selected_hidv2_descriptor.lock().unwrap().is_none() { + if !hidv2.descriptor_set() { buffer.replace(HIDReportMessage::default()).expect("couldn't serialize return"); continue } else { - match hidv2_queue.pop_front() { + match hidv2.read_report() { Some(report) => { data.data = report; data.has_data = true; @@ -1533,7 +1501,7 @@ pub(crate) fn main_hw() -> ! { buffer.replace(data).expect("couldn't serialize return"); }, Some(Opcode::HIDWriteReport) => { - if selected_hidv2_descriptor.lock().unwrap().is_none() { + if !hidv2.descriptor_set() { log::warn!("trying to write a HID report with no descriptor set!"); continue } @@ -1543,9 +1511,7 @@ pub(crate) fn main_hw() -> ! { }; let data = buffer.to_original::().unwrap(); - log::info!("HIDWriteReport: {:?}", data); - let hidv2_device = hidv2_class.device::, _>(); - hidv2_device.write_report(&data).ok(); + hidv2.write_report(data); }, Some(Opcode::Quit) => { log::warn!("Quit received, goodbye world!");