openlogi-hid 0.7.0

HID++ device discovery for OpenLogi, wrapping the hidpp crate over async-hid.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
//! Wireless device pairing for Logi Bolt and Unifying receivers.
//!
//! The published `hidpp 0.2` can only *read* existing pairings, and its
//! `BoltReceiver` is closed to extension. So OpenLogi drives the receiver's
//! HID++ 1.0 registers directly over the public [`HidppChannel`] primitives,
//! the same way [`crate::write`] and [`crate::gesture`] bypass the crate's
//! higher-level abstractions.
//!
//! The register layout and notification framing below are reverse engineered
//! from Solaar (the authoritative open-source reference) and cross-checked
//! against `hidpp 0.2`'s own `0x41` device-connection parser. Two families,
//! two flows:
//!
//! - **Bolt** (`046d:c548`): open *discovery* → the receiver streams nearby
//!   unpaired devices → pick one → pair by its BTLE address → the device
//!   shows a *passkey* the user types (keyboard) or clicks (pointer) →
//!   success carries the assigned slot.
//! - **Unifying** (`046d:c52b`, `046d:c532`): open a pairing *lock*; the next
//!   powered-on unpaired device in range links on its own. No discovery list,
//!   no passkey.
//!
//! Drive a session with [`run_pairing`]: it streams [`PairingEvent`]s out and
//! takes [`PairingCommand`]s in (the Bolt device pick / cancel). [`unpair`]
//! removes a slot; [`list_pairing_receivers`] reports what's connectable.

use std::{collections::HashMap, sync::Arc};

use hidpp::{
    channel::{HidppChannel, HidppMessage},
    receiver::{self, Receiver},
};
use tokio::sync::mpsc;
use tracing::{debug, trace};

pub use hidpp::receiver::bolt::DeviceKind as BoltDeviceKind;
// Click / PasskeyMethod / ReceiverSelector / PairingError are pure data with
// no HID++/async-hid I/O, so they live in `openlogi_core::hid::pairing`;
// re-exported here unchanged so this module's own API surface doesn't churn.
pub use openlogi_core::hid::pairing::{Click, PairingError, PasskeyMethod, ReceiverSelector};

use crate::transport::{enumerate_hidpp_devices, open_hidpp_channel};

mod notification;
mod registers;

use notification::{Notification, decode, parse_notification, subscribe};
use registers::{
    BOLT_DISCOVERY, BOLT_PAIRING, NOTIFICATION_FLAGS, NOTIFICATIONS, UNIFYING_PAIRING,
    write_long_register, write_register,
};

/// HID++ device index addressing the receiver itself (not a paired device).
const RECEIVER_INDEX: u8 = 0xff;

/// Receiver pairing family. Each uses a different register flow.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum ReceiverFamily {
    /// Logi Bolt receiver.
    Bolt,
    /// Logitech Unifying receiver.
    Unifying,
}

#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum PairingPhase {
    BoltDiscovery,
    BoltPairing,
    UnifyingPairing,
}

impl From<ReceiverFamily> for PairingPhase {
    fn from(family: ReceiverFamily) -> Self {
        match family {
            ReceiverFamily::Bolt => Self::BoltDiscovery,
            ReceiverFamily::Unifying => Self::UnifyingPairing,
        }
    }
}

fn family_for(product_id: u16) -> Option<ReceiverFamily> {
    if crate::BOLT_PIDS.contains(&product_id) {
        Some(ReceiverFamily::Bolt)
    } else if crate::speaks_unifying_protocol(product_id) {
        // Unifying proper plus protocol-compatible Lightspeed receivers.
        Some(ReceiverFamily::Unifying)
    } else {
        None
    }
}

/// A pairing-capable receiver currently connected to the host.
#[derive(Clone, Debug)]
pub struct PairingReceiver {
    /// Bolt unique ID, when readable. `None` for Unifying (no read path yet).
    pub uid: Option<String>,
    /// Receiver protocol family.
    pub family: ReceiverFamily,
    /// USB product ID of the receiver.
    pub product_id: u16,
}

/// A nearby unpaired device surfaced by Bolt discovery.
#[derive(Clone, Debug)]
pub struct DiscoveredDevice {
    /// 6-byte BTLE address used to pair.
    pub address: [u8; 6],
    /// Authentication-method bitfield (bit 0 = passkey typed on keyboard).
    pub authentication: u8,
    /// Device class reported by the receiver discovery notification.
    pub kind: BoltDeviceKind,
    /// Human-readable name advertised by the discovered device.
    pub name: String,
}

