From b62912914b985ca61c0d7557ae4ff88c059d5f68 Mon Sep 17 00:00:00 2001 From: Gianguido Sora Date: Tue, 26 Dec 2023 18:34:37 +0100 Subject: [PATCH 01/13] apps: add hidv2 demo app --- Cargo.toml | 1 + apps/hidv2/Cargo.toml | 22 ++++ apps/hidv2/locales/i18n.json | 9 ++ apps/hidv2/src/main.rs | 237 +++++++++++++++++++++++++++++++++++ apps/manifest.json | 8 ++ 5 files changed, 277 insertions(+) create mode 100644 apps/hidv2/Cargo.toml create mode 100644 apps/hidv2/locales/i18n.json create mode 100644 apps/hidv2/src/main.rs diff --git a/Cargo.toml b/Cargo.toml index 6bc1c7802..b33d4e9b2 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -84,6 +84,7 @@ members = [ "apps/vault/tools/vaultbackup-rs", "apps/transientdisk", "apps/chat-test", + "apps/hidv2", "services/libstd-test", "services/ffi-test", "services/tts", diff --git a/apps/hidv2/Cargo.toml b/apps/hidv2/Cargo.toml new file mode 100644 index 000000000..3f8fe8c12 --- /dev/null +++ b/apps/hidv2/Cargo.toml @@ -0,0 +1,22 @@ +[package] +name = "hidv2" +version = "0.1.0" +edition = "2021" + +[dependencies] +log = "0.4.14" +num-derive = {version = "0.3.3", default-features = false} +num-traits = {version = "0.2.14", default-features = false} +xous = "0.9.53" +xous-ipc = "0.9.53" +log-server = { package = "xous-api-log", version = "0.1.49" } +xous-names = { package = "xous-api-names", version = "0.9.51" } +gam = {path = "../../services/gam" } +graphics-server = {path = "../../services/graphics-server" } +locales = {path = "../../locales"} +tts-frontend = {path="../../services/tts"} +usb-device-xous = {path="../../services/usb-device-xous"} + +[features] +tts = [] +default = [] diff --git a/apps/hidv2/locales/i18n.json b/apps/hidv2/locales/i18n.json new file mode 100644 index 000000000..d7b873462 --- /dev/null +++ b/apps/hidv2/locales/i18n.json @@ -0,0 +1,9 @@ +{ + "helloworld.hello": { + "en": "Hello World!", + "en-tts": "Hello World!", + "fr": "Bonjour le monde!", + "ja": "Hello World!", + "zh": "大家好!" + } +} diff --git a/apps/hidv2/src/main.rs b/apps/hidv2/src/main.rs new file mode 100644 index 000000000..6d7cf9533 --- /dev/null +++ b/apps/hidv2/src/main.rs @@ -0,0 +1,237 @@ +#![cfg_attr(target_os = "none", no_std)] +#![cfg_attr(target_os = "none", no_main)] + +use core::fmt::Write; +use graphics_server::api::GlyphStyle; +use graphics_server::{DrawStyle, Gid, PixelColor, Point, Rectangle, TextBounds, TextView}; +use num_traits::*; +use std::sync::mpsc::{self, Receiver, Sender}; +use usb_device_xous::UsbHid; + +pub(crate) const SERVER_NAME_HIDV2: &str = "_HIDv2_"; + +// stealing fido report for the lulz +const FIDO_REPORT_DESCRIPTOR: &[u8] = &[ + 0x06, 0xD0, 0xF1, // Usage Page (FIDO), + 0x09, 0x01, // Usage (U2F Authenticator Device) + 0xA1, 0x01, // Collection (Application), + 0x09, 0x20, // Usage (Data In), + 0x15, 0x00, // Logical Minimum(0), + 0x26, 0xFF, 0x00, // Logical Maxs (0x00FF), + 0x75, 0x08, // Report size (8) + 0x95, 0x40, // Report count (64) + 0x81, 0x02, // Input (Data | Variable | Absolute) + 0x09, 0x21, // Usage (Data Out), + 0x15, 0x00, // Logical Minimum(0), + 0x26, 0xFF, 0x00, // Logical Maxs (0x00FF), + 0x75, 0x08, // Report size (8) + 0x95, 0x40, // Report count (64) + 0x91, 0x02, // Output (Data | Variable | Absolute) + 0xC0, // End Collection +]; + +/// Top level application events. +#[derive(Debug, num_derive::FromPrimitive, num_derive::ToPrimitive)] +pub(crate) enum HIDv2Op { + /// Redraw the screen + Redraw = 0, + + /// Enter/exit app + FocusChange, + + /// Quit the application + Quit, +} + +struct HIDv2Demo { + content: Gid, + gam: gam::Gam, + _gam_token: [u32; 4], + screensize: Point, +} + +impl HIDv2Demo { + fn new(xns: &xous_names::XousNames, sid: xous::SID) -> Self { + let gam = gam::Gam::new(&xns).expect("Can't connect to GAM"); + let gam_token = gam + .register_ux(gam::UxRegistration { + app_name: xous_ipc::String::<128>::from_str(gam::APP_NAME_HIDV2), + ux_type: gam::UxType::Chat, + predictor: None, + listener: sid.to_array(), + redraw_id: HIDv2Op::Redraw.to_u32().unwrap(), + gotinput_id: None, + audioframe_id: None, + rawkeys_id: None, + focuschange_id: Some(HIDv2Op::FocusChange.to_u32().unwrap()), + }) + .expect("Could not register GAM UX") + .unwrap(); + + let content = gam + .request_content_canvas(gam_token) + .expect("Could not get content canvas"); + let screensize = gam + .get_canvas_bounds(content) + .expect("Could not get canvas dimensions"); + Self { + gam, + _gam_token: gam_token, + content, + screensize, + } + } + + /// Clear the entire screen. + fn clear_area(&self) { + self.gam + .draw_rectangle( + self.content, + Rectangle::new_with_style( + Point::new(0, 0), + self.screensize, + DrawStyle { + fill_color: Some(PixelColor::Light), + stroke_color: None, + stroke_width: 0, + }, + ), + ) + .expect("can't clear content area"); + } + + /// Redraw the text view onto the screen. + fn redraw(&mut self) { + self.clear_area(); + + let mut text_view = TextView::new( + self.content, + TextBounds::GrowableFromBr( + Point::new( + self.screensize.x - (self.screensize.x / 2) + 40, + self.screensize.y - (self.screensize.y / 2), + ), + (self.screensize.x / 5 * 4) as u16, + ), + ); + + text_view.border_width = 1; + text_view.draw_border = true; + text_view.clear_area = true; + text_view.rounded_border = Some(3); + text_view.style = GlyphStyle::Regular; + write!(text_view.text, "{}", "Echoing whatever on HID USB stack...") + .expect("Could not write to text view"); + + self.gam + .post_textview(&mut text_view) + .expect("Could not render text view"); + self.gam.redraw().expect("Could not redraw screen"); + } +} + +fn main() -> ! { + log_server::init_wait().unwrap(); + log::set_max_level(log::LevelFilter::Info); + log::info!("HIDv2 Demo PID is {}", xous::process::id()); + + let xns = xous_names::XousNames::new().unwrap(); + + let mut allow_redraw = true; + + // Register the server with xous + let sid = xns + .register_name(SERVER_NAME_HIDV2, None) + .expect("can't register server"); + + let mut hidv2_demo = HIDv2Demo::new(&xns, sid); + + let mut hid_thread_handle: Option> = None; + + loop { + let msg = xous::receive_message(sid).unwrap(); + log::debug!("Got message: {:?}", msg); + + match FromPrimitive::from_usize(msg.body.id()) { + Some(HIDv2Op::Redraw) => { + log::debug!("Got redraw"); + + if !allow_redraw { + continue; + } + + hidv2_demo.redraw(); + } + Some(HIDv2Op::Quit) => { + log::info!("Quitting application"); + break; + } + Some(HIDv2Op::FocusChange) => xous::msg_scalar_unpack!(msg, new_state_code, _, _, _, { + let new_state = gam::FocusState::convert_focus_change(new_state_code); + log::info!("focus change: {:?}", new_state); + match new_state { + gam::FocusState::Background => { + allow_redraw = false; // this instantly terminates future updates, even if Pump messages are in our input queue + match hid_thread_handle { + Some(handle) => { + handle.send(true).unwrap(); + hid_thread_handle = None; + } + None => (), + } + } + gam::FocusState::Foreground => { + allow_redraw = true; + hid_thread_handle = Some(start_hid_thread()) + } + } + }), + _ => { + log::error!("Got unknown message"); + } + } + } + + log::info!("Quitting"); + xous::terminate_process(0) +} + +fn start_hid_thread() -> Sender { + let (tx, rx): (Sender, Receiver) = mpsc::channel(); + + let usbd = UsbHid::new(); + + usbd.connect_hid_app(FIDO_REPORT_DESCRIPTOR.to_vec()) + .unwrap(); + + usbd.switch_to_core(usb_device_xous::UsbDeviceType::HIDv2) + .unwrap(); + + std::thread::spawn(move || { + loop { + match rx.try_recv() { + Ok(_) => break, + Err(_) => { + match usbd.read_report() { + Err(err) => match err { + xous::Error::UnknownError => (), + _ => log::error!("error while reading report! {:#?}", err), + }, + Ok(report) => { + log::info!("report! {:#?}", report); + log::info!("echoing back"); + usbd.write_report(report).unwrap(); + } + }; + } + } + + std::thread::sleep(std::time::Duration::from_millis(50)); + } + + usbd.switch_to_core(usb_device_xous::UsbDeviceType::Debug) + .unwrap(); + }); + + return tx; +} diff --git a/apps/manifest.json b/apps/manifest.json index 6e00842f5..364f58751 100644 --- a/apps/manifest.json +++ b/apps/manifest.json @@ -33,6 +33,14 @@ } } }, + "hidv2": { + "context_name": "HID v2 demo", + "menu_name": { + "appmenu.hidv2": { + "en": "HID v2 demo" + } + } + }, "mtxcli": { "context_name": "Matrix cli", "menu_name": { From 26740a44f61378bdbac92db563cc370ce2bc5e5c Mon Sep 17 00:00:00 2001 From: Gianguido Sora Date: Tue, 26 Dec 2023 18:37:41 +0100 Subject: [PATCH 02/13] services/usb-device-xous: implement HIDv2 device Allows apps to expose HID devices from userspace. Documentation coming soon. --- Cargo.lock | 25 +++- services/usb-device-xous/Cargo.toml | 1 + services/usb-device-xous/src/api.rs | 39 +++++ services/usb-device-xous/src/hid.rs | 91 ++++++++++++ services/usb-device-xous/src/lib.rs | 62 ++++++++ services/usb-device-xous/src/main.rs | 2 + services/usb-device-xous/src/main_hw.rs | 184 +++++++++++++++++++++--- 7 files changed, 378 insertions(+), 26 deletions(-) create mode 100644 services/usb-device-xous/src/hid.rs diff --git a/Cargo.lock b/Cargo.lock index 480e62f7e..cb9ec3ed9 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1889,9 +1889,9 @@ dependencies = [ [[package]] name = "frunk_core" -version = "0.4.0" +version = "0.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1246cf43ec80bf8b2505b5c360b8fb999c97dabd17dbb604d85558d5cbc25482" +checksum = "af2469fab0bd07e64ccf0ad57a1438f63160c69b2e57f04a439653d68eb558d6" [[package]] name = "frunk_derives" @@ -2299,6 +2299,24 @@ dependencies = [ "pkg-config", ] +[[package]] +name = "hidv2" +version = "0.1.0" +dependencies = [ + "gam", + "graphics-server", + "locales", + "log", + "num-derive", + "num-traits", + "tts-frontend", + "usb-device-xous", + "xous 0.9.55 (registry+https://github.com/rust-lang/crates.io-index)", + "xous-api-log", + "xous-api-names", + "xous-ipc 0.9.55 (registry+https://github.com/rust-lang/crates.io-index)", +] + [[package]] name = "hkdf" version = "0.11.0" @@ -5274,6 +5292,7 @@ version = "0.1.0" dependencies = [ "bitfield", "embedded-time", + "fugit", "ghostfat", "keyboard", "llio", @@ -6283,7 +6302,7 @@ dependencies = [ [[package]] name = "xous-usb-hid" version = "0.4.3" -source = "git+https://github.com/betrusted-io/xous-usb-hid.git#eba35e886d08e504cf10026221aec0fbfc63e201" +source = "git+https://github.com/betrusted-io/xous-usb-hid.git#793ec00243c525f2d17dc1d3a185abdeec57aaf6" dependencies = [ "frunk", "fugit", diff --git a/services/usb-device-xous/Cargo.toml b/services/usb-device-xous/Cargo.toml index 87e9b1d6c..bf45550bd 100644 --- a/services/usb-device-xous/Cargo.toml +++ b/services/usb-device-xous/Cargo.toml @@ -39,6 +39,7 @@ usbd_mass_storage = { path = "../../libs/mass-storage/usbd_mass_storage", option usbd-serial = "0.1.1" ghostfat = "0.5.0" +fugit = "0.3.7" [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/api.rs b/services/usb-device-xous/src/api.rs index 2e674b96f..ad571da64 100644 --- a/services/usb-device-xous/src/api.rs +++ b/services/usb-device-xous/src/api.rs @@ -59,6 +59,19 @@ pub(crate) enum Opcode { #[cfg(feature="mass-storage")] ResetBlockDevice = 1026, + // HIDv2 + /// Read a HID report + HIDReadReport = 1027, + + /// Write a HID report + HIDWriteReport = 1028, + + /// Set the HID descriptor to be pushed to the USB host + HIDSetDescriptor = 1029, + + /// Unset HID descriptor and reset HIDv2 state + HIDUnsetDescriptor = 1030, + /// Handle the USB interrupt UsbIrqHandler = 2048, /// Suspend/resume callback @@ -107,8 +120,10 @@ pub enum UsbDeviceType { #[cfg(feature="mass-storage")] MassStorage = 3, Serial = 4, + HIDv2 = 5, } use std::convert::TryFrom; + impl TryFrom for UsbDeviceType { type Error = &'static str; @@ -120,6 +135,7 @@ impl TryFrom for UsbDeviceType { #[cfg(feature="mass-storage")] 3 => Ok(UsbDeviceType::MassStorage), 4 => Ok(UsbDeviceType::Serial), + 5 => Ok(UsbDeviceType::HIDv2), _ => Err("Invalid UsbDeviceType specifier"), } } @@ -138,3 +154,26 @@ pub struct UsbSerialBinary { pub d: [u8; SERIAL_BINARY_BUFLEN], pub len: usize, } + +pub const MAX_HID_REPORT_DESCRIPTOR_LEN: usize = 1024; + +#[derive(Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize, Copy, Clone)] +pub struct HIDReportDescriptorMessage { + pub descriptor: [u8; MAX_HID_REPORT_DESCRIPTOR_LEN], + pub len: usize, +} + +#[derive(Copy, Clone, Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)] +pub struct HIDReport(pub [u8; 64]); + +impl Default for HIDReport { + fn default() -> Self { + return Self([0u8; 64]) + } +} + +#[derive(Debug, Default, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize, Copy, Clone)] +pub struct HIDReportMessage { + pub data: HIDReport, + pub has_data: bool, +} \ No newline at end of file diff --git a/services/usb-device-xous/src/hid.rs b/services/usb-device-xous/src/hid.rs new file mode 100644 index 000000000..78fa661a1 --- /dev/null +++ b/services/usb-device-xous/src/hid.rs @@ -0,0 +1,91 @@ +use usb_device::class_prelude::{UsbBus, UsbBusAllocator}; +use xous_usb_hid::{ + device::DeviceClass, + interface::{ + HeapInterface, HeapInterfaceBuilder, HeapInterfaceConfig, InBytes64, OutBytes64, + ReportSingle, UsbAllocatable, + }, + UsbHidError, +}; + +use crate::api::HIDReport; +use fugit::ExtU32; + +pub struct AppHID<'a, B: UsbBus> { + interface: HeapInterface<'a, B, InBytes64, OutBytes64, ReportSingle>, +} + +impl<'a, B: UsbBus> AppHID<'a, B> { + pub fn write_report(&mut self, report: &HIDReport) -> Result<(), UsbHidError> { + self.interface + .write_report(&report.0) + .map(|_| ()) + .map_err(UsbHidError::from) + } + + pub fn read_report(&mut self) -> usb_device::Result { + let mut report = HIDReport::default(); + match self.interface.read_report(&mut report.0) { + Err(e) => Err(e), + Ok(_) => Ok(report), + } + } + + pub fn set_device_descriptor( + &mut self, + descriptor: Vec, + ) -> Result<(), usb_device::UsbError> { + self.interface.set_report_descriptor(descriptor) + } +} + +impl<'a, B: UsbBus> DeviceClass<'a> for AppHID<'a, B> { + type I = HeapInterface<'a, B, InBytes64, OutBytes64, ReportSingle>; + + fn interface(&mut self) -> &mut Self::I { + &mut self.interface + } + + fn reset(&mut self) {} + + fn tick(&mut self) -> Result<(), UsbHidError> { + Ok(()) + } +} + +pub struct AppHIDConfig<'a> { + interface: HeapInterfaceConfig<'a, InBytes64, OutBytes64, ReportSingle>, +} + +impl<'a> Default for AppHIDConfig<'a> { + #[must_use] + fn default() -> Self { + let iface = HeapInterfaceBuilder::new(vec![0]) + .unwrap() + .description("Xous HID application") + .in_endpoint(5.millis()) + .unwrap() + .with_out_endpoint(5.millis()) + .unwrap() + .build(); + + Self::new(iface) + } +} + +impl<'a> AppHIDConfig<'a> { + #[must_use] + pub fn new(interface: HeapInterfaceConfig<'a, InBytes64, OutBytes64, ReportSingle>) -> Self { + Self { interface } + } +} + +impl<'a, B: UsbBus + 'a> UsbAllocatable<'a, B> for AppHIDConfig<'a> { + type Allocated = AppHID<'a, B>; + + fn allocate(self, usb_alloc: &'a UsbBusAllocator) -> Self::Allocated { + Self::Allocated { + interface: HeapInterface::new(usb_alloc, self.interface), + } + } +} diff --git a/services/usb-device-xous/src/lib.rs b/services/usb-device-xous/src/lib.rs index b9e57f9eb..042487d80 100644 --- a/services/usb-device-xous/src/lib.rs +++ b/services/usb-device-xous/src/lib.rs @@ -411,6 +411,68 @@ impl UsbHid { ) ).unwrap(); } + + // HID v2 + pub fn connect_hid_app(&self, descriptor: Vec) -> Result<(), xous::Error> { + if descriptor.len() > MAX_HID_REPORT_DESCRIPTOR_LEN { + return Err(xous::Error::OutOfMemory) + } + + let mut container = HIDReportDescriptorMessage{ + descriptor: [0u8; MAX_HID_REPORT_DESCRIPTOR_LEN], + len: descriptor.len(), + }; + + for (place, element) in container.descriptor.iter_mut().zip(descriptor.iter()) { + *place = *element; + } + + let mut buf = Buffer::into_buf(container).or(Err(xous::Error::InternalError))?; + buf.lend_mut(self.conn, Opcode::HIDSetDescriptor.to_u32().unwrap()).map(|_| ())?; + + Ok(()) + } + + pub fn disconnect_hid_app(&self) -> Result<(), xous::Error> { + match send_message(self.conn, Message::new_blocking_scalar( + Opcode::HIDUnsetDescriptor.to_usize().unwrap(), + 0, 0, 0, 0) + ) { + Ok(_) => Ok(()), + Err(err) => Err(err), + } + } + + pub fn read_report(&self) -> Result { + let report = HIDReportMessage::default(); + + let mut buf = Buffer::into_buf(report).or(Err(xous::Error::InternalError))?; + buf.lend_mut(self.conn, Opcode::HIDReadReport.to_u32().unwrap()).map(|_| ())?; + + let report = buf.as_flat::().unwrap(); + + match report.has_data { + true => { + let mut ret = HIDReport::default(); + + // copy the data back + for (&s, d) in report.data.0[..report.data.0.len() as usize].iter().zip(ret.0.iter_mut()) { + *d = s; + } + + Ok(ret) + + }, + false => Err(xous::Error::UnknownError), + } + } + + pub fn write_report(&self, report: HIDReport) -> Result<(), xous::Error> { + let buf = Buffer::into_buf(report).or(Err(xous::Error::InternalError))?; + buf.lend(self.conn, Opcode::HIDWriteReport.to_u32().unwrap()).map(|_| ())?; + + Ok(()) + } } use core::sync::atomic::{AtomicU32, Ordering}; diff --git a/services/usb-device-xous/src/main.rs b/services/usb-device-xous/src/main.rs index df5d845d2..76ea81083 100644 --- a/services/usb-device-xous/src/main.rs +++ b/services/usb-device-xous/src/main.rs @@ -23,6 +23,8 @@ use spinal_udc::*; #[cfg(all(any(feature="precursor", feature="renode"),feature="mass-storage"))] mod apps_block_device; +#[cfg(any(feature="precursor", feature="renode"))] +mod hid; #[cfg(not(target_os = "xous"))] mod hosted; #[cfg(not(target_os = "xous"))] diff --git a/services/usb-device-xous/src/main_hw.rs b/services/usb-device-xous/src/main_hw.rs index 275942a81..6478de611 100644 --- a/services/usb-device-xous/src/main_hw.rs +++ b/services/usb-device-xous/src/main_hw.rs @@ -1,5 +1,6 @@ use crate::*; - +use crate::hid::AppHID; +use crate::hid::AppHIDConfig; use num_traits::*; use usb_device_xous::KeyboardLedsReport; use usb_device_xous::UsbDeviceType; @@ -13,6 +14,7 @@ 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::*; @@ -32,7 +34,7 @@ use usbd_serial::SerialPort; /// Time allowed for switchover between device core types. It's longer because some hosts /// get really confused when you have the same VID/PID show up with a different set of endpoints. const EXTENDED_CORE_RESET_MS: usize = 4000; -#[derive(Eq, PartialEq)] +#[derive(Eq, PartialEq, Debug)] #[repr(usize)] enum Views { FidoWithKbd = 0, @@ -40,6 +42,7 @@ enum Views { #[cfg(feature="mass-storage")] MassStorage = 2, Serial = 3, + HIDv2 = 4, } #[derive(num_derive::FromPrimitive, num_derive::ToPrimitive, Debug)] @@ -185,7 +188,7 @@ pub(crate) fn main_hw() -> ! { let mut usbmgmt = usb_fidokbd_dev.get_iface(); // before doing any allocs, clone a copy of the hardware access structure so we can build a second // view into the hardware with only FIDO descriptors - let usb_fido_dev = SpinalUsbDevice::new(usbdev_sid, usb.clone(), csr.clone()); + let usb_fido_dev: SpinalUsbDevice = SpinalUsbDevice::new(usbdev_sid, usb.clone(), csr.clone()); usb_fido_dev.init(); // do the same thing for mass storage #[cfg(feature="mass-storage")] @@ -292,6 +295,27 @@ 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_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; // under the theory that PIDs cannot be forged. TODO: check that PIDs cannot be forged. @@ -434,32 +458,25 @@ pub(crate) fn main_hw() -> ! { usbmgmt.xous_resume1(); match view { Views::FidoWithKbd => { - match usb_dev.force_reset() { - Err(e) => log::warn!("USB reset on resume failed: {:?}", e), - _ => () - }; + usb_dev.force_reset() } Views::FidoOnly => { - match fido_dev.force_reset() { - Err(e) => log::warn!("USB reset on resume failed: {:?}", e), - _ => () - }; + fido_dev.force_reset() } #[cfg(feature="mass-storage")] Views::MassStorage => { - // TODO: test this - match ums_device.force_reset() { - Err(e) => log::warn!("USB reset on resume failed: {:?}", e), - _ => () - }; + ums_device.force_reset() } Views::Serial => { - match serial_device.force_reset() { - Err(e) => log::warn!("USB reset on resume failed: {:?}", e), - _ => () - } + serial_device.force_reset() + }, + Views::HIDv2 => { + hidv2_dev.force_reset() } - } + }.unwrap_or_else(|err| { + log::warn!("USB reset for view {:?} on resume failed: {:?}", view, err) + }); + // resume2 brings us to our last application state usbmgmt.xous_resume2(); lockstatus_force_update = true; // notify the status bar that yes, it does need to redraw the lock status, even if the value hasn't changed since the last read @@ -543,6 +560,7 @@ pub(crate) fn main_hw() -> ! { #[cfg(feature="mass-storage")] Views::MassStorage => panic!("did not expect u2f tx when in mass storage mode!"), Views::Serial => panic!("did not expect u2f tx while in serial mode!"), + Views::HIDv2 => panic!("did not expect u2f tx while in hidv2 mode!"), }; u2f.write_report(&u2f_msg).ok(); log::debug!("sent U2F packet {:x?}", u2f_ipc.data); @@ -584,7 +602,7 @@ pub(crate) fn main_hw() -> ! { }, Views::Serial => { if serial_device.poll(&mut [&mut serial_port]) { - let mut data = [0u8; SERIAL_BUF_LEN]; + let mut data: [u8; 1024] = [0u8; SERIAL_BUF_LEN]; match serial_listen_mode { SerialListenMode::NoListener => { match serial_port.read(&mut data) { @@ -685,6 +703,25 @@ 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), + } + + } + + None + } }; if let Some(u2f) = maybe_u2f { match u2f.read_report() { @@ -715,6 +752,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, }; if is_suspend { log::info!("suspend detected"); @@ -822,6 +860,20 @@ pub(crate) fn main_hw() -> ! { usbmgmt.ll_reset(false); } } + }, + UsbDeviceType::HIDv2 => { + log::info!("Connectiing HIDv2 device"); + match view { + Views::HIDv2 => usbmgmt.connect_device_core(true), + _ => { + view = Views::HIDv2; + usbmgmt.ll_reset(true); + tt.sleep_ms(1000).ok(); + usbmgmt.ll_connect_device_core(true); + tt.sleep_ms(EXTENDED_CORE_RESET_MS).ok(); + usbmgmt.ll_reset(false); + } + } } } xous::return_scalar(msg.sender, 0).unwrap(); @@ -931,6 +983,22 @@ pub(crate) fn main_hw() -> ! { } } } + UsbDeviceType::HIDv2 => { + log::info!("Ensuring HIDv2 device"); + if !usbmgmt.is_device_connected() { + view = Views::HIDv2; + usbmgmt.connect_device_core(true); + } else { + if view != Views::HIDv2 { + view = Views::HIDv2; + usbmgmt.ll_reset(true); + tt.sleep_ms(1000).ok(); + usbmgmt.ll_connect_device_core(true); + tt.sleep_ms(EXTENDED_CORE_RESET_MS).ok(); + usbmgmt.ll_reset(false); + } + } + } } xous::return_scalar(msg.sender, 0).unwrap(); }), @@ -942,6 +1010,7 @@ pub(crate) fn main_hw() -> ! { #[cfg(feature="mass-storage")] Views::MassStorage => xous::return_scalar(msg.sender, UsbDeviceType::MassStorage as usize).unwrap(), Views::Serial => xous::return_scalar(msg.sender, UsbDeviceType::Serial as usize).unwrap(), + Views::HIDv2 => xous::return_scalar(msg.sender, UsbDeviceType::HIDv2 as usize).unwrap(), } } else { xous::return_scalar(msg.sender, UsbDeviceType::Debug as usize).unwrap(); @@ -998,6 +1067,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(), } }), Some(Opcode::SendKeyCode) => msg_blocking_scalar_unpack!(msg, code0, code1, code2, autoup, { @@ -1409,6 +1479,74 @@ pub(crate) fn main_hw() -> ! { serial_trng_interval.store(TRNG_REFILL_DELAY_MS, Ordering::SeqCst); } } + Some(Opcode::HIDSetDescriptor) => { + let buffer = unsafe { + Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap()) + }; + 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()) { + Ok(_) => (), + Err(err) => { + log::error!("can't set hidv2 device descriptor: {:?}", err); + continue; + }, + }; + + 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") + } + Some(Opcode::HIDReadReport) => { + let mut buffer = unsafe { + Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap()) + }; + + let mut data = buffer.to_original::().unwrap(); + + if selected_hidv2_descriptor.lock().unwrap().is_none() { + buffer.replace(HIDReportMessage::default()).expect("couldn't serialize return"); + continue + } else { + match hidv2_queue.pop_front() { + Some(report) => { + data.data = report; + data.has_data = true; + } + _ => () + } + } + + buffer.replace(data).expect("couldn't serialize return"); + }, + Some(Opcode::HIDWriteReport) => { + if selected_hidv2_descriptor.lock().unwrap().is_none() { + log::warn!("trying to write a HID report with no descriptor set!"); + continue + } + + let buffer = unsafe { + Buffer::from_memory_message(msg.body.memory_message().unwrap()) + }; + let data = buffer.to_original::().unwrap(); + + log::info!("HIDWriteReport: {:?}", data); + let hidv2_device = hidv2_class.device::, _>(); + hidv2_device.write_report(&data).ok(); + }, Some(Opcode::Quit) => { log::warn!("Quit received, goodbye world!"); break; @@ -1424,4 +1562,4 @@ pub(crate) fn main_hw() -> ! { xous::destroy_server(usbdev_sid).unwrap(); log::trace!("quitting"); xous::terminate_process(0) -} \ No newline at end of file +} From 81772377e5d530f60ee47c36bc00952e72d634e5 Mon Sep 17 00:00:00 2001 From: Gianguido Sora Date: Thu, 28 Dec 2023 18:40:23 +0100 Subject: [PATCH 03/13] 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!"); From fe7678cff3c3bc0aa5d0aac85f25cab3e63dbb31 Mon Sep 17 00:00:00 2001 From: Gianguido Sora Date: Fri, 29 Dec 2023 18:37:45 +0100 Subject: [PATCH 04/13] services/usb-device-xous: use an Option rather than bool+slice when returning a report message --- services/usb-device-xous/src/api.rs | 3 +-- services/usb-device-xous/src/main_hw.rs | 23 +++++++++-------------- 2 files changed, 10 insertions(+), 16 deletions(-) diff --git a/services/usb-device-xous/src/api.rs b/services/usb-device-xous/src/api.rs index ad571da64..f73440393 100644 --- a/services/usb-device-xous/src/api.rs +++ b/services/usb-device-xous/src/api.rs @@ -174,6 +174,5 @@ impl Default for HIDReport { #[derive(Debug, Default, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize, Copy, Clone)] pub struct HIDReportMessage { - pub data: HIDReport, - pub has_data: bool, + pub data: Option, } \ No newline at end of file diff --git a/services/usb-device-xous/src/main_hw.rs b/services/usb-device-xous/src/main_hw.rs index b8045b362..abca01897 100644 --- a/services/usb-device-xous/src/main_hw.rs +++ b/services/usb-device-xous/src/main_hw.rs @@ -1463,7 +1463,9 @@ pub(crate) fn main_hw() -> ! { }; let data = buffer.to_original::().unwrap(); - // TODO(gsora): do something with the error + // This branch can only error if data.descriptor is longer than the + // expected maximum. + // The userland library checks this for us already. match hidv2.set_device_report(Vec::from(&data.descriptor[..data.len])) { Ok(_) => (), Err(error) => { @@ -1472,31 +1474,24 @@ pub(crate) fn main_hw() -> ! { } } Some(Opcode::HIDUnsetDescriptor) => { - // 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) => { + if !hidv2.descriptor_set() { + log::warn!("trying to read a HID report with no descriptor set!"); + continue + } + let mut buffer = unsafe { Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap()) }; let mut data = buffer.to_original::().unwrap(); - if !hidv2.descriptor_set() { - buffer.replace(HIDReportMessage::default()).expect("couldn't serialize return"); - continue - } else { - match hidv2.read_report() { - Some(report) => { - data.data = report; - data.has_data = true; - } - _ => () - } - } + data.data = hidv2.read_report(); buffer.replace(data).expect("couldn't serialize return"); }, From acc1871ab01a125ad83ac13914137b74cd77ca7b Mon Sep 17 00:00:00 2001 From: Gianguido Sora Date: Fri, 29 Dec 2023 18:38:12 +0100 Subject: [PATCH 05/13] services/usb-device-xous: initialize UsbClass before UsbDevice --- services/usb-device-xous/src/hid.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/services/usb-device-xous/src/hid.rs b/services/usb-device-xous/src/hid.rs index 202502698..1374fc181 100644 --- a/services/usb-device-xous/src/hid.rs +++ b/services/usb-device-xous/src/hid.rs @@ -138,14 +138,14 @@ impl<'a, B: UsbBus> AppHID<'a, B> { config: AppHIDConfig<'a>, max_stored_reports: usize, ) -> Self { + let class = UsbHidClassBuilder::new().add_device(config).build(alloc); + 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(), From cb9a279537da9f3afc068b0ca1254fa8a2ba3ee6 Mon Sep 17 00:00:00 2001 From: Gianguido Sora Date: Fri, 29 Dec 2023 18:38:35 +0100 Subject: [PATCH 06/13] services/usb-device-xous: add documentation, and use Option in read_report --- services/usb-device-xous/src/lib.rs | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/services/usb-device-xous/src/lib.rs b/services/usb-device-xous/src/lib.rs index 042487d80..ea21b1a0b 100644 --- a/services/usb-device-xous/src/lib.rs +++ b/services/usb-device-xous/src/lib.rs @@ -412,7 +412,8 @@ impl UsbHid { ).unwrap(); } - // HID v2 + /// Sets the userland application HID device descriptor. + /// It cannot be longer than 1024 bytes. pub fn connect_hid_app(&self, descriptor: Vec) -> Result<(), xous::Error> { if descriptor.len() > MAX_HID_REPORT_DESCRIPTOR_LEN { return Err(xous::Error::OutOfMemory) @@ -433,6 +434,8 @@ impl UsbHid { Ok(()) } + /// Unset the userland application HID device descriptor and discards the cached + /// reports. pub fn disconnect_hid_app(&self) -> Result<(), xous::Error> { match send_message(self.conn, Message::new_blocking_scalar( Opcode::HIDUnsetDescriptor.to_usize().unwrap(), @@ -443,6 +446,7 @@ impl UsbHid { } } + /// Reads a HID report off the USB bus. pub fn read_report(&self) -> Result { let report = HIDReportMessage::default(); @@ -451,22 +455,22 @@ impl UsbHid { let report = buf.as_flat::().unwrap(); - match report.has_data { - true => { + match &report.data { + rkyv::core_impl::ArchivedOption::Some(data) => { let mut ret = HIDReport::default(); - // copy the data back - for (&s, d) in report.data.0[..report.data.0.len() as usize].iter().zip(ret.0.iter_mut()) { + for (&s, d) in data.0[..data.0.len() as usize].iter().zip(ret.0.iter_mut()) { *d = s; } Ok(ret) }, - false => Err(xous::Error::UnknownError), + rkyv::core_impl::ArchivedOption::None => Err(xous::Error::UnknownError), } } + /// Writes a HID report on the USB bus. pub fn write_report(&self, report: HIDReport) -> Result<(), xous::Error> { let buf = Buffer::into_buf(report).or(Err(xous::Error::InternalError))?; buf.lend(self.conn, Opcode::HIDWriteReport.to_u32().unwrap()).map(|_| ())?; From 5d9cedaf1a059cef8892d7cab73fded6b381e1b4 Mon Sep 17 00:00:00 2001 From: Gianguido Sora Date: Sat, 30 Dec 2023 16:47:41 +0100 Subject: [PATCH 07/13] services/usb-device-xous: refactor inner function scopes to be actually correct --- services/usb-device-xous/src/hid.rs | 40 +++++++++++++++---------- services/usb-device-xous/src/main_hw.rs | 5 +++- 2 files changed, 28 insertions(+), 17 deletions(-) diff --git a/services/usb-device-xous/src/hid.rs b/services/usb-device-xous/src/hid.rs index 1374fc181..985533e72 100644 --- a/services/usb-device-xous/src/hid.rs +++ b/services/usb-device-xous/src/hid.rs @@ -179,35 +179,47 @@ impl<'a, B: UsbBus> AppHID<'a, B> { let hidv2_device = self.class.device::, _>(); match hidv2_device.read_report() { Ok(report) => { - let result = { + let result = 'result_scope : { let reports_stored = self.incoming_reports.len(); - if reports_stored <= self.max_stored_reports { - return Ok(()); + if reports_stored < self.max_stored_reports { + break 'result_scope Ok(()); } - self.incoming_reports.pop_back().unwrap(); - Err(AppHIDError::OldestReportDropped) + self.incoming_reports.pop_front().unwrap(); + break 'result_scope Err(AppHIDError::OldestReportDropped) }; self.incoming_reports.push_back(report); result } - Err(err) => Err(AppHIDError::UsbError(err)), + Err(err) => { + // If we have something that isn't WouldBlock, maybe stuff's about to blow up: return to caller. + if !matches!(err, UsbError::WouldBlock) { + return Err(AppHIDError::UsbError(err)); + } + + return Ok(()); + } } } /// 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 descr_len = descriptor.len(); 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(); - }) + *self.device_descr_set.lock().unwrap() = match descr_len { + 0 => false, + _ => true, + }; + + self.device.force_reset().ok(); + + Ok(()) }) } @@ -215,11 +227,7 @@ impl<'a, B: UsbBus> AppHID<'a, B> { /// 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; - }) - }) + self.set_device_report(vec![]) } /// Returns true if there is a device descriptor set for the AppHID. @@ -233,7 +241,7 @@ impl<'a, B: UsbBus> AppHID<'a, B> { return None; } - self.incoming_reports.pop_back() + self.incoming_reports.pop_front() } /// Writes a HID report on the USB bus. diff --git a/services/usb-device-xous/src/main_hw.rs b/services/usb-device-xous/src/main_hw.rs index abca01897..513d0005d 100644 --- a/services/usb-device-xous/src/main_hw.rs +++ b/services/usb-device-xous/src/main_hw.rs @@ -695,7 +695,7 @@ pub(crate) fn main_hw() -> ! { Views::HIDv2 => { match hidv2.poll() { Ok(_) => (), - Err(error) => log::error!("hidv2 read report error: {:?}", error), + Err(error) => log::error!("hidv2 poll error: {:?}", error), } None @@ -1506,6 +1506,9 @@ pub(crate) fn main_hw() -> ! { }; let data = buffer.to_original::().unwrap(); + + log::info!("report to be written to USB: {:?}", data); + hidv2.write_report(data); }, Some(Opcode::Quit) => { From 59837474cc56e7e9e7a56e8157f3836c75195ab4 Mon Sep 17 00:00:00 2001 From: Gianguido Sora Date: Tue, 9 Jan 2024 12:21:06 +0100 Subject: [PATCH 08/13] apps/hidv2: don't print the whole report on logs --- apps/hidv2/src/main.rs | 2 -- 1 file changed, 2 deletions(-) diff --git a/apps/hidv2/src/main.rs b/apps/hidv2/src/main.rs index 6d7cf9533..965907be3 100644 --- a/apps/hidv2/src/main.rs +++ b/apps/hidv2/src/main.rs @@ -218,8 +218,6 @@ fn start_hid_thread() -> Sender { _ => log::error!("error while reading report! {:#?}", err), }, Ok(report) => { - log::info!("report! {:#?}", report); - log::info!("echoing back"); usbd.write_report(report).unwrap(); } }; From 8fa259e35a0ce7315a31c7cc35cd30499cabf6dc Mon Sep 17 00:00:00 2001 From: Gianguido Sora Date: Tue, 9 Jan 2024 12:21:53 +0100 Subject: [PATCH 09/13] services/usb-device-xous: align HIDReport to C repr --- services/usb-device-xous/src/api.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/services/usb-device-xous/src/api.rs b/services/usb-device-xous/src/api.rs index f73440393..89cacae5a 100644 --- a/services/usb-device-xous/src/api.rs +++ b/services/usb-device-xous/src/api.rs @@ -164,6 +164,7 @@ pub struct HIDReportDescriptorMessage { } #[derive(Copy, Clone, Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)] +#[repr(C, align(8))] pub struct HIDReport(pub [u8; 64]); impl Default for HIDReport { From 96088ecffd33c780993aff0429ee43ca1ed86bd4 Mon Sep 17 00:00:00 2001 From: Gianguido Sora Date: Tue, 9 Jan 2024 12:23:57 +0100 Subject: [PATCH 10/13] services/usb-device-xous: increase HID max stored report to 100 About 6.4kb --- services/usb-device-xous/src/main_hw.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/usb-device-xous/src/main_hw.rs b/services/usb-device-xous/src/main_hw.rs index 513d0005d..6587d8abc 100644 --- a/services/usb-device-xous/src/main_hw.rs +++ b/services/usb-device-xous/src/main_hw.rs @@ -301,7 +301,7 @@ pub(crate) fn main_hw() -> ! { &serial_number, &hidv2_alloc, AppHIDConfig::default(), - 10, + 100, // 100 * 64 bytes = 6.4kb, quite the backlog ); From 270c47157771efcfa17f81e71ec201c32ab1b79f Mon Sep 17 00:00:00 2001 From: Gianguido Sora Date: Tue, 30 Jan 2024 19:04:58 +0100 Subject: [PATCH 11/13] services/usb-device-xous: cleanup --- services/usb-device-xous/src/main_hw.rs | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/services/usb-device-xous/src/main_hw.rs b/services/usb-device-xous/src/main_hw.rs index d6fe647dc..a39baeea7 100644 --- a/services/usb-device-xous/src/main_hw.rs +++ b/services/usb-device-xous/src/main_hw.rs @@ -27,8 +27,6 @@ use xous_usb_hid::device::DeviceClass; use xous_usb_hid::page::Keyboard; use xous_usb_hid::prelude::*; -use crate::*; - /// Time allowed for switchover between device core types. It's longer because some hosts /// get really confused when you have the same VID/PID show up with a different set of endpoints. const EXTENDED_CORE_RESET_MS: usize = 4000; @@ -98,7 +96,7 @@ pub(crate) fn main_hw() -> ! { if soc_ver < minimum_ver { if soc_ver.min != 0 { // don't show during hosted mode, which reports 0.0.0+0 - tt.sleep_ms(1500).ok(); // wait for some system boot to happen before popping up the modal + tt.sleep_ms(1500).ok(); // wait for some system boot to happen before popping up the modal let modals = modals::Modals::new(&xns).unwrap(); modals.show_notification( &format!("SoC version >= 0.9.8+20 required for USB HID. Detected rev: {}. Refusing to start USB driver.", @@ -499,7 +497,10 @@ pub(crate) fn main_hw() -> ! { }; } Views::HIDv2 => { - hidv2.force_reset() + match hidv2.force_reset() { + Err(e) => log::warn!("USB reset on resume failed: {:?}", e), + _ => (), + }; } Views::Serial => match serial_device.force_reset() { Err(e) => log::warn!("USB reset on resume failed: {:?}", e), From a64edbdf2fac175b0f1b0595f78d3a78e99bb343 Mon Sep 17 00:00:00 2001 From: Gianguido Sora Date: Tue, 30 Jan 2024 19:05:17 +0100 Subject: [PATCH 12/13] services/usb-device-xous: use main branch for xous-usb-hid --- Cargo.lock | 20 +++++++++++++++++--- services/usb-device-xous/Cargo.toml | 2 +- 2 files changed, 18 insertions(+), 4 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 6667f6463..2e646919a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5366,7 +5366,7 @@ dependencies = [ "xous-api-ticktimer", "xous-ipc 0.9.57 (registry+https://github.com/rust-lang/crates.io-index)", "xous-semver", - "xous-usb-hid", + "xous-usb-hid 0.4.3 (git+https://github.com/betrusted-io/xous-usb-hid.git?branch=main)", ] [[package]] @@ -5389,7 +5389,7 @@ dependencies = [ "xous-api-names", "xous-api-susres", "xous-api-ticktimer", - "xous-usb-hid", + "xous-usb-hid 0.4.3 (git+https://github.com/betrusted-io/xous-usb-hid.git)", ] [[package]] @@ -5572,7 +5572,7 @@ dependencies = [ "xous-api-susres", "xous-api-ticktimer", "xous-ipc 0.9.57 (registry+https://github.com/rust-lang/crates.io-index)", - "xous-usb-hid", + "xous-usb-hid 0.4.3 (git+https://github.com/betrusted-io/xous-usb-hid.git)", ] [[package]] @@ -6349,6 +6349,20 @@ dependencies = [ "xous-ipc 0.9.57 (registry+https://github.com/rust-lang/crates.io-index)", ] +[[package]] +name = "xous-usb-hid" +version = "0.4.3" +source = "git+https://github.com/betrusted-io/xous-usb-hid.git?branch=main#793ec00243c525f2d17dc1d3a185abdeec57aaf6" +dependencies = [ + "frunk", + "fugit", + "heapless 0.7.16", + "num_enum 0.6.1", + "option-block", + "packed_struct", + "usb-device", +] + [[package]] name = "xous-usb-hid" version = "0.4.3" diff --git a/services/usb-device-xous/Cargo.toml b/services/usb-device-xous/Cargo.toml index d06b13c94..ce18cfbc7 100644 --- a/services/usb-device-xous/Cargo.toml +++ b/services/usb-device-xous/Cargo.toml @@ -28,7 +28,7 @@ xous-semver = "0.1.2" utralib = { version = "0.1.24", optional = true, default-features = false } trng = { path = "../trng" } -xous-usb-hid = { git = "https://github.com/betrusted-io/xous-usb-hid.git" } +xous-usb-hid = { git = "https://github.com/betrusted-io/xous-usb-hid.git", branch="main" } embedded-time = "0.12.1" # required by the keyboard interface packed_struct = { version = "0.10", default-features = false } # used by the xous-usb-hid crate num_enum = { version = "0.5", default-features = false } # used by the xous-usb-hid crate From 73d3563cb6a7878ef9a977c861bc0ae12fe6938d Mon Sep 17 00:00:00 2001 From: Gianguido Sora Date: Tue, 30 Jan 2024 19:12:19 +0100 Subject: [PATCH 13/13] services/usb-device-xous: format code --- services/usb-device-xous/src/api.rs | 6 +- services/usb-device-xous/src/hid.rs | 76 ++++++++++--------------- services/usb-device-xous/src/main_hw.rs | 49 +++++++--------- 3 files changed, 53 insertions(+), 78 deletions(-) diff --git a/services/usb-device-xous/src/api.rs b/services/usb-device-xous/src/api.rs index 36ec625fe..f5c7d218f 100644 --- a/services/usb-device-xous/src/api.rs +++ b/services/usb-device-xous/src/api.rs @@ -171,9 +171,7 @@ pub struct HIDReportDescriptorMessage { pub struct HIDReport(pub [u8; 64]); impl Default for HIDReport { - fn default() -> Self { - return Self([0u8; 64]) - } + fn default() -> Self { return Self([0u8; 64]) } } #[derive(Debug, Default, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize, Copy, Clone)] @@ -186,4 +184,4 @@ pub struct HIDReportMessage { pub(crate) struct UsbListenerRegistration { pub server_name: xous_ipc::String<64>, pub listener_op_id: usize, -} \ No newline at end of file +} diff --git a/services/usb-device-xous/src/hid.rs b/services/usb-device-xous/src/hid.rs index 985533e72..3044060ad 100644 --- a/services/usb-device-xous/src/hid.rs +++ b/services/usb-device-xous/src/hid.rs @@ -1,8 +1,8 @@ -use crate::api::HIDReport; -use frunk_core::hlist::{HCons, HNil}; -use fugit::ExtU32; use std::sync::Arc; use std::{collections::VecDeque, sync::Mutex}; + +use frunk_core::hlist::{HCons, HNil}; +use fugit::ExtU32; use usb_device::device::UsbDeviceBuilder; use usb_device::{ class_prelude::{UsbBus, UsbBusAllocator}, @@ -13,13 +13,15 @@ use usb_device_xous::UsbDeviceState; use xous_usb_hid::{ device::DeviceClass, interface::{ - HeapInterface, HeapInterfaceBuilder, HeapInterfaceConfig, InBytes64, OutBytes64, - ReportSingle, UsbAllocatable, + HeapInterface, HeapInterfaceBuilder, HeapInterfaceConfig, InBytes64, OutBytes64, ReportSingle, + UsbAllocatable, }, usb_class::{UsbHidClass, UsbHidClassBuilder}, UsbHidError, }; +use crate::api::HIDReport; + /// AppHIDDevice implements a UsbBus device whose internal USB interface allows for a heap-allocated /// device report descriptor. pub struct AppHIDDevice<'a, B: UsbBus> { @@ -28,10 +30,7 @@ pub struct AppHIDDevice<'a, B: UsbBus> { impl<'a, B: UsbBus> AppHIDDevice<'a, B> { pub fn write_report(&mut self, report: &HIDReport) -> Result<(), UsbHidError> { - self.interface - .write_report(&report.0) - .map(|_| ()) - .map_err(UsbHidError::from) + self.interface.write_report(&report.0).map(|_| ()).map_err(UsbHidError::from) } pub fn read_report(&mut self) -> usb_device::Result { @@ -42,10 +41,7 @@ impl<'a, B: UsbBus> AppHIDDevice<'a, B> { } } - pub fn set_device_descriptor( - &mut self, - descriptor: Vec, - ) -> Result<(), usb_device::UsbError> { + pub fn set_device_descriptor(&mut self, descriptor: Vec) -> Result<(), usb_device::UsbError> { self.interface.set_report_descriptor(descriptor) } } @@ -53,15 +49,11 @@ impl<'a, B: UsbBus> AppHIDDevice<'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 { - &mut self.interface - } + fn interface(&mut self) -> &mut Self::I { &mut self.interface } fn reset(&mut self) {} - fn tick(&mut self) -> Result<(), UsbHidError> { - Ok(()) - } + fn tick(&mut self) -> Result<(), UsbHidError> { Ok(()) } } pub struct AppHIDConfig<'a> { @@ -95,9 +87,7 @@ impl<'a, B: UsbBus + 'a> UsbAllocatable<'a, B> for AppHIDConfig<'a> { type Allocated = AppHIDDevice<'a, B>; fn allocate(self, usb_alloc: &'a UsbBusAllocator) -> Self::Allocated { - Self::Allocated { - interface: HeapInterface::new(usb_alloc, self.interface), - } + Self::Allocated { interface: HeapInterface::new(usb_alloc, self.interface) } } } @@ -118,8 +108,8 @@ pub enum AppHIDError { /// 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. +/// 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, @@ -157,14 +147,10 @@ impl<'a, B: UsbBus> AppHID<'a, B> { /// 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() - } + 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() - } + 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> { @@ -179,21 +165,22 @@ impl<'a, B: UsbBus> AppHID<'a, B> { let hidv2_device = self.class.device::, _>(); match hidv2_device.read_report() { Ok(report) => { - let result = 'result_scope : { + let result = 'result_scope: { let reports_stored = self.incoming_reports.len(); if reports_stored < self.max_stored_reports { break 'result_scope Ok(()); } self.incoming_reports.pop_front().unwrap(); - break 'result_scope Err(AppHIDError::OldestReportDropped) + break 'result_scope Err(AppHIDError::OldestReportDropped); }; self.incoming_reports.push_back(report); result } Err(err) => { - // If we have something that isn't WouldBlock, maybe stuff's about to blow up: return to caller. + // If we have something that isn't WouldBlock, maybe stuff's about to blow up: return to + // caller. if !matches!(err, UsbError::WouldBlock) { return Err(AppHIDError::UsbError(err)); } @@ -208,19 +195,16 @@ impl<'a, B: UsbBus> AppHID<'a, B> { pub fn set_device_report(&mut self, descriptor: Vec) -> Result<(), AppHIDError> { let descr_len = descriptor.len(); let hidv2_device = self.class.device::, _>(); - hidv2_device - .set_device_descriptor(descriptor) - .map_err(|e| AppHIDError::UsbError(e)) - .and_then(|_| { - *self.device_descr_set.lock().unwrap() = match descr_len { - 0 => false, - _ => true, - }; + hidv2_device.set_device_descriptor(descriptor).map_err(|e| AppHIDError::UsbError(e)).and_then(|_| { + *self.device_descr_set.lock().unwrap() = match descr_len { + 0 => false, + _ => true, + }; - self.device.force_reset().ok(); + self.device.force_reset().ok(); - Ok(()) - }) + Ok(()) + }) } /// Resets the stored device descriptor report and drops all the stored incoming reports, if any. @@ -231,9 +215,7 @@ impl<'a, B: UsbBus> AppHID<'a, B> { } /// Returns true if there is a device descriptor set for the AppHID. - pub fn descriptor_set(&self) -> bool { - *self.device_descr_set.lock().unwrap() - } + 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 { diff --git a/services/usb-device-xous/src/main_hw.rs b/services/usb-device-xous/src/main_hw.rs index a39baeea7..8fb19a322 100644 --- a/services/usb-device-xous/src/main_hw.rs +++ b/services/usb-device-xous/src/main_hw.rs @@ -1,5 +1,3 @@ -use crate::*; -use crate::hid::AppHIDConfig; use core::num::NonZeroU8; use core::sync::atomic::{AtomicBool, AtomicU32, Ordering}; use std::collections::VecDeque; @@ -27,6 +25,9 @@ use xous_usb_hid::device::DeviceClass; use xous_usb_hid::page::Keyboard; use xous_usb_hid::prelude::*; +use crate::hid::AppHIDConfig; +use crate::*; + /// Time allowed for switchover between device core types. It's longer because some hosts /// get really confused when you have the same VID/PID show up with a different set of endpoints. const EXTENDED_CORE_RESET_MS: usize = 4000; @@ -96,7 +97,7 @@ pub(crate) fn main_hw() -> ! { if soc_ver < minimum_ver { if soc_ver.min != 0 { // don't show during hosted mode, which reports 0.0.0+0 - tt.sleep_ms(1500).ok(); // wait for some system boot to happen before popping up the modal + tt.sleep_ms(1500).ok(); // wait for some system boot to happen before popping up the modal let modals = modals::Modals::new(&xns).unwrap(); modals.show_notification( &format!("SoC version >= 0.9.8+20 required for USB HID. Detected rev: {}. Refusing to start USB driver.", @@ -294,7 +295,6 @@ pub(crate) fn main_hw() -> ! { 100, // 100 * 64 bytes = 6.4kb, quite the backlog ); - let mut led_state: KeyboardLedsReport = KeyboardLedsReport::default(); let mut fido_listener: Option = None; // under the theory that PIDs cannot be forged. TODO: check that PIDs cannot be forged. @@ -935,7 +935,7 @@ pub(crate) fn main_hw() -> ! { usbmgmt.ll_reset(false); } } - }, + } UsbDeviceType::HIDv2 => { log::info!("Connectiing HIDv2 device"); match view { @@ -1103,7 +1103,9 @@ pub(crate) fn main_hw() -> ! { Views::Serial => { xous::return_scalar(msg.sender, UsbDeviceType::Serial as usize).unwrap() } - Views::HIDv2 => xous::return_scalar(msg.sender, UsbDeviceType::HIDv2 as usize).unwrap(), + Views::HIDv2 => { + xous::return_scalar(msg.sender, UsbDeviceType::HIDv2 as usize).unwrap() + } } } else { xous::return_scalar(msg.sender, UsbDeviceType::Debug as usize).unwrap(); @@ -1612,9 +1614,8 @@ pub(crate) fn main_hw() -> ! { } } Some(Opcode::HIDSetDescriptor) => { - let buffer = unsafe { - Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap()) - }; + let buffer = + unsafe { Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap()) }; let data = buffer.to_original::().unwrap(); // This branch can only error if data.descriptor is longer than the @@ -1624,47 +1625,41 @@ pub(crate) fn main_hw() -> ! { Ok(_) => (), Err(error) => { log::error!("cannot set hidv2 device report: {:?}", error); - }, - } - } - Some(Opcode::HIDUnsetDescriptor) => { - match hidv2.reset_device_report() { - Ok(_) => (), - Err(error) => log::error!("cannot reset hidv2 device report: {:?}", error), + } } } + Some(Opcode::HIDUnsetDescriptor) => match hidv2.reset_device_report() { + Ok(_) => (), + Err(error) => log::error!("cannot reset hidv2 device report: {:?}", error), + }, Some(Opcode::HIDReadReport) => { if !hidv2.descriptor_set() { log::warn!("trying to read a HID report with no descriptor set!"); - continue + continue; } - let mut buffer = unsafe { - Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap()) - }; + let mut buffer = + unsafe { Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap()) }; let mut data = buffer.to_original::().unwrap(); data.data = hidv2.read_report(); buffer.replace(data).expect("couldn't serialize return"); - }, + } Some(Opcode::HIDWriteReport) => { if !hidv2.descriptor_set() { log::warn!("trying to write a HID report with no descriptor set!"); - continue + continue; } - let buffer = unsafe { - Buffer::from_memory_message(msg.body.memory_message().unwrap()) - }; + let buffer = unsafe { Buffer::from_memory_message(msg.body.memory_message().unwrap()) }; let data = buffer.to_original::().unwrap(); - log::info!("report to be written to USB: {:?}", data); hidv2.write_report(data); - }, + } Some(Opcode::RegisterUsbObserver) => { let buffer = unsafe { Buffer::from_memory_message(msg.body.memory_message().unwrap()) }; let ur = buffer.as_flat::().unwrap();