async_hid/backend/hidraw/
mod.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
mod descriptor;
mod ioctl;
mod utils;

use std::fs::{read_dir, read_to_string, OpenOptions};
use std::os::fd::{AsRawFd, OwnedFd};
use std::os::unix::fs::OpenOptionsExt;
use std::path::{Path, PathBuf};

use futures_core::Stream;
use nix::fcntl::OFlag;
use nix::unistd::{read, write};
use tokio::io::unix::AsyncFd;
use tokio::io::Interest;

use crate::backend::hidraw::descriptor::HidrawReportDescriptor;
use crate::backend::hidraw::ioctl::hidraw_ioc_grdescsize;
use crate::backend::hidraw::utils::{iter, TryIterExt};
use crate::{ensure, AccessMode, DeviceInfo, ErrorSource, HidError, HidResult};

pub async fn enumerate() -> HidResult<impl Stream<Item = DeviceInfo>> {
    let devices = read_dir("/sys/class/hidraw/")?
        .map(|r| r.map(|e| e.path()))
        .try_collect_vec()?;
    let devices = devices
        .into_iter()
        .map(get_device_info_raw)
        .filter_map(|r| {
            r.map_err(|e| log::trace!("Failed to query device information\n\tbecause {e:?}"))
                .ok()
        })
        .flatten();
    Ok(iter(devices))
}

fn get_device_info_raw(path: PathBuf) -> HidResult<Vec<DeviceInfo>> {
    let properties = read_to_string(path.join("uevent"))?;
    let id = read_property(&properties, "DEVNAME")
        .ok_or(HidError::custom("Can't find dev name"))
        .and_then(mange_dev_name)?;

    let properties = read_to_string(path.join("device/uevent"))?;

    let (_bus, vendor_id, product_id) = read_property(&properties, "HID_ID")
        .and_then(parse_hid_vid_pid)
        .ok_or(HidError::custom("Can't find hid ids"))?;

    let name = read_property(&properties, "HID_NAME")
        .ok_or(HidError::custom("Can't find hid name"))?
        .to_string();

    let info = DeviceInfo {
        id: id.into(),
        name,
        product_id,
        vendor_id,
        usage_id: 0,
        usage_page: 0
    };

    let results = HidrawReportDescriptor::from_syspath(&path)
        .map(|descriptor| {
            descriptor
                .usages()
                .map(|(usage_page, usage_id)| DeviceInfo {
                    usage_page,
                    usage_id,
                    ..info.clone()
                })
                .collect()
        })
        .unwrap_or_else(|_| vec![info]);
    Ok(results)
}

fn read_property<'a>(properties: &'a str, key: &str) -> Option<&'a str> {
    properties
        .lines()
        .filter_map(|l| l.split_once('='))
        .find_map(|(k, v)| (k == key).then_some(v))
}

fn mange_dev_name(dev_name: &str) -> HidResult<PathBuf> {
    let path = Path::new(dev_name);
    if path.is_absolute() {
        ensure!(
            dev_name
                .strip_prefix("/dev/")
                .is_some_and(|z| !z.is_empty()),
            HidError::custom("Absolute device paths must start with /dev/")
        );
        Ok(path.to_path_buf())
    } else {
        Ok(Path::new("/dev/").join(path))
    }
}

fn parse_hid_vid_pid(s: &str) -> Option<(u16, u16, u16)> {
    let mut elems = s.split(':').filter_map(|s| u16::from_str_radix(s, 16).ok());
    let devtype = elems.next()?;
    let vendor = elems.next()?;
    let product = elems.next()?;

    Some((devtype, vendor, product))
}

#[derive(Debug)]
pub struct BackendDevice {
    fd: AsyncFd<OwnedFd>
}

impl BackendDevice {
    pub async fn read_input_report(&self, buf: &mut [u8]) -> HidResult<usize> {
        self.fd
            .async_io(Interest::READABLE, |fd| read(fd.as_raw_fd(), buf).map_err(BackendError::from))
            .await
            .map_err(HidError::from)
    }

    pub async fn write_output_report(&self, data: &[u8]) -> HidResult<()> {
        ensure!(!data.is_empty(), HidError::zero_sized_data());
        self.fd
            .async_io(Interest::WRITABLE, |fd| write(fd.as_raw_fd(), data).map_err(BackendError::from))
            .await
            .map_err(HidError::from)
            .map(|i| debug_assert_eq!(i, data.len()))
    }
}

pub async fn open(id: &BackendDeviceId, mode: AccessMode) -> HidResult<BackendDevice> {
    let fd: OwnedFd = OpenOptions::new()
        .read(mode.readable())
        .write(mode.writeable())
        .custom_flags((OFlag::O_CLOEXEC | OFlag::O_NONBLOCK).bits())
        .open(id)?
        .into();

    let mut size = 0i32;
    unsafe { hidraw_ioc_grdescsize(fd.as_raw_fd(), &mut size) }
        .map_err(|e| HidError::custom(format!("ioctl(GRDESCSIZE) error for {:?}, not a HIDRAW device?: {}", id, e)))?;

    Ok(BackendDevice { fd: AsyncFd::new(fd)? })
}

pub type BackendDeviceId = PathBuf;
pub type BackendError = std::io::Error;

impl From<BackendError> for ErrorSource {
    fn from(value: BackendError) -> Self {
        ErrorSource::PlatformSpecific(value)
    }
}

/*
udev device searching

pub async fn enumerate() -> HidResult<impl Stream<Item = DeviceInfo>> {
    let mut enumerator = Enumerator::new()?;
    enumerator.match_subsystem("hidraw")?;
    let devices: Vec<Device> = enumerator
        .scan_devices()?
        .collect();
    let devices = devices
        .into_iter()
        .map(get_device_info)
        .filter_map(|r| {
            r.map_err(|e| log::trace!("Failed to query device information\n\tbecause {e:?}"))
                .ok()
        })
        .flatten();
    Ok(iter(devices))
}

fn get_device_info(raw_device: Device) -> HidResult<Vec<DeviceInfo>> {
  let device = raw_device
      .parent_with_subsystem("hid")?
      .ok_or(HidError::custom("Can't find hid interface"))?;

  let (_bus, vendor_id, product_id) = device
      .property_value("HID_ID")
      .and_then(|s| s.to_str())
      .and_then(parse_hid_vid_pid)
      .ok_or(HidError::custom("Can't find hid ids"))?;

  let id = raw_device
      .devnode()
      .ok_or(HidError::custom("Can't find device node"))?
      .to_path_buf();

  let name = device
      .property_value("HID_NAME")
      .ok_or(HidError::custom("Can't find hid name"))?
      .to_string_lossy()
      .to_string();

  let info = DeviceInfo {
      id: id.into(),
      name,
      product_id,
      vendor_id,
      usage_id: 0,
      usage_page: 0
  };
  let results = HidrawReportDescriptor::from_syspath(raw_device.syspath())
      .map(|descriptor| {
          descriptor
              .usages()
              .map(|(usage_page, usage_id)| DeviceInfo {
                  usage_page,
                  usage_id,
                  ..info.clone()
              })
              .collect()
      })
      .unwrap_or_else(|_| vec![info]);
  Ok(results)
}
*/