read_async/
read_async.rs

1use rusb_async::TransferPool;
2
3use rusb::{Context, UsbContext};
4
5use std::str::FromStr;
6use std::sync::Arc;
7use std::time::Duration;
8
9fn convert_argument(input: &str) -> u16 {
10    if input.starts_with("0x") {
11        return u16::from_str_radix(input.trim_start_matches("0x"), 16).unwrap();
12    }
13    u16::from_str_radix(input, 10)
14        .expect("Invalid input, be sure to add `0x` for hexadecimal values.")
15}
16
17fn main() {
18    let args: Vec<String> = std::env::args().collect();
19
20    if args.len() < 4 {
21        eprintln!("Usage: read_async <base-10/0xbase-16> <base-10/0xbase-16> <endpoint>");
22        return;
23    }
24
25    let vid = convert_argument(args[1].as_ref());
26    let pid = convert_argument(args[2].as_ref());
27    let endpoint: u8 = FromStr::from_str(args[3].as_ref()).unwrap();
28
29    let ctx = Context::new().expect("Could not initialize libusb");
30    let device = Arc::new(
31        ctx.open_device_with_vid_pid(vid, pid)
32            .expect("Could not find device"),
33    );
34
35    const NUM_TRANSFERS: usize = 32;
36    const BUF_SIZE: usize = 64;
37
38    let mut async_pool = TransferPool::new(device).expect("Failed to create async pool!");
39
40    while async_pool.pending() < NUM_TRANSFERS {
41        async_pool
42            .submit_bulk(endpoint, Vec::with_capacity(BUF_SIZE))
43            .expect("Failed to submit transfer");
44    }
45
46    let timeout = Duration::from_secs(10);
47    loop {
48        let data = async_pool.poll(timeout).expect("Transfer failed");
49        println!("Got data: {} {:?}", data.len(), data);
50        async_pool
51            .submit_bulk(endpoint, data)
52            .expect("Failed to resubmit transfer");
53    }
54}