diff options
Diffstat (limited to 'rust/qmk-hid-com/src/hid/mod.rs')
-rw-r--r-- | rust/qmk-hid-com/src/hid/mod.rs | 44 |
1 files changed, 44 insertions, 0 deletions
diff --git a/rust/qmk-hid-com/src/hid/mod.rs b/rust/qmk-hid-com/src/hid/mod.rs new file mode 100644 index 0000000..b80c835 --- /dev/null +++ b/rust/qmk-hid-com/src/hid/mod.rs @@ -0,0 +1,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(()) +} |