openlogi-device 0.8.14

The contract between OpenLogi's HID++ layer and the HID stack beneath it.
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
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
//! 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::session::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, NotificationFlags, 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++/backend I/O, so they live in `openlogi_core::hid::pairing`; the
// pairing API names them through here.
pub use openlogi_core::hid::pairing::{Click, PairingError, PasskeyMethod, ReceiverSelector};

use openlogi_core::hid::DeviceRoute;

use crate::backend::{HidBackend, NodeId};
use crate::host_lock::{RECEIVER_REGISTER_TIMEOUT, ReceiverRegisterPhase, lock_receiver_registers};

mod notification;
mod registers;

use notification::{Notification, decode, parse_notification, subscribe};
use registers::{
    BOLT_DISCOVERY, BOLT_PAIRING, PAIRING_NOTIFICATIONS, UNIFYING_PAIRING, read_notification_flags,
    write_long_register, write_notification_flags, 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,
}

enum SessionState {
    BoltDiscovery(BoltDiscovery),
    BoltPairing(BoltPairing),
    /// Unifying: the receiver acknowledged the lock-open write but has not yet
    /// confirmed with a `0x4a` notification that the lock is open. The write
    /// ACK only says the receiver took the request.
    UnifyingOpening,
    /// Unifying: the receiver confirmed the pairing lock is open.
    UnifyingPairing,
}

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

impl SessionState {
    async fn open(&self, channel: &HidppChannel) -> Result<(), PairingError> {
        match self {
            Self::BoltDiscovery(_) => {
                write_register(channel, BOLT_DISCOVERY, [DISCOVERY_TIMEOUT, 0x01, 0x00]).await
            }
            Self::UnifyingOpening => {
                write_register(channel, UNIFYING_PAIRING, [0x01, 0x00, DISCOVERY_TIMEOUT]).await
            }
            Self::BoltPairing(_) | Self::UnifyingPairing => {
                unreachable!("a session starts in receiver-open state")
            }
        }
    }

    fn select_bolt_device(&mut self, device: &DiscoveredDevice) -> Result<(), PairingError> {
        match self {
            Self::BoltDiscovery(_) | Self::BoltPairing(_) => {
                *self = Self::BoltPairing(BoltPairing {
                    authentication: device.authentication,
                });
                Ok(())
            }
            Self::UnifyingOpening | Self::UnifyingPairing => Err(PairingError::UnsupportedCommand),
        }
    }

    /// Applies a Unifying `0x4a` lock-state notification. `Ok(true)` when it
    /// confirms the lock just opened, which starts the search.
    fn unifying_lock(&mut self, open: bool, error: u8) -> Result<bool, PairingError> {
        if error != 0 {
            return Err(PairingError::Device(error));
        }
        match (open, &*self) {
            (true, Self::UnifyingOpening) => {
                *self = Self::UnifyingPairing;
                Ok(true)
            }
            (true, _) => Ok(false),
            // Closed before it was ever reported open.
            (false, Self::UnifyingOpening) => Err(lock_not_opened()),
            // Lock closed without a connection notification: nothing paired.
            (false, _) => Err(PairingError::Timeout),
        }
    }
}

#[derive(Default)]
struct BoltDiscovery {
    partial: HashMap<u16, PartialDevice>,
}

struct BoltPairing {
    authentication: u8,
}

fn family_for(product_id: u16) -> Option<ReceiverFamily> {
    match crate::find_receiver(crate::LOGITECH_VENDOR_ID, product_id)?.protocol {
        crate::ReceiverProtocol::Bolt => Some(ReceiverFamily::Bolt),
        crate::ReceiverProtocol::Unifying => Some(ReceiverFamily::Unifying),
    }
}

/// 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,
}

/// Lists supported pairing-capable receivers connected to the host.
pub async fn list_pairing_receivers(
    backend: &dyn HidBackend,
) -> Result<Vec<PairingReceiver>, PairingError> {
    let mut out = Vec::new();
    for node in backend.enumerate_hidpp().await? {
        let Some(channel) = backend.open_hidpp(&node).await? else {
            continue;
        };
        let Some(family) = family_for(channel.product_id) else {
            continue;
        };
        let uid = match family {
            ReceiverFamily::Bolt => read_receiver_uid(&channel, &node.id).await,
            ReceiverFamily::Unifying => None,
        };
        out.push(PairingReceiver {
            uid,
            family,
            product_id: channel.product_id,
        });
    }
    Ok(out)
}

/// Reads a receiver's unique ID under its register phase. `None` when the
/// read fails — or when another OpenLogi process still holds the phase, which
/// is not read into.
async fn read_receiver_uid(channel: &Arc<HidppChannel>, node: &NodeId) -> Option<String> {
    let receiver = receiver::detect(Arc::clone(channel))?;
    let _registers = lock_receiver_registers(node, RECEIVER_REGISTER_TIMEOUT).await?;
    match receiver {
        Receiver::Bolt(bolt) => bolt.get_unique_id().await.ok(),
        Receiver::Unifying(unifying) => unifying.get_unique_id().await.ok(),
        // `Receiver` is non-exhaustive; a family this crate cannot pair has no
        // UID worth matching.
        _ => None,
    }
}

