Struct HidDevice

Source
pub struct HidDevice { /* private fields */ }
Expand description

Object for accessing HID device

Implementations§

Source§

impl HidDevice

Source

pub fn check_error(&self) -> HidResult<HidError>

Get the last error, which happened in the underlying hidapi C library.

The Ok() variant of the result will contain a HidError::HidApiError.

When Err() is returned, then acquiring the error string from the hidapi C library failed. The contained HidError is the cause, why no error could be fetched.

Examples found in repository?
examples/static_lifetime_bound.rs (line 42)
26fn test_lt() -> Rc<HidDevice> {
27    let api = HidApi::new().expect("Hidapi init failed");
28
29    let mut devices = api.device_list();
30
31    let dev_info = devices
32        .nth(0)
33        .expect("There is not a single hid device available");
34
35    let dev = Rc::new(
36        api.open(dev_info.vendor_id(), dev_info.product_id())
37            .expect("Can not open device"),
38    );
39
40    let dev_1 = dev.clone();
41    requires_static_lt_bound(move || {
42        println!("{}", dev_1.check_error().unwrap()); //<! Can be captured by closure with static lt
43    });
44
45    dev //<! Can be returned from a function, which exceeds the lifetime of the API context
46}
Source

pub fn write(&self, data: &[u8]) -> HidResult<usize>

The first byte of data must contain the Report ID. For devices which only support a single report, this must be set to 0x0. The remaining bytes contain the report data. Since the Report ID is mandatory, calls to write() will always contain one more byte than the report contains. For example, if a hid report is 16 bytes long, 17 bytes must be passed to write(), the Report ID (or 0x0, for devices with a single report), followed by the report data (16 bytes). In this example, the length passed in would be 17. write() will send the data on the first OUT endpoint, if one exists. If it does not, it will send the data through the Control Endpoint (Endpoint 0).

Source

pub fn read(&self, buf: &mut [u8]) -> HidResult<usize>

Input reports are returned to the host through the ‘INTERRUPT IN’ endpoint. The first byte will contain the Report number if the device uses numbered reports.

Examples found in repository?
examples/readhid.rs (line 24)
17fn main() {
18    let api = HidApi::new().expect("Failed to create API instance");
19
20    let joystick = api.open(1103, 45320).expect("Failed to open device");
21
22    loop {
23        let mut buf = [0u8; 256];
24        let res = joystick.read(&mut buf[..]).unwrap();
25
26        let mut data_string = String::new();
27
28        for u in &buf[..res] {
29            data_string.push_str(&(u.to_string() + "\t"));
30        }
31
32        println!("{}", data_string);
33    }
34}
More examples
Hide additional examples
examples/open_first_device.rs (line 40)
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    }
Source

pub fn read_timeout(&self, buf: &mut [u8], timeout: i32) -> HidResult<usize>

Input reports are returned to the host through the ‘INTERRUPT IN’ endpoint. The first byte will contain the Report number if the device uses numbered reports. Timeout measured in milliseconds, set -1 for blocking wait.

Examples found in repository?
examples/co2mon.rs (line 116)
90fn main() {
91    let api = HidApi::new().expect("HID API object creation failed");
92
93    let dev = open_device(&api);
94
95    dev.send_feature_report(&[0; PACKET_SIZE])
96        .expect("Feature report failed");
97
98    println!(
99        "Manufacurer:\t{:?}",
100        dev.get_manufacturer_string()
101            .expect("Failed to read manufacurer string")
102    );
103    println!(
104        "Product:\t{:?}",
105        dev.get_product_string()
106            .expect("Failed to read product string")
107    );
108    println!(
109        "Serial number:\t{:?}",
110        dev.get_serial_number_string()
111            .expect("Failed to read serial number")
112    );
113
114    loop {
115        let mut buf = [0; PACKET_SIZE];
116        match dev.read_timeout(&mut buf[..], HID_TIMEOUT) {
117            Ok(PACKET_SIZE) => (),
118            Ok(res) => {
119                println!("Error: unexpected length of data: {}/{}", res, PACKET_SIZE);
120                continue;
121            }
122            Err(err) => {
123                println!("Error: {:}", err);
124                sleep(Duration::from_secs(RETRY_SEC));
125                continue;
126            }
127        }
128        match decode_buf(buf) {
129            CO2Result::Temperature(val) => println!("Temp:\t{:?}", val),
130            CO2Result::Concentration(val) => println!("Conc:\t{:?}", val),
131            CO2Result::Unknown(..) => (),
132            CO2Result::Error(val) => {
133                println!("Error:\t{}", val);
134                sleep(Duration::from_secs(RETRY_SEC));
135            }
136        }
137    }
138}
Source

