Skip to main content

openlogi_core/
device.rs

1//! Serializable device-model types.
2//!
3//! These mirror the HID++ types from the `hidpp` crate but live here so the
4//! CLI and any future GUI can depend on them without dragging in the protocol
5//! crate or its async transport.
6
7use serde::Serialize;
8
9/// What a paired peripheral is. Mirrors `hidpp::receiver::bolt::BoltDeviceKind`
10/// but is owned by us so consumers don't depend on `hidpp`.
11///
12/// Several upstream "device type" vocabularies feed this one enum, and they do
13/// **not** agree on numbers: the Bolt pairing register uses `Unknown=0,
14/// Keyboard=1, Mouse=2, …`, while the HID++ `0x0005` feature uses
15/// `Keyboard=0, …, Mouse=3, …` (no `Unknown` at all). The asset registry adds a
16/// third, free-form *string* type (`"mouse"`, case-inconsistently `"MOUSE"`).
17/// They are converted to this enum at their respective boundaries — never by
18/// reinterpreting one source's raw byte with another's table — so the numeric
19/// mismatch can't leak past those mappers.
20#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize)]
21#[serde(rename_all = "lowercase")]
22pub enum DeviceKind {
23    Mouse,
24    Keyboard,
25    Numpad,
26    Presenter,
27    Remote,
28    Trackball,
29    Touchpad,
30    Tablet,
31    Gamepad,
32    Joystick,
33    Headset,
34    Unknown,
35}
36
37impl DeviceKind {
38    /// Parse the OpenLogi asset registry's `type` string into a [`DeviceKind`].
39    ///
40    /// The registry field is free-form and case-inconsistent (both `"mouse"`
41    /// and `"MOUSE"` ship), so we case-fold before matching. Values we don't
42    /// model map to [`DeviceKind::Unknown`], which callers treat as "no asset
43    /// opinion" and fall back to the HID++ classification.
44    #[must_use]
45    pub fn from_registry_type(raw: &str) -> Self {
46        match raw.trim().to_ascii_lowercase().as_str() {
47            "mouse" => Self::Mouse,
48            "keyboard" => Self::Keyboard,
49            "numpad" => Self::Numpad,
50            "presenter" => Self::Presenter,
51            "remote" | "remotecontrol" => Self::Remote,
52            "trackball" => Self::Trackball,
53            "touchpad" | "trackpad" => Self::Touchpad,
54            "tablet" => Self::Tablet,
55            "gamepad" => Self::Gamepad,
56            "joystick" => Self::Joystick,
57            "headset" => Self::Headset,
58            _ => Self::Unknown,
59        }
60    }
61}
62
63/// What a device can be *configured* to do, derived from the HID++ feature
64/// table it reports (feature `0x0001`). This is the source of truth for which
65/// configuration panels the UI offers — a panel shows iff the device exposes
66/// the feature that drives it. Gating on capability rather than on
67/// [`DeviceKind`] is what keeps a misclassified device from losing its panels
68/// (issue #127): kind is an identity guess, capability is what the firmware
69/// actually announced.
70#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize)]
71pub struct Capabilities {
72    /// Reprogrammable buttons — HID++ `0x1b00`–`0x1b04` (ReprogControls).
73    pub buttons: bool,
74    /// Adjustable pointer resolution — HID++ `0x2201` / `0x2202` (AdjustableDpi).
75    pub pointer: bool,
76    /// Controllable lighting — HID++ `0x8040`/`0x8070`/`0x8071`/`0x8080`/`0x8081`
77    /// (RGB) or `0x1981`–`0x1983`/`0x1990` (backlight/illumination).
78    pub lighting: bool,
79}
80
81impl Capabilities {
82    /// Derive capabilities from the set of HID++ feature IDs a device reports.
83    /// Membership of a driving feature ID flips the corresponding flag.
84    #[must_use]
85    pub fn from_feature_ids(ids: &[u16]) -> Self {
86        const BUTTONS: [u16; 5] = [0x1b00, 0x1b01, 0x1b02, 0x1b03, 0x1b04];
87        const POINTER: [u16; 2] = [0x2201, 0x2202];
88        const LIGHTING: [u16; 9] = [
89            0x8040, 0x8070, 0x8071, 0x8080, 0x8081, 0x1981, 0x1982, 0x1983, 0x1990,
90        ];
91        let has = |family: &[u16]| ids.iter().any(|id| family.contains(id));
92        Self {
93            buttons: has(&BUTTONS),
94            pointer: has(&POINTER),
95            lighting: has(&LIGHTING),
96        }
97    }
98
99    /// Best-effort capabilities for a device we could not probe (offline /
100    /// never reached), guessed from its [`DeviceKind`]. Used only as a fallback
101    /// when no measured [`Capabilities`] exist — a sleeping mouse should still
102    /// show its button/pointer panels so its bindings (host-side) stay
103    /// configurable.
104    #[must_use]
105    pub fn presumed_from_kind(kind: DeviceKind) -> Self {
106        match kind {
107            DeviceKind::Mouse | DeviceKind::Trackball => Self {
108                buttons: true,
109                pointer: true,
110                lighting: false,
111            },
112            DeviceKind::Keyboard => Self {
113                lighting: true,
114                ..Self::default()
115            },
116            _ => Self::default(),
117        }
118    }
119}
120
121/// Coarse battery bucket reported by the device firmware.
122#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize)]
123#[serde(rename_all = "lowercase")]
124pub enum BatteryLevel {
125    Critical,
126    Low,
127    Good,
128    Full,
129    Unknown,
130}
131
132/// Charging state. Mirrors `hidpp 0.2`'s `BatteryStatus` plus `Unknown` for
133/// values added in future protocol versions.
134#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize)]
135#[serde(rename_all = "snake_case")]
136pub enum BatteryStatus {
137    Discharging,
138    Charging,
139    ChargingSlow,
140    Full,
141    Error,
142    Unknown,
143}
144
145#[derive(Debug, Clone, Serialize)]
146pub struct BatteryInfo {
147    pub percentage: u8,
148    pub level: BatteryLevel,
149    pub status: BatteryStatus,
150}
151
152#[derive(Debug, Clone, Serialize)]
153pub struct ReceiverInfo {
154    pub name: String,
155    pub vendor_id: u16,
156    pub product_id: u16,
157    pub unique_id: Option<String>,
158}
159
160/// HID++ `DeviceInformation` (feature 0x0003) snapshot used to identify a
161/// device against external registries (e.g. the OpenLogi asset index).
162///
163/// `model_ids` is the per-transport PID array reported by the firmware,
164/// ordered to match the transports flagged in [`Self::transports`] (USB,
165/// eQuad, BTLE, Bluetooth) — slots that aren't enabled stay `0`. The Logi
166/// Options+ asset registry's `modelId` (e.g. `"6b023"`) is the concatenation
167/// of an extended-model byte and one of these PIDs, so callers usually want
168/// to format `extended_model_id` + `model_ids[N]` to match.
169#[derive(Debug, Clone, Serialize)]
170pub struct DeviceModelInfo {
171    pub entity_count: u8,
172    /// HID++ DeviceInformation serial number, when the device supports the
173    /// optional serial-number function.
174    pub serial_number: Option<String>,
175    pub unit_id: [u8; 4],
176    pub transports: DeviceTransports,
177    pub model_ids: [u16; 3],
178    pub extended_model_id: u8,
179}
180
181impl DeviceModelInfo {
182    /// Stable identifier used to key per-device configuration (button
183    /// bindings, etc.) and to look up assets in the OpenLogi asset registry.
184    ///
185    /// Format: `{extended_model_id:x}{model_ids[0]:04x}` — the same string
186    /// the depot `manifest.json` uses for its `modelId` field. Example: an
187    /// MX Master 4 with `extended_model_id = 0x02` and `model_ids[0] = 0xb042`
188    /// resolves to `"2b042"`.
189    #[must_use]
190    pub fn config_key(&self) -> String {
191        format!("{:x}{:04x}", self.extended_model_id, self.model_ids[0])
192    }
193}
194
195/// Mirror of hidpp's `DeviceTransport` bitfield — one bool per protocol the
196/// device firmware exposes. The shape is dictated by HID++ feature 0x0003;
197/// a state machine doesn't fit since a single device can announce multiple
198/// transports simultaneously.
199#[allow(
200    clippy::struct_excessive_bools,
201    reason = "bitfield mirroring HID++ DeviceInformation; transports are independent flags"
202)]
203#[derive(Debug, Clone, Copy, Default, Serialize)]
204pub struct DeviceTransports {
205    pub usb: bool,
206    pub equad: bool,
207    pub btle: bool,
208    pub bluetooth: bool,
209}
210
211#[derive(Debug, Clone, Serialize)]
212pub struct PairedDevice {
213    /// Receiver-assigned slot (1..=6 for Bolt).
214    pub slot: u8,
215    pub codename: Option<String>,
216    /// Wireless product ID. `None` for offline / unreachable devices on hidpp 0.2.
217    pub wpid: Option<u16>,
218    pub kind: DeviceKind,
219    pub online: bool,
220    pub battery: Option<BatteryInfo>,
221    /// Output of HID++ feature 0x0003 — populated for online devices that
222    /// expose the feature. Drives asset-registry lookups in the GUI.
223    pub model_info: Option<DeviceModelInfo>,
224    /// Configuration capabilities derived from the device's HID++ feature
225    /// table. `None` for devices we couldn't probe (offline / unreachable);
226    /// the GUI then falls back to [`Capabilities::presumed_from_kind`].
227    pub capabilities: Option<Capabilities>,
228}
229
230#[derive(Debug, Clone, Serialize)]
231pub struct DeviceInventory {
232    pub receiver: ReceiverInfo,
233    pub paired: Vec<PairedDevice>,
234}
235
236#[cfg(test)]
237mod tests {
238    use super::DeviceKind;
239
240    #[test]
241    fn registry_type_is_case_folded() {
242        // The registry ships both `"mouse"` and `"MOUSE"`; both must resolve so
243        // the asset cross-check can't silently miss a depot.
244        assert_eq!(DeviceKind::from_registry_type("mouse"), DeviceKind::Mouse);
245        assert_eq!(DeviceKind::from_registry_type("MOUSE"), DeviceKind::Mouse);
246        assert_eq!(
247            DeviceKind::from_registry_type("  Keyboard "),
248            DeviceKind::Keyboard
249        );
250    }
251
252    #[test]
253    fn unknown_registry_type_defers_to_the_caller() {
254        // Unmodelled / empty → Unknown, i.e. "no asset opinion".
255        assert_eq!(
256            DeviceKind::from_registry_type("webcam"),
257            DeviceKind::Unknown
258        );
259        assert_eq!(DeviceKind::from_registry_type(""), DeviceKind::Unknown);
260    }
261
262    #[test]
263    fn capabilities_track_the_driving_feature_ids() {
264        use super::Capabilities;
265        // A typical MX mouse: ReprogControls (0x1b04) + ExtendedAdjustableDpi
266        // (0x2202), no lighting.
267        let mouse = Capabilities::from_feature_ids(&[0x0003, 0x1b04, 0x2202, 0x2110]);
268        assert_eq!(
269            mouse,
270            Capabilities {
271                buttons: true,
272                pointer: true,
273                lighting: false,
274            }
275        );
276        // A wired G-series keyboard: PerKeyLighting (0x8080), no DPI/buttons.
277        let keyboard = Capabilities::from_feature_ids(&[0x0001, 0x8080]);
278        assert_eq!(
279            keyboard,
280            Capabilities {
281                buttons: false,
282                pointer: false,
283                lighting: true,
284            }
285        );
286        // No driving features → nothing offered.
287        assert_eq!(
288            Capabilities::from_feature_ids(&[0x0000, 0x0003]),
289            Capabilities::default()
290        );
291    }
292
293    #[test]
294    fn presumed_capabilities_keep_an_unprobed_mouse_configurable() {
295        use super::Capabilities;
296        let mouse = Capabilities::presumed_from_kind(DeviceKind::Mouse);
297        assert!(mouse.buttons && mouse.pointer && !mouse.lighting);
298        assert!(Capabilities::presumed_from_kind(DeviceKind::Keyboard).lighting);
299        // An unidentified device presumes nothing — it must be measured.
300        assert_eq!(
301            Capabilities::presumed_from_kind(DeviceKind::Unknown),
302            Capabilities::default()
303        );
304    }
305}