I need to use hid device with tokio. I am using tokio="1.22.0" and hidapi="2.0.2". Here is a code snippet with shorthands.
pub async fn new_hid( to_net : tokio::syn::cmpsc::Sender<Vec<u8>>,
mut from_net : tokio::syn::mpsc::Receiver<Vec<u8>>,
) -> Result<(), Box<dyn Error>> {
let api = HidApi::new()?;
for d in api.device_list() {
if d.vendor_id()==VENDOR_ID && d.product_id()==PRODUCT_ID {
let d=d.open_device(&api)?; // ***** d is HidDevice *****
d.set_blocking_mode(false)?;
let d=Arc::new(Mutex::new(d));
// let d=d.clone();
tokio::spawn(async move {
let mut inbuf = vec![0u8;HID_INPUT_REPORT_SZ+1];
let mut outbuf = vec![0u8;HID_OUTPUT_REPORT_SZ+1];
'outer: loop {
'read: loop {
if let Ok(sz) = d.lock().unwrap().read(&mut inbuf){
if sz>1 {
if let Err(_) = to_net.send(Vec::from(& inbuf[1..=sz])).await {
break 'outer;
}
}else{
break 'read;
}
}else{
break 'outer;
}
}
match from_net.recv().await {
Some(b) => {
outbuf[1 ..= b.len()].copy_from_slice(b);
if let Err(r) = d.lock().unwrap().send_feature_report(&outbuf[ ..= b.len()]) {
break 'outer;
}
},
None => {
break 'outer;
}
}
sleep(Duration::from_millis(50)).await;
}
});
return Ok(())
}
}
Err(Box::new(io::Error::new(io::ErrorKind::NotFound,"device not found")))
}
But the compiler reports an error
error: future cannot be sent between threads safely help: within `HidDevice`, the trait `Sync` is not implemented for `*mut c_void` note: future is not `Send` as this value is used across an await
How can hidapi::HidDevice be used in asynchronous programming with tokio?