mirror of
https://github.com/G2-Games/cross-usb.git
synced 2025-04-20 05:42:53 -05:00
Compare commits
12 commits
Author | SHA1 | Date | |
---|---|---|---|
71fafc0b0d | |||
9505ef0204 | |||
782cbfa7f5 | |||
1c193fb97c | |||
a04497594e | |||
924a19d4c8 | |||
f1fa9dd19d | |||
fea600bff7 | |||
ff2d6f89da | |||
9790653260 | |||
fdd88a75f5 | |||
19d19e2d81 |
8 changed files with 404 additions and 113 deletions
19
Cargo.toml
19
Cargo.toml
|
@ -1,26 +1,26 @@
|
||||||
[package]
|
[package]
|
||||||
name = "cross_usb"
|
name = "cross_usb"
|
||||||
version = "0.3.3"
|
version = "0.4.0"
|
||||||
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"]
|
keywords = ["usb", "wasm", "web-usb", "webusb"]
|
||||||
categories = ["wasm", "web-programming", "hardware-support"]
|
categories = ["wasm", "web-programming", "hardware-support"]
|
||||||
readme = "README.md"
|
readme = "README.md"
|
||||||
license = "MIT"
|
license = "MIT"
|
||||||
edition = "2021"
|
edition = "2024"
|
||||||
|
|
||||||
[lib]
|
[lib]
|
||||||
crate-type = ["cdylib", "rlib"]
|
crate-type = ["cdylib", "rlib"]
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
thiserror = "1.0.56"
|
thiserror = "2.0"
|
||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
tokio-test = "0.4.3"
|
tokio-test = "0.4"
|
||||||
|
|
||||||
# Wasm deps
|
# Wasm deps
|
||||||
[target.'cfg(target_family = "wasm")'.dependencies]
|
[target.'cfg(target_family = "wasm")'.dependencies]
|
||||||
|
@ -48,14 +48,11 @@ 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)'] }
|
||||||
|
|
201
LICENSE-APACHE
Normal file
201
LICENSE-APACHE
Normal file
|
@ -0,0 +1,201 @@
|
||||||
|
Apache License
|
||||||
|
Version 2.0, January 2004
|
||||||
|
http://www.apache.org/licenses/
|
||||||
|
|
||||||
|
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||||
|
|
||||||
|
1. Definitions.
|
||||||
|
|
||||||
|
"License" shall mean the terms and conditions for use, reproduction,
|
||||||
|
and distribution as defined by Sections 1 through 9 of this document.
|
||||||
|
|
||||||
|
"Licensor" shall mean the copyright owner or entity authorized by
|
||||||
|
the copyright owner that is granting the License.
|
||||||
|
|
||||||
|
"Legal Entity" shall mean the union of the acting entity and all
|
||||||
|
other entities that control, are controlled by, or are under common
|
||||||
|
control with that entity. For the purposes of this definition,
|
||||||
|
"control" means (i) the power, direct or indirect, to cause the
|
||||||
|
direction or management of such entity, whether by contract or
|
||||||
|
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||||
|
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||||
|
|
||||||
|
"You" (or "Your") shall mean an individual or Legal Entity
|
||||||
|
exercising permissions granted by this License.
|
||||||
|
|
||||||
|
"Source" form shall mean the preferred form for making modifications,
|
||||||
|
including but not limited to software source code, documentation
|
||||||
|
source, and configuration files.
|
||||||
|
|
||||||
|
"Object" form shall mean any form resulting from mechanical
|
||||||
|
transformation or translation of a Source form, including but
|
||||||
|
not limited to compiled object code, generated documentation,
|
||||||
|
and conversions to other media types.
|
||||||
|
|
||||||
|
"Work" shall mean the work of authorship, whether in Source or
|
||||||
|
Object form, made available under the License, as indicated by a
|
||||||
|
copyright notice that is included in or attached to the work
|
||||||
|
(an example is provided in the Appendix below).
|
||||||
|
|
||||||
|
"Derivative Works" shall mean any work, whether in Source or Object
|
||||||
|
form, that is based on (or derived from) the Work and for which the
|
||||||
|
editorial revisions, annotations, elaborations, or other modifications
|
||||||
|
represent, as a whole, an original work of authorship. For the purposes
|
||||||
|
of this License, Derivative Works shall not include works that remain
|
||||||
|
separable from, or merely link (or bind by name) to the interfaces of,
|
||||||
|
the Work and Derivative Works thereof.
|
||||||
|
|
||||||
|
"Contribution" shall mean any work of authorship, including
|
||||||
|
the original version of the Work and any modifications or additions
|
||||||
|
to that Work or Derivative Works thereof, that is intentionally
|
||||||
|
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||||
|
or by an individual or Legal Entity authorized to submit on behalf of
|
||||||
|
the copyright owner. For the purposes of this definition, "submitted"
|
||||||
|
means any form of electronic, verbal, or written communication sent
|
||||||
|
to the Licensor or its representatives, including but not limited to
|
||||||
|
communication on electronic mailing lists, source code control systems,
|
||||||
|
and issue tracking systems that are managed by, or on behalf of, the
|
||||||
|
Licensor for the purpose of discussing and improving the Work, but
|
||||||
|
excluding communication that is conspicuously marked or otherwise
|
||||||
|
designated in writing by the copyright owner as "Not a Contribution."
|
||||||
|
|
||||||
|
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||||
|
on behalf of whom a Contribution has been received by Licensor and
|
||||||
|
subsequently incorporated within the Work.
|
||||||
|
|
||||||
|
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||||
|
this License, each Contributor hereby grants to You a perpetual,
|
||||||
|
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||||
|
copyright license to reproduce, prepare Derivative Works of,
|
||||||
|
publicly display, publicly perform, sublicense, and distribute the
|
||||||
|
Work and such Derivative Works in Source or Object form.
|
||||||
|
|
||||||
|
3. Grant of Patent License. Subject to the terms and conditions of
|
||||||
|
this License, each Contributor hereby grants to You a perpetual,
|
||||||
|
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||||
|
(except as stated in this section) patent license to make, have made,
|
||||||
|
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||||
|
where such license applies only to those patent claims licensable
|
||||||
|
by such Contributor that are necessarily infringed by their
|
||||||
|
Contribution(s) alone or by combination of their Contribution(s)
|
||||||
|
with the Work to which such Contribution(s) was submitted. If You
|
||||||
|
institute patent litigation against any entity (including a
|
||||||
|
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||||
|
or a Contribution incorporated within the Work constitutes direct
|
||||||
|
or contributory patent infringement, then any patent licenses
|
||||||
|
granted to You under this License for that Work shall terminate
|
||||||
|
as of the date such litigation is filed.
|
||||||
|
|
||||||
|
4. Redistribution. You may reproduce and distribute copies of the
|
||||||
|
Work or Derivative Works thereof in any medium, with or without
|
||||||
|
modifications, and in Source or Object form, provided that You
|
||||||
|
meet the following conditions:
|
||||||
|
|
||||||
|
(a) You must give any other recipients of the Work or
|
||||||
|
Derivative Works a copy of this License; and
|
||||||
|
|
||||||
|
(b) You must cause any modified files to carry prominent notices
|
||||||
|
stating that You changed the files; and
|
||||||
|
|
||||||
|
(c) You must retain, in the Source form of any Derivative Works
|
||||||
|
that You distribute, all copyright, patent, trademark, and
|
||||||
|
attribution notices from the Source form of the Work,
|
||||||
|
excluding those notices that do not pertain to any part of
|
||||||
|
the Derivative Works; and
|
||||||
|
|
||||||
|
(d) If the Work includes a "NOTICE" text file as part of its
|
||||||
|
distribution, then any Derivative Works that You distribute must
|
||||||
|
include a readable copy of the attribution notices contained
|
||||||
|
within such NOTICE file, excluding those notices that do not
|
||||||
|
pertain to any part of the Derivative Works, in at least one
|
||||||
|
of the following places: within a NOTICE text file distributed
|
||||||
|
as part of the Derivative Works; within the Source form or
|
||||||
|
documentation, if provided along with the Derivative Works; or,
|
||||||
|
within a display generated by the Derivative Works, if and
|
||||||
|
wherever such third-party notices normally appear. The contents
|
||||||
|
of the NOTICE file are for informational purposes only and
|
||||||
|
do not modify the License. You may add Your own attribution
|
||||||
|
notices within Derivative Works that You distribute, alongside
|
||||||
|
or as an addendum to the NOTICE text from the Work, provided
|
||||||
|
that such additional attribution notices cannot be construed
|
||||||
|
as modifying the License.
|
||||||
|
|
||||||
|
You may add Your own copyright statement to Your modifications and
|
||||||
|
may provide additional or different license terms and conditions
|
||||||
|
for use, reproduction, or distribution of Your modifications, or
|
||||||
|
for any such Derivative Works as a whole, provided Your use,
|
||||||
|
reproduction, and distribution of the Work otherwise complies with
|
||||||
|
the conditions stated in this License.
|
||||||
|
|
||||||
|
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||||
|
any Contribution intentionally submitted for inclusion in the Work
|
||||||
|
by You to the Licensor shall be under the terms and conditions of
|
||||||
|
this License, without any additional terms or conditions.
|
||||||
|
Notwithstanding the above, nothing herein shall supersede or modify
|
||||||
|
the terms of any separate license agreement you may have executed
|
||||||
|
with Licensor regarding such Contributions.
|
||||||
|
|
||||||
|
6. Trademarks. This License does not grant permission to use the trade
|
||||||
|
names, trademarks, service marks, or product names of the Licensor,
|
||||||
|
except as required for reasonable and customary use in describing the
|
||||||
|
origin of the Work and reproducing the content of the NOTICE file.
|
||||||
|
|
||||||
|
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||||
|
agreed to in writing, Licensor provides the Work (and each
|
||||||
|
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||||
|
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||||
|
implied, including, without limitation, any warranties or conditions
|
||||||
|
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||||
|
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||||
|
appropriateness of using or redistributing the Work and assume any
|
||||||
|
risks associated with Your exercise of permissions under this License.
|
||||||
|
|
||||||
|
8. Limitation of Liability. In no event and under no legal theory,
|
||||||
|
whether in tort (including negligence), contract, or otherwise,
|
||||||
|
unless required by applicable law (such as deliberate and grossly
|
||||||
|
negligent acts) or agreed to in writing, shall any Contributor be
|
||||||
|
liable to You for damages, including any direct, indirect, special,
|
||||||
|
incidental, or consequential damages of any character arising as a
|
||||||
|
result of this License or out of the use or inability to use the
|
||||||
|
Work (including but not limited to damages for loss of goodwill,
|
||||||
|
work stoppage, computer failure or malfunction, or any and all
|
||||||
|
other commercial damages or losses), even if such Contributor
|
||||||
|
has been advised of the possibility of such damages.
|
||||||
|
|
||||||
|
9. Accepting Warranty or Additional Liability. While redistributing
|
||||||
|
the Work or Derivative Works thereof, You may choose to offer,
|
||||||
|
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||||
|
or other liability obligations and/or rights consistent with this
|
||||||
|
License. However, in accepting such obligations, You may act only
|
||||||
|
on Your own behalf and on Your sole responsibility, not on behalf
|
||||||
|
of any other Contributor, and only if You agree to indemnify,
|
||||||
|
defend, and hold each Contributor harmless for any liability
|
||||||
|
incurred by, or claims asserted against, such Contributor by reason
|
||||||
|
of your accepting any such warranty or additional liability.
|
||||||
|
|
||||||
|
END OF TERMS AND CONDITIONS
|
||||||
|
|
||||||
|
APPENDIX: How to apply the Apache License to your work.
|
||||||
|
|
||||||
|
To apply the Apache License to your work, attach the following
|
||||||
|
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||||
|
replaced with your own identifying information. (Don't include
|
||||||
|
the brackets!) The text should be enclosed in the appropriate
|
||||||
|
comment syntax for the file format. We also recommend that a
|
||||||
|
file or class name and description of purpose be included on the
|
||||||
|
same "printed page" as the copyright notice for easier
|
||||||
|
identification within third-party archives.
|
||||||
|
|
||||||
|
Copyright [yyyy] [name of copyright owner]
|
||||||
|
|
||||||
|
Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
you may not use this file except in compliance with the License.
|
||||||
|
You may obtain a copy of the License at
|
||||||
|
|
||||||
|
http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
|
||||||
|
Unless required by applicable law or agreed to in writing, software
|
||||||
|
distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
See the License for the specific language governing permissions and
|
||||||
|
limitations under the License.
|
54
README.md
54
README.md
|
@ -10,23 +10,65 @@ A USB library which works seamlessly across most native and WASM targets.
|
||||||
> Web USB only works in Chromium based browsers for now.
|
> Web USB only works in Chromium based browsers for now.
|
||||||
|
|
||||||
> [!NOTE]
|
> [!NOTE]
|
||||||
> Web USB has certain interation requirements in browsers, along with requiring
|
> Web USB has certain interaction requirements in browsers, along with requiring
|
||||||
> a **Secure context**. Please read more about this on the
|
> a **Secure context**. Please read more about this on the
|
||||||
> [mdn web docs](https://developer.mozilla.org/en-US/docs/Web/API/WebUSB_API)
|
> [mdn web docs](https://developer.mozilla.org/en-US/docs/Web/API/WebUSB_API)
|
||||||
|
|
||||||
> [!IMPORTANT]
|
> [!IMPORTANT]
|
||||||
> When compiling this crate on a WASM target, you must use either
|
> When compiling this crate on a WASM target, you must use either the rustflags
|
||||||
> `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: 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
|
||||||
|
|
||||||
## Dependencies
|
## 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).
|
||||||
|
|
||||||
|
```rust
|
||||||
|
use cross_usb::prelude::*;
|
||||||
|
use cross_usb::usb::{Recipient, ControlType, ControlIn};
|
||||||
|
use cross_usb::device_filter;
|
||||||
|
|
||||||
|
// Obtain a device descriptor using a DeviceFilter,
|
||||||
|
// in this case with its VendorID and ProductID
|
||||||
|
let filters = vec![
|
||||||
|
device_filter!{vendor_id: 0x054c, product_id: 0x00c9}
|
||||||
|
];
|
||||||
|
let dev_descriptor = cross_usb::get_device(filters).await.expect("Failed to find device");
|
||||||
|
|
||||||
|
// Open the device that the descriptor is describing
|
||||||
|
let dev = dev_descriptor.open().await.expect("Failed to open device");
|
||||||
|
|
||||||
|
// Obtain an interface of the device
|
||||||
|
let interface = dev.open_interface(0).await.expect("Failed to open interface");
|
||||||
|
|
||||||
|
// Send a Control transfer to the device, obtaining
|
||||||
|
// the result and storing it in `result`
|
||||||
|
let result = interface.control_in(ControlIn {
|
||||||
|
control_type: ControlType::Vendor,
|
||||||
|
recipient: Recipient::Interface,
|
||||||
|
request: 0x01,
|
||||||
|
value: 0,
|
||||||
|
index: 0,
|
||||||
|
length: 4,
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
.expect("Sending control transfer failed");
|
||||||
|
```
|
||||||
|
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 `nusb`
|
- [ ] Add choice for native backend between `libusb` wrapper and pure rust
|
||||||
|
`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 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::{
|
use crate::usb::{
|
||||||
ControlIn, ControlOut, ControlType, UsbDescriptor, UsbDevice, UsbInterface, Recipient, UsbError,
|
ControlIn, ControlOut, ControlType, UsbDeviceInfo, UsbDevice, UsbInterface, Recipient, Error,
|
||||||
};
|
};
|
||||||
|
|
||||||
#[derive(Clone, Debug)]
|
#[derive(Clone, Debug)]
|
||||||
pub struct Descriptor {
|
pub struct DeviceInfo {
|
||||||
device_info: nusb::DeviceInfo,
|
device_info: nusb::DeviceInfo,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
pub struct Device {
|
pub struct Device {
|
||||||
device_info: Descriptor,
|
device_info: DeviceInfo,
|
||||||
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<Descriptor, UsbError> {
|
) -> Result<DeviceInfo, Error> {
|
||||||
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(UsbError::DeviceNotFound),
|
None => return Err(Error::DeviceNotFound),
|
||||||
};
|
};
|
||||||
|
|
||||||
Ok(Descriptor { device_info })
|
Ok(DeviceInfo { 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 = Descriptor>, UsbError> {
|
) -> Result<impl Iterator<Item = DeviceInfo>, Error> {
|
||||||
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(UsbError::DeviceNotFound);
|
return Err(Error::DeviceNotFound);
|
||||||
}
|
}
|
||||||
|
|
||||||
let devices_opened: Vec<Descriptor> = devices
|
let devices_opened: Vec<DeviceInfo> = devices
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.map(|d| Descriptor { device_info: d })
|
.map(|d| DeviceInfo { device_info: d })
|
||||||
.collect();
|
.collect();
|
||||||
|
|
||||||
Ok(devices_opened.into_iter())
|
Ok(devices_opened.into_iter())
|
||||||
}
|
}
|
||||||
|
|
||||||
impl UsbDescriptor for Descriptor {
|
impl UsbDeviceInfo for DeviceInfo {
|
||||||
type Device = Device;
|
type Device = Device;
|
||||||
|
|
||||||
async fn open(self) -> Result<Self::Device, UsbError> {
|
async fn open(self) -> Result<Self::Device, Error> {
|
||||||
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(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 {
|
impl UsbDevice for Device {
|
||||||
type Interface = Interface;
|
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) {
|
let interface = match self.device.claim_interface(number) {
|
||||||
Ok(inter) => inter,
|
Ok(inter) => inter,
|
||||||
Err(err) => return Err(UsbError::CommunicationError(err.to_string())),
|
Err(err) => return Err(Error::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, UsbError> {
|
async fn detach_and_open_interface(&self, number: u8) -> Result<Self::Interface, Error> {
|
||||||
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(UsbError::CommunicationError(err.to_string())),
|
Err(err) => return Err(Error::CommunicationError(err.to_string())),
|
||||||
};
|
};
|
||||||
|
|
||||||
Ok(Interface {
|
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() {
|
match self.device.reset() {
|
||||||
Ok(_) => Ok(()),
|
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
|
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>, UsbError> {
|
async fn control_in(&self, data: ControlIn) -> Result<Vec<u8>, Error> {
|
||||||
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(UsbError::TransferError),
|
Err(_) => return Err(Error::TransferError),
|
||||||
};
|
};
|
||||||
|
|
||||||
Ok(result)
|
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() {
|
match self.interface.control_out(data.into()).await.into_result() {
|
||||||
Ok(bytes) => Ok(bytes.actual_length()),
|
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);
|
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(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
|
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(UsbError::TransferError),
|
Err(_) => Err(Error::TransferError),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -10,12 +10,12 @@ use web_sys::{
|
||||||
|
|
||||||
// Crate stuff
|
// Crate stuff
|
||||||
use crate::usb::{
|
use crate::usb::{
|
||||||
ControlIn, ControlOut, ControlType, UsbDescriptor, UsbDevice, UsbInterface, Recipient, UsbError,
|
ControlIn, ControlOut, ControlType, UsbDeviceInfo, UsbDevice, UsbInterface, Recipient, Error,
|
||||||
};
|
};
|
||||||
|
|
||||||
#[wasm_bindgen]
|
#[wasm_bindgen]
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub struct Descriptor {
|
pub struct DeviceInfo {
|
||||||
device: WasmUsbDevice,
|
device: WasmUsbDevice,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -61,7 +61,7 @@ impl DeviceFilter {
|
||||||
}
|
}
|
||||||
|
|
||||||
#[wasm_bindgen]
|
#[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 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<Descriptor,
|
||||||
result
|
result
|
||||||
}) {
|
}) {
|
||||||
let _open_promise = JsFuture::from(Promise::resolve(&device.open())).await?;
|
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?;
|
let _open_promise = JsFuture::from(Promise::resolve(&device.open())).await?;
|
||||||
|
|
||||||
Ok(Descriptor { device })
|
Ok(DeviceInfo { device })
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
|
||||||
#[wasm_bindgen]
|
#[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 window = web_sys::window().unwrap();
|
||||||
|
|
||||||
let navigator = window.navigator();
|
let navigator = window.navigator();
|
||||||
|
@ -208,7 +207,7 @@ pub async fn get_device_list(device_filter: Vec<DeviceFilter>) -> Result<Vec<Usb
|
||||||
result
|
result
|
||||||
}) {
|
}) {
|
||||||
let _open_promise = JsFuture::from(Promise::resolve(&device.open())).await?;
|
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?;
|
let _open_promise = JsFuture::from(Promise::resolve(&device.open())).await?;
|
||||||
|
|
||||||
devices.push(UsbDescriptor { device });
|
devices.push(DeviceInfo { device });
|
||||||
|
|
||||||
return Ok(devices);
|
return Ok(devices);
|
||||||
}
|
}
|
||||||
*/
|
|
||||||
|
|
||||||
impl UsbDescriptor for Descriptor {
|
impl UsbDeviceInfo for DeviceInfo {
|
||||||
type Device = Device;
|
type Device = Device;
|
||||||
|
|
||||||
async fn open(self) -> Result<Self::Device, UsbError> {
|
async fn open(self) -> Result<Self::Device, Error> {
|
||||||
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.vendor_id()
|
self.device.product_id()
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn vendor_id(&self) -> u16 {
|
async fn vendor_id(&self) -> u16 {
|
||||||
self.device.product_id()
|
self.device.vendor_id()
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn class(&self) -> u8 {
|
async fn class(&self) -> u8 {
|
||||||
|
@ -310,7 +308,7 @@ impl UsbDescriptor for Descriptor {
|
||||||
impl UsbDevice for Device {
|
impl UsbDevice for Device {
|
||||||
type Interface = Interface;
|
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 =
|
let dev_promise =
|
||||||
JsFuture::from(Promise::resolve(&self.device.claim_interface(number))).await;
|
JsFuture::from(Promise::resolve(&self.device.claim_interface(number))).await;
|
||||||
|
|
||||||
|
@ -318,7 +316,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(UsbError::CommunicationError(
|
return Err(Error::CommunicationError(
|
||||||
err.as_string().unwrap_or_default(),
|
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
|
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;
|
let result = JsFuture::from(Promise::resolve(&self.device.reset())).await;
|
||||||
|
|
||||||
match result {
|
match result {
|
||||||
Ok(_) => Ok(()),
|
Ok(_) => Ok(()),
|
||||||
Err(err) => Err(UsbError::CommunicationError(
|
Err(err) => Err(Error::CommunicationError(
|
||||||
err.as_string().unwrap_or_default(),
|
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;
|
let result = JsFuture::from(Promise::resolve(&self.device.forget())).await;
|
||||||
|
|
||||||
match result {
|
match result {
|
||||||
Ok(_) => Ok(()),
|
Ok(_) => Ok(()),
|
||||||
Err(err) => Err(UsbError::CommunicationError(
|
Err(err) => Err(Error::CommunicationError(
|
||||||
err.as_string().unwrap_or_default(),
|
err.as_string().unwrap_or_default(),
|
||||||
)),
|
)),
|
||||||
}
|
}
|
||||||
|
@ -382,7 +380,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>, UsbError> {
|
async fn control_in(&self, data: crate::usb::ControlIn) -> Result<Vec<u8>, Error> {
|
||||||
let length = data.length;
|
let length = data.length;
|
||||||
let params: UsbControlTransferParameters = data.into();
|
let params: UsbControlTransferParameters = data.into();
|
||||||
|
|
||||||
|
@ -391,12 +389,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(UsbError::TransferError),
|
Err(_) => return Err(Error::TransferError),
|
||||||
};
|
};
|
||||||
|
|
||||||
let data = match transfer_result.data() {
|
let data = match transfer_result.data() {
|
||||||
Some(res) => res.buffer(),
|
Some(res) => res.buffer(),
|
||||||
None => return Err(UsbError::TransferError),
|
None => return Err(Error::TransferError),
|
||||||
};
|
};
|
||||||
|
|
||||||
let array = Uint8Array::new(&data);
|
let array = Uint8Array::new(&data);
|
||||||
|
@ -404,7 +402,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, UsbError> {
|
async fn control_out(&self, data: crate::usb::ControlOut<'a>) -> Result<usize, Error> {
|
||||||
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();
|
||||||
|
@ -412,30 +410,32 @@ impl<'a> UsbInterface<'a> for Interface {
|
||||||
let result: UsbOutTransferResult = match JsFuture::from(Promise::resolve(
|
let result: UsbOutTransferResult = match JsFuture::from(Promise::resolve(
|
||||||
&self
|
&self
|
||||||
.device
|
.device
|
||||||
.control_transfer_out_with_buffer_source(¶ms, array_obj),
|
.control_transfer_out_with_buffer_source(¶ms, array_obj)
|
||||||
|
.map_err(|j| Error::CommunicationError(j.as_string().unwrap_or_default()))?
|
||||||
|
.into(),
|
||||||
))
|
))
|
||||||
.await
|
.await
|
||||||
{
|
{
|
||||||
Ok(res) => res.into(),
|
Ok(res) => res.into(),
|
||||||
Err(_) => return Err(UsbError::TransferError),
|
Err(_) => return Err(Error::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>, 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 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(UsbError::TransferError),
|
Err(_) => return Err(Error::TransferError),
|
||||||
};
|
};
|
||||||
|
|
||||||
let data = match transfer_result.data() {
|
let data = match transfer_result.data() {
|
||||||
Some(res) => res.buffer(),
|
Some(res) => res.buffer(),
|
||||||
None => return Err(UsbError::TransferError),
|
None => return Err(Error::TransferError),
|
||||||
};
|
};
|
||||||
|
|
||||||
let array = Uint8Array::new(&data);
|
let array = Uint8Array::new(&data);
|
||||||
|
@ -443,21 +443,23 @@ 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, UsbError> {
|
async fn bulk_out(&self, endpoint: u8, data: &[u8]) -> Result<usize, Error> {
|
||||||
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();
|
||||||
|
|
||||||
let promise = Promise::resolve(
|
let promise = Promise::resolve(
|
||||||
&self
|
&self
|
||||||
.device
|
.device
|
||||||
.transfer_out_with_buffer_source(endpoint, array_obj),
|
.transfer_out_with_buffer_source(endpoint, array_obj)
|
||||||
|
.map_err(|j| Error::CommunicationError(j.as_string().unwrap_or_default()))?
|
||||||
|
.into(),
|
||||||
);
|
);
|
||||||
|
|
||||||
let result = JsFuture::from(promise).await;
|
let result = JsFuture::from(promise).await;
|
||||||
|
|
||||||
let transfer_result: UsbOutTransferResult = match result {
|
let transfer_result: UsbOutTransferResult = match result {
|
||||||
Ok(res) => res.into(),
|
Ok(res) => res.into(),
|
||||||
Err(_) => return Err(UsbError::TransferError),
|
Err(_) => return Err(Error::TransferError),
|
||||||
};
|
};
|
||||||
|
|
||||||
Ok(transfer_result.bytes_written() as usize)
|
Ok(transfer_result.bytes_written() as usize)
|
||||||
|
|
43
src/lib.rs
43
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/)
|
//! 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:
|
||||||
//! * 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.
|
||||||
//!
|
//!
|
||||||
//! * Until [this pull request](https://github.com/rustwasm/wasm-bindgen/issues/3155)
|
//! * Hotplug support is not implemented. Waiting on
|
||||||
//! is merged into wasm bindgen, getting a list of USB devices is not possible on WASM
|
//! [hotplug support in nusb](https://github.com/kevinmehall/nusb/pull/20).
|
||||||
//! 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: 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:
|
//! ## 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::UsbDescriptor;
|
pub use crate::usb::UsbDeviceInfo;
|
||||||
pub use crate::usb::UsbDevice;
|
pub use crate::usb::UsbDevice;
|
||||||
pub use crate::usb::UsbInterface;
|
pub use crate::usb::UsbInterface;
|
||||||
}
|
}
|
||||||
|
@ -79,24 +79,31 @@ mod context;
|
||||||
mod context;
|
mod context;
|
||||||
|
|
||||||
#[doc(inline)]
|
#[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
|
/// 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 with which to perform transfers on
|
/// A USB interface to perform transfers with.
|
||||||
pub use crate::context::Interface;
|
pub use crate::context::Interface;
|
||||||
|
|
||||||
/// Information about a USB device for use in [`get_device`]
|
/// Information about a USB device for use in [`get_device`] or
|
||||||
/// or [`get_device_list`]
|
/// [`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 [`Descriptor`] from a list of VendorID
|
/// Gets a single (the first found) device as a [`DeviceInfo`] from a list of VendorID
|
||||||
/// and ProductIDs
|
/// and ProductIDs
|
||||||
///
|
///
|
||||||
/// ## Example
|
/// ## Example
|
||||||
|
@ -115,7 +122,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 [`Descriptor`]s from a list of VendorID and ProductIDs
|
/// Gets a list of [`DeviceInfo`]s from a list of VendorID and ProductIDs
|
||||||
///
|
///
|
||||||
/// ## Example
|
/// ## Example
|
||||||
/// ```no_run
|
/// ```no_run
|
||||||
|
@ -165,7 +172,7 @@ macro_rules! device_filter {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(not(web_sys_unstable_apis))]
|
#[cfg(all(target_family = "wasm", 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."
|
||||||
|
|
76
src/usb.rs
76
src/usb.rs
|
@ -4,12 +4,13 @@
|
||||||
|
|
||||||
use thiserror::Error;
|
use thiserror::Error;
|
||||||
|
|
||||||
pub trait UsbDescriptor {
|
/// Information about a USB device before claiming it.
|
||||||
|
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, UsbError>;
|
async fn open(self) -> Result<Self::Device, Error>;
|
||||||
|
|
||||||
/// 16 bit device Product ID
|
/// 16 bit device Product ID
|
||||||
async fn product_id(&self) -> u16;
|
async fn product_id(&self) -> u16;
|
||||||
|
@ -32,28 +33,30 @@ pub trait UsbDescriptor {
|
||||||
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, UsbError>;
|
async fn open_interface(&self, number: u8) -> Result<Self::Interface, Error>;
|
||||||
|
|
||||||
/// 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, 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
|
/// 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<(), 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]
|
/// 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<(), UsbError>;
|
async fn forget(&self) -> Result<(), Error>;
|
||||||
|
|
||||||
/// 16 bit device Product ID
|
/// 16 bit device Product ID
|
||||||
async fn product_id(&self) -> u16;
|
async fn product_id(&self) -> u16;
|
||||||
|
@ -80,23 +83,22 @@ 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>, UsbError>;
|
async fn control_in(&self, data: ControlIn) -> Result<Vec<u8>, Error>;
|
||||||
|
|
||||||
/// 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, UsbError>;
|
async fn control_out(&self, data: ControlOut<'a>) -> Result<usize, Error>;
|
||||||
|
|
||||||
/// 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>, UsbError>;
|
async fn bulk_in(&self, endpoint: u8, length: usize) -> Result<Vec<u8>, Error>;
|
||||||
|
|
||||||
/// 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, UsbError>;
|
async fn bulk_out(&self, endpoint: u8, data: &[u8]) -> Result<usize, Error>;
|
||||||
|
|
||||||
/* 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>;
|
||||||
|
@ -109,54 +111,94 @@ 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 UsbError {
|
pub enum Error {
|
||||||
|
/// 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 transfer
|
/// The type of USB control 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],
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in a new issue