impl DiscoveredDevice {
    /// Whether authentication is by typing a passkey on a keyboard (vs. a
    /// pointer click sequence).
    #[must_use]
    pub fn passkey_on_keyboard(&self) -> bool {
        self.authentication & 0x01 != 0
    }

    /// Pairing entropy: keyboards use 20 bits, everything else 10.
    fn entropy(&self) -> u8 {
        if self.kind == BoltDeviceKind::Keyboard {
            20
        } else {
            10
        }
    }
}

/// Renders a Bolt passkey value as a 10-bit MSB-first left/right click sequence.
fn passkey_to_clicks(value: u32) -> Vec<Click> {
    (0..10)
        .rev()
        .map(|bit| {
            if value & (1 << bit) != 0 {
                Click::Right
            } else {
                Click::Left
            }
        })
        .collect()
}

/// Events streamed out of a pairing session.
#[derive(Clone, Debug)]
pub enum PairingEvent {
    /// Discovery (Bolt) or the pairing lock (Unifying) is now open.
    Searching,
    /// Bolt only: a nearby unpaired device was discovered.
    DeviceFound(DiscoveredDevice),
    /// Bolt only: the device asks the user to enter a passkey to authenticate.
    Passkey(PasskeyMethod),
    /// A device was paired and assigned a receiver slot.
    Paired {
        /// Assigned pairing slot.
        slot: u8,
    },
    /// The flow ended without pairing a device.
    Failed(PairingError),
}

/// Commands fed into a pairing session.
#[derive(Clone, Debug)]
pub enum PairingCommand {
    /// Bolt: pair with a previously discovered device.
    Pair(DiscoveredDevice),
    /// Abort the in-progress flow.
    Cancel,
}

/// Converts an `async_hid` transport error into [`PairingError`].
///
/// A plain function rather than a `From` impl: with `PairingError` defined
/// in `openlogi-core`, `impl From<async_hid::HidError> for PairingError`
/// here would implement a foreign trait for a foreign type and violate the
/// orphan rule.
fn classify_hid_error(error: &async_hid::HidError) -> PairingError {
    PairingError::Hid(error.to_string())
}

/// Lists supported pairing-capable receivers connected to the host.
pub async fn list_pairing_receivers() -> Result<Vec<PairingReceiver>, PairingError> {
    let mut out = Vec::new();
    for dev in enumerate_hidpp_devices()
        .await
        .map_err(|e| classify_hid_error(&e))?
    {
        let Some((_, channel)) = open_hidpp_channel(dev)
            .await
            .map_err(|e| classify_hid_error(&e))?
        else {
            continue;
        };
        let Some(family) = family_for(channel.product_id) else {
            continue;
        };
        let uid = match family {
            ReceiverFamily::Bolt => read_bolt_uid(&channel).await,
            ReceiverFamily::Unifying => None,
        };
        out.push(PairingReceiver {
            uid,
            family,
            product_id: channel.product_id,
        });
    }
    Ok(out)
}

/// Reads a Bolt receiver's unique ID via the crate's `BoltReceiver`.
async fn read_bolt_uid(channel: &Arc<HidppChannel>) -> Option<String> {
    let Some(Receiver::Bolt(bolt)) = receiver::detect(Arc::clone(channel)) else {
        return None;
    };
    bolt.get_unique_id().await.ok()
}

/// Opens the channel for the receiver named by `target`.
async fn open_receiver(
    target: &ReceiverSelector,
) -> Result<(Arc<HidppChannel>, ReceiverFamily), PairingError> {
    for dev in enumerate_hidpp_devices()
        .await
        .map_err(|e| classify_hid_error(&e))?
    {
        let Some((_, channel)) = open_hidpp_channel(dev)
            .await
            .map_err(|e| classify_hid_error(&e))?
        else {
            continue;
        };
        let Some(family) = family_for(channel.product_id) else {
            continue;
        };
        match target {
            ReceiverSelector::First => return Ok((channel, family)),
            ReceiverSelector::BoltUid(want) => {
                if family == ReceiverFamily::Bolt
                    && read_bolt_uid(&channel)
                        .await
                        .is_some_and(|uid| uid.eq_ignore_ascii_case(want))
                {
                    return Ok((channel, family));
                }
            }
        }
    }
    Err(PairingError::ReceiverNotFound)
}

/// Overall guard so a wedged receiver can't hang the session forever.
const SESSION_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(90);
/// Discovery / lock window opened on the receiver, in seconds.
const DISCOVERY_TIMEOUT: u8 = 30;