/// Which receiver an operation addresses.
enum ReceiverTarget<'a> {
    /// The receiver a pairing session was asked to open.
    Selector(&'a ReceiverSelector),
    /// The receiver a paired device's route names.
    Route {
        family: ReceiverFamily,
        uid: &'a str,
    },
}

/// An open receiver channel and the register phase a session runs under.
struct OpenReceiver {
    channel: Arc<HidppChannel>,
    family: ReceiverFamily,
    /// Held for the whole session: every register write in the flow — the
    /// notification flags, discovery, pairing — is receiver register I/O,
    /// and the flow waits on the user between them, so the phase is taken
    /// once up front rather than around each write. Inventory probes in
    /// every OpenLogi process defer to it meanwhile, replaying their last
    /// snapshot, and pick the new pairing up once it is released.
    _registers: ReceiverRegisterPhase,
}

/// Opens the channel for the receiver named by `target` and takes its
/// register phase.
async fn open_receiver(
    backend: &dyn HidBackend,
    target: &ReceiverTarget<'_>,
) -> Result<OpenReceiver, PairingError> {
    for node in backend.enumerate_hidpp().await? {
        let Some(channel) = backend.open_hidpp(&node).await? else {
            continue;
        };
        let Some(family) = family_for(channel.product_id) else {
            continue;
        };
        let (want_family, want_uid) = match target {
            ReceiverTarget::Selector(ReceiverSelector::First) => (None, None),
            ReceiverTarget::Selector(ReceiverSelector::BoltUid(uid)) => {
                (Some(ReceiverFamily::Bolt), Some(uid.as_str()))
            }
            ReceiverTarget::Route { family, uid } => (Some(*family), Some(*uid)),
        };
        if want_family.is_some_and(|want| want != family) {
            continue;
        }
        let matched = match want_uid {
            None => true,
            Some(want) => read_receiver_uid(&channel, &node.id)
                .await
                .is_some_and(|uid| uid.eq_ignore_ascii_case(want)),
        };
        if !matched {
            continue;
        }
        let Some(registers) = lock_receiver_registers(&node.id, RECEIVER_REGISTER_TIMEOUT).await
        else {
            return Err(PairingError::Register(
                "the receiver's registers are held by another OpenLogi process".to_string(),
            ));
        };
        return Ok(OpenReceiver {
            channel,
            family,
            _registers: registers,
        });
    }
    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;
/// How long a Unifying receiver has, after acknowledging the lock-open write,
/// to confirm with a `0x4a` notification that the lock is open. Solaar gives
/// up after about 1.5 s (three 500 ms checks of `lock_open`); this is a little
/// more lenient.
const LOCK_CONFIRMATION_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(2);

/// The error for a Unifying pairing lock that the receiver never confirmed
/// open, or reported closed while the session waited for it to open.
fn lock_not_opened() -> PairingError {
    PairingError::Register("the receiver did not open the pairing lock".to_owned())
}

/// 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(
    backend: &dyn HidBackend,
    target: ReceiverSelector,
    mut commands: mpsc::UnboundedReceiver<PairingCommand>,
    events: mpsc::UnboundedSender<PairingEvent>,
) -> Result<(), PairingError> {
    let receiver = match open_receiver(backend, &ReceiverTarget::Selector(&target)).await {
        Ok(receiver) => receiver,
        Err(e) => {
            let _ = events.send(PairingEvent::Failed(e.clone()));
            return Err(e);
        }
    };
    let OpenReceiver {
        channel, family, ..
    } = &receiver;
    let (listener, mut notifications) = subscribe(channel);

    let original = read_notification_flags(channel).await;
    let result = match &original {
        Ok(original) => {
            run_session(
                channel,
                *family,
                *original,
                &mut commands,
                &mut notifications,
                &events,
            )
            .await
        }
        Err(e) => Err(e.clone()),
    };

    drop(listener);
    // Best-effort restore of the flags found before the session: inventory
    // owns WIRELESS and other host software sets bits of its own, so pairing
    // hands back exactly what it read. A failed read wrote nothing.
    if let Ok(original) = original {
        let _ = write_notification_flags(channel, original).await;
    }
    // The register phase is released with the receiver, after that write.
    drop(receiver);

    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.
/// `notifications_found` is the receiver's flag word before the session; the
/// caller restores it.
async fn run_session(
    channel: &HidppChannel,
    family: ReceiverFamily,
    notifications_found: NotificationFlags,
    commands: &mut mpsc::UnboundedReceiver<PairingCommand>,
    notifications: &mut mpsc::UnboundedReceiver<HidppMessage>,
    events: &mpsc::UnboundedSender<PairingEvent>,
) -> Result<(), PairingError> {
    let mut state = SessionState::from(family);
    let result = drive(
        channel,
        &mut state,
        notifications_found,
        commands,
        notifications,
        events,
    )
    .await;
    if result.is_err() {
        cancel(channel, &state).await;
    }
    result
}

/// Core session loop.
async fn drive(
    channel: &HidppChannel,
    state: &mut SessionState,
    notifications_found: NotificationFlags,
    commands: &mut mpsc::UnboundedReceiver<PairingCommand>,
    notifications: &mut mpsc::UnboundedReceiver<HidppMessage>,
    events: &mpsc::UnboundedSender<PairingEvent>,
) -> Result<(), PairingError> {
    write_notification_flags(channel, notifications_found | PAIRING_NOTIFICATIONS).await?;
    state.open(channel).await?;
    // Bolt discovery is reported open once its write is acknowledged. A
    // Unifying lock is open only once the receiver says so with `0x4a`; the
    // listener was installed before the write, so a notification that beat
    // the ACK is already queued.
    if !matches!(state, SessionState::UnifyingOpening) {
        let _ = events.send(PairingEvent::Searching);
    }

    let deadline = tokio::time::sleep(SESSION_TIMEOUT);
    tokio::pin!(deadline);
    let lock_confirmation = tokio::time::sleep(LOCK_CONFIRMATION_TIMEOUT);
    tokio::pin!(lock_confirmation);

    loop {
        let awaiting_lock = matches!(state, SessionState::UnifyingOpening);
        tokio::select! {
            () = &mut deadline => return Err(PairingError::Timeout),
            () = &mut lock_confirmation, if awaiting_lock => return Err(lock_not_opened()),

            cmd = commands.recv() => match cmd {
                Some(PairingCommand::Pair(device)) => {
                    state.select_bolt_device(&device)?;
                    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;
                };
                // Discovery is phase-bound: a late DeviceFound would move the
                // event owner back from Pairing to Found after selection.
                match note {
                    Notification::DiscoveryInfo { counter, kind, address, authentication } => {
                        let SessionState::BoltDiscovery(discovery) = state else {
                            continue;
                        };
                        let entry = discovery.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 SessionState::BoltDiscovery(discovery) = state else {
                            continue;
                        };
                        let entry = discovery.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 state {
                            SessionState::BoltPairing(pairing)
                                if pairing.authentication & 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 matches!(state, SessionState::UnifyingPairing) => {
                        if established {
                            let _ = events.send(PairingEvent::Paired { slot });
                            return Ok(());
                        }
                    }
                    Notification::Connected { .. } => {}
                    Notification::UnifyingLock { open, error } => {
                        if state.unifying_lock(open, error)? {
                            let _ = events.send(PairingEvent::Searching);
                        }
                    }
                }
            }
        }
    }
}

/// 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, state: &SessionState) {
    let res = match state {
        SessionState::BoltDiscovery(_) => {
            write_register(channel, BOLT_DISCOVERY, [DISCOVERY_TIMEOUT, 0x02, 0x00]).await
        }
        SessionState::BoltPairing(_) => {
            let mut payload = [0u8; 16];
            payload[0] = 0x02;
            write_long_register(channel, BOLT_PAIRING, payload).await
        }
        // The lock may have opened without the notification arriving, so a
        // session still waiting for it closes the lock as well.
        SessionState::UnifyingOpening | SessionState::UnifyingPairing => {
            write_register(channel, UNIFYING_PAIRING, [0x02, 0x00, 0x00]).await
        }
    };
    if let Err(e) = res {
        let phase = match state {
            SessionState::BoltDiscovery(_) => "Bolt discovery",
            SessionState::BoltPairing(_) => "Bolt pairing",
            SessionState::UnifyingOpening | SessionState::UnifyingPairing => "Unifying pairing",
        };
        debug!(phase, ?e, "cancel write failed");
    }
}

/// Removes the device `route` reaches from the receiver it is paired to. The
/// slot is freed: the device reaches this host through that receiver again
/// only once it is paired again. A route that names no receiver slot has no
/// receiver to find.
pub async fn unpair(backend: &dyn HidBackend, route: &DeviceRoute) -> Result<(), PairingError> {
    let (family, uid, slot) = match route {
        DeviceRoute::Bolt { receiver_uid, slot } => (ReceiverFamily::Bolt, receiver_uid, *slot),
        DeviceRoute::Unifying { receiver_uid, slot } => {
            (ReceiverFamily::Unifying, receiver_uid, *slot)
        }
        DeviceRoute::Direct { .. } | DeviceRoute::RawHid { .. } => {
            return Err(PairingError::ReceiverNotFound);
        }
    };
    let receiver = open_receiver(backend, &ReceiverTarget::Route { family, uid }).await?;
    let channel = &receiver.channel;
    match receiver.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;