//! Direct hidraw access for the beyerdynamic MMX 150 wireless dongle. //! //! The dongle exposes a vendor HID interface (`2e50:0035`) alongside its USB //! audio interfaces. The kernel binds it to `hid-generic`, which shows up as //! `/dev/hidrawN`. We talk to it with the standard `HIDIOCGFEATURE`, //! `HIDIOCSFEATURE`, `HIDIOCGINPUT`, `HIDIOCGSOUTPUT` ioctls plus plain //! `read`/`write` on the interrupt endpoints. use std::fs; use std::io; use std::os::fd::AsRawFd; use std::path::{Path, PathBuf}; /// beyerdynamic USB vendor ID. pub const BEYERDYNAMIC_VID: u16 = 0x2e50; /// MMX 150 wireless low-latency dongle product ID. pub const MMX150_DONGLE_PID: u16 = 0x0035; const HIDRAW_SYSFS: &str = "/sys/class/hidraw"; const IOC_NRSHIFT: u32 = 0; const IOC_TYPESHIFT: u32 = 8; const IOC_SIZESHIFT: u32 = 16; const IOC_DIRSHIFT: u32 = 30; const IOC_READ: u32 = 2; const IOC_WRITE: u32 = 1; fn ioc(dir: u32, ty: u8, nr: u32, size: u32) -> libc::c_ulong { ((dir << IOC_DIRSHIFT) | ((ty as u32) << IOC_TYPESHIFT) | (nr << IOC_NRSHIFT) | (size << IOC_SIZESHIFT)) as libc::c_ulong } const HIDIOCGFEATURE_NR: u32 = 0x06; const HIDIOCSFEATURE_NR: u32 = 0x07; const HIDIOCGINPUT_NR: u32 = 0x0a; const HIDIOCGSOUTPUT_NR: u32 = 0x0d; fn hid_get_feature_cmd(size: u32) -> libc::c_ulong { ioc(IOC_READ, b'H', HIDIOCGFEATURE_NR, size) } fn hid_set_feature_cmd(size: u32) -> libc::c_ulong { ioc(IOC_WRITE, b'H', HIDIOCSFEATURE_NR, size) } fn hid_get_input_cmd(size: u32) -> libc::c_ulong { ioc(IOC_READ, b'H', HIDIOCGINPUT_NR, size) } fn hid_get_output_cmd(size: u32) -> libc::c_ulong { ioc(IOC_WRITE, b'H', HIDIOCGSOUTPUT_NR, size) } /// A HID device discovered on the system. #[derive(Debug, Clone)] pub struct HidDevice { pub vid: u16, pub pid: u16, pub name: String, pub devnode: PathBuf, } /// Enumerate hidraw devices matching `vid`/`pid` by reading the sysfs `uevent` /// of each `/sys/class/hidraw/hidrawN`. pub fn find_devices(vid: u16, pid: u16) -> io::Result> { let mut out = Vec::new(); for entry in fs::read_dir(HIDRAW_SYSFS)? { let entry = entry?; let name = entry.file_name(); let Some(name) = name.to_str() else { continue; }; if !name.starts_with("hidraw") { continue; } let Some(uevent) = read_sysfs(&entry.path().join("device/uevent")) else { continue; }; let Some((bus, v, p)) = parse_hid_id(&uevent) else { continue; }; if bus != 3 { continue; // USB only } if v == vid && p == pid { let dev_name = uevent .lines() .find(|l| l.starts_with("HID_NAME=")) .map(|l| l.trim_start_matches("HID_NAME=").to_string()) .unwrap_or_default(); out.push(HidDevice { vid: v, pid: p, name: dev_name, devnode: PathBuf::from("/dev").join(name), }); } } Ok(out) } /// Find the first (only) MMX 150 dongle HID device. pub fn find_mmx150() -> io::Result> { Ok(find_devices(BEYERDYNAMIC_VID, MMX150_DONGLE_PID)? .into_iter() .next()) } /// Enumerate all hidraw devices belonging to a vendor. pub fn find_devices_by_vendor(vid: u16) -> io::Result> { let mut out = Vec::new(); for entry in fs::read_dir(HIDRAW_SYSFS)? { let entry = entry?; let name = entry.file_name(); let Some(name) = name.to_str() else { continue; }; if !name.starts_with("hidraw") { continue; } let Some(uevent) = read_sysfs(&entry.path().join("device/uevent")) else { continue; }; let Some((bus, v, p)) = parse_hid_id(&uevent) else { continue; }; if bus != 3 || v != vid { continue; } let dev_name = uevent .lines() .find(|l| l.starts_with("HID_NAME=")) .map(|l| l.trim_start_matches("HID_NAME=").to_string()) .unwrap_or_default(); out.push(HidDevice { vid: v, pid: p, name: dev_name, devnode: PathBuf::from("/dev").join(name), }); } Ok(out) } /// An open hidraw file descriptor. pub struct Hidraw { file: fs::File, pub devnode: PathBuf, } impl Hidraw { pub fn open(devnode: impl AsRef) -> io::Result { let file = fs::OpenOptions::new() .read(true) .write(true) .open(devnode.as_ref())?; Ok(Hidraw { file, devnode: devnode.as_ref().to_path_buf(), }) } /// Returns the underlying raw file descriptor. pub fn as_raw_fd(&self) -> std::os::fd::RawFd { self.file.as_raw_fd() } /// `HIDIOCGFEATURE`: fetch `report_id` into `data` (report length + 1 /// bytes including the report-id byte). Returns bytes received. pub fn get_feature(&self, report_id: u8, len: usize) -> io::Result> { let mut buf = vec![0u8; len]; buf[0] = report_id; self.raw_ioctl(hid_get_feature_cmd(len as u32), &mut buf)?; Ok(buf) } /// `HIDIOCSFEATURE`: set a feature report (`data[0]` is the report id). pub fn set_feature(&self, data: &[u8]) -> io::Result { self.raw_ioctl(hid_set_feature_cmd(data.len() as u32), &mut data.to_vec()) } /// `HIDIOCGINPUT`: fetch an input report by id. pub fn get_input(&self, report_id: u8, len: usize) -> io::Result> { let mut buf = vec![0u8; len]; buf[0] = report_id; self.raw_ioctl(hid_get_input_cmd(len as u32), &mut buf)?; Ok(buf) } /// `HIDIOCGSOUTPUT`: send an output report (`data[0]` is the report id) /// via a control transfer, without going through the interrupt endpoint. pub fn send_output(&self, data: &[u8]) -> io::Result { self.raw_ioctl(hid_get_output_cmd(data.len() as u32), &mut data.to_vec()) } /// Read from the interrupt IN endpoint (asynchronous input reports). pub fn read(&mut self, buf: &mut [u8]) -> io::Result { use std::io::Read; self.file.read(buf) } /// Write to the interrupt OUT endpoint. pub fn write(&mut self, buf: &[u8]) -> io::Result { use std::io::Write; self.file.write(buf) } fn raw_ioctl(&self, request: libc::c_ulong, buf: &mut [u8]) -> io::Result { // SAFETY: buf is owned and valid for the duration of the call. let ret = unsafe { libc::ioctl( self.file.as_raw_fd(), request, buf.as_mut_ptr() as *mut libc::c_void, ) }; if ret < 0 { return Err(io::Error::last_os_error()); } Ok(ret as usize) } } fn read_sysfs(path: &Path) -> Option { fs::read_to_string(path).ok() } /// Parse the `HID_ID=::` line (hex values). fn parse_hid_id(uevent: &str) -> Option<(u32, u16, u16)> { let line = uevent.lines().find(|l| l.starts_with("HID_ID="))?; let id = line.trim_start_matches("HID_ID="); let mut parts = id.split(':'); let bus = u32::from_str_radix(parts.next()?, 16).ok()?; let vid = u16::from_str_radix(parts.next()?, 16).ok()?; let pid = u16::from_str_radix(parts.next()?, 16).ok()?; Some((bus, vid, pid)) } #[cfg(test)] mod tests { use super::*; #[test] fn parses_hid_id() { let uevent = "MAJOR=240\nMINOR=1\nDEVNAME=hidraw1\nHID_ID=0003:00002E50:00000035\nHID_NAME=beyerdynamic Dongle MMX 150 wireless\n"; let (bus, vid, pid) = parse_hid_id(uevent).unwrap(); assert_eq!(bus, 3); assert_eq!(vid, 0x2e50); assert_eq!(pid, 0x0035); } }