/// Runs a pairing session against `target`, streaming [`PairingEvent`]s to
/// `events` and consuming [`PairingCommand`]s from `commands`. Returns when the
/// flow finishes (paired, failed, cancelled, or timed out).
///
/// The caller owns the orchestration: spawn this on a runtime, hold the command
/// sender to forward the user's device pick / cancel, and read events to drive
/// the UI.
pub async fn run_pairing(
    target: ReceiverSelector,
    mut commands: mpsc::UnboundedReceiver<PairingCommand>,
    events: mpsc::UnboundedSender<PairingEvent>,
) -> Result<(), PairingError> {
    let (channel, family) = match open_receiver(&target).await {
        Ok(receiver) => receiver,
        Err(e) => {
            let _ = events.send(PairingEvent::Failed(e.clone()));
            return Err(e);
        }
    };
    let (listener, mut notifications) = subscribe(&channel);

    let result = run_session(&channel, family, &mut commands, &mut notifications, &events).await;

    drop(listener);
    // Best-effort restore: clear notification flags we set.
    let _ = channel
        .write_register(RECEIVER_INDEX, NOTIFICATIONS, [0, 0, 0])
        .await;

    if let Err(ref e) = result {
        let _ = events.send(PairingEvent::Failed(e.clone()));
    }
    result
}

/// Runs the core flow and phase-correct cancellation on every unsuccessful exit.
async fn run_session(
    channel: &HidppChannel,
    family: ReceiverFamily,
    commands: &mut mpsc::UnboundedReceiver<PairingCommand>,
    notifications: &mut mpsc::UnboundedReceiver<HidppMessage>,
    events: &mpsc::UnboundedSender<PairingEvent>,
) -> Result<(), PairingError> {
    let mut phase = PairingPhase::from(family);
    let result = drive(channel, family, &mut phase, commands, notifications, events).await;
    if result.is_err() {
        cancel(channel, phase).await;
    }
    result
}

/// Core session loop.
async fn drive(
    channel: &HidppChannel,
    family: ReceiverFamily,
    phase: &mut PairingPhase,
    commands: &mut mpsc::UnboundedReceiver<PairingCommand>,
    notifications: &mut mpsc::UnboundedReceiver<HidppMessage>,
    events: &mpsc::UnboundedSender<PairingEvent>,
) -> Result<(), PairingError> {
    write_register(channel, NOTIFICATIONS, NOTIFICATION_FLAGS).await?;

    match family {
        ReceiverFamily::Bolt => {
            write_register(channel, BOLT_DISCOVERY, [DISCOVERY_TIMEOUT, 0x01, 0x00]).await?;
        }
        ReceiverFamily::Unifying => {
            write_register(channel, UNIFYING_PAIRING, [0x01, 0x00, DISCOVERY_TIMEOUT]).await?;
        }
    }
    let _ = events.send(PairingEvent::Searching);

    // Partial Bolt discovery frames, keyed by discovery counter.
    let mut partial: HashMap<u16, PartialDevice> = HashMap::new();
    // Auth byte of the device the user chose to pair, for passkey rendering.
    let mut pairing_auth: Option<u8> = None;
    let deadline = tokio::time::sleep(SESSION_TIMEOUT);
    tokio::pin!(deadline);

    loop {
        tokio::select! {
            () = &mut deadline => return Err(PairingError::Timeout),

            cmd = commands.recv() => match cmd {
                Some(PairingCommand::Pair(device)) => {
                    pairing_auth = Some(device.authentication);
                    if *phase == PairingPhase::BoltDiscovery {
                        *phase = PairingPhase::BoltPairing;
                    }
                    pair_bolt_device(channel, &device).await?;
                }
                Some(PairingCommand::Cancel) | None => {
                    return Err(PairingError::Cancelled);
                }
            },

            msg = notifications.recv() => {
                let Some(msg) = msg else {
                    return Err(PairingError::Hid("receiver channel closed".into()));
                };
                let (device_index, sub_id, payload) = decode(&msg);
                // Reverse-engineered wire format — log every notification so a
                // mis-parse can be diagnosed against real hardware.
                trace!(sub_id = format_args!("{sub_id:#04x}"), ?payload, "pairing notification");
                let Some(note) = parse_notification(sub_id, device_index, payload) else {
                    continue;
                };
                match note {
                    Notification::DiscoveryInfo { counter, kind, address, authentication } => {
                        let entry = partial.entry(counter).or_default();
                        entry.kind = Some(kind);
                        entry.address = Some(address);
                        entry.authentication = Some(authentication);
                        if let Some(device) = entry.build() {
                            let _ = events.send(PairingEvent::DeviceFound(device));
                        }
                    }
                    Notification::DiscoveryName { counter, name } => {
                        let entry = partial.entry(counter).or_default();
                        entry.name = Some(name);
                        if let Some(device) = entry.build() {
                            let _ = events.send(PairingEvent::DeviceFound(device));
                        }
                    }
                    Notification::Passkey { digits, value } => {
                        let method = match pairing_auth {
                            Some(auth) if auth & 0x01 != 0 => PasskeyMethod::Keyboard(digits),
                            _ => PasskeyMethod::Pointer {
                                clicks: passkey_to_clicks(value),
                                passkey: digits,
                            },
                        };
                        let _ = events.send(PairingEvent::Passkey(method));
                    }
                    Notification::MalformedPasskey => {
                        return Err(PairingError::MalformedNotification("passkey digits"));
                    }
                    Notification::PairingSucceeded { slot } => {
                        let _ = events.send(PairingEvent::Paired { slot });
                        return Ok(());
                    }
                    Notification::PairingError(code) => return Err(PairingError::Device(code)),
                    Notification::Connected { slot, established } if family == ReceiverFamily::Unifying => {
                        if established {
                            let _ = events.send(PairingEvent::Paired { slot });
                            return Ok(());
                        }
                    }
                    Notification::Connected { .. } => {}
                    Notification::UnifyingLock { open, error } => {
                        if error != 0 {
                            return Err(PairingError::Device(error));
                        }
                        if !open {
                            // Lock closed without a connection notification: nothing paired.
                            return Err(PairingError::Timeout);
                        }
                    }
                }
            }
        }
    }
}

