Merge pull request #494 from gsora/gsora/app-hid

services/usb-device-xous: generic USB HID framework
This commit is contained in:
bunnie 2024-02-01 13:11:41 +08:00 committed by GitHub
commit 71d38008b8
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
12 changed files with 770 additions and 10 deletions

44
Cargo.lock generated
View file

@ -1927,9 +1927,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"
@ -2339,6 +2339,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.57 (registry+https://github.com/rust-lang/crates.io-index)",
"xous-api-log",
"xous-api-names",
"xous-ipc 0.9.57 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "hkdf"
version = "0.12.4"
@ -5308,6 +5326,8 @@ version = "0.1.0"
dependencies = [
"bitfield",
"embedded-time",
"frunk_core",
"fugit",
"ghostfat",
"keyboard",
"llio",
@ -5334,7 +5354,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]]
@ -5357,7 +5377,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]]
@ -5540,7 +5560,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]]
@ -6317,6 +6337,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"

View file

@ -85,6 +85,7 @@ members = [
"apps/vault/tools/vaultbackup-rs",
"apps/transientdisk",
"apps/chat-test",
"apps/hidv2",
"services/libstd-test",
"services/ffi-test",
"services/tts",

22
apps/hidv2/Cargo.toml Normal file
View file

@ -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 = []

View file

@ -0,0 +1,9 @@
{
"helloworld.hello": {
"en": "Hello World!",
"en-tts": "Hello World!",
"fr": "Bonjour le monde!",
"ja": "Hello World!",
"zh": "大家好!"
}
}

235
apps/hidv2/src/main.rs Normal file
View file

@ -0,0 +1,235 @@
#![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<Sender<bool>> = 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<bool> {
let (tx, rx): (Sender<bool>, Receiver<bool>) = 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) => {
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;
}

View file

@ -49,6 +49,14 @@
}
}
},
"hidv2": {
"context_name": "HID v2 demo",
"menu_name": {
"appmenu.hidv2": {
"en": "HID v2 demo"
}
}
},
"mtxchat": {
"context_name": "[matrix]",
"menu_name": {
@ -124,4 +132,4 @@
},
"submenu": 1
}
}
}

View file

@ -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
@ -41,6 +41,8 @@ usbd_mass_storage = { path = "../../libs/mass-storage/usbd_mass_storage", option
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

View file

@ -62,6 +62,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
@ -110,8 +123,10 @@ pub enum UsbDeviceType {
#[cfg(feature = "mass-storage")]
MassStorage = 3,
Serial = 4,
HIDv2 = 5,
}
use std::convert::TryFrom;
impl TryFrom<usize> for UsbDeviceType {
type Error = &'static str;
@ -123,6 +138,7 @@ impl TryFrom<usize> for UsbDeviceType {
#[cfg(feature = "mass-storage")]
3 => Ok(UsbDeviceType::MassStorage),
4 => Ok(UsbDeviceType::Serial),
5 => Ok(UsbDeviceType::HIDv2),
_ => Err("Invalid UsbDeviceType specifier"),
}
}
@ -142,6 +158,27 @@ pub struct UsbSerialBinary {
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)]
#[repr(C, align(8))]
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: Option<HIDReport>,
}
/// this structure is used to register a USB listener.
#[derive(Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize, Copy, Clone)]
pub(crate) struct UsbListenerRegistration {

View file

@ -0,0 +1,234 @@
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},
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;
/// 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> AppHIDDevice<'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<HIDReport> {
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<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 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 = AppHIDDevice<'a, B>;
fn allocate(self, usb_alloc: &'a UsbBusAllocator<B>) -> Self::Allocated {
Self::Allocated { interface: HeapInterface::new(usb_alloc, self.interface) }
}
}
#[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<HIDReport>,
device_descr_set: Arc<Mutex<bool>>,
class: UsbHidClass<'a, B, HCons<AppHIDDevice<'a, B>, 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<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();
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::<AppHIDDevice<'_, _>, _>();
match hidv2_device.read_report() {
Ok(report) => {
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);
};
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 !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<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,
};
self.device.force_reset().ok();
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![])
}
/// 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<HIDReport> {
if !self.descriptor_set() {
return None;
}
self.incoming_reports.pop_front()
}
/// Writes a HID report on the USB bus.
pub fn write_report(&mut self, data: HIDReport) {
let hidv2_device = self.class.device::<AppHIDDevice<'_, _>, _>();
hidv2_device.write_report(&data).ok();
}
}

View file

@ -380,6 +380,72 @@ impl UsbHid {
buf.lend(self.conn, Opcode::RegisterUsbObserver.to_u32().unwrap())
.expect("couldn't register listener");
}
/// Sets the userland application HID device descriptor.
/// It cannot be longer than 1024 bytes.
pub fn connect_hid_app(&self, descriptor: Vec<u8>) -> 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(())
}
/// 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(),
0, 0, 0, 0)
) {
Ok(_) => Ok(()),
Err(err) => Err(err),
}
}
/// Reads a HID report off the USB bus.
pub fn read_report(&self) -> Result<HIDReport, xous::Error> {
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::<HIDReportMessage, _>().unwrap();
match &report.data {
rkyv::core_impl::ArchivedOption::Some(data) => {
let mut ret = HIDReport::default();
for (&s, d) in data.0[..data.0.len() as usize].iter().zip(ret.0.iter_mut()) {
*d = s;
}
Ok(ret)
},
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(|_| ())?;
Ok(())
}
}
use core::sync::atomic::{AtomicU32, Ordering};

View file

@ -24,6 +24,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;
use std::collections::BTreeMap;

View file

@ -25,12 +25,13 @@ 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;
#[derive(Eq, PartialEq)]
#[derive(Eq, PartialEq, Debug)]
#[repr(usize)]
enum Views {
FidoWithKbd = 0,
@ -38,6 +39,7 @@ enum Views {
#[cfg(feature = "mass-storage")]
MassStorage = 2,
Serial = 3,
HIDv2 = 4,
}
#[derive(num_derive::FromPrimitive, num_derive::ToPrimitive, Debug)]
@ -187,7 +189,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")]
@ -282,6 +284,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
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(),
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.
@ -483,6 +496,12 @@ pub(crate) fn main_hw() -> ! {
_ => (),
};
}
Views::HIDv2 => {
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),
_ => (),
@ -604,6 +623,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);
@ -645,7 +665,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) {
Ok(len) => match std::str::from_utf8(&data[..len]) {
@ -757,6 +777,14 @@ pub(crate) fn main_hw() -> ! {
}
None
}
Views::HIDv2 => {
match hidv2.poll() {
Ok(_) => (),
Err(error) => log::error!("hidv2 poll error: {:?}", error),
}
None
}
};
if let Some(u2f) = maybe_u2f {
match u2f.read_report() {
@ -789,6 +817,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.state() == UsbDeviceState::Suspend,
};
if is_suspend {
log::info!("suspend detected");
@ -907,6 +936,20 @@ pub(crate) fn main_hw() -> ! {
}
}
}
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();
}),
@ -1025,6 +1068,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();
}),
@ -1044,6 +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()
}
}
} else {
xous::return_scalar(msg.sender, UsbDeviceType::Debug as usize).unwrap();
@ -1096,6 +1158,7 @@ pub(crate) fn main_hw() -> ! {
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.state() as usize).unwrap(),
}
}),
Some(Opcode::SendKeyCode) => msg_blocking_scalar_unpack!(msg, code0, code1, code2, autoup, {
@ -1550,6 +1613,53 @@ 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::<HIDReportDescriptorMessage, _>().unwrap();
// 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) => {
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::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::<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;
}
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();