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::{Deserialize, 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, Deserialize)]
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, Deserialize)]
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 /// Per-key RGB the lighting panel can actually drive — HID++ `PerKeyLighting`
77 /// (`0x8080`), the feature `set_keyboard_color` writes. Legacy/zone/backlight
78 /// lighting families aren't driven by the panel, so they don't flip this and
79 /// don't earn an inert Lighting tab.
80 pub lighting: bool,
81}
82
83impl Capabilities {
84 /// Derive capabilities from the set of HID++ feature IDs a device reports.
85 /// Membership of a driving feature ID flips the corresponding flag.
86 #[must_use]
87 pub fn from_feature_ids(ids: &[u16]) -> Self {
88 const BUTTONS: [u16; 5] = [0x1b00, 0x1b01, 0x1b02, 0x1b03, 0x1b04];
89 const POINTER: [u16; 2] = [0x2201, 0x2202];
90 // Only PerKeyLighting (0x8080) — the feature the lighting panel drives via
91 // `set_keyboard_color`. Advertising a non-per-key family (legacy 0x8070,
92 // backlight 0x198x) would otherwise earn a tab the panel can't drive.
93 const LIGHTING: [u16; 1] = [0x8080];
94 let has = |family: &[u16]| ids.iter().any(|id| family.contains(id));
95 Self {
96 buttons: has(&BUTTONS),
97 pointer: has(&POINTER),
98 lighting: has(&LIGHTING),
99 }
100 }
101
102 /// Best-effort capabilities for a device we could not probe (offline /
103 /// never reached), guessed from its [`DeviceKind`]. Used only as a fallback
104 /// when no measured [`Capabilities`] exist — a sleeping mouse should still
105 /// show its button/pointer panels so its bindings (host-side) stay
106 /// configurable.
107 #[must_use]
108 pub fn presumed_from_kind(kind: DeviceKind) -> Self {
109 match kind {
110 DeviceKind::Mouse | DeviceKind::Trackball => Self {
111 buttons: true,
112 pointer: true,
113 lighting: false,
114 },
115 DeviceKind::Keyboard => Self {
116 lighting: true,
117 ..Self::default()
118 },
119 _ => Self::default(),
120 }
121 }
122}
123
124/// Coarse battery bucket reported by the device firmware.
125#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
126#[serde(rename_all = "lowercase")]
127pub enum BatteryLevel {
128 Critical,
129 Low,
130 Good,
131 Full,
132 Unknown,
133}
134
135/// Charging state. Mirrors `hidpp 0.2`'s `BatteryStatus` plus `Unknown` for
136/// values added in future protocol versions.
137#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
138#[serde(rename_all = "snake_case")]
139pub enum BatteryStatus {
140 Discharging,
141 Charging,
142 ChargingSlow,
143 Full,
144 Error,
145 Unknown,
146}
147
148#[derive(Debug, Clone, Serialize, Deserialize)]
149pub struct BatteryInfo {
150 pub percentage: u8,
151 pub level: BatteryLevel,
152 pub status: BatteryStatus,
153}
154
155#[derive(Debug, Clone, Serialize, Deserialize)]
156pub struct ReceiverInfo {
157 pub name: String,
158 pub vendor_id: u16,
159 pub product_id: u16,
160 pub unique_id: Option<String>,
161}
162
163/// HID++ `DeviceInformation` (feature 0x0003) snapshot used to identify a
164/// device against external registries (e.g. the OpenLogi asset index).
165///
166/// `model_ids` is the per-transport PID array reported by the firmware,
167/// ordered to match the transports flagged in [`Self::transports`] (USB,
168/// eQuad, BTLE, Bluetooth) — slots that aren't enabled stay `0`. The Logi
169/// Options+ asset registry's `modelId` (e.g. `"6b023"`) is the concatenation
170/// of an extended-model byte and one of these PIDs, so callers usually want
171/// to format `extended_model_id` + `model_ids[N]` to match.
172#[derive(Debug, Clone, Serialize, Deserialize)]
173pub struct DeviceModelInfo {
174 pub entity_count: u8,
175 /// HID++ DeviceInformation serial number, when the device supports the
176 /// optional serial-number function.
177 pub serial_number: Option<String>,
178 pub unit_id: [u8; 4],
179 pub transports: DeviceTransports,
180 pub model_ids: [u16; 3],
181 pub extended_model_id: u8,
182}
183
184impl DeviceModelInfo {
185 /// Stable identifier used to key per-device configuration (button
186 /// bindings, etc.) and to look up assets in the OpenLogi asset registry.
187 ///
188 /// Format: `{extended_model_id:x}{model_ids[0]:04x}` — the same string
189 /// the depot `manifest.json` uses for its `modelId` field. Example: an
190 /// MX Master 4 with `extended_model_id = 0x02` and `model_ids[0] = 0xb042`
191 /// resolves to `"2b042"`.
192 #[must_use]
193 pub fn config_key(&self) -> String {
194 format!("{:x}{:04x}", self.extended_model_id, self.model_ids[0])
195 }
196}
197
198/// Mirror of hidpp's `DeviceTransport` bitfield — one bool per protocol the
199/// device firmware exposes. The shape is dictated by HID++ feature 0x0003;
200/// a state machine doesn't fit since a single device can announce multiple
201/// transports simultaneously.
202#[allow(
203 clippy::struct_excessive_bools,
204 reason = "bitfield mirroring HID++ DeviceInformation; transports are independent flags"
205)]
206#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize)]
207pub struct DeviceTransports {
208 pub usb: bool,
209 pub equad: bool,
210 pub btle: bool,
211 pub bluetooth: bool,
212}
213
214#[derive(Debug, Clone, Serialize, Deserialize)]
215pub struct PairedDevice {
216 /// Receiver-assigned slot (1..=6 for Bolt).
217 pub slot: u8,
218 pub codename: Option<String>,
219 /// Wireless product ID. `None` for offline / unreachable devices on hidpp 0.2.
220 pub wpid: Option<u16>,
221 pub kind: DeviceKind,
222 pub online: bool,
223 pub battery: Option<BatteryInfo>,
224 /// Output of HID++ feature 0x0003 — populated for online devices that
225 /// expose the feature. Drives asset-registry lookups in the GUI.
226 pub model_info: Option<DeviceModelInfo>,
227 /// Configuration capabilities derived from the device's HID++ feature
228 /// table. `None` for devices we couldn't probe (offline / unreachable);
229 /// the GUI then falls back to [`Capabilities::presumed_from_kind`].
230 pub capabilities: Option<Capabilities>,
231}
232
233#[derive(Debug, Clone, Serialize, Deserialize)]
234pub struct DeviceInventory {
235 pub receiver: ReceiverInfo,
236 pub paired: Vec<PairedDevice>,
237}
238
239#[cfg(test)]
240mod tests {
241 use super::DeviceKind;
242
243 #[test]
244 fn registry_type_is_case_folded() {
245 // The registry ships both `"mouse"` and `"MOUSE"`; both must resolve so
246 // the asset cross-check can't silently miss a depot.
247 assert_eq!(DeviceKind::from_registry_type("mouse"), DeviceKind::Mouse);
248 assert_eq!(DeviceKind::from_registry_type("MOUSE"), DeviceKind::Mouse);
249 assert_eq!(
250 DeviceKind::from_registry_type(" Keyboard "),
251 DeviceKind::Keyboard
252 );
253 }
254
255 #[test]
256 fn unknown_registry_type_defers_to_the_caller() {
257 // Unmodelled / empty → Unknown, i.e. "no asset opinion".
258 assert_eq!(
259 DeviceKind::from_registry_type("webcam"),
260 DeviceKind::Unknown
261 );
262 assert_eq!(DeviceKind::from_registry_type(""), DeviceKind::Unknown);
263 }
264
265 #[test]
266 fn capabilities_track_the_driving_feature_ids() {
267 use super::Capabilities;
268 // A typical MX mouse: ReprogControls (0x1b04) + ExtendedAdjustableDpi
269 // (0x2202), no lighting.
270 let mouse = Capabilities::from_feature_ids(&[0x0003, 0x1b04, 0x2202, 0x2110]);
271 assert_eq!(
272 mouse,
273 Capabilities {
274 buttons: true,
275 pointer: true,
276 lighting: false,
277 }
278 );
279 // A wired G-series keyboard: PerKeyLighting (0x8080), no DPI/buttons.
280 let keyboard = Capabilities::from_feature_ids(&[0x0001, 0x8080]);
281 assert_eq!(
282 keyboard,
283 Capabilities {
284 buttons: false,
285 pointer: false,
286 lighting: true,
287 }
288 );
289 // No driving features → nothing offered.
290 assert_eq!(
291 Capabilities::from_feature_ids(&[0x0000, 0x0003]),
292 Capabilities::default()
293 );
294 }
295
296 #[test]
297 fn presumed_capabilities_keep_an_unprobed_mouse_configurable() {
298 use super::Capabilities;
299 let mouse = Capabilities::presumed_from_kind(DeviceKind::Mouse);
300 assert!(mouse.buttons && mouse.pointer && !mouse.lighting);
301 assert!(Capabilities::presumed_from_kind(DeviceKind::Keyboard).lighting);
302 // An unidentified device presumes nothing — it must be measured.
303 assert_eq!(
304 Capabilities::presumed_from_kind(DeviceKind::Unknown),
305 Capabilities::default()
306 );
307 }
308}