/// Accumulates the two Bolt discovery frames for one device.
#[derive(Default)]
struct PartialDevice {
    kind: Option<u8>,
    address: Option<[u8; 6]>,
    authentication: Option<u8>,
    name: Option<String>,
    emitted: bool,
}

impl PartialDevice {
    /// Builds a [`DiscoveredDevice`] once both frames have arrived, exactly once.
    fn build(&mut self) -> Option<DiscoveredDevice> {
        if self.emitted {
            return None;
        }
        let (kind, address, authentication, name) = (
            self.kind?,
            self.address?,
            self.authentication?,
            self.name.clone()?,
        );
        self.emitted = true;
        Some(DiscoveredDevice {
            address,
            authentication,
            kind: BoltDeviceKind::from(kind & 0x0f),
            name,
        })
    }
}

/// Sends the Bolt pair command (action `0x01`, auto slot) for `device`.
async fn pair_bolt_device(
    channel: &HidppChannel,
    device: &DiscoveredDevice,
) -> Result<(), PairingError> {
    let mut payload = [0u8; 16];
    payload[0] = 0x01; // action: pair
    payload[1] = 0x00; // slot: auto-assign
    payload[2..8].copy_from_slice(&device.address);
    payload[8] = device.authentication;
    payload[9] = device.entropy();
    write_long_register(channel, BOLT_PAIRING, payload).await
}

/// Best-effort cancel of an in-progress flow.
async fn cancel(channel: &HidppChannel, phase: PairingPhase) {
    let res = match phase {
        PairingPhase::BoltDiscovery => {
            write_register(channel, BOLT_DISCOVERY, [DISCOVERY_TIMEOUT, 0x02, 0x00]).await
        }
        PairingPhase::BoltPairing => {
            let mut payload = [0u8; 16];
            payload[0] = 0x02;
            write_long_register(channel, BOLT_PAIRING, payload).await
        }
        PairingPhase::UnifyingPairing => {
            write_register(channel, UNIFYING_PAIRING, [0x02, 0x00, 0x00]).await
        }
    };
    if let Err(e) = res {
        debug!(?phase, ?e, "cancel write failed");
    }
}

/// Removes the device on `slot` from the receiver named by `target`.
pub async fn unpair(target: ReceiverSelector, slot: u8) -> Result<(), PairingError> {
    let (channel, family) = open_receiver(&target).await?;
    match family {
        ReceiverFamily::Bolt => {
            let mut payload = [0u8; 16];
            payload[0] = 0x03; // action: unpair
            payload[1] = slot;
            write_long_register(&channel, BOLT_PAIRING, payload).await
        }
        ReceiverFamily::Unifying => {
            write_register(&channel, UNIFYING_PAIRING, [0x03, slot, 0x00]).await
        }
    }
}

#[cfg(test)]
mod tests;