Skip to main content

razers_transport_hidapi/
lib.rs

1// SPDX-License-Identifier: GPL-2.0-or-later
2
3//! Cross-platform HID discovery with privacy-preserving interface summaries.
4//!
5//! This milestone enumerates descriptors only. It does not open devices or send
6//! feature, input, or output reports.
7//!
8//! 跨平台、保护隐私的 HID 发现。当前仅枚举描述符,不打开设备,也不发送功能、输入或输出报文。
9
10use hidapi::HidApi;
11use thiserror::Error;
12
13pub const RAZER_VENDOR_ID: u16 = 0x1532;
14
15/// Non-sensitive information needed to match a HID interface to the registry.
16///
17/// Device paths and serial-number values are deliberately excluded because they
18/// can contain stable identifiers. Callers only learn whether a serial exists.
19///
20/// 接口摘要仅保留匹配清单所需的非敏感信息。不包含设备路径或序列号值,只报告序列号是否存在。
21#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
22pub struct HidInterfaceSummary {
23    pub vendor_id: u16,
24    pub product_id: u16,
25    pub release_number: u16,
26    pub usage_page: u16,
27    pub usage: u16,
28    pub interface_number: i32,
29    pub manufacturer: Option<String>,
30    pub product: Option<String>,
31    pub serial_number_present: bool,
32}
33
34impl HidInterfaceSummary {
35    /// Classify the HID collection using descriptor data only.
36    ///
37    /// 仅根据描述符数据判断 HID 集合类型。
38    pub const fn collection_kind(&self) -> HidCollectionKind {
39        HidCollectionKind::from_usage(self.usage_page, self.usage)
40    }
41
42    /// Whether this descriptor is a possible vendor-command collection.
43    ///
44    /// This is only a discovery hint. It does not authorize opening the
45    /// interface or sending a report; a curated manifest must still match it.
46    ///
47    /// 可能的厂商命令集合仅是发现提示,不授权打开接口或发送报文,仍须匹配已审阅清单。
48    pub const fn is_vendor_defined_collection(&self) -> bool {
49        matches!(self.collection_kind(), HidCollectionKind::VendorDefined)
50    }
51}
52
53#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
54pub enum HidCollectionKind {
55    ConsumerControl,
56    Keyboard,
57    Mouse,
58    Other,
59    VendorDefined,
60}
61
62impl HidCollectionKind {
63    pub const fn from_usage(usage_page: u16, usage: u16) -> Self {
64        match (usage_page, usage) {
65            (0xff00..=0xffff, _) => Self::VendorDefined,
66            (0x0001, 0x0002) => Self::Mouse,
67            (0x0001, 0x0006) => Self::Keyboard,
68            (0x000c, _) => Self::ConsumerControl,
69            _ => Self::Other,
70        }
71    }
72
73    pub const fn as_str(self) -> &'static str {
74        match self {
75            Self::ConsumerControl => "consumer-control",
76            Self::Keyboard => "keyboard",
77            Self::Mouse => "mouse",
78            Self::Other => "other",
79            Self::VendorDefined => "vendor-defined",
80        }
81    }
82}
83
84/// Enumerate Razer HID interfaces without opening them.
85///
86/// 枚举 Razer HID 接口,不打开设备。
87pub fn enumerate_razer() -> Result<Vec<HidInterfaceSummary>, HidEnumerationError> {
88    enumerate_vendor(RAZER_VENDOR_ID)
89}
90
91/// Enumerate interfaces for one USB vendor without opening them.
92///
93/// 枚举指定 USB 厂商的 HID 接口,不打开设备。
94pub fn enumerate_vendor(vendor_id: u16) -> Result<Vec<HidInterfaceSummary>, HidEnumerationError> {
95    let api = HidApi::new().map_err(HidEnumerationError::Initialize)?;
96    let mut interfaces = api
97        .device_list()
98        .filter(|device| device.vendor_id() == vendor_id)
99        .map(|device| HidInterfaceSummary {
100            vendor_id: device.vendor_id(),
101            product_id: device.product_id(),
102            release_number: device.release_number(),
103            usage_page: device.usage_page(),
104            usage: device.usage(),
105            interface_number: device.interface_number(),
106            manufacturer: device.manufacturer_string().map(str::to_owned),
107            product: device.product_string().map(str::to_owned),
108            serial_number_present: device.serial_number().is_some(),
109        })
110        .collect::<Vec<_>>();
111    interfaces.sort();
112    Ok(interfaces)
113}
114
115#[derive(Debug, Error)]
116pub enum HidEnumerationError {
117    #[error("unable to initialize the HID subsystem: {0}")]
118    Initialize(hidapi::HidError),
119}
120
121#[cfg(test)]
122mod tests {
123    use super::*;
124
125    #[test]
126    fn distinguishes_input_and_vendor_defined_collections() {
127        assert_eq!(
128            HidCollectionKind::from_usage(0x0001, 0x0002),
129            HidCollectionKind::Mouse
130        );
131        assert_eq!(
132            HidCollectionKind::from_usage(0x0001, 0x0006),
133            HidCollectionKind::Keyboard
134        );
135        assert_eq!(
136            HidCollectionKind::from_usage(0xff01, 0x0001),
137            HidCollectionKind::VendorDefined
138        );
139    }
140
141    #[test]
142    fn never_treats_standard_input_as_a_vendor_collection() {
143        for (usage_page, usage) in [(0x0001, 0x0002), (0x0001, 0x0006), (0x000c, 0x0001)] {
144            assert_ne!(
145                HidCollectionKind::from_usage(usage_page, usage),
146                HidCollectionKind::VendorDefined
147            );
148        }
149    }
150}