open_first_device/
open_first_device.rs

1/****************************************************************************
2    Copyright (c) 2018 Roland Ruckerbauer All Rights Reserved.
3
4    This file is part of hidapi-rs, based on hidapi-rs by Osspial
5****************************************************************************/
6
7//! Opens the first hid device it can find, and reads data in a blocking fashion
8//! from it in an endless loop.
9
10#[cfg(all(feature = "linux-static-rusb", not(target_os = "macos")))]
11extern crate rusb;
12
13extern crate hidapi_rusb;
14
15use hidapi_rusb::{HidApi, HidError};
16
17fn main() {
18    fn run() -> Result<(), HidError> {
19        let hidapi = HidApi::new()?;
20
21        let device_info = hidapi
22            .device_list()
23            .next()
24            .expect("No devices are available!")
25            .clone();
26
27        println!(
28            "Opening device:\n VID: {:04x}, PID: {:04x}\n",
29            device_info.vendor_id(),
30            device_info.product_id()
31        );
32
33        let device = device_info.open_device(&hidapi)?;
34
35        let mut buf = vec![0; 64];
36
37        println!("Reading data from device ...\n");
38
39        loop {
40            let len = device.read(&mut buf)?;
41            println!("{:?}", &buf[..len]);
42        }
43    }
44
45    if let Err(e) = run() {
46        eprintln!("Error: {}", e);
47    }
48}