Compare commits

..

No commits in common. "1c193fb97c5dee01400a58b35e4aa2da9f1ad543" and "fea600bff79ed8dc5651c9d47148fe80fc40e3d5" have entirely different histories.

7 changed files with 110 additions and 159 deletions

View file

@ -3,5 +3,5 @@ rustflags = ["--cfg=web_sys_unstable_apis"]
[build] [build]
#just comment in the "current" target #just comment in the "current" target
target = "x86_64-unknown-linux-gnu" #target = "x86_64-unknown-linux-gnu"
#target = "wasm32-unknown-unknown" target = "wasm32-unknown-unknown"

View file

@ -1,13 +1,13 @@
[package] [package]
name = "cross_usb" name = "cross_usb"
version = "0.4.0" version = "0.3.4"
authors = ["G2-Games <ke0bhogsg@gmail.com>"] authors = ["G2-Games <ke0bhogsg@gmail.com>"]
repository = "https://github.com/G2-Games/cross-usb" repository = "https://github.com/G2-Games/cross-usb"
documentation = "https://docs.rs/cross_usb" documentation = "https://docs.rs/cross_usb"
description = """ description = """
A Rust USB library which works seamlessly across both native and WASM targets. A Rust USB library which works seamlessly across both native and WASM targets.
""" """
keywords = ["usb", "wasm", "web-usb", "webusb"] keywords = ["usb", "wasm", "web-usb"]
categories = ["wasm", "web-programming", "hardware-support"] categories = ["wasm", "web-programming", "hardware-support"]
readme = "README.md" readme = "README.md"
license = "MIT" license = "MIT"
@ -17,7 +17,7 @@ edition = "2021"
crate-type = ["cdylib", "rlib"] crate-type = ["cdylib", "rlib"]
[dependencies] [dependencies]
thiserror = "1.0" thiserror = "1.0.56"
[dev-dependencies] [dev-dependencies]
tokio-test = "0.4.3" tokio-test = "0.4.3"
@ -48,11 +48,14 @@ features = [
[target.'cfg(not(target_family = "wasm"))'.dependencies] [target.'cfg(not(target_family = "wasm"))'.dependencies]
nusb = "0.1" nusb = "0.1"
[profile.release]
lto = true
strip = true
opt-level = "z"
codegen-units = 1
[package.metadata.wasm-pack.profile.dev.wasm-bindgen] [package.metadata.wasm-pack.profile.dev.wasm-bindgen]
dwarf-debug-info = true dwarf-debug-info = true
[package.metadata.docs.rs] [package.metadata.docs.rs]
targets = ["x86_64-unknown-linux-gnu", "x86_64-pc-windows-msvc", "x86_64-apple-darwin", "aarch64-apple-darwin", "wasm32-unknown-unknown"] targets = ["x86_64-unknown-linux-gnu", "x86_64-pc-windows-msvc", "x86_64-apple-darwin", "aarch64-apple-darwin", "wasm32-unknown-unknown"]
[lints.rust]
unexpected_cfgs = { level = "warn", check-cfg = ['cfg(web_sys_unstable_apis)'] }

View file

@ -21,13 +21,9 @@ A USB library which works seamlessly across most native and WASM targets.
## Dependencies ## Dependencies
For native USB, the crate utilizies [nusb](https://github.com/kevinmehall/nusb), For native USB, the crate utilizies [nusb](https://github.com/kevinmehall/nusb), a pure rust library similar to the very popular libusb.
a pure rust library similar to the very popular libusb. **If you don't need WASM
support, just using `nusb` is the way to go!**
For WASM, this crate utilizes [web-sys](https://crates.io/crates/web-sys) which For WASM, this crate utilizes [web-sys](https://crates.io/crates/web-sys) which gives access to browser API calls, and in this case is used to interact with [WebUSB](https://developer.mozilla.org/en-US/docs/Web/API/WebUSB_API)
gives access to browser API calls, and in this case is used to interact with
[WebUSB](https://developer.mozilla.org/en-US/docs/Web/API/WebUSB_API).
## Example ## Example
To learn about how USB communciations work, check out [USB in a NutShell](https://www.beyondlogic.org/usbnutshell/usb1.shtml). To learn about how USB communciations work, check out [USB in a NutShell](https://www.beyondlogic.org/usbnutshell/usb1.shtml).
@ -67,8 +63,6 @@ Check out the [documentation](https://docs.rs/cross_usb/latest/) as well!
## TODO ## TODO
- [ ] Add choice for native backend between `libusb` wrapper and pure rust - [ ] Add choice for native backend between `libusb` wrapper and pure rust `nusb`
`nusb`
- [ ] Allow platform-specific operations if the user requires them - [ ] Allow platform-specific operations if the user requires them
- [ ] Hot plug support... requires either using `libusb` as an optional backend - [ ] Hot plug support... requires either using `libusb` as an optional backend or for [`nusb` to implement it](https://github.com/kevinmehall/nusb/issues/5)
or for [`nusb` to implement it](https://github.com/kevinmehall/nusb/issues/5)

View file

@ -1,15 +1,15 @@
use crate::usb::{ use crate::usb::{
ControlIn, ControlOut, ControlType, UsbDeviceInfo, UsbDevice, UsbInterface, Recipient, Error, ControlIn, ControlOut, ControlType, UsbDescriptor, UsbDevice, UsbInterface, Recipient, UsbError,
}; };
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
pub struct DeviceInfo { pub struct Descriptor {
device_info: nusb::DeviceInfo, device_info: nusb::DeviceInfo,
} }
#[derive(Clone)] #[derive(Clone)]
pub struct Device { pub struct Device {
device_info: DeviceInfo, device_info: Descriptor,
device: nusb::Device, device: nusb::Device,
} }
@ -60,7 +60,7 @@ impl DeviceFilter {
pub async fn get_device( pub async fn get_device(
device_filters: Vec<DeviceFilter> device_filters: Vec<DeviceFilter>
) -> Result<DeviceInfo, Error> { ) -> Result<Descriptor, UsbError> {
let devices = nusb::list_devices().unwrap(); let devices = nusb::list_devices().unwrap();
let mut device_info = None; let mut device_info = None;
@ -98,15 +98,15 @@ pub async fn get_device(
let device_info = match device_info { let device_info = match device_info {
Some(dev) => dev, Some(dev) => dev,
None => return Err(Error::DeviceNotFound), None => return Err(UsbError::DeviceNotFound),
}; };
Ok(DeviceInfo { device_info }) Ok(Descriptor { device_info })
} }
pub async fn get_device_list( pub async fn get_device_list(
device_filters: Vec<DeviceFilter>, device_filters: Vec<DeviceFilter>,
) -> Result<impl Iterator<Item = DeviceInfo>, Error> { ) -> Result<impl Iterator<Item = Descriptor>, UsbError> {
let devices_info = nusb::list_devices().unwrap(); let devices_info = nusb::list_devices().unwrap();
let mut devices = Vec::new(); let mut devices = Vec::new();
@ -142,27 +142,27 @@ pub async fn get_device_list(
} }
if devices.is_empty() { if devices.is_empty() {
return Err(Error::DeviceNotFound); return Err(UsbError::DeviceNotFound);
} }
let devices_opened: Vec<DeviceInfo> = devices let devices_opened: Vec<Descriptor> = devices
.into_iter() .into_iter()
.map(|d| DeviceInfo { device_info: d }) .map(|d| Descriptor { device_info: d })
.collect(); .collect();
Ok(devices_opened.into_iter()) Ok(devices_opened.into_iter())
} }
impl UsbDeviceInfo for DeviceInfo { impl UsbDescriptor for Descriptor {
type Device = Device; type Device = Device;
async fn open(self) -> Result<Self::Device, Error> { async fn open(self) -> Result<Self::Device, UsbError> {
match self.device_info.open() { match self.device_info.open() {
Ok(dev) => Ok(Self::Device { Ok(dev) => Ok(Self::Device {
device_info: self, device_info: self,
device: dev, device: dev,
}), }),
Err(err) => Err(Error::CommunicationError(err.to_string())), Err(err) => Err(UsbError::CommunicationError(err.to_string())),
} }
} }
@ -194,10 +194,10 @@ impl UsbDeviceInfo for DeviceInfo {
impl UsbDevice for Device { impl UsbDevice for Device {
type Interface = Interface; type Interface = Interface;
async fn open_interface(&self, number: u8) -> Result<Self::Interface, Error> { async fn open_interface(&self, number: u8) -> Result<Self::Interface, UsbError> {
let interface = match self.device.claim_interface(number) { let interface = match self.device.claim_interface(number) {
Ok(inter) => inter, Ok(inter) => inter,
Err(err) => return Err(Error::CommunicationError(err.to_string())), Err(err) => return Err(UsbError::CommunicationError(err.to_string())),
}; };
Ok(Interface { Ok(Interface {
@ -206,10 +206,10 @@ impl UsbDevice for Device {
}) })
} }
async fn detach_and_open_interface(&self, number: u8) -> Result<Self::Interface, Error> { async fn detach_and_open_interface(&self, number: u8) -> Result<Self::Interface, UsbError> {
let interface = match self.device.detach_and_claim_interface(number) { let interface = match self.device.detach_and_claim_interface(number) {
Ok(inter) => inter, Ok(inter) => inter,
Err(err) => return Err(Error::CommunicationError(err.to_string())), Err(err) => return Err(UsbError::CommunicationError(err.to_string())),
}; };
Ok(Interface { Ok(Interface {
@ -218,14 +218,14 @@ impl UsbDevice for Device {
}) })
} }
async fn reset(&self) -> Result<(), Error> { async fn reset(&self) -> Result<(), UsbError> {
match self.device.reset() { match self.device.reset() {
Ok(_) => Ok(()), Ok(_) => Ok(()),
Err(err) => Err(Error::CommunicationError(err.to_string())), Err(err) => Err(UsbError::CommunicationError(err.to_string())),
} }
} }
async fn forget(&self) -> Result<(), Error> { async fn forget(&self) -> Result<(), UsbError> {
self.reset().await self.reset().await
} }
@ -261,23 +261,23 @@ impl Drop for Device {
} }
impl<'a> UsbInterface<'a> for Interface { impl<'a> UsbInterface<'a> for Interface {
async fn control_in(&self, data: ControlIn) -> Result<Vec<u8>, Error> { async fn control_in(&self, data: ControlIn) -> Result<Vec<u8>, UsbError> {
let result = match self.interface.control_in(data.into()).await.into_result() { let result = match self.interface.control_in(data.into()).await.into_result() {
Ok(res) => res, Ok(res) => res,
Err(_) => return Err(Error::TransferError), Err(_) => return Err(UsbError::TransferError),
}; };
Ok(result) Ok(result)
} }
async fn control_out(&self, data: ControlOut<'a>) -> Result<usize, Error> { async fn control_out(&self, data: ControlOut<'a>) -> Result<usize, UsbError> {
match self.interface.control_out(data.into()).await.into_result() { match self.interface.control_out(data.into()).await.into_result() {
Ok(bytes) => Ok(bytes.actual_length()), Ok(bytes) => Ok(bytes.actual_length()),
Err(_) => Err(Error::TransferError), Err(_) => Err(UsbError::TransferError),
} }
} }
async fn bulk_in(&self, endpoint: u8, length: usize) -> Result<Vec<u8>, Error> { async fn bulk_in(&self, endpoint: u8, length: usize) -> Result<Vec<u8>, UsbError> {
let request_buffer = nusb::transfer::RequestBuffer::new(length); let request_buffer = nusb::transfer::RequestBuffer::new(length);
match self match self
@ -287,11 +287,11 @@ impl<'a> UsbInterface<'a> for Interface {
.into_result() .into_result()
{ {
Ok(res) => Ok(res), Ok(res) => Ok(res),
Err(_) => Err(Error::TransferError), Err(_) => Err(UsbError::TransferError),
} }
} }
async fn bulk_out(&self, endpoint: u8, data: &[u8]) -> Result<usize, Error> { async fn bulk_out(&self, endpoint: u8, data: &[u8]) -> Result<usize, UsbError> {
match self match self
.interface .interface
.bulk_out(endpoint, data.to_vec()) .bulk_out(endpoint, data.to_vec())
@ -299,7 +299,7 @@ impl<'a> UsbInterface<'a> for Interface {
.into_result() .into_result()
{ {
Ok(len) => Ok(len.actual_length()), Ok(len) => Ok(len.actual_length()),
Err(_) => Err(Error::TransferError), Err(_) => Err(UsbError::TransferError),
} }
} }

View file

@ -10,12 +10,12 @@ use web_sys::{
// Crate stuff // Crate stuff
use crate::usb::{ use crate::usb::{
ControlIn, ControlOut, ControlType, UsbDeviceInfo, UsbDevice, UsbInterface, Recipient, Error, ControlIn, ControlOut, ControlType, UsbDescriptor, UsbDevice, UsbInterface, Recipient, UsbError,
}; };
#[wasm_bindgen] #[wasm_bindgen]
#[derive(Debug)] #[derive(Debug)]
pub struct DeviceInfo { pub struct Descriptor {
device: WasmUsbDevice, device: WasmUsbDevice,
} }
@ -61,7 +61,7 @@ impl DeviceFilter {
} }
#[wasm_bindgen] #[wasm_bindgen]
pub async fn get_device(device_filter: Vec<DeviceFilter>) -> Result<DeviceInfo, js_sys::Error> { pub async fn get_device(device_filter: Vec<DeviceFilter>) -> Result<Descriptor, js_sys::Error> {
let window = web_sys::window().unwrap(); let window = web_sys::window().unwrap();
let navigator = window.navigator(); let navigator = window.navigator();
@ -102,7 +102,7 @@ pub async fn get_device(device_filter: Vec<DeviceFilter>) -> Result<DeviceInfo,
result result
}) { }) {
let _open_promise = JsFuture::from(Promise::resolve(&device.open())).await?; let _open_promise = JsFuture::from(Promise::resolve(&device.open())).await?;
return Ok(DeviceInfo { device }); return Ok(Descriptor { device });
} }
} }
@ -161,11 +161,12 @@ pub async fn get_device(device_filter: Vec<DeviceFilter>) -> Result<DeviceInfo,
let _open_promise = JsFuture::from(Promise::resolve(&device.open())).await?; let _open_promise = JsFuture::from(Promise::resolve(&device.open())).await?;
Ok(DeviceInfo { device }) Ok(Descriptor { device })
} }
/*
#[wasm_bindgen] #[wasm_bindgen]
pub async fn get_device_list(device_filter: Vec<DeviceFilter>) -> Result<Vec<DeviceInfo>, js_sys::Error> { pub async fn get_device_list(device_filter: Vec<DeviceFilter>) -> Result<Vec<UsbDescriptor>, js_sys::Error> {
let window = web_sys::window().unwrap(); let window = web_sys::window().unwrap();
let navigator = window.navigator(); let navigator = window.navigator();
@ -207,7 +208,7 @@ pub async fn get_device_list(device_filter: Vec<DeviceFilter>) -> Result<Vec<Dev
result result
}) { }) {
let _open_promise = JsFuture::from(Promise::resolve(&device.open())).await?; let _open_promise = JsFuture::from(Promise::resolve(&device.open())).await?;
devices.push(DeviceInfo { device }); devices.push(UsbDescriptor { device });
} }
} }
@ -266,26 +267,27 @@ pub async fn get_device_list(device_filter: Vec<DeviceFilter>) -> Result<Vec<Dev
let _open_promise = JsFuture::from(Promise::resolve(&device.open())).await?; let _open_promise = JsFuture::from(Promise::resolve(&device.open())).await?;
devices.push(DeviceInfo { device }); devices.push(UsbDescriptor { device });
return Ok(devices); return Ok(devices);
} }
*/
impl UsbDeviceInfo for DeviceInfo { impl UsbDescriptor for Descriptor {
type Device = Device; type Device = Device;
async fn open(self) -> Result<Self::Device, Error> { async fn open(self) -> Result<Self::Device, UsbError> {
Ok(Self::Device { Ok(Self::Device {
device: self.device, device: self.device,
}) })
} }
async fn product_id(&self) -> u16 { async fn product_id(&self) -> u16 {
self.device.product_id() self.device.vendor_id()
} }
async fn vendor_id(&self) -> u16 { async fn vendor_id(&self) -> u16 {
self.device.vendor_id() self.device.product_id()
} }
async fn class(&self) -> u8 { async fn class(&self) -> u8 {
@ -308,7 +310,7 @@ impl UsbDeviceInfo for DeviceInfo {
impl UsbDevice for Device { impl UsbDevice for Device {
type Interface = Interface; type Interface = Interface;
async fn open_interface(&self, number: u8) -> Result<Interface, Error> { async fn open_interface(&self, number: u8) -> Result<Interface, UsbError> {
let dev_promise = let dev_promise =
JsFuture::from(Promise::resolve(&self.device.claim_interface(number))).await; JsFuture::from(Promise::resolve(&self.device.claim_interface(number))).await;
@ -316,7 +318,7 @@ impl UsbDevice for Device {
let _device: WasmUsbDevice = match dev_promise { let _device: WasmUsbDevice = match dev_promise {
Ok(dev) => dev.into(), Ok(dev) => dev.into(),
Err(err) => { Err(err) => {
return Err(Error::CommunicationError( return Err(UsbError::CommunicationError(
err.as_string().unwrap_or_default(), err.as_string().unwrap_or_default(),
)); ));
} }
@ -328,27 +330,27 @@ impl UsbDevice for Device {
}) })
} }
async fn detach_and_open_interface(&self, number: u8) -> Result<Self::Interface, Error> { async fn detach_and_open_interface(&self, number: u8) -> Result<Self::Interface, UsbError> {
self.open_interface(number).await self.open_interface(number).await
} }
async fn reset(&self) -> Result<(), Error> { async fn reset(&self) -> Result<(), UsbError> {
let result = JsFuture::from(Promise::resolve(&self.device.reset())).await; let result = JsFuture::from(Promise::resolve(&self.device.reset())).await;
match result { match result {
Ok(_) => Ok(()), Ok(_) => Ok(()),
Err(err) => Err(Error::CommunicationError( Err(err) => Err(UsbError::CommunicationError(
err.as_string().unwrap_or_default(), err.as_string().unwrap_or_default(),
)), )),
} }
} }
async fn forget(&self) -> Result<(), Error> { async fn forget(&self) -> Result<(), UsbError> {
let result = JsFuture::from(Promise::resolve(&self.device.forget())).await; let result = JsFuture::from(Promise::resolve(&self.device.forget())).await;
match result { match result {
Ok(_) => Ok(()), Ok(_) => Ok(()),
Err(err) => Err(Error::CommunicationError( Err(err) => Err(UsbError::CommunicationError(
err.as_string().unwrap_or_default(), err.as_string().unwrap_or_default(),
)), )),
} }
@ -380,7 +382,7 @@ impl UsbDevice for Device {
} }
impl<'a> UsbInterface<'a> for Interface { impl<'a> UsbInterface<'a> for Interface {
async fn control_in(&self, data: crate::usb::ControlIn) -> Result<Vec<u8>, Error> { async fn control_in(&self, data: crate::usb::ControlIn) -> Result<Vec<u8>, UsbError> {
let length = data.length; let length = data.length;
let params: UsbControlTransferParameters = data.into(); let params: UsbControlTransferParameters = data.into();
@ -389,12 +391,12 @@ impl<'a> UsbInterface<'a> for Interface {
let transfer_result: UsbInTransferResult = match result { let transfer_result: UsbInTransferResult = match result {
Ok(res) => res.into(), Ok(res) => res.into(),
Err(_) => return Err(Error::TransferError), Err(_) => return Err(UsbError::TransferError),
}; };
let data = match transfer_result.data() { let data = match transfer_result.data() {
Some(res) => res.buffer(), Some(res) => res.buffer(),
None => return Err(Error::TransferError), None => return Err(UsbError::TransferError),
}; };
let array = Uint8Array::new(&data); let array = Uint8Array::new(&data);
@ -402,7 +404,7 @@ impl<'a> UsbInterface<'a> for Interface {
Ok(array.to_vec()) Ok(array.to_vec())
} }
async fn control_out(&self, data: crate::usb::ControlOut<'a>) -> Result<usize, Error> { async fn control_out(&self, data: crate::usb::ControlOut<'a>) -> Result<usize, UsbError> {
let array = Uint8Array::from(data.data); let array = Uint8Array::from(data.data);
let array_obj = Object::try_from(&array).unwrap(); let array_obj = Object::try_from(&array).unwrap();
let params: UsbControlTransferParameters = data.into(); let params: UsbControlTransferParameters = data.into();
@ -415,25 +417,25 @@ impl<'a> UsbInterface<'a> for Interface {
.await .await
{ {
Ok(res) => res.into(), Ok(res) => res.into(),
Err(_) => return Err(Error::TransferError), Err(_) => return Err(UsbError::TransferError),
}; };
Ok(result.bytes_written() as usize) Ok(result.bytes_written() as usize)
} }
async fn bulk_in(&self, endpoint: u8, length: usize) -> Result<Vec<u8>, Error> { async fn bulk_in(&self, endpoint: u8, length: usize) -> Result<Vec<u8>, UsbError> {
let promise = Promise::resolve(&self.device.transfer_in(endpoint, length as u32)); let promise = Promise::resolve(&self.device.transfer_in(endpoint, length as u32));
let result = JsFuture::from(promise).await; let result = JsFuture::from(promise).await;
let transfer_result: UsbInTransferResult = match result { let transfer_result: UsbInTransferResult = match result {
Ok(res) => res.into(), Ok(res) => res.into(),
Err(_) => return Err(Error::TransferError), Err(_) => return Err(UsbError::TransferError),
}; };
let data = match transfer_result.data() { let data = match transfer_result.data() {
Some(res) => res.buffer(), Some(res) => res.buffer(),
None => return Err(Error::TransferError), None => return Err(UsbError::TransferError),
}; };
let array = Uint8Array::new(&data); let array = Uint8Array::new(&data);
@ -441,7 +443,7 @@ impl<'a> UsbInterface<'a> for Interface {
Ok(array.to_vec()) Ok(array.to_vec())
} }
async fn bulk_out(&self, endpoint: u8, data: &[u8]) -> Result<usize, Error> { async fn bulk_out(&self, endpoint: u8, data: &[u8]) -> Result<usize, UsbError> {
let array = Uint8Array::from(data); let array = Uint8Array::from(data);
let array_obj = Object::try_from(&array).unwrap(); let array_obj = Object::try_from(&array).unwrap();
@ -455,7 +457,7 @@ impl<'a> UsbInterface<'a> for Interface {
let transfer_result: UsbOutTransferResult = match result { let transfer_result: UsbOutTransferResult = match result {
Ok(res) => res.into(), Ok(res) => res.into(),
Err(_) => return Err(Error::TransferError), Err(_) => return Err(UsbError::TransferError),
}; };
Ok(transfer_result.bytes_written() as usize) Ok(transfer_result.bytes_written() as usize)

View file

@ -7,18 +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/) //! 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). //! 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: //! ### CURRENT LIMITATIONS:
//! * Isochronous and interrupt transfers are currently not supported. This //! * Hotplug support is not implemented. Waiting on [hotplug support in nusb](https://github.com/kevinmehall/nusb/pull/20).
//! will probably change in a future release.
//! //!
//! * Hotplug support is not implemented. Waiting on //! * Until [this pull request](https://github.com/rustwasm/wasm-bindgen/issues/3155)
//! [hotplug support in nusb](https://github.com/kevinmehall/nusb/pull/20). //! is merged into wasm bindgen, getting a list of USB devices is not possible on WASM
//! targets. However, this isn't a huge deal as the user gets a list to select from anyway.
//! //!
//! * When compiling this crate on a WASM target, you **must** use either //! * 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 //! `RUSTFLAGS=--cfg=web_sys_unstable_apis` or by passing the argument in a
//! `.cargo/config.toml` file. Read more here: //! `.cargo/config.toml` file. Read more here: https://rustwasm.github.io/wasm-bindgen/web-sys/unstable-apis.html
//! <https://rustwasm.github.io/wasm-bindgen/web-sys/unstable-apis.html>
//! //!
//! ## Example: //! ## Example:
//! ```no_run //! ```no_run
@ -63,7 +63,7 @@ pub mod usb;
/// use cross_usb::prelude::*; /// use cross_usb::prelude::*;
/// ``` /// ```
pub mod prelude { pub mod prelude {
pub use crate::usb::UsbDeviceInfo; pub use crate::usb::UsbDescriptor;
pub use crate::usb::UsbDevice; pub use crate::usb::UsbDevice;
pub use crate::usb::UsbInterface; pub use crate::usb::UsbInterface;
} }
@ -79,31 +79,24 @@ mod context;
mod context; mod context;
#[doc(inline)] #[doc(inline)]
/// Information about a USB device, containing information about a device /// A descriptor of a USB device, containing information about a device
/// without claiming it /// without claiming it
/// pub use crate::context::Descriptor;
/// **Note:** On WASM targets, a device *must* be claimed in order to get
/// information about it in normal circumstances, so this is not as useful
/// on WASM.
pub use crate::context::DeviceInfo;
#[doc(inline)] #[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; pub use crate::context::Device;
#[doc(inline)] #[doc(inline)]
/// A USB interface to perform transfers with. /// A USB interface with which to perform transfers on
pub use crate::context::Interface; pub use crate::context::Interface;
/// Information about a USB device for use in [`get_device`] or /// Information about a USB device for use in [`get_device`]
/// [`get_device_list`]. /// or [`get_device_list`]
///
/// It's easiest to construct this using the [`device_filter`]
/// macro.
#[doc(inline)] #[doc(inline)]
pub use crate::context::DeviceFilter; pub use crate::context::DeviceFilter;
/// Gets a single (the first found) device as a [`DeviceInfo`] from a list of VendorID /// Gets a single (the first found) device as a [`Descriptor`] from a list of VendorID
/// and ProductIDs /// and ProductIDs
/// ///
/// ## Example /// ## Example
@ -122,7 +115,7 @@ pub use crate::context::DeviceFilter;
#[doc(inline)] #[doc(inline)]
pub use crate::context::get_device; pub use crate::context::get_device;
/// Gets a list of [`DeviceInfo`]s from a list of VendorID and ProductIDs /// Gets a list of [`Descriptor`]s from a list of VendorID and ProductIDs
/// ///
/// ## Example /// ## Example
/// ```no_run /// ```no_run
@ -172,7 +165,8 @@ macro_rules! device_filter {
} }
} }
#[cfg(all(target_family = "wasm", not(web_sys_unstable_apis)))] #[cfg(target_family = "wasm")]
#[cfg(not(web_sys_unstable_apis))]
compile_error!{ compile_error!{
"Cannot compile `web-sys` (a dependency of this crate) with USB support without `web_sys_unstable_apis`! "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." Please check https://rustwasm.github.io/wasm-bindgen/web-sys/unstable-apis.html for more info."

View file

@ -4,13 +4,12 @@
use thiserror::Error; use thiserror::Error;
/// Information about a USB device before claiming it. pub trait UsbDescriptor {
pub trait UsbDeviceInfo {
/// A unique USB Device /// A unique USB Device
type Device; type Device;
/// Opens the USB connection, returning a [Self::Device] /// Opens the USB connection, returning a [Self::Device]
async fn open(self) -> Result<Self::Device, Error>; async fn open(self) -> Result<Self::Device, UsbError>;
/// 16 bit device Product ID /// 16 bit device Product ID
async fn product_id(&self) -> u16; async fn product_id(&self) -> u16;
@ -33,30 +32,28 @@ pub trait UsbDeviceInfo {
async fn product_string(&self) -> Option<String>; async fn product_string(&self) -> Option<String>;
} }
/// A unique USB device. /// A unique USB device
///
/// In order to perform transfers, an interface must be opened.
pub trait UsbDevice { pub trait UsbDevice {
/// A unique Interface on a USB Device /// A unique Interface on a USB Device
type Interface; type Interface;
/// Open a specific interface of the device /// Open a specific interface of the device
async fn open_interface(&self, number: u8) -> Result<Self::Interface, Error>; async fn open_interface(&self, number: u8) -> Result<Self::Interface, UsbError>;
/// Open a specific interface of the device, detaching any /// Open a specific interface of the device, detaching any
/// kernel drivers and claiming it. /// kernel drivers and claiming it.
/// ///
/// **Note:** This only has an effect on Native, and only on Linux. /// **Note:** This only has an effect on Native, and only on Linux.
async fn detach_and_open_interface(&self, number: u8) -> Result<Self::Interface, Error>; async fn detach_and_open_interface(&self, number: u8) -> Result<Self::Interface, UsbError>;
/// Reset the device, which causes it to no longer be usable. You must /// Reset the device, which causes it to no longer be usable. You must
/// request a new device with [crate::get_device] /// request a new device with [crate::get_device]
async fn reset(&self) -> Result<(), Error>; async fn reset(&self) -> Result<(), UsbError>;
/// Remove the device from the paired devices list, causing it to no longer be usable. You must request to reconnect using [crate::get_device] /// Remove the device from the paired devices list, causing it to no longer be usable. You must request to reconnect using [crate::get_device]
/// ///
/// **Note:** On Native this simply resets the device. /// **Note:** On Native this simply resets the device.
async fn forget(&self) -> Result<(), Error>; async fn forget(&self) -> Result<(), UsbError>;
/// 16 bit device Product ID /// 16 bit device Product ID
async fn product_id(&self) -> u16; async fn product_id(&self) -> u16;
@ -83,22 +80,23 @@ pub trait UsbDevice {
pub trait UsbInterface<'a> { pub trait UsbInterface<'a> {
/// A USB control in transfer (device to host) /// A USB control in transfer (device to host)
/// Returns a [Result] with the bytes in a `Vec<u8>` /// Returns a [Result] with the bytes in a `Vec<u8>`
async fn control_in(&self, data: ControlIn) -> Result<Vec<u8>, Error>; async fn control_in(&self, data: ControlIn) -> Result<Vec<u8>, UsbError>;
/// A USB control out transfer (host to device) /// A USB control out transfer (host to device)
async fn control_out(&self, data: ControlOut<'a>) -> Result<usize, Error>; async fn control_out(&self, data: ControlOut<'a>) -> Result<usize, UsbError>;
/// A USB bulk in transfer (device to host) /// A USB bulk in transfer (device to host)
/// It takes in a bulk endpoint to send to along with the length of /// It takes in a bulk endpoint to send to along with the length of
/// data to read, and returns a [Result] with the bytes /// data to read, and returns a [Result] with the bytes
async fn bulk_in(&self, endpoint: u8, length: usize) -> Result<Vec<u8>, Error>; async fn bulk_in(&self, endpoint: u8, length: usize) -> Result<Vec<u8>, UsbError>;
/// A USB bulk out transfer (host to device). /// A USB bulk out transfer (host to device).
/// It takes in a bulk endpoint to send to along with some data as /// It takes in a bulk endpoint to send to along with some data as
/// a slice, and returns a [Result] containing the number of bytes transferred /// a slice, and returns a [Result] containing the number of bytes transferred
async fn bulk_out(&self, endpoint: u8, data: &[u8]) -> Result<usize, Error>; async fn bulk_out(&self, endpoint: u8, data: &[u8]) -> Result<usize, UsbError>;
/* TODO: Figure out interrupt transfers on Web USB /* TODO: Figure out interrupt transfers on Web USB
/// A USB interrupt in transfer (device to host). /// A USB interrupt in transfer (device to host).
/// Takes in an endpoint and a buffer to fill /// Takes in an endpoint and a buffer to fill
async fn interrupt_in(&self, endpoint: u8, length: usize) -> Result<Vec<u8>, UsbError>; async fn interrupt_in(&self, endpoint: u8, length: usize) -> Result<Vec<u8>, UsbError>;
@ -111,94 +109,54 @@ pub trait UsbInterface<'a> {
/// An error from a USB interface /// An error from a USB interface
#[derive(Error, Debug, PartialEq, Eq, PartialOrd, Ord)] #[derive(Error, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub enum Error { pub enum UsbError {
/// The device was not found.
#[error("device not found")] #[error("device not found")]
DeviceNotFound, DeviceNotFound,
/// An error occured during a transfer.
#[error("device transfer failed")] #[error("device transfer failed")]
TransferError, TransferError,
/// There was an error communicating with the device.
#[error("device communication failed")] #[error("device communication failed")]
CommunicationError(String), CommunicationError(String),
/// The device was disconnected and can no longer be accesed.
#[error("device disconnected")] #[error("device disconnected")]
Disconnected, Disconnected,
/// The device has gone into an invalid state, and needs to be
/// reconnected to.
#[error("device no longer valid")] #[error("device no longer valid")]
Invalid, Invalid,
} }
/// The type of USB control transfer. /// The type of USB transfer
pub enum ControlType { pub enum ControlType {
/// A standard transfer.
Standard = 0, Standard = 0,
/// A Class Device transfer.
Class = 1, Class = 1,
/// A Vendor defined transfer.
Vendor = 2, Vendor = 2,
} }
/// The recipient of a USB transfer. /// The recipient of a USB transfer
pub enum Recipient { pub enum Recipient {
/// The device is the recipient.
Device = 0, Device = 0,
/// An interface is the recipient.
Interface = 1, Interface = 1,
/// An endpoint is the recipient.
Endpoint = 2, Endpoint = 2,
/// Something else is the recipient.
Other = 3, Other = 3,
} }
/// Parameters for [UsbInterface::control_in]. /// Parameters for [UsbInterface::control_in]
pub struct ControlIn { pub struct ControlIn {
/// The [`ControlType`] of this transfer, in the `bmRequestType` field.
pub control_type: ControlType, pub control_type: ControlType,
/// The [`Recipient`] of this transfer, in the `bmRequestType` field.
pub recipient: Recipient, pub recipient: Recipient,
/// The value of `bRequest` field.
pub request: u8, pub request: u8,
/// The value of the `wValue` field.
pub value: u16, pub value: u16,
/// The value of the `wIndex` field.
pub index: u16, pub index: u16,
/// The number of bytes to read.
pub length: u16, pub length: u16,
} }
/// Parameters for [UsbInterface::control_out]. /// Parameters for [UsbInterface::control_out]
pub struct ControlOut<'a> { pub struct ControlOut<'a> {
/// The [`ControlType`] of this transfer, in the `bmRequestType` field.
pub control_type: ControlType, pub control_type: ControlType,
/// The [`Recipient`] of this transfer, in the `bmRequestType` field.
pub recipient: Recipient, pub recipient: Recipient,
/// The value of `bRequest` field.
pub request: u8, pub request: u8,
/// The value of the `wValue` field.
pub value: u16, pub value: u16,
/// The value of the `wIndex` field.
pub index: u16, pub index: u16,
/// The data to send in this transfer.
pub data: &'a [u8], pub data: &'a [u8],
} }