pub fn send_feature_report(&self, data: &[u8]) -> HidResult<()>

Send a Feature report to the device. Feature reports are sent over the Control endpoint as a Set_Report transfer. The first byte of data must contain the ‘Report ID’. For devices which only support a single report, this must be set to 0x0. The remaining bytes contain the report data. Since the ‘Report ID’ is mandatory, calls to send_feature_report() will always contain one more byte than the report contains. For example, if a hid report is 16 bytes long, 17 bytes must be passed to send_feature_report(): ‘the Report ID’ (or 0x0, for devices which do not use numbered reports), followed by the report data (16 bytes). In this example, the length passed in would be 17.

Examples found in repository?
examples/co2mon.rs (line 95)
90fn main() {
91    let api = HidApi::new().expect("HID API object creation failed");
92
93    let dev = open_device(&api);
94
95    dev.send_feature_report(&[0; PACKET_SIZE])
96        .expect("Feature report failed");
97
98    println!(
99        "Manufacurer:\t{:?}",
100        dev.get_manufacturer_string()
101            .expect("Failed to read manufacurer string")
102    );
103    println!(
104        "Product:\t{:?}",
105        dev.get_product_string()
106            .expect("Failed to read product string")
107    );
108    println!(
109        "Serial number:\t{:?}",
110        dev.get_serial_number_string()
111            .expect("Failed to read serial number")
112    );
113
114    loop {
115        let mut buf = [0; PACKET_SIZE];
116        match dev.read_timeout(&mut buf[..], HID_TIMEOUT) {
117            Ok(PACKET_SIZE) => (),
118            Ok(res) => {
119                println!("Error: unexpected length of data: {}/{}", res, PACKET_SIZE);
120                continue;
121            }
122            Err(err) => {
123                println!("Error: {:}", err);
124                sleep(Duration::from_secs(RETRY_SEC));
125                continue;
126            }
127        }
128        match decode_buf(buf) {
129            CO2Result::Temperature(val) => println!("Temp:\t{:?}", val),
130            CO2Result::Concentration(val) => println!("Conc:\t{:?}", val),
131            CO2Result::Unknown(..) => (),
132            CO2Result::Error(val) => {
133                println!("Error:\t{}", val);
134                sleep(Duration::from_secs(RETRY_SEC));
135            }
136        }
137    }
138}
Source

pub fn get_feature_report(&self, buf: &mut [u8]) -> HidResult<usize>

Set the first byte of buf to the ‘Report ID’ of the report to be read. Upon return, the first byte will still contain the Report ID, and the report data will start in buf[1].

Source

pub fn set_blocking_mode(&self, blocking: bool) -> HidResult<()>

Set the device handle to be in blocking or in non-blocking mode. In non-blocking mode calls to read() will return immediately with an empty slice if there is no data to be read. In blocking mode, read() will wait (block) until there is data to read before returning. Modes can be changed at any time.

Source

pub fn get_manufacturer_string(&self) -> HidResult<Option<String>>

Get The Manufacturer String from a HID device.

Examples found in repository?
examples/co2mon.rs (line 100)
90fn main() {
91    let api = HidApi::new().expect("HID API object creation failed");
92
93    let dev = open_device(&api);
94
95    dev.send_feature_report(&[0; PACKET_SIZE])
96        .expect("Feature report failed");
97
98    println!(
99        "Manufacurer:\t{:?}",
100        dev.get_manufacturer_string()
101            .expect("Failed to read manufacurer string")
102    );
103    println!(
104        "Product:\t{:?}",
105        dev.get_product_string()
106            .expect("Failed to read product string")
107    );
108    println!(
109        "Serial number:\t{:?}",
110        dev.get_serial_number_string()
111            .expect("Failed to read serial number")
112    );
113
114    loop {
115        let mut buf = [0; PACKET_SIZE];
116        match dev.read_timeout(&mut buf[..], HID_TIMEOUT) {
117            Ok(PACKET_SIZE) => (),
118            Ok(res) => {
119                println!("Error: unexpected length of data: {}/{}", res, PACKET_SIZE);
120                continue;
121            }
122            Err(err) => {
123                println!("Error: {:}", err);
124                sleep(Duration::from_secs(RETRY_SEC));
125                continue;
126            }
127        }
128        match decode_buf(buf) {
129            CO2Result::Temperature(val) => println!("Temp:\t{:?}", val),
130            CO2Result::Concentration(val) => println!("Conc:\t{:?}", val),
131            CO2Result::Unknown(..) => (),
132            CO2Result::Error(val) => {
133                println!("Error:\t{}", val);
134                sleep(Duration::from_secs(RETRY_SEC));
135            }
136        }
137    }
138}
Source

