Skip to content

Commit

Permalink
Renamed many items to be less redundant
Browse files Browse the repository at this point in the history
  • Loading branch information
G2-Games committed Mar 24, 2024
1 parent 092cb05 commit 93e621e
Show file tree
Hide file tree
Showing 4 changed files with 76 additions and 32 deletions.
62 changes: 43 additions & 19 deletions src/backend/native.rs
Original file line number Diff line number Diff line change
@@ -1,18 +1,34 @@
use crate::usb::{
ControlIn, ControlOut, ControlType, Descriptor, Device, Interface, Recipient, UsbError,
ControlIn, ControlOut, ControlType, UsbDescriptor, UsbDevice, UsbInterface, Recipient, UsbError,
};

pub struct UsbDescriptor {
#[derive(Clone, Debug)]
pub struct Descriptor {
device_info: nusb::DeviceInfo,
}

pub struct UsbDevice {
device_info: UsbDescriptor,
#[derive(Clone)]
pub struct Device {
device_info: Descriptor,
device: nusb::Device,
}

pub struct UsbInterface {
impl std::fmt::Debug for Device {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{:?}", self.device_info)
}
}

#[derive(Clone)]
pub struct Interface {
interface: nusb::Interface,
number: u8,
}

impl std::fmt::Debug for Interface {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "Interface {:?}", self.number)
}
}

#[derive(PartialEq, Clone, Default)]
Expand Down Expand Up @@ -42,7 +58,9 @@ impl DeviceFilter {
}
}

pub async fn get_device(device_filters: Vec<DeviceFilter>) -> Result<UsbDescriptor, UsbError> {
pub async fn get_device(
device_filters: Vec<DeviceFilter>
) -> Result<Descriptor, UsbError> {
let devices = nusb::list_devices().unwrap();

let mut device_info = None;
Expand Down Expand Up @@ -83,12 +101,12 @@ pub async fn get_device(device_filters: Vec<DeviceFilter>) -> Result<UsbDescript
None => return Err(UsbError::DeviceNotFound),
};

Ok(UsbDescriptor { device_info })
Ok(Descriptor { device_info })
}

pub async fn get_device_list(
device_filters: Vec<DeviceFilter>,
) -> Result<Vec<UsbDescriptor>, UsbError> {
) -> Result<impl Iterator<Item = Descriptor>, UsbError> {
let devices_info = nusb::list_devices().unwrap();

let mut devices = Vec::new();
Expand Down Expand Up @@ -127,16 +145,16 @@ pub async fn get_device_list(
return Err(UsbError::DeviceNotFound);
}

let devices_opened: Vec<UsbDescriptor> = devices
let devices_opened: Vec<Descriptor> = devices
.into_iter()
.map(|d| UsbDescriptor { device_info: d })
.map(|d| Descriptor { device_info: d })
.collect();

Ok(devices_opened)
Ok(devices_opened.into_iter())
}

impl Descriptor for UsbDescriptor {
type Device = UsbDevice;
impl UsbDescriptor for Descriptor {
type Device = Device;

async fn open(self) -> Result<Self::Device, UsbError> {
match self.device_info.open() {
Expand Down Expand Up @@ -173,16 +191,19 @@ impl Descriptor for UsbDescriptor {
}
}

impl Device for UsbDevice {
type Interface = UsbInterface;
impl UsbDevice for Device {
type Interface = Interface;

async fn open_interface(&self, number: u8) -> Result<Self::Interface, UsbError> {
let interface = match self.device.claim_interface(number) {
Ok(inter) => inter,
Err(err) => return Err(UsbError::CommunicationError(err.to_string())),
};

Ok(UsbInterface { interface })
Ok(Interface {
interface,
number
})
}

async fn detach_and_open_interface(&self, number: u8) -> Result<Self::Interface, UsbError> {
Expand All @@ -191,7 +212,10 @@ impl Device for UsbDevice {
Err(err) => return Err(UsbError::CommunicationError(err.to_string())),
};

Ok(UsbInterface { interface })
Ok(Interface {
interface,
number
})
}

async fn reset(&self) -> Result<(), UsbError> {
Expand Down Expand Up @@ -230,13 +254,13 @@ impl Device for UsbDevice {
}
}

impl Drop for UsbDevice {
impl Drop for Device {
fn drop(&mut self) {
let _ = self.device.reset();
}
}

impl<'a> Interface<'a> for UsbInterface {
impl<'a> UsbInterface<'a> for Interface {
async fn control_in(&self, data: ControlIn) -> Result<Vec<u8>, UsbError> {
let result = match self.interface.control_in(data.into()).await.into_result() {
Ok(res) => res,
Expand Down
3 changes: 3 additions & 0 deletions src/backend/wasm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,16 +14,19 @@ use crate::usb::{
};

#[wasm_bindgen]
#[derive(Debug)]
pub struct UsbDescriptor {
device: WasmUsbDevice,
}

#[wasm_bindgen]
#[derive(Debug)]
pub struct UsbDevice {
device: WasmUsbDevice,
}

#[wasm_bindgen]
#[derive(Debug)]
pub struct UsbInterface {
device: WasmUsbDevice,
_number: u8,
Expand Down
37 changes: 27 additions & 10 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
//! and comparable to the very popular `libusb` C library. Web Assembly support is provided by [web-sys](https://docs.rs/web-sys/latest/web_sys/)
//! with the [Web USB API](https://developer.mozilla.org/en-US/docs/Web/API/WebUSB_API).
//!
//! When a [UsbInterface] is dropped, it is automatically released.
//! When a [`UsbInterface`] is dropped, it is automatically released.
//!
//! ### CURRENT LIMITATIONS:
//! * Hotplug support is not implemented. Waiting on [hotplug support in nusb](https://github.com/kevinmehall/nusb/pull/20).
Expand Down Expand Up @@ -62,22 +62,23 @@ mod context;

#[doc(inline)]
/// An implementation of a USB device descriptor
pub use crate::context::UsbDescriptor;
pub use crate::context::Descriptor;

#[doc(inline)]
/// An implementation of a USB device
pub use crate::context::UsbDevice;
/// A USB device, you must open a [`UsbInterface`] to perform transfers
pub use crate::context::Device;

#[doc(inline)]
/// An implementation of a USB interface
pub use crate::context::UsbInterface;
/// A USB interface with which to perform transfers on
pub use crate::context::Interface;

/// Information about a USB device for finding it while trying
/// to look for new USB devices using [get_device]
/// Information about a USB device for use in [`get_device`]
/// or [`get_device_list`]
#[doc(inline)]
pub use crate::context::DeviceFilter;

/// Gets a single device descriptor ([UsbDescriptor]) from a list of VendorID and ProductIDs
/// Gets a single (the first found) [`UsbDescriptor`] from a list of VendorID
/// and ProductIDs
///
/// ## Example
/// ```no_run
Expand All @@ -95,7 +96,23 @@ pub use crate::context::DeviceFilter;
#[doc(inline)]
pub use crate::context::get_device;

/// Gets a list of devices from a list of VendorID and ProductIDs
/// Gets a list of [`UsbDescriptor`]s from a list of VendorID and ProductIDs
///
/// ## Example
/// ```no_run
/// # tokio_test::block_on(async {
/// use cross_usb::{get_device_list, DeviceFilter, device_filter};
///
/// let filter = vec![
/// device_filter!{vendor_id: 0x054c, product_id: 0x00c9},
/// device_filter!{vendor_id: 0x054c},
/// ];
///
/// let device_list = get_device_list(filter).await.expect("Could not find device in list");
///
/// /* Do something with the list of devices... */
/// # })
/// ```
#[cfg(not(target_family = "wasm"))]
#[doc(inline)]
pub use crate::context::get_device_list;
Expand Down
6 changes: 3 additions & 3 deletions src/usb.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

use thiserror::Error;

pub trait Descriptor {
pub trait UsbDescriptor {
/// A unique USB Device
type Device;

Expand Down Expand Up @@ -33,7 +33,7 @@ pub trait Descriptor {
}

/// A unique USB device
pub trait Device {
pub trait UsbDevice {
/// A unique Interface on a USB Device
type Interface;

Expand Down Expand Up @@ -77,7 +77,7 @@ pub trait Device {
}

/// A specific interface of a USB device
pub trait Interface<'a> {
pub trait UsbInterface<'a> {
/// A USB control in transfer (device to host)
/// Returns a [Result] with the bytes in a `Vec<u8>`
async fn control_in(&self, data: ControlIn) -> Result<Vec<u8>, UsbError>;
Expand Down

0 comments on commit 93e621e

Please sign in to comment.