Skip to content

Commit

Permalink
Add UsbHostDeviceHandler for #7
Browse files Browse the repository at this point in the history
  • Loading branch information
jiegec committed Feb 1, 2023
1 parent 84b8d9d commit f112f76
Show file tree
Hide file tree
Showing 2 changed files with 62 additions and 6 deletions.
58 changes: 55 additions & 3 deletions src/host.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,17 @@ use super::*;

/// A handler to pass requests to a USB device of the host
#[derive(Clone)]
pub struct UsbHostHandler {
pub struct UsbHostInterfaceHandler {
handle: Arc<Mutex<DeviceHandle<GlobalContext>>>,
}

impl UsbHostHandler {
impl UsbHostInterfaceHandler {
pub fn new(handle: Arc<Mutex<DeviceHandle<GlobalContext>>>) -> Self {
Self { handle }
}
}

impl UsbInterfaceHandler for UsbHostHandler {
impl UsbInterfaceHandler for UsbHostInterfaceHandler {
fn handle_urb(
&mut self,
_interface: &UsbInterface,
Expand Down Expand Up @@ -90,3 +90,55 @@ impl UsbInterfaceHandler for UsbHostHandler {
self
}
}

/// A handler to pass requests to a USB device of the host
#[derive(Clone)]
pub struct UsbHostDeviceHandler {
handle: Arc<Mutex<DeviceHandle<GlobalContext>>>,
}

impl UsbHostDeviceHandler {
pub fn new(handle: Arc<Mutex<DeviceHandle<GlobalContext>>>) -> Self {
Self { handle }
}
}

impl UsbDeviceHandler for UsbHostDeviceHandler {
fn handle_urb(&mut self, setup: SetupPacket, req: &[u8]) -> Result<Vec<u8>> {
debug!("To host device: setup={:?} req={:?}", setup, req);
let mut buffer = [0u8; 1024];
let timeout = std::time::Duration::new(1, 0);
let handle = self.handle.lock().unwrap();
// control
if setup.request_type & 0x80 == 0 {
// control out
handle
.write_control(
setup.request_type,
setup.request,
setup.value,
setup.index,
req,
timeout,
)
.ok();
} else {
// control in
if let Ok(len) = handle.read_control(
setup.request_type,
setup.request,
setup.value,
setup.index,
&mut buffer,
timeout,
) {
return Ok(Vec::from(&buffer[..len]));
}
}
Ok(vec![])
}

fn as_any(&mut self) -> &mut dyn Any {
self
}
}
10 changes: 7 additions & 3 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -81,9 +81,10 @@ impl UsbIpServer {
});
}

let handler =
Arc::new(Mutex::new(Box::new(UsbHostHandler::new(handle.clone()))
as Box<dyn UsbInterfaceHandler + Send>));
let handler = Arc::new(Mutex::new(Box::new(UsbHostInterfaceHandler::new(
handle.clone(),
))
as Box<dyn UsbInterfaceHandler + Send>));
interfaces.push(UsbInterface {
interface_class: intf_desc.class_code(),
interface_subclass: intf_desc.sub_class_code(),
Expand Down Expand Up @@ -130,6 +131,9 @@ impl UsbIpServer {
interval: 0,
},
interfaces,
device_handler: Some(Arc::new(Mutex::new(Box::new(
UsbHostDeviceHandler::new(handle.clone()),
)))),
..UsbDevice::default()
};

Expand Down

0 comments on commit f112f76

Please sign in to comment.