Skip to content

Commit

Permalink
services/usb-device-xous: format code
Browse files Browse the repository at this point in the history
  • Loading branch information
Gianguido Sora committed Jan 30, 2024
1 parent a64edbd commit 73d3563
Show file tree
Hide file tree
Showing 3 changed files with 53 additions and 78 deletions.
6 changes: 2 additions & 4 deletions services/usb-device-xous/src/api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)]
Expand All @@ -186,4 +184,4 @@ pub struct HIDReportMessage {
pub(crate) struct UsbListenerRegistration {
pub server_name: xous_ipc::String<64>,
pub listener_op_id: usize,
}
}
76 changes: 29 additions & 47 deletions services/usb-device-xous/src/hid.rs
Original file line number Diff line number Diff line change
@@ -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},
Expand All @@ -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> {
Expand All @@ -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<HIDReport> {
Expand All @@ -42,26 +41,19 @@ impl<'a, B: UsbBus> AppHIDDevice<'a, B> {
}
}

pub fn set_device_descriptor(
&mut self,
descriptor: Vec<u8>,
) -> Result<(), usb_device::UsbError> {
pub fn set_device_descriptor(&mut self, descriptor: Vec<u8>) -> Result<(), usb_device::UsbError> {
self.interface.set_report_descriptor(descriptor)
}
}

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> {
Expand Down Expand Up @@ -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<B>) -> Self::Allocated {
Self::Allocated {
interface: HeapInterface::new(usb_alloc, self.interface),
}
Self::Allocated { interface: HeapInterface::new(usb_alloc, self.interface) }
}
}

Expand All @@ -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<HIDReport>,
Expand Down Expand Up @@ -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> {
Expand All @@ -179,21 +165,22 @@ impl<'a, B: UsbBus> AppHID<'a, B> {
let hidv2_device = self.class.device::<AppHIDDevice<'_, _>, _>();
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));
}
Expand All @@ -208,19 +195,16 @@ impl<'a, B: UsbBus> AppHID<'a, B> {
pub fn set_device_report(&mut self, descriptor: Vec<u8>) -> Result<(), AppHIDError> {
let descr_len = descriptor.len();
let hidv2_device = self.class.device::<AppHIDDevice<'_, _>, _>();
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.
Expand All @@ -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<HIDReport> {
Expand Down
49 changes: 22 additions & 27 deletions services/usb-device-xous/src/main_hw.rs
Original file line number Diff line number Diff line change
@@ -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;
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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.",
Expand Down Expand Up @@ -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<xous::MessageEnvelope> = None;
// under the theory that PIDs cannot be forged. TODO: check that PIDs cannot be forged.
Expand Down Expand Up @@ -935,7 +935,7 @@ pub(crate) fn main_hw() -> ! {
usbmgmt.ll_reset(false);
}
}
},
}
UsbDeviceType::HIDv2 => {
log::info!("Connectiing HIDv2 device");
match view {
Expand Down Expand Up @@ -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();
Expand Down Expand Up @@ -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::<HIDReportDescriptorMessage, _>().unwrap();

// This branch can only error if data.descriptor is longer than the
Expand All @@ -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::<HIDReportMessage, _>().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::<HIDReport, _>().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::<UsbListenerRegistration, _>().unwrap();
Expand Down

0 comments on commit 73d3563

Please sign in to comment.