Skip to main content

dualsense_tools/
dualsense.rs

1use hidapi::{HidApi, HidDevice, HidResult};
2
3use crate::state::DualsenseState;
4use crate::{PRODUCT_ID, VENDOR_ID};
5
6/// Interface used to interact with a Dualsense controller; encapsulates
7/// a [hidapi::HidDevice] and a buffer to be re-used when reading input
8/// reports from the hid device.
9#[derive(Debug)]
10pub struct Dualsense {
11    device: HidDevice,
12    input_buf: [u8; 64],
13}
14
15impl Dualsense {
16    /// Creates a new Dualsense instance; will error if no device is
17    /// connected to the USB port.
18    pub fn new(hid_api: &mut HidApi) -> HidResult<Dualsense> {
19        hid_api.reset_devices()?;
20        hid_api.add_devices(VENDOR_ID, PRODUCT_ID)?;
21
22        let device = hid_api.open(VENDOR_ID, PRODUCT_ID)?;
23
24        Ok(Dualsense {
25            device,
26            input_buf: [0; 64],
27        })
28    }
29
30    /// Reads an input report from the device into a provided mutable reference
31    /// to a gamepad state.
32    pub fn read_into(&mut self, state: &mut DualsenseState) -> HidResult<()> {
33        self.device.read(&mut self.input_buf)?;
34        state.update_from_hid_report(&self.input_buf);
35
36        Ok(())
37    }
38
39    /// Reads an input report from the device and returns a gamepad state.
40    pub fn read(&mut self) -> HidResult<DualsenseState> {
41        let mut state = DualsenseState::default();
42        self.read_into(&mut state)?;
43        Ok(state)
44    }
45}