mirror of
https://github.com/G2-Games/cross-usb.git
synced 2025-04-19 13:22:53 -05:00
Compare commits
4 commits
fea600bff7
...
1c193fb97c
Author | SHA1 | Date | |
---|---|---|---|
1c193fb97c | |||
a04497594e | |||
924a19d4c8 | |||
f1fa9dd19d |
7 changed files with 159 additions and 110 deletions
|
@ -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"
|
||||
|
|
15
Cargo.toml
15
Cargo.toml
|
@ -1,13 +1,13 @@
|
|||
[package]
|
||||
name = "cross_usb"
|
||||
version = "0.3.4"
|
||||
version = "0.4.0"
|
||||
authors = ["G2-Games <ke0bhogsg@gmail.com>"]
|
||||
repository = "https://github.com/G2-Games/cross-usb"
|
||||
documentation = "https://docs.rs/cross_usb"
|
||||
description = """
|
||||
A Rust USB library which works seamlessly across both native and WASM targets.
|
||||
"""
|
||||
keywords = ["usb", "wasm", "web-usb"]
|
||||
keywords = ["usb", "wasm", "web-usb", "webusb"]
|
||||
categories = ["wasm", "web-programming", "hardware-support"]
|
||||
readme = "README.md"
|
||||
license = "MIT"
|
||||
|
@ -17,7 +17,7 @@ edition = "2021"
|
|||
crate-type = ["cdylib", "rlib"]
|
||||
|
||||
[dependencies]
|
||||
thiserror = "1.0.56"
|
||||
thiserror = "1.0"
|
||||
|
||||
[dev-dependencies]
|
||||
tokio-test = "0.4.3"
|
||||
|
@ -48,14 +48,11 @@ features = [
|
|||
[target.'cfg(not(target_family = "wasm"))'.dependencies]
|
||||
nusb = "0.1"
|
||||
|
||||
[profile.release]
|
||||
lto = true
|
||||
strip = true
|
||||
opt-level = "z"
|
||||
codegen-units = 1
|
||||
|
||||
[package.metadata.wasm-pack.profile.dev.wasm-bindgen]
|
||||
dwarf-debug-info = true
|
||||
|
||||
[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"]
|
||||
|
||||
[lints.rust]
|
||||
unexpected_cfgs = { level = "warn", check-cfg = ['cfg(web_sys_unstable_apis)'] }
|
||||
|
|
14
README.md
14
README.md
|
@ -21,9 +21,13 @@ A USB library which works seamlessly across most native and WASM targets.
|
|||
|
||||
## Dependencies
|
||||
|
||||
For native USB, the crate utilizies [nusb](https://github.com/kevinmehall/nusb), a pure rust library similar to the very popular libusb.
|
||||
For native USB, the crate utilizies [nusb](https://github.com/kevinmehall/nusb),
|
||||
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 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)
|
||||
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).
|
||||
|
||||
## Example
|
||||
To learn about how USB communciations work, check out [USB in a NutShell](https://www.beyondlogic.org/usbnutshell/usb1.shtml).
|
||||
|
@ -63,6 +67,8 @@ Check out the [documentation](https://docs.rs/cross_usb/latest/) as well!
|
|||
|
||||
## TODO
|
||||
|
||||
- [ ] Add choice for native backend between `libusb` wrapper and pure rust `nusb`
|
||||
- [ ] Add choice for native backend between `libusb` wrapper and pure rust
|
||||
`nusb`
|
||||
- [ ] Allow platform-specific operations if the user requires them
|
||||
- [ ] Hot plug support... requires either using `libusb` as an optional backend or for [`nusb` to implement it](https://github.com/kevinmehall/nusb/issues/5)
|
||||
- [ ] Hot plug support... requires either using `libusb` as an optional backend
|
||||
or for [`nusb` to implement it](https://github.com/kevinmehall/nusb/issues/5)
|
||||
|
|
|
@ -1,15 +1,15 @@
|
|||
use crate::usb::{
|
||||
ControlIn, ControlOut, ControlType, UsbDescriptor, UsbDevice, UsbInterface, Recipient, UsbError,
|
||||
ControlIn, ControlOut, ControlType, UsbDeviceInfo, UsbDevice, UsbInterface, Recipient, Error,
|
||||
};
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Descriptor {
|
||||
pub struct DeviceInfo {
|
||||
device_info: nusb::DeviceInfo,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct Device {
|
||||
device_info: Descriptor,
|
||||
device_info: DeviceInfo,
|
||||
device: nusb::Device,
|
||||
}
|
||||
|
||||
|
@ -60,7 +60,7 @@ impl DeviceFilter {
|
|||
|
||||
pub async fn get_device(
|
||||
device_filters: Vec<DeviceFilter>
|
||||
) -> Result<Descriptor, UsbError> {
|
||||
) -> Result<DeviceInfo, Error> {
|
||||
let devices = nusb::list_devices().unwrap();
|
||||
|
||||
let mut device_info = None;
|
||||
|
@ -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(Descriptor { device_info })
|
||||
Ok(DeviceInfo { device_info })
|
||||
}
|
||||
|
||||
pub async fn get_device_list(
|
||||
device_filters: Vec<DeviceFilter>,
|
||||
) -> Result<impl Iterator<Item = Descriptor>, UsbError> {
|
||||
) -> Result<impl Iterator<Item = DeviceInfo>, Error> {
|
||||
let devices_info = nusb::list_devices().unwrap();
|
||||
|
||||
let mut devices = Vec::new();
|
||||
|
@ -142,27 +142,27 @@ pub async fn get_device_list(
|
|||
}
|
||||
|
||||
if devices.is_empty() {
|
||||
return Err(UsbError::DeviceNotFound);
|
||||
return Err(Error::DeviceNotFound);
|
||||
}
|
||||
|
||||
let devices_opened: Vec<Descriptor> = devices
|
||||
let devices_opened: Vec<DeviceInfo> = devices
|
||||
.into_iter()
|
||||
.map(|d| Descriptor { device_info: d })
|
||||
.map(|d| DeviceInfo { device_info: d })
|
||||
.collect();
|
||||
|
||||
Ok(devices_opened.into_iter())
|
||||
}
|
||||
|
||||
impl UsbDescriptor for Descriptor {
|
||||
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())),
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -194,10 +194,10 @@ impl UsbDescriptor for Descriptor {
|
|||
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 {
|
||||
|
@ -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 {
|
||||
|
@ -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
|
||||
}
|
||||
|
||||
|
@ -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
|
||||
|
@ -287,11 +287,11 @@ 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())
|
||||
|
@ -299,7 +299,7 @@ impl<'a> UsbInterface<'a> for Interface {
|
|||
.into_result()
|
||||
{
|
||||
Ok(len) => Ok(len.actual_length()),
|
||||
Err(_) => Err(UsbError::TransferError),
|
||||
Err(_) => Err(Error::TransferError),
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -10,12 +10,12 @@ use web_sys::{
|
|||
|
||||
// Crate stuff
|
||||
use crate::usb::{
|
||||
ControlIn, ControlOut, ControlType, UsbDescriptor, UsbDevice, UsbInterface, Recipient, UsbError,
|
||||
ControlIn, ControlOut, ControlType, UsbDeviceInfo, UsbDevice, UsbInterface, Recipient, Error,
|
||||
};
|
||||
|
||||
#[wasm_bindgen]
|
||||
#[derive(Debug)]
|
||||
pub struct Descriptor {
|
||||
pub struct DeviceInfo {
|
||||
device: WasmUsbDevice,
|
||||
}
|
||||
|
||||
|
@ -61,7 +61,7 @@ impl DeviceFilter {
|
|||
}
|
||||
|
||||
#[wasm_bindgen]
|
||||
pub async fn get_device(device_filter: Vec<DeviceFilter>) -> Result<Descriptor, js_sys::Error> {
|
||||
pub async fn get_device(device_filter: Vec<DeviceFilter>) -> Result<DeviceInfo, js_sys::Error> {
|
||||
let window = web_sys::window().unwrap();
|
||||
|
||||
let navigator = window.navigator();
|
||||
|
@ -102,7 +102,7 @@ pub async fn get_device(device_filter: Vec<DeviceFilter>) -> Result<Descriptor,
|
|||
result
|
||||
}) {
|
||||
let _open_promise = JsFuture::from(Promise::resolve(&device.open())).await?;
|
||||
return Ok(Descriptor { device });
|
||||
return Ok(DeviceInfo { device });
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -161,12 +161,11 @@ pub async fn get_device(device_filter: Vec<DeviceFilter>) -> Result<Descriptor,
|
|||
|
||||
let _open_promise = JsFuture::from(Promise::resolve(&device.open())).await?;
|
||||
|
||||
Ok(Descriptor { device })
|
||||
Ok(DeviceInfo { device })
|
||||
}
|
||||
|
||||
/*
|
||||
#[wasm_bindgen]
|
||||
pub async fn get_device_list(device_filter: Vec<DeviceFilter>) -> Result<Vec<UsbDescriptor>, js_sys::Error> {
|
||||
pub async fn get_device_list(device_filter: Vec<DeviceFilter>) -> Result<Vec<DeviceInfo>, js_sys::Error> {
|
||||
let window = web_sys::window().unwrap();
|
||||
|
||||
let navigator = window.navigator();
|
||||
|
@ -208,7 +207,7 @@ pub async fn get_device_list(device_filter: Vec<DeviceFilter>) -> Result<Vec<Usb
|
|||
result
|
||||
}) {
|
||||
let _open_promise = JsFuture::from(Promise::resolve(&device.open())).await?;
|
||||
devices.push(UsbDescriptor { device });
|
||||
devices.push(DeviceInfo { device });
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -267,27 +266,26 @@ pub async fn get_device_list(device_filter: Vec<DeviceFilter>) -> Result<Vec<Usb
|
|||
|
||||
let _open_promise = JsFuture::from(Promise::resolve(&device.open())).await?;
|
||||
|
||||
devices.push(UsbDescriptor { device });
|
||||
devices.push(DeviceInfo { device });
|
||||
|
||||
return Ok(devices);
|
||||
}
|
||||
*/
|
||||
|
||||
impl UsbDescriptor for Descriptor {
|
||||
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,
|
||||
})
|
||||
}
|
||||
|
||||
async fn product_id(&self) -> u16 {
|
||||
self.device.vendor_id()
|
||||
self.device.product_id()
|
||||
}
|
||||
|
||||
async fn vendor_id(&self) -> u16 {
|
||||
self.device.product_id()
|
||||
self.device.vendor_id()
|
||||
}
|
||||
|
||||
async fn class(&self) -> u8 {
|
||||
|
@ -310,7 +308,7 @@ impl UsbDescriptor for Descriptor {
|
|||
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;
|
||||
|
||||
|
@ -318,7 +316,7 @@ impl UsbDevice for Device {
|
|||
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(),
|
||||
));
|
||||
}
|
||||
|
@ -330,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(),
|
||||
)),
|
||||
}
|
||||
|
@ -382,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();
|
||||
|
||||
|
@ -391,12 +389,12 @@ 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);
|
||||
|
@ -404,7 +402,7 @@ impl<'a> UsbInterface<'a> for Interface {
|
|||
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();
|
||||
|
@ -417,25 +415,25 @@ 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);
|
||||
|
@ -443,7 +441,7 @@ impl<'a> UsbInterface<'a> for Interface {
|
|||
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();
|
||||
|
||||
|
@ -457,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)
|
||||
|
|
44
src/lib.rs
44
src/lib.rs
|
@ -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/)
|
||||
//! 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).
|
||||
//! ## CURRENT LIMITATIONS:
|
||||
//! * Isochronous and interrupt transfers are currently not supported. This
|
||||
//! will probably change in a future release.
|
||||
//!
|
||||
//! * Until [this pull request](https://github.com/rustwasm/wasm-bindgen/issues/3155)
|
||||
//! 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.
|
||||
//! * 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
|
||||
//! * 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
|
||||
|
@ -63,7 +63,7 @@ pub mod usb;
|
|||
/// use cross_usb::prelude::*;
|
||||
/// ```
|
||||
pub mod prelude {
|
||||
pub use crate::usb::UsbDescriptor;
|
||||
pub use crate::usb::UsbDeviceInfo;
|
||||
pub use crate::usb::UsbDevice;
|
||||
pub use crate::usb::UsbInterface;
|
||||
}
|
||||
|
@ -79,24 +79,31 @@ mod context;
|
|||
mod context;
|
||||
|
||||
#[doc(inline)]
|
||||
/// A descriptor of a USB device, containing information about a device
|
||||
/// Information about a USB device, containing information about a device
|
||||
/// 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)]
|
||||
/// 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;
|
||||
|
||||
/// Gets a single (the first found) device as a [`Descriptor`] from a list of VendorID
|
||||
/// Gets a single (the first found) device as a [`DeviceInfo`] from a list of VendorID
|
||||
/// and ProductIDs
|
||||
///
|
||||
/// ## Example
|
||||
|
@ -115,7 +122,7 @@ pub use crate::context::DeviceFilter;
|
|||
#[doc(inline)]
|
||||
pub use crate::context::get_device;
|
||||
|
||||
/// Gets a list of [`Descriptor`]s from a list of VendorID and ProductIDs
|
||||
/// Gets a list of [`DeviceInfo`]s from a list of VendorID and ProductIDs
|
||||
///
|
||||
/// ## Example
|
||||
/// ```no_run
|
||||
|
@ -165,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."
|
||||
|
|
76
src/usb.rs
76
src/usb.rs
|
@ -4,12 +4,13 @@
|
|||
|
||||
use thiserror::Error;
|
||||
|
||||
pub trait UsbDescriptor {
|
||||
/// Information about a USB device before claiming it.
|
||||
pub trait UsbDeviceInfo {
|
||||
/// A unique USB Device
|
||||
type Device;
|
||||
|
||||
/// Opens the USB connection, returning a [Self::Device]
|
||||
async fn open(self) -> Result<Self::Device, UsbError>;
|
||||
async fn open(self) -> Result<Self::Device, Error>;
|
||||
|
||||
/// 16 bit device Product ID
|
||||
async fn product_id(&self) -> u16;
|
||||
|
@ -32,28 +33,30 @@ pub trait UsbDescriptor {
|
|||
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 {
|
||||
/// A unique Interface on a USB Device
|
||||
type Interface;
|
||||
|
||||
/// Open a specific interface of the device
|
||||
async fn open_interface(&self, number: u8) -> Result<Self::Interface, UsbError>;
|
||||
async fn open_interface(&self, number: u8) -> Result<Self::Interface, Error>;
|
||||
|
||||
/// Open a specific interface of the device, detaching any
|
||||
/// kernel drivers and claiming it.
|
||||
///
|
||||
/// **Note:** This only has an effect on Native, and only on Linux.
|
||||
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>;
|
||||
|
||||
/// Reset the device, which causes it to no longer be usable. You must
|
||||
/// request a new device with [crate::get_device]
|
||||
async fn reset(&self) -> Result<(), UsbError>;
|
||||
async fn reset(&self) -> Result<(), Error>;
|
||||
|
||||
/// 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.
|
||||
async fn forget(&self) -> Result<(), UsbError>;
|
||||
async fn forget(&self) -> Result<(), Error>;
|
||||
|
||||
/// 16 bit device Product ID
|
||||
async fn product_id(&self) -> u16;
|
||||
|
@ -80,23 +83,22 @@ pub trait UsbDevice {
|
|||
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>;
|
||||
async fn control_in(&self, data: ControlIn) -> Result<Vec<u8>, Error>;
|
||||
|
||||
/// A USB control out transfer (host to device)
|
||||
async fn control_out(&self, data: ControlOut<'a>) -> Result<usize, UsbError>;
|
||||
async fn control_out(&self, data: ControlOut<'a>) -> Result<usize, Error>;
|
||||
|
||||
/// A USB bulk in transfer (device to host)
|
||||
/// It takes in a bulk endpoint to send to along with the length of
|
||||
/// data to read, and returns a [Result] with the bytes
|
||||
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>;
|
||||
|
||||
/// A USB bulk out transfer (host to device).
|
||||
/// 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
|
||||
async fn bulk_out(&self, endpoint: u8, data: &[u8]) -> Result<usize, UsbError>;
|
||||
async fn bulk_out(&self, endpoint: u8, data: &[u8]) -> Result<usize, Error>;
|
||||
|
||||
/* TODO: Figure out interrupt transfers on Web USB
|
||||
|
||||
/// A USB interrupt in transfer (device to host).
|
||||
/// Takes in an endpoint and a buffer to fill
|
||||
async fn interrupt_in(&self, endpoint: u8, length: usize) -> Result<Vec<u8>, UsbError>;
|
||||
|
@ -109,54 +111,94 @@ pub trait UsbInterface<'a> {
|
|||
|
||||
/// An error from a USB interface
|
||||
#[derive(Error, Debug, PartialEq, Eq, PartialOrd, Ord)]
|
||||
pub enum UsbError {
|
||||
pub enum Error {
|
||||
/// The device was not found.
|
||||
#[error("device not found")]
|
||||
DeviceNotFound,
|
||||
|
||||
/// An error occured during a transfer.
|
||||
#[error("device transfer failed")]
|
||||
TransferError,
|
||||
|
||||
/// There was an error communicating with the device.
|
||||
#[error("device communication failed")]
|
||||
CommunicationError(String),
|
||||
|
||||
/// The device was disconnected and can no longer be accesed.
|
||||
#[error("device disconnected")]
|
||||
Disconnected,
|
||||
|
||||
/// The device has gone into an invalid state, and needs to be
|
||||
/// reconnected to.
|
||||
#[error("device no longer valid")]
|
||||
Invalid,
|
||||
}
|
||||
|
||||
/// The type of USB transfer
|
||||
/// The type of USB control transfer.
|
||||
pub enum ControlType {
|
||||
/// A standard transfer.
|
||||
Standard = 0,
|
||||
|
||||
/// A Class Device transfer.
|
||||
Class = 1,
|
||||
|
||||
/// A Vendor defined transfer.
|
||||
Vendor = 2,
|
||||
}
|
||||
|
||||
/// The recipient of a USB transfer
|
||||
/// The recipient of a USB transfer.
|
||||
pub enum Recipient {
|
||||
/// The device is the recipient.
|
||||
Device = 0,
|
||||
|
||||
/// An interface is the recipient.
|
||||
Interface = 1,
|
||||
|
||||
/// An endpoint is the recipient.
|
||||
Endpoint = 2,
|
||||
|
||||
/// Something else is the recipient.
|
||||
Other = 3,
|
||||
}
|
||||
|
||||
/// Parameters for [UsbInterface::control_in]
|
||||
/// Parameters for [UsbInterface::control_in].
|
||||
pub struct ControlIn {
|
||||
/// The [`ControlType`] of this transfer, in the `bmRequestType` field.
|
||||
pub control_type: ControlType,
|
||||
|
||||
/// The [`Recipient`] of this transfer, in the `bmRequestType` field.
|
||||
pub recipient: Recipient,
|
||||
|
||||
/// The value of `bRequest` field.
|
||||
pub request: u8,
|
||||
|
||||
/// The value of the `wValue` field.
|
||||
pub value: u16,
|
||||
|
||||
/// The value of the `wIndex` field.
|
||||
pub index: u16,
|
||||
|
||||
/// The number of bytes to read.
|
||||
pub length: u16,
|
||||
}
|
||||
|
||||
/// Parameters for [UsbInterface::control_out]
|
||||
/// Parameters for [UsbInterface::control_out].
|
||||
pub struct ControlOut<'a> {
|
||||
/// The [`ControlType`] of this transfer, in the `bmRequestType` field.
|
||||
pub control_type: ControlType,
|
||||
|
||||
/// The [`Recipient`] of this transfer, in the `bmRequestType` field.
|
||||
pub recipient: Recipient,
|
||||
|
||||
/// The value of `bRequest` field.
|
||||
pub request: u8,
|
||||
|
||||
/// The value of the `wValue` field.
|
||||
pub value: u16,
|
||||
|
||||
/// The value of the `wIndex` field.
|
||||
pub index: u16,
|
||||
|
||||
/// The data to send in this transfer.
|
||||
pub data: &'a [u8],
|
||||
}
|
||||
|
|
Loading…
Reference in a new issue