1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
|
use hidapi::{HidApi, HidDevice};
fn find_device(api: &HidApi, usage_id: u16, usage_page: u16) -> anyhow::Result<HidDevice> {
Ok({
let devs = api
.device_list()
.filter(|dev| dev.usage() == usage_id && dev.usage_page() == usage_page)
.collect::<Vec<_>>();
assert_eq!(
devs.len(),
1,
"Only one device should have such a usage:usage_page value"
);
api.open(devs[0].vendor_id(), devs[0].product_id())?
})
}
pub fn monitor(api: &HidApi, usage_id: u16, usage_page: u16) -> anyhow::Result<()> {
let device = find_device(api, usage_id, usage_page)?;
loop {
// Read data from device
let mut buf = [0u8; 4];
let res = device.read(&mut buf[..]).unwrap();
let value = u32::from_le_bytes([buf[0], buf[1], buf[2], buf[3]]);
println!("Read: {:?} ({} bytes) -> {value:x}", &buf[..res], res);
}
}
pub fn send(api: &HidApi, usage_id: u16, usage_page: u16, message: u8) -> anyhow::Result<()> {
let device = find_device(api, usage_id, usage_page)?;
// Write data to device
let mut buf = [0u8; 33];
buf[1] = message;
let res = device.write(&buf)?;
println!("Wrote: {:#?} byte(s)", res);
Ok(())
}
|