Skip to main content

openlogi_core/hid/
route.rs

1//! How to reach a controllable HID++ device — addressing data only, no I/O.
2//!
3//! Two addressing modes:
4//!
5//! - [`DeviceRoute::Bolt`] — a device paired to a Logi Bolt receiver, reached
6//!   through the receiver channel at a pairing slot.
7//! - [`DeviceRoute::Direct`] — a device attached straight to the host over a
8//!   USB cable or Bluetooth, reached on its own channel at the HID++
9//!   self-index [`DIRECT_DEVICE_INDEX`].
10//!
11//! Opening the channel a route names is `openlogi_hid::channel::route::open_route_channel`
12//! — the one place both the write path and the capture session resolve a
13//! route to an open channel, so the Bolt-vs-direct branch lives in exactly
14//! one place.
15
16use std::fmt;
17
18use serde::{Deserialize, Serialize};
19
20use crate::device::DeviceInventory;
21
22/// HID++ device index that addresses a directly-attached device's own
23/// features (USB-cable or Bluetooth, no receiver indirection).
24pub const DIRECT_DEVICE_INDEX: u8 = 0xff;
25
26/// Logitech's USB/Bluetooth vendor ID. `u16` because that is the width of the
27/// field itself; readers whose API hands back a wider integer widen at the
28/// comparison.
29pub const LOGITECH_VENDOR_ID: u16 = 0x046d;
30
31/// How to reach a controllable HID++ device.
32///
33/// Crosses the agent↔GUI IPC (every per-device RPC takes one), so variant and
34/// field order are wire format — changes require a `PROTOCOL_VERSION` bump
35/// (guarded by `openlogi-ipc/tests/wire_format.rs`).
36#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
37pub enum DeviceRoute {
38    /// Paired to a Logi Bolt receiver. `receiver_uid` disambiguates multiple
39    /// plugged-in receivers; `slot` is the device's pairing slot (1..=6).
40    Bolt {
41        /// Receiver unique ID used to select the physical Bolt receiver.
42        receiver_uid: String,
43        /// Pairing slot of the target device on that receiver.
44        slot: u8,
45    },
46    /// Paired to a Logi Unifying receiver. Same addressing structure as Bolt
47    /// (receiver channel + pairing slot) but the receiver speaks HID++ 1.0.
48    Unifying {
49        /// Receiver unique ID used to select the physical Unifying receiver.
50        receiver_uid: String,
51        /// Pairing slot of the target device on that receiver.
52        slot: u8,
53    },
54    /// Attached straight to the host over USB cable or Bluetooth, addressed at
55    /// the HID++ self-index. Re-found by matching the HID node's vendor/product
56    /// id — two identical mice on one host are indistinguishable here, so the
57    /// first match wins (acceptable for v0).
58    Direct {
59        /// USB/HID vendor ID of the direct device.
60        vendor_id: u16,
61        /// USB/HID product ID of the direct device.
62        product_id: u16,
63    },
64    /// Standalone raw-HID device, such as a Litra light. The identity is an
65    /// opaque transport-generated value used to disambiguate duplicate HID
66    /// nodes; this route must never be passed to HID++ channel code.
67    RawHid {
68        /// HID vendor ID.
69        vendor_id: u16,
70        /// HID product ID.
71        product_id: u16,
72        /// HID usage page.
73        usage_page: u16,
74        /// HID usage ID.
75        usage_id: u16,
76        /// Stable/opaque device identity selected during enumeration.
77        identity: String,
78    },
79}
80
81/// USB product IDs that identify Logi Bolt receivers.
82pub const BOLT_PIDS: &[u16] = &[0xc548];
83
84/// USB product IDs that identify Logi Unifying receivers. Used by callers that
85/// need to construct the correct [`DeviceRoute`] variant from a raw inventory.
86///
87/// `0xc537` is the Nano receiver bundled with the G602. It answers the same
88/// HID++ 1.0 enumeration and pairing-information registers as Unifying, so it
89/// routes as [`DeviceRoute::Unifying`].
90pub const UNIFYING_PIDS: &[u16] = &[0xc52b, 0xc532, 0xc537];
91
92/// USB product IDs that identify Logitech Lightspeed receivers — the
93/// receivers bundled with G-series wireless devices. `0xc539` ships with the
94/// G502 LIGHTSPEED and the G Pro Wireless — its USB product string is
95/// literally `LIGHTSPEED Receiver`; `0xc53f` is the nano receiver of wireless
96/// mice such as the G305; `0xc547` ships with newer G-series devices such as
97/// the G915 keyboard and the G502 X LIGHTSPEED.
98/// They speak the same HID++ 1.0 receiver register protocol as Unifying, so
99/// they are enumerated, routed, and paired through the Unifying code path;
100/// only the user-facing receiver name (see [`receiver_display_name`]) differs.
101pub const LIGHTSPEED_PIDS: &[u16] = &[0xc539, 0xc53f, 0xc547];
102
103/// Whether `product_id` is a receiver that speaks the Unifying HID++ 1.0
104/// register protocol — a Unifying receiver proper, or a protocol-compatible
105/// Lightspeed receiver. Such receivers are addressed with
106/// [`DeviceRoute::Unifying`].
107#[must_use]
108pub fn speaks_unifying_protocol(product_id: u16) -> bool {
109    UNIFYING_PIDS.contains(&product_id) || LIGHTSPEED_PIDS.contains(&product_id)
110}
111
112/// Whether `product_id` is a known Logitech receiver dongle of any family
113/// (Bolt, Unifying, or Lightspeed).
114#[must_use]
115pub fn is_receiver_pid(product_id: u16) -> bool {
116    BOLT_PIDS.contains(&product_id) || speaks_unifying_protocol(product_id)
117}
118
119/// Human-readable name for a receiver identified by `product_id`, used to label
120/// it in the inventory. Lightspeed receivers share the Unifying protocol path
121/// but are surfaced under their own name.
122#[must_use]
123pub fn receiver_display_name(product_id: u16) -> &'static str {
124    if LIGHTSPEED_PIDS.contains(&product_id) {
125        "Lightspeed Receiver"
126    } else {
127        "Unifying Receiver"
128    }
129}
130
131impl DeviceRoute {
132    /// Whether two receiver routes use the same physical HID transport.
133    /// Direct routes cannot prove identity because they carry only VID/PID.
134    #[must_use]
135    pub fn shares_transport(&self, other: &Self) -> bool {
136        match (self, other) {
137            (
138                Self::Bolt {
139                    receiver_uid: left, ..
140                },
141                Self::Bolt {
142                    receiver_uid: right,
143                    ..
144                },
145            )
146            | (
147                Self::Unifying {
148                    receiver_uid: left, ..
149                },
150                Self::Unifying {
151                    receiver_uid: right,
152                    ..
153                },
154            ) => left.eq_ignore_ascii_case(right),
155            _ => false,
156        }
157    }
158
159    /// The HID++ device index features are addressed at for this route: the
160    /// pairing slot for a Bolt device, the self-index for a direct one.
161    #[must_use]
162    pub fn device_index(&self) -> u8 {
163        match self {
164            Self::Bolt { slot, .. } | Self::Unifying { slot, .. } => *slot,
165            Self::Direct { .. } | Self::RawHid { .. } => DIRECT_DEVICE_INDEX,
166        }
167    }
168
169    /// Build the route that reaches a paired device from a receiver inventory.
170    ///
171    /// Picks [`DeviceRoute::Unifying`] or [`DeviceRoute::Bolt`] based on the
172    /// receiver's product ID via [`speaks_unifying_protocol`] (Unifying proper
173    /// plus protocol-compatible Lightspeed receivers). Any receiver that does
174    /// not speak the Unifying protocol — including future Bolt variants whose
175    /// PID isn't yet in `BOLT_PIDS` — defaults to [`DeviceRoute::Bolt`] so
176    /// writes keep working rather than silently dropping.
177    /// [`DeviceRoute::Direct`] is used for directly-attached devices
178    /// (slot == [`DIRECT_DEVICE_INDEX`] with no receiver UID). Returns `None`
179    /// when the receiver UID is unknown (writes are skipped, not mis-routed).
180    #[must_use]
181    pub fn device_route_for(inv: &DeviceInventory, slot: u8) -> Option<Self> {
182        match &inv.receiver.unique_id {
183            Some(uid) if speaks_unifying_protocol(inv.receiver.product_id) => {
184                Some(Self::Unifying {
185                    receiver_uid: uid.clone(),
186                    slot,
187                })
188            }
189            Some(uid) => {
190                // Default to Bolt for any receiver that does not speak the
191                // Unifying protocol. This covers both known Bolt PIDs
192                // (BOLT_PIDS) and any future Bolt-compatible receiver with a new
193                // PID — returning None would silently drop writes for such
194                // receivers.
195                if !BOLT_PIDS.contains(&inv.receiver.product_id) {
196                    tracing::debug!(
197                        pid = format_args!("{:04x}", inv.receiver.product_id),
198                        "unknown receiver PID — routing as Bolt"
199                    );
200                }
201                Some(Self::Bolt {
202                    receiver_uid: uid.clone(),
203                    slot,
204                })
205            }
206            None if slot == DIRECT_DEVICE_INDEX => Some(Self::Direct {
207                vendor_id: inv.receiver.vendor_id,
208                product_id: inv.receiver.product_id,
209            }),
210            None => None,
211        }
212    }
213}
214
215impl fmt::Display for DeviceRoute {
216    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
217        match self {
218            Self::Bolt { receiver_uid, slot } | Self::Unifying { receiver_uid, slot } => {
219                write!(f, "slot {slot} on receiver {receiver_uid}")
220            }
221            Self::Direct {
222                vendor_id,
223                product_id,
224            } => write!(f, "direct {vendor_id:04x}:{product_id:04x}"),
225            Self::RawHid {
226                vendor_id,
227                product_id,
228                usage_page,
229                usage_id,
230                identity,
231            } => write!(
232                f,
233                "raw {vendor_id:04x}:{product_id:04x} usage {usage_page:04x}:{usage_id:04x} ({identity})"
234            ),
235        }
236    }
237}
238
239#[cfg(test)]
240mod tests {
241    use std::assert_matches;
242
243    use crate::device::{DeviceInventory, ReceiverInfo};
244
245    use super::{
246        DIRECT_DEVICE_INDEX, DeviceRoute, LIGHTSPEED_PIDS, UNIFYING_PIDS, receiver_display_name,
247    };
248
249    fn inv(product_id: u16, unique_id: Option<&str>) -> DeviceInventory {
250        DeviceInventory {
251            receiver: ReceiverInfo {
252                name: "test".into(),
253                vendor_id: 0x046d,
254                product_id,
255                unique_id: unique_id.map(str::to_string),
256            },
257            paired: vec![],
258        }
259    }
260
261    #[test]
262    fn device_route_for_unifying_pids_create_unifying_route() {
263        for &pid in UNIFYING_PIDS {
264            let route = DeviceRoute::device_route_for(&inv(pid, Some("A1B2")), 2);
265            assert!(
266                matches!(route, Some(DeviceRoute::Unifying { ref receiver_uid, slot: 2 }) if receiver_uid == "A1B2"),
267                "pid {pid:#06x} should produce Unifying route"
268            );
269        }
270    }
271
272    #[test]
273    fn device_route_for_lightspeed_pids_create_unifying_route() {
274        // Lightspeed nano receivers (e.g. the G305's) speak the Unifying
275        // protocol, so writes must be routed through DeviceRoute::Unifying —
276        // not defaulted to Bolt, which would address the pairing slot wrong.
277        for &pid in LIGHTSPEED_PIDS {
278            let route = DeviceRoute::device_route_for(&inv(pid, Some("A1B2")), 2);
279            assert!(
280                matches!(route, Some(DeviceRoute::Unifying { ref receiver_uid, slot: 2 }) if receiver_uid == "A1B2"),
281                "lightspeed pid {pid:#06x} should produce a Unifying route"
282            );
283        }
284    }
285
286    #[test]
287    fn lightspeed_receiver_has_its_own_display_name() {
288        // 0xc539 is the receiver bundled with the G502 LIGHTSPEED and the
289        // G Pro Wireless. It routes through the Unifying code path, but it is
290        // Lightspeed hardware and says so in its own USB product string, so it
291        // must not be surfaced as a Unifying receiver.
292        assert_eq!(receiver_display_name(0xc539), "Lightspeed Receiver");
293        assert_eq!(receiver_display_name(0xc53f), "Lightspeed Receiver");
294        assert_eq!(receiver_display_name(0xc547), "Lightspeed Receiver");
295        assert_eq!(receiver_display_name(0xc52b), "Unifying Receiver");
296        assert_eq!(receiver_display_name(0xc532), "Unifying Receiver");
297    }
298
299    #[test]
300    fn device_route_for_bolt_pid_creates_bolt_route() {
301        // 0xC548 is Bolt; anything not in UNIFYING_PIDS defaults to Bolt so
302        // future Bolt variants with unknown PIDs still work.
303        let route = DeviceRoute::device_route_for(&inv(0xc548, Some("UID")), 1);
304        assert_matches!(
305            route,
306            Some(DeviceRoute::Bolt { ref receiver_uid, slot: 1 }) if receiver_uid == "UID"
307        );
308    }
309
310    #[test]
311    fn device_route_for_direct_when_no_uid_and_direct_slot() {
312        let route = DeviceRoute::device_route_for(&inv(0xb025, None), DIRECT_DEVICE_INDEX);
313        assert_matches!(
314            route,
315            Some(DeviceRoute::Direct {
316                vendor_id: 0x046d,
317                product_id: 0xb025
318            })
319        );
320    }
321
322    #[test]
323    fn device_route_for_none_when_no_uid_and_non_direct_slot() {
324        let route = DeviceRoute::device_route_for(&inv(0xc52b, None), 1);
325        assert!(route.is_none());
326    }
327
328    #[test]
329    fn unifying_device_index_is_the_slot() {
330        let route = DeviceRoute::Unifying {
331            receiver_uid: "X".into(),
332            slot: 4,
333        };
334        assert_eq!(route.device_index(), 4);
335    }
336
337    #[test]
338    fn unifying_display_matches_bolt_format() {
339        let r = DeviceRoute::Unifying {
340            receiver_uid: "AABBCC".into(),
341            slot: 3,
342        };
343        assert_eq!(r.to_string(), "slot 3 on receiver AABBCC");
344    }
345}