read_write_async/
read_write_async.rs1use rusb_async::TransferPool;
2
3use rusb::{Context, UsbContext};
4
5use std::time::Duration;
6use std::{sync::Arc, thread};
7
8fn main() {
9 let args: Vec<String> = std::env::args().collect();
10
11 if args.len() < 5 {
12 eprintln!("Usage: read_write_async <vendor-id> <product-id> <out-endpoint> <in-endpoint> (all numbers hex)");
13 return;
14 }
15
16 let vid = u16::from_str_radix(args[1].as_ref(), 16).unwrap();
17 let pid = u16::from_str_radix(args[2].as_ref(), 16).unwrap();
18 let out_endpoint = u8::from_str_radix(args[3].as_ref(), 16).unwrap();
19 let in_endpoint = u8::from_str_radix(args[4].as_ref(), 16).unwrap();
20
21 let ctx = Context::new().expect("Could not initialize libusb");
22 let device = Arc::new(
23 ctx.open_device_with_vid_pid(vid, pid)
24 .expect("Could not find device"),
25 );
26
27 thread::spawn({
28 let device = device.clone();
29 move || {
30 let mut write_pool = TransferPool::new(device).expect("Failed to create async pool!");
31
32 let mut i = 0u8;
33
34 loop {
35 let mut buf = if write_pool.pending() < 8 {
36 Vec::with_capacity(64)
37 } else {
38 write_pool
39 .poll(Duration::from_secs(5))
40 .expect("Failed to poll OUT transfer")
41 };
42
43 buf.clear();
44 buf.push(i);
45 buf.resize(64, 0x2);
46
47 write_pool
48 .submit_bulk(out_endpoint, buf)
49 .expect("Failed to submit OUT transfer");
50 println!("Wrote {}", i);
51 i = i.wrapping_add(1);
52 }
53 }
54 });
55
56 let mut read_pool = TransferPool::new(device).expect("Failed to create async pool!");
57
58 while read_pool.pending() < 8 {
59 read_pool
60 .submit_bulk(in_endpoint, Vec::with_capacity(1024))
61 .expect("Failed to submit IN transfer");
62 }
63
64 loop {
65 let data = read_pool
66 .poll(Duration::from_secs(10))
67 .expect("Failed to poll IN transfer");
68 println!("Got data: {} {:?}", data.len(), data[0]);
69 read_pool
70 .submit_bulk(in_endpoint, data)
71 .expect("Failed to resubmit IN transfer");
72 }
73}