pub fn get_product_string(&self) -> HidResult<Option<String>>

Get The Manufacturer String from a HID device.

Examples found in repository?
examples/co2mon.rs (line 105)
90fn main() {
91    let api = HidApi::new().expect("HID API object creation failed");
92
93    let dev = open_device(&api);
94
95    dev.send_feature_report(&[0; PACKET_SIZE])
96        .expect("Feature report failed");
97
98    println!(
99        "Manufacurer:\t{:?}",
100        dev.get_manufacturer_string()
101            .expect("Failed to read manufacurer string")
102    );
103    println!(
104        "Product:\t{:?}",
105        dev.get_product_string()
106            .expect("Failed to read product string")
107    );
108    println!(
109        "Serial number:\t{:?}",
110        dev.get_serial_number_string()
111            .expect("Failed to read serial number")
112    );
113
114    loop {
115        let mut buf = [0; PACKET_SIZE];
116        match dev.read_timeout(&mut buf[..], HID_TIMEOUT) {
117            Ok(PACKET_SIZE) => (),
118            Ok(res) => {
119                println!("Error: unexpected length of data: {}/{}", res, PACKET_SIZE);
120                continue;
121            }
122            Err(err) => {
123                println!("Error: {:}", err);
124                sleep(Duration::from_secs(RETRY_SEC));
125                continue;
126            }
127        }
128        match decode_buf(buf) {
129            CO2Result::Temperature(val) => println!("Temp:\t{:?}", val),
130            CO2Result::Concentration(val) => println!("Conc:\t{:?}", val),
131            CO2Result::Unknown(..) => (),
132            CO2Result::Error(val) => {
133                println!("Error:\t{}", val);
134                sleep(Duration::from_secs(RETRY_SEC));
135            }
136        }
137    }
138}
Source

pub fn get_serial_number_string(&self) -> HidResult<Option<String>>

Get The Serial Number String from a HID device.

Examples found in repository?
examples/co2mon.rs (line 110)
90fn main() {
91    let api = HidApi::new().expect("HID API object creation failed");
92
93    let dev = open_device(&api);
94
95    dev.send_feature_report(&[0; PACKET_SIZE])
96        .expect("Feature report failed");
97
98    println!(
99        "Manufacurer:\t{:?}",
100        dev.get_manufacturer_string()
101            .expect("Failed to read manufacurer string")
102    );
103    println!(
104        "Product:\t{:?}",
105        dev.get_product_string()
106            .expect("Failed to read product string")
107    );
108    println!(
109        "Serial number:\t{:?}",
110        dev.get_serial_number_string()
111            .expect("Failed to read serial number")
112    );
113
114    loop {
115        let mut buf = [0; PACKET_SIZE];
116        match dev.read_timeout(&mut buf[..], HID_TIMEOUT) {
117            Ok(PACKET_SIZE) => (),
118            Ok(res) => {
119                println!("Error: unexpected length of data: {}/{}", res, PACKET_SIZE);
120                continue;
121            }
122            Err(err) => {
123                println!("Error: {:}", err);
124                sleep(Duration::from_secs(RETRY_SEC));
125                continue;
126            }
127        }
128        match decode_buf(buf) {
129            CO2Result::Temperature(val) => println!("Temp:\t{:?}", val),
130            CO2Result::Concentration(val) => println!("Conc:\t{:?}", val),
131            CO2Result::Unknown(..) => (),
132            CO2Result::Error(val) => {
133                println!("Error:\t{}", val);
134                sleep(Duration::from_secs(RETRY_SEC));
135            }
136        }
137    }
138}
Source

pub fn get_indexed_string(&self, index: i32) -> HidResult<Option<String>>

Get a string from a HID device, based on its string index.

Trait Implementations§

Source§

impl Drop for HidDevice

Source§

fn drop(&mut self)

Executes the destructor for this type. Read more
Source§

impl Send for HidDevice

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.