Skip to content

Commit b283459

Browse files
committed
Add example for monitoring devices
1 parent fec26a3 commit b283459

1 file changed

Lines changed: 39 additions & 0 deletions

File tree

examples/monitor.rs

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
fn log_device(prefix: &str, info: &hidapi::DeviceInfo) {
2+
let manufacturer = info.manufacturer_string().unwrap_or_default();
3+
let product = info.product_string().unwrap_or_default();
4+
let vendor_id = info.vendor_id();
5+
let product_id = info.product_id();
6+
let path = info.path().to_string_lossy();
7+
8+
println!("\
9+
\n{prefix}\
10+
\n path: {path}\
11+
\n manufacturer: {manufacturer}\
12+
\n product: {product}\
13+
\n id: {vendor_id:4x}:{product_id:4x}\
14+
");
15+
}
16+
17+
fn main() -> Result<(), hidapi::HidError> {
18+
let hidapi1 = hidapi::HidApi::new_without_enumerate()?;
19+
let mut hidapi2 = hidapi::HidApi::new_without_enumerate()?;
20+
21+
// Create the monitor before enumerating existing devices so that we get
22+
// duplicates if a device is plugged in during enumeration instead of missing it
23+
let monitor = hidapi1.monitor()?;
24+
25+
hidapi2.add_devices(0, 0)?;
26+
27+
for device in hidapi2.device_list() {
28+
log_device("initial device", device);
29+
}
30+
31+
for event in monitor {
32+
match event {
33+
hidapi::Event::Add(device) => log_device("new device", &device),
34+
event => println!("unknown monitor event: {event:?}"),
35+
}
36+
}
37+
38+
Ok(())
39+
}

0 commit comments

Comments
 (0)