Skip to content

Commit

Permalink
Renamed error type, improved documentation
Browse files Browse the repository at this point in the history
  • Loading branch information
G2-Games committed Aug 14, 2024
1 parent f1fa9dd commit 924a19d
Show file tree
Hide file tree
Showing 5 changed files with 118 additions and 68 deletions.
4 changes: 2 additions & 2 deletions .cargo/config.toml
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,5 @@ rustflags = ["--cfg=web_sys_unstable_apis"]

[build]
#just comment in the "current" target
#target = "x86_64-unknown-linux-gnu"
target = "wasm32-unknown-unknown"
target = "x86_64-unknown-linux-gnu"
#target = "wasm32-unknown-unknown"
44 changes: 22 additions & 22 deletions src/backend/native.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use crate::usb::{
ControlIn, ControlOut, ControlType, UsbDeviceInfo, UsbDevice, UsbInterface, Recipient, UsbError,
ControlIn, ControlOut, ControlType, UsbDeviceInfo, UsbDevice, UsbInterface, Recipient, Error,
};

#[derive(Clone, Debug)]
Expand Down Expand Up @@ -60,7 +60,7 @@ impl DeviceFilter {

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

let mut device_info = None;
Expand Down Expand Up @@ -98,15 +98,15 @@ pub async fn get_device(

let device_info = match device_info {
Some(dev) => dev,
None => return Err(UsbError::DeviceNotFound),
None => return Err(Error::DeviceNotFound),
};

Ok(DeviceInfo { device_info })
}

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

let mut devices = Vec::new();
Expand Down Expand Up @@ -142,7 +142,7 @@ pub async fn get_device_list(
}

if devices.is_empty() {
return Err(UsbError::DeviceNotFound);
return Err(Error::DeviceNotFound);
}

let devices_opened: Vec<DeviceInfo> = devices
Expand All @@ -156,13 +156,13 @@ pub async fn get_device_list(
impl UsbDeviceInfo for DeviceInfo {
type Device = Device;

async fn open(self) -> Result<Self::Device, UsbError> {
async fn open(self) -> Result<Self::Device, Error> {
match self.device_info.open() {
Ok(dev) => Ok(Self::Device {
device_info: self,
device: dev,
}),
Err(err) => Err(UsbError::CommunicationError(err.to_string())),
Err(err) => Err(Error::CommunicationError(err.to_string())),
}
}

Expand Down Expand Up @@ -194,10 +194,10 @@ impl UsbDeviceInfo for DeviceInfo {
impl UsbDevice for Device {
type Interface = Interface;

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

Ok(Interface {
Expand All @@ -206,10 +206,10 @@ impl UsbDevice for Device {
})
}

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

Ok(Interface {
Expand All @@ -218,14 +218,14 @@ impl UsbDevice for Device {
})
}

async fn reset(&self) -> Result<(), UsbError> {
async fn reset(&self) -> Result<(), Error> {
match self.device.reset() {
Ok(_) => Ok(()),
Err(err) => Err(UsbError::CommunicationError(err.to_string())),
Err(err) => Err(Error::CommunicationError(err.to_string())),
}
}

async fn forget(&self) -> Result<(), UsbError> {
async fn forget(&self) -> Result<(), Error> {
self.reset().await
}

Expand Down Expand Up @@ -261,23 +261,23 @@ impl Drop for Device {
}

impl<'a> UsbInterface<'a> for Interface {
async fn control_in(&self, data: ControlIn) -> Result<Vec<u8>, UsbError> {
async fn control_in(&self, data: ControlIn) -> Result<Vec<u8>, Error> {
let result = match self.interface.control_in(data.into()).await.into_result() {
Ok(res) => res,
Err(_) => return Err(UsbError::TransferError),
Err(_) => return Err(Error::TransferError),
};

Ok(result)
}

async fn control_out(&self, data: ControlOut<'a>) -> Result<usize, UsbError> {
async fn control_out(&self, data: ControlOut<'a>) -> Result<usize, Error> {
match self.interface.control_out(data.into()).await.into_result() {
Ok(bytes) => Ok(bytes.actual_length()),
Err(_) => Err(UsbError::TransferError),
Err(_) => Err(Error::TransferError),
}
}

async fn bulk_in(&self, endpoint: u8, length: usize) -> Result<Vec<u8>, UsbError> {
async fn bulk_in(&self, endpoint: u8, length: usize) -> Result<Vec<u8>, Error> {
let request_buffer = nusb::transfer::RequestBuffer::new(length);

match self
Expand All @@ -287,19 +287,19 @@ impl<'a> UsbInterface<'a> for Interface {
.into_result()
{
Ok(res) => Ok(res),
Err(_) => Err(UsbError::TransferError),
Err(_) => Err(Error::TransferError),
}
}

async fn bulk_out(&self, endpoint: u8, data: &[u8]) -> Result<usize, UsbError> {
async fn bulk_out(&self, endpoint: u8, data: &[u8]) -> Result<usize, Error> {
match self
.interface
.bulk_out(endpoint, data.to_vec())
.await
.into_result()
{
Ok(len) => Ok(len.actual_length()),
Err(_) => Err(UsbError::TransferError),
Err(_) => Err(Error::TransferError),
}
}

Expand Down
38 changes: 19 additions & 19 deletions src/backend/wasm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ use web_sys::{

// Crate stuff
use crate::usb::{
ControlIn, ControlOut, ControlType, UsbDeviceInfo, UsbDevice, UsbInterface, Recipient, UsbError,
ControlIn, ControlOut, ControlType, UsbDeviceInfo, UsbDevice, UsbInterface, Recipient, Error,
};

#[wasm_bindgen]
Expand Down Expand Up @@ -274,7 +274,7 @@ pub async fn get_device_list(device_filter: Vec<DeviceFilter>) -> Result<Vec<Dev
impl UsbDeviceInfo for DeviceInfo {
type Device = Device;

async fn open(self) -> Result<Self::Device, UsbError> {
async fn open(self) -> Result<Self::Device, Error> {
Ok(Self::Device {
device: self.device,
})
Expand Down Expand Up @@ -308,15 +308,15 @@ impl UsbDeviceInfo for DeviceInfo {
impl UsbDevice for Device {
type Interface = Interface;

async fn open_interface(&self, number: u8) -> Result<Interface, UsbError> {
async fn open_interface(&self, number: u8) -> Result<Interface, Error> {
let dev_promise =
JsFuture::from(Promise::resolve(&self.device.claim_interface(number))).await;

// Wait for the interface to be claimed
let _device: WasmUsbDevice = match dev_promise {
Ok(dev) => dev.into(),
Err(err) => {
return Err(UsbError::CommunicationError(
return Err(Error::CommunicationError(
err.as_string().unwrap_or_default(),
));
}
Expand All @@ -328,27 +328,27 @@ impl UsbDevice for Device {
})
}

async fn detach_and_open_interface(&self, number: u8) -> Result<Self::Interface, UsbError> {
async fn detach_and_open_interface(&self, number: u8) -> Result<Self::Interface, Error> {
self.open_interface(number).await
}

async fn reset(&self) -> Result<(), UsbError> {
async fn reset(&self) -> Result<(), Error> {
let result = JsFuture::from(Promise::resolve(&self.device.reset())).await;

match result {
Ok(_) => Ok(()),
Err(err) => Err(UsbError::CommunicationError(
Err(err) => Err(Error::CommunicationError(
err.as_string().unwrap_or_default(),
)),
}
}

async fn forget(&self) -> Result<(), UsbError> {
async fn forget(&self) -> Result<(), Error> {
let result = JsFuture::from(Promise::resolve(&self.device.forget())).await;

match result {
Ok(_) => Ok(()),
Err(err) => Err(UsbError::CommunicationError(
Err(err) => Err(Error::CommunicationError(
err.as_string().unwrap_or_default(),
)),
}
Expand Down Expand Up @@ -380,7 +380,7 @@ impl UsbDevice for Device {
}

impl<'a> UsbInterface<'a> for Interface {
async fn control_in(&self, data: crate::usb::ControlIn) -> Result<Vec<u8>, UsbError> {
async fn control_in(&self, data: crate::usb::ControlIn) -> Result<Vec<u8>, Error> {
let length = data.length;
let params: UsbControlTransferParameters = data.into();

Expand All @@ -389,20 +389,20 @@ impl<'a> UsbInterface<'a> for Interface {

let transfer_result: UsbInTransferResult = match result {
Ok(res) => res.into(),
Err(_) => return Err(UsbError::TransferError),
Err(_) => return Err(Error::TransferError),
};

let data = match transfer_result.data() {
Some(res) => res.buffer(),
None => return Err(UsbError::TransferError),
None => return Err(Error::TransferError),
};

let array = Uint8Array::new(&data);

Ok(array.to_vec())
}

async fn control_out(&self, data: crate::usb::ControlOut<'a>) -> Result<usize, UsbError> {
async fn control_out(&self, data: crate::usb::ControlOut<'a>) -> Result<usize, Error> {
let array = Uint8Array::from(data.data);
let array_obj = Object::try_from(&array).unwrap();
let params: UsbControlTransferParameters = data.into();
Expand All @@ -415,33 +415,33 @@ impl<'a> UsbInterface<'a> for Interface {
.await
{
Ok(res) => res.into(),
Err(_) => return Err(UsbError::TransferError),
Err(_) => return Err(Error::TransferError),
};

Ok(result.bytes_written() as usize)
}

async fn bulk_in(&self, endpoint: u8, length: usize) -> Result<Vec<u8>, UsbError> {
async fn bulk_in(&self, endpoint: u8, length: usize) -> Result<Vec<u8>, Error> {
let promise = Promise::resolve(&self.device.transfer_in(endpoint, length as u32));

let result = JsFuture::from(promise).await;

let transfer_result: UsbInTransferResult = match result {
Ok(res) => res.into(),
Err(_) => return Err(UsbError::TransferError),
Err(_) => return Err(Error::TransferError),
};

let data = match transfer_result.data() {
Some(res) => res.buffer(),
None => return Err(UsbError::TransferError),
None => return Err(Error::TransferError),
};

let array = Uint8Array::new(&data);

Ok(array.to_vec())
}

async fn bulk_out(&self, endpoint: u8, data: &[u8]) -> Result<usize, UsbError> {
async fn bulk_out(&self, endpoint: u8, data: &[u8]) -> Result<usize, Error> {
let array = Uint8Array::from(data);
let array_obj = Object::try_from(&array).unwrap();

Expand All @@ -455,7 +455,7 @@ impl<'a> UsbInterface<'a> for Interface {

let transfer_result: UsbOutTransferResult = match result {
Ok(res) => res.into(),
Err(_) => return Err(UsbError::TransferError),
Err(_) => return Err(Error::TransferError),
};

Ok(transfer_result.bytes_written() as usize)
Expand Down
27 changes: 17 additions & 10 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,18 @@
//! 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 an [`Interface`] 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).
//! * Isochronous and interrupt transfers are currently not supported. This
//! will probably change in a future release.
//!
//! * Hotplug support is not implemented. Waiting on
//! [hotplug support in nusb](https://github.com/kevinmehall/nusb/pull/20).
//!
//! * When compiling this crate on a WASM target, you **must** use either
//! `RUSTFLAGS=--cfg=web_sys_unstable_apis` or by passing the argument in a
//! `.cargo/config.toml` file. Read more here: <https://rustwasm.github.io/wasm-bindgen/web-sys/unstable-apis.html>
//! `.cargo/config.toml` file. Read more here:
//! <https://rustwasm.github.io/wasm-bindgen/web-sys/unstable-apis.html>
//!
//! ## Example:
//! ```no_run
Expand Down Expand Up @@ -79,19 +83,23 @@ mod context;
/// without claiming it
///
/// **Note:** On WASM targets, a device *must* be claimed in order to get
/// information about it in normal circumstances.
/// information about it in normal circumstances, so this is not as useful
/// on WASM.
pub use crate::context::DeviceInfo;

#[doc(inline)]
/// A USB device, you must open an [`Interface`] to perform transfers
/// A USB device, you must open an [`Interface`] to perform transfers.
pub use crate::context::Device;

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

/// Information about a USB device for use in [`get_device`]
/// or [`get_device_list`]
/// Information about a USB device for use in [`get_device`] or
/// [`get_device_list`].
///
/// It's easiest to construct this using the [`device_filter`]
/// macro.
#[doc(inline)]
pub use crate::context::DeviceFilter;

Expand Down Expand Up @@ -164,8 +172,7 @@ macro_rules! device_filter {
}
}

#[cfg(target_family = "wasm")]
#[cfg(not(web_sys_unstable_apis))]
#[cfg(all(target_family = "wasm", not(web_sys_unstable_apis)))]
compile_error!{
"Cannot compile `web-sys` (a dependency of this crate) with USB support without `web_sys_unstable_apis`!
Please check https://rustwasm.github.io/wasm-bindgen/web-sys/unstable-apis.html for more info."
Expand Down
Loading

0 comments on commit 924a19d

Please sign in to comment.