Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ travis-ci = { repository = "a1ien/rusb" }
vendored = [ "libusb1-sys/vendored" ]

[workspace]
members = ["libusb1-sys"]
members = ["libusb1-sys", "rusb-async"]

[dependencies]
libusb1-sys = { path = "libusb1-sys", version = "0.6.0" }
Expand Down
26 changes: 26 additions & 0 deletions rusb-async/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
[package]
name = "rusb-async"
version = "0.0.1-alpha-2"
edition = "2021"
authors = [
"Ilya Averyanov <[email protected]>",
"Ryan Butler <[email protected]>",
"Kevin Mehall <[email protected]>",
]

description = "Rust library for accessing USB devices."
license = "MIT"
homepage = "https://github.com/a1ien/rusb"
repository = "https://github.com/a1ien/rusb.git"
keywords = ["usb", "libusb", "async"]

[features]
vendored = [ "rusb/vendored" ]

[dependencies]
async-trait = "0.1"
rusb = { path = "..", version = "0.9.1" }
libc = "0.2"

[dev-dependencies]
tokio = { version = "1", features = ["macros", "rt-multi-thread"] }
57 changes: 57 additions & 0 deletions rusb-async/examples/read_async.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
use rusb::UsbContext as _;
use rusb_async::{Context, DeviceHandleExt as _};

use std::sync::Arc;
use std::time::Duration;

const BUF_SIZE: usize = 64;

fn convert_argument_u16(input: &str) -> u16 {
if input.starts_with("0x") {
return u16::from_str_radix(input.trim_start_matches("0x"), 16).unwrap();
}
u16::from_str_radix(input, 10)
.expect("Invalid input, be sure to add `0x` for hexadecimal values.")
}

fn convert_argument_u8(input: &str) -> u8 {
if input.starts_with("0x") {
return u8::from_str_radix(input.trim_start_matches("0x"), 16).unwrap();
}
u8::from_str_radix(input, 10)
.expect("Invalid input, be sure to add `0x` for hexadecimal values.")
}

#[tokio::main]
async fn main() {
let args: Vec<String> = std::env::args().collect();

if args.len() < 4 {
eprintln!("Usage: read_async <base-10/0xbase-16> <base-10/0xbase-16> <endpoint>");
return;
}

let vid = convert_argument_u16(args[1].as_ref());
let pid = convert_argument_u16(args[2].as_ref());
let endpoint = convert_argument_u8(args[3].as_ref());

let ctx = Context::new().expect("Could not initialize libusb");
let device = Arc::new(
ctx.open_device_with_vid_pid(vid, pid)
.expect("Could not find device"),
);

let timeout = Duration::from_secs(10);
let mut buffer = vec![0u8; BUF_SIZE].into_boxed_slice();

loop {
let (bytes, n) = device
.read_bulk_async(endpoint, buffer, timeout)
.await
.expect("Failed to submit transfer");

println!("Got data: {} {:?}", n, &bytes[..n]);

buffer = bytes;
}
}
68 changes: 68 additions & 0 deletions rusb-async/src/context.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::thread::JoinHandle;
use std::time::Duration;

use rusb::ffi::*;
use rusb::{Error, UsbContext};

struct EventThread {
thread: Option<JoinHandle<Result<(), Error>>>,
should_quit: Arc<AtomicBool>,
}

impl EventThread {
fn new(context: &mut rusb::Context) -> Self {
let thread_context = context.clone();
let tx = Arc::new(AtomicBool::new(false));
let rx = tx.clone();

let thread = std::thread::spawn(move || -> Result<(), Error> {
while !rx.load(Ordering::SeqCst) {
thread_context.handle_events(Some(Duration::from_millis(0)))?;
}

Ok(())
});

Self {
thread: Some(thread),
should_quit: tx,
}
}
}

impl Drop for EventThread {
fn drop(&mut self) {
self.should_quit.store(true, Ordering::SeqCst);

let _ = self.thread.take().map(|thread| thread.join());
}
}

/// A `libusb` context with a dedicated thread to handle events in the background.
#[derive(Clone)]
pub struct Context {
inner: rusb::Context,
_thread: Arc<EventThread>,
}

impl Context {
/// Opens a new `libusb` context and spawns a thread to handle events in the background for
/// that context.
pub fn new() -> Result<Self, Error> {
let mut inner = rusb::Context::new()?;
let thread = EventThread::new(&mut inner);

Ok(Self {
inner,
_thread: Arc::new(thread),
})
}
}

impl UsbContext for Context {
fn as_raw(&self) -> *mut libusb_context {
self.inner.as_raw()
}
}
5 changes: 5 additions & 0 deletions rusb-async/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
pub mod context;
pub mod transfer;

pub use crate::context::Context;
pub use crate::transfer::{CancellationToken, DeviceHandleExt, Transfer};
Loading