openlogi-hidpp 0.7.1

OpenLogi's hard fork of the `hidpp` crate (Logitech HID++ protocol).
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
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
//! The notifications a Bolt receiver broadcasts, and their decoding.
//!
//! The receiver reports device arrivals, discovery results, and pairing
//! progress as unsolicited HID++1.0 messages. Their layout is not publicly
//! documented — it comes from reading other implementations (primarily Solaar)
//! and from fuzzing registers — so every offset and mask here is pinned by a
//! test rather than by a specification.

use num_enum::{FromPrimitive, IntoPrimitive, TryFromPrimitive};

use crate::{protocol::v10, receiver::RECEIVER_DEVICE_INDEX};

/// The notification sub-ids this module decodes.
///
/// Modelling the sub-id as an enum rather than matching bare bytes makes the
/// dispatch below exhaustive: a new notification cannot be added here without
/// the compiler demanding a decode for it.
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, IntoPrimitive, TryFromPrimitive)]
#[repr(u8)]
enum Notification {
    /// A device connected to, or disconnected from, the receiver.
    DeviceConnection = 0x41,

    /// The receiver asks for a passkey to authenticate a device being paired.
    PairingPasskeyRequest = 0x4d,

    /// The user pressed a key while entering a pairing passkey.
    PairingPasskeyPressed = 0x4e,

    /// Details or the name of a device found while discovering.
    DeviceDiscovery = 0x4f,

    /// Device discovery was enabled or disabled.
    DeviceDiscoveryStatus = 0x53,

    /// A pairing attempt progressed, succeeded, or failed.
    PairingStatus = 0x54,
}

/// The two payload kinds a [`Notification::DeviceDiscovery`] report carries,
/// selected by `payload[2]`.
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, IntoPrimitive, TryFromPrimitive)]
#[repr(u8)]
enum DiscoveryPart {
    /// Address, kind, and product id of the discovered device.
    Details = 0,

    /// The discovered device's advertised name.
    Name = 1,
}

/// Decodes an unsolicited receiver message into the event it carries.
///
/// Returns `None` for a report this crate does not model, one addressed
/// elsewhere, or one whose payload does not parse — all of which the listener
/// drops.
///
/// Kept separate from the message listener in [`super::Receiver::new`] so the
/// wire layout is reachable from tests without a HID channel behind it.
pub(super) fn decode(msg: &v10::Message) -> Option<Event> {
    let header = msg.header();
    let payload = msg.extend_payload();

    let notification = Notification::try_from(header.sub_id).ok()?;

    // Every notification but a device connection is addressed to the receiver
    // itself. A connection notification instead carries the device's slot in
    // the header — the only place that index is reported.
    if notification != Notification::DeviceConnection
        && header.device_index != RECEIVER_DEVICE_INDEX
    {
        return None;
    }

    match notification {
        Notification::DeviceConnection => Some(Event::DeviceConnection(DeviceConnection {
            index: header.device_index,
            // Kind is identity-only; an unrecognised nibble folds to `Unknown`
            // instead of dropping the event, which would hide the device
            // entirely.
            kind: DeviceKind::from(payload[1] & 0x0f),
            encrypted: payload[1] & (1 << 5) != 0,
            online: payload[1] & (1 << 6) == 0,
            wpid: u16::from_le_bytes([payload[2], payload[3]]),
        })),

        Notification::DeviceDiscovery => match DiscoveryPart::try_from(payload[2]).ok()? {
            DiscoveryPart::Details => Some(Event::DeviceDiscoveryDeviceDetails {
                counter: discovery_counter(&payload),
                kind: DeviceKind::from(payload[4] & 0x0f),
                wpid: u16::from_le_bytes([payload[5], payload[6]]),
                address: address6(&payload, 7),
                authentication: payload[15],
            }),
            DiscoveryPart::Name => {
                let name = discovery_name(&payload)?;
                Some(Event::DeviceDiscoveryDeviceName {
                    counter: discovery_counter(&payload),
                    name: name.to_string(),
                })
            }
        },

        Notification::DeviceDiscoveryStatus => Some(Event::DeviceDiscoveryStatus {
            discovery_enabled: payload[0] == 0x00,
        }),

        Notification::PairingStatus => Some(Event::PairingStatus {
            device_address: address6(&payload, 2),
            // `payload[0]` carries some further status this crate does not
            // model. An unrecognised error code still means "pairing failed" —
            // dropping it would turn the failure into a session timeout, so
            // carry the raw code instead.
            pairing_error: (payload[1] != 0x00).then(|| PairingError::from(payload[1])),
            slot: (payload[8] != 0x00).then_some(payload[8]),
        }),

        Notification::PairingPasskeyRequest => Some(Event::PairingPasskeyRequest {
            device_address: address6(&payload, 7),
            passkey: passkey(&payload)?.to_string(),
        }),

        Notification::PairingPasskeyPressed => Some(Event::PairingPasskeyPressed {
            device_address: address6(&payload, 1),
            press_type: PairingPasskeyPressType::from(payload[0]),
        }),
    }
}

/// The little-endian counter that pairs a discovery details report with the
/// name report describing the same device.
fn discovery_counter(payload: &[u8; 17]) -> u16 {
    u16::from_le_bytes([payload[0], payload[1]])
}

/// Extracts 6 contiguous bytes starting at `start` from a receiver-event
/// payload into a BTLE device-address array.
///
/// Every call site above passes a compile-time-fixed `start` (1, 2, or 7)
/// comfortably within the fixed 17-byte payload, so this never panics in
/// practice.
fn address6(payload: &[u8; 17], start: usize) -> [u8; 6] {
    [
        payload[start],
        payload[start + 1],
        payload[start + 2],
        payload[start + 3],
        payload[start + 4],
        payload[start + 5],
    ]
}

/// Reads the name out of a device-discovery name notification.
///
/// `payload[3]` is the device-reported name length. The byte comes straight
/// off the radio, so it must never index past the report: a length that does
/// not fit the packet (or non-UTF-8 bytes) drops the event instead of
/// panicking the listener.
fn discovery_name(payload: &[u8; 17]) -> Option<&str> {
    let end = 4usize.checked_add(usize::from(payload[3]))?;
    str::from_utf8(payload.get(4..end)?).ok()
}

/// Reads the passkey out of a passkey-request notification.
///
/// The passkey occupies 6 bytes and is NUL-padded when it is shorter.
fn passkey(payload: &[u8; 17]) -> Option<&str> {
    let digits = &payload[1..=6];
    let len = digits.iter().position(|&b| b == 0).unwrap_or(digits.len());
    str::from_utf8(&digits[..len]).ok()
}

/// Represents an event emitted by the receiver.
///
/// You can listen to these events using [`super::Receiver::listen`]. Only
/// enabled notifications as indicated by
/// [`super::Receiver::get_notification_state`] are emitted.
#[derive(Clone, PartialEq, Eq, Hash, Debug)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[non_exhaustive]
pub enum Event {
    /// Is emitted whenever a device connects to or disconnects from the
    /// receiver, but only if
    /// [`NotificationState::wireless_notifications`](super::NotificationState::wireless_notifications)
    /// is enabled.
    ///
    /// Can be triggered for all paired devices using
    /// [`Receiver::trigger_device_arrival`](super::Receiver::trigger_device_arrival)
    /// to allow easy device enumeration.
    ///
    /// [`Receiver::collect_paired_devices`](super::Receiver::collect_paired_devices)
    /// implements a simple mechanism to collect all paired devices.
    DeviceConnection(DeviceConnection),

    /// Is emitted whenever the device discovery status changes.
    DeviceDiscoveryStatus {
        /// Whether discovery mode is enabled.
        discovery_enabled: bool,
    },

    /// Is emitted many times for every device discovered using
    /// [`Receiver::discover_devices`](super::Receiver::discover_devices).
    ///
    /// This event contains device details, including its address required to
    /// start pairing. The [`Event::DeviceDiscoveryDeviceName`] event will also
    /// be emitted and contains the device name.
    DeviceDiscoveryDeviceDetails {
        /// The incrementing event counter. This can be used to map
        /// [`Event::DeviceDiscoveryDeviceDetails`] and
        /// [`Event::DeviceDiscoveryDeviceName`] events.
        counter: u16,

        /// Device kind reported by discovery.
        kind: DeviceKind,

        /// Wireless product ID of the discovered device.
        wpid: u16,

        /// The address of the device required to pair it using
        /// [`Receiver::pair_device`](super::Receiver::pair_device).
        ///
        /// This can also be used as the unique device identifier when
        /// collecting discovered devices.
        address: [u8; 6],

        /// The authentication type(s) the device supports. Unfortunately, there
        /// is not much information about this value and whether it is a
        /// single value or a bitfield.
        authentication: u8,
    },

    /// Is emitted many times for every device discovered using
    /// [`Receiver::discover_devices`](super::Receiver::discover_devices).
    ///
    /// This event only contains the device name. Device details will be
    /// provided using the [`Event::DeviceDiscoveryDeviceDetails`] event.
    DeviceDiscoveryDeviceName {
        /// The incrementing event counter. This can be used to map
        /// [`Event::DeviceDiscoveryDeviceDetails`] and
        /// [`Event::DeviceDiscoveryDeviceName`] events.
        counter: u16,

        /// Discovered device name.
        name: String,
    },

    /// Is emitted whenever the status of a pairing process changes.
    PairingStatus {
        /// BTLE address of the device being paired.
        device_address: [u8; 6],

        /// Optional pairing error reported by the receiver.
        pairing_error: Option<PairingError>,

        /// The receiver slot the newly paired device was paired to. This can be
        /// used as the device index for subsequent operations.
        slot: Option<u8>,
    },

    /// Is emitted once the receiver requests a passkey to be entered on a
    /// device that should be paired to it.
    PairingPasskeyRequest {
        /// BTLE address of the device being paired.
        device_address: [u8; 6],

        /// The passkey the user has to enter in order to pair the device.
        ///
        /// Depending on the device and authentication type, this value has
        /// different implications.
        ///
        /// For mice, this value will be a valid 6-digit number. After parsing
        /// this into an integer, the (least significant) bits represent
        /// the sequence of mouse presses (`0` = left, `1` = right) the
        /// user has to perform, with an additional press of both mouse
        /// buttons simultaneously.
        ///
        /// The amount of bits significant to this equals to the `entropy`
        /// passed to [`Receiver::pair_device`](super::Receiver::pair_device).
        passkey: String,
    },

    /// Is emitted for every keypress a user performs while entering a pairing
    /// passkey.
    PairingPasskeyPressed {
        /// BTLE address of the device being paired.
        device_address: [u8; 6],

        /// The type of the keypress the user performed.
        ///
        /// Every passkey sequence starts with an event where this value is set
        /// to [`PairingPasskeyPressType::Initialization`]. Each time the user
        /// presses a key, an event with a press type of
        /// [`PairingPasskeyPressType::Keypress`] is emitted. Once the user
        /// submits their passkey, this value will be
        /// [`PairingPasskeyPressType::Submit`].
        press_type: PairingPasskeyPressType,
    },
}

/// Represents a device connected to a Bolt receiver.
///
/// This information is emitted by the [`Event::DeviceConnection`] event and can
/// be conveniently collected using
/// [`Receiver::collect_paired_devices`](super::Receiver::collect_paired_devices).
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[non_exhaustive]
pub struct DeviceConnection {
    /// Slot index (1-based) of the device.
    pub index: u8,

    /// Device kind reported by the receiver.
    pub kind: DeviceKind,

    /// Whether the link is encrypted.
    pub encrypted: bool,

    /// Whether the device is currently online.
    pub online: bool,

    /// Wireless product ID of the device.
    pub wpid: u16,
}

/// Represents the kind of a device paired to a Bolt receiver.
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, IntoPrimitive, FromPrimitive)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[non_exhaustive]
#[repr(u8)]
pub enum DeviceKind {
    /// Unknown device kind — also the fold target for values this crate
    /// does not model (kind is identity-only and must never drop an event).
    #[num_enum(default)]
    Unknown = 0x00,
    /// Keyboard device.
    Keyboard = 0x01,
    /// Mouse device.
    Mouse = 0x02,
    /// Numeric keypad device.
    Numpad = 0x03,
    /// Presenter device.
    Presenter = 0x04,
    /// Remote-control device.
    Remote = 0x07,
    /// Trackball device.
    Trackball = 0x08,
    /// Touchpad device.
    Touchpad = 0x09,
    /// Tablet device.
    Tablet = 0x0a,
    /// Gamepad device.
    Gamepad = 0x0b,
    /// Joystick device.
    Joystick = 0x0c,
    /// Headset device.
    Headset = 0x0d,
}

/// Represents an error during device pairing.
///
/// This is reported by the [`Event::PairingStatus`] event.
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, FromPrimitive, IntoPrimitive)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[non_exhaustive]
#[repr(u8)]
pub enum PairingError {
    /// Device timed out during pairing.
    DeviceTimeout = 0x01,
    /// Pairing failed.
    Failed = 0x02,
    /// An error code this crate does not model; carries the raw byte.
    #[num_enum(catch_all)]
    Other(u8),
}

/// Represents the type of a single passkey press.
///
/// This is reported by the [`Event::PairingPasskeyPressed`] event, which also
/// includes some further information about the context of these values.
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, FromPrimitive, IntoPrimitive)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[non_exhaustive]
#[repr(u8)]
pub enum PairingPasskeyPressType {
    /// Passkey entry has started.
    Initialization = 0x00,
    /// A passkey keypress was entered.
    Keypress = 0x01,
    /// Passkey entry was submitted.
    Submit = 0x04,
    /// A press type this crate does not model; carries the raw byte.
    #[num_enum(catch_all)]
    Other(u8),
}

#[cfg(test)]
#[allow(
    clippy::unwrap_used,
    clippy::expect_used,
    reason = "expect/unwrap are idiomatic in tests"
)]
mod tests {
    use super::{
        DeviceConnection, DeviceKind, Event, PairingError, PairingPasskeyPressType, decode,
        discovery_name,
    };
    use crate::{
        protocol::v10::{Message, MessageHeader},
        receiver::RECEIVER_DEVICE_INDEX,
    };

    /// Builds the long notification the receiver broadcasts, with `payload`
    /// laid out exactly as the 17 bytes following the header.
    fn notification(device_index: u8, sub_id: u8, payload: [u8; 17]) -> Message {
        Message::Long(
            MessageHeader {
                device_index,
                sub_id,
            },
            payload,
        )
    }

    /// A receiver-addressed notification.
    fn from_receiver(sub_id: u8, payload: [u8; 17]) -> Message {
        notification(RECEIVER_DEVICE_INDEX, sub_id, payload)
    }

    #[test]
    fn device_connection_reads_slot_from_the_header_not_the_payload() {
        // A connection notification is the only one addressed to the device's
        // own slot rather than to the receiver, and that header byte is the
        // only place the slot is reported.
        let mut payload = [0u8; 17];
        payload[1] = 0x02; // mouse, not encrypted, online
        payload[2] = 0x0b;
        payload[3] = 0x40;

        let event = decode(&notification(3, 0x41, payload)).unwrap();

        assert_eq!(
            event,
            Event::DeviceConnection(DeviceConnection {
                index: 3,
                kind: DeviceKind::Mouse,
                encrypted: false,
                online: true,
                wpid: 0x400b,
            })
        );
    }

    #[test]
    fn device_connection_decodes_its_status_bits() {
        // Bit 5 is the link encryption flag and bit 6 is *inverted*: it is set
        // when the device is offline. Bolt puts encryption on a different bit
        // than Unifying does (bit 4), so this is not a shared layout.
        let connection = |status: u8| {
            let mut payload = [0u8; 17];
            payload[1] = status;
            match decode(&notification(1, 0x41, payload)) {
                Some(Event::DeviceConnection(connection)) => connection,
                other => panic!("expected a device connection, got {other:?}"),
            }
        };

        let encrypted_online = connection(1 << 5);
        assert!(encrypted_online.encrypted);
        assert!(encrypted_online.online);

        let plain_offline = connection(1 << 6);
        assert!(!plain_offline.encrypted);
        assert!(!plain_offline.online);
    }

    #[test]
    fn unmodelled_device_kind_folds_to_unknown_instead_of_dropping_the_event() {
        // Losing the event would hide the device from enumeration entirely,
        // which is far worse than reporting an unknown kind.
        let mut payload = [0u8; 17];
        payload[1] = 0x0e;

        let Some(Event::DeviceConnection(connection)) = decode(&notification(1, 0x41, payload))
        else {
            panic!("an unknown kind must still produce an event");
        };
        assert_eq!(connection.kind, DeviceKind::Unknown);
    }

    #[test]
    fn discovery_details_and_name_share_a_counter() {
        // The counter is what lets a caller join the two halves of one
        // discovered device, so both must read it from the same little-endian
        // pair.
        let mut details = [0u8; 17];
        details[0] = 0x34;
        details[1] = 0x12;
        details[2] = 0; // details part
        details[4] = 0x01; // keyboard
        details[5] = 0xcd;
        details[6] = 0xab;
        details[7..13].copy_from_slice(&[1, 2, 3, 4, 5, 6]);
        details[15] = 0x20;

        assert_eq!(
            decode(&from_receiver(0x4f, details)).unwrap(),
            Event::DeviceDiscoveryDeviceDetails {
                counter: 0x1234,
                kind: DeviceKind::Keyboard,
                wpid: 0xabcd,
                address: [1, 2, 3, 4, 5, 6],
                authentication: 0x20,
            }
        );

        let mut name = [0u8; 17];
        name[0] = 0x34;
        name[1] = 0x12;
        name[2] = 1; // name part
        name[3] = 4;
        name[4..8].copy_from_slice(b"Casa");

        assert_eq!(
            decode(&from_receiver(0x4f, name)).unwrap(),
            Event::DeviceDiscoveryDeviceName {
                counter: 0x1234,
                name: "Casa".to_string(),
            }
        );
    }

    #[test]
    fn unmodelled_discovery_part_is_dropped() {
        let mut payload = [0u8; 17];
        payload[2] = 9;

        assert_eq!(decode(&from_receiver(0x4f, payload)), None);
    }

    #[test]
    fn discovery_status_is_inverted_on_the_wire() {
        let enabled = |byte: u8| {
            let mut payload = [0u8; 17];
            payload[0] = byte;
            decode(&from_receiver(0x53, payload)).unwrap()
        };

        assert_eq!(
            enabled(0x00),
            Event::DeviceDiscoveryStatus {
                discovery_enabled: true
            }
        );
        assert_eq!(
            enabled(0x01),
            Event::DeviceDiscoveryStatus {
                discovery_enabled: false
            }
        );
    }

    #[test]
    fn pairing_status_carries_an_unmodelled_error_code_rather_than_dropping_it() {
        // Dropping an unrecognised code would turn a reported failure into a
        // silent session timeout.
        let mut payload = [0u8; 17];
        payload[1] = 0x7f;
        payload[2..8].copy_from_slice(&[9, 8, 7, 6, 5, 4]);
        payload[8] = 2;

        assert_eq!(
            decode(&from_receiver(0x54, payload)).unwrap(),
            Event::PairingStatus {
                device_address: [9, 8, 7, 6, 5, 4],
                pairing_error: Some(PairingError::Other(0x7f)),
                slot: Some(2),
            }
        );
    }

    #[test]
    fn pairing_status_reports_success_as_no_error_and_slot_zero_as_none() {
        let payload = [0u8; 17];

        assert_eq!(
            decode(&from_receiver(0x54, payload)).unwrap(),
            Event::PairingStatus {
                device_address: [0; 6],
                pairing_error: None,
                slot: None,
            }
        );
    }

    #[test]
    fn passkey_request_stops_at_the_nul_padding() {
        let mut payload = [0u8; 17];
        payload[1..5].copy_from_slice(b"1234");
        payload[7..13].copy_from_slice(&[0xaa; 6]);

        assert_eq!(
            decode(&from_receiver(0x4d, payload)).unwrap(),
            Event::PairingPasskeyRequest {
                device_address: [0xaa; 6],
                passkey: "1234".to_string(),
            }
        );
    }

    #[test]
    fn passkey_request_uses_all_six_digits_when_unpadded() {
        let mut payload = [0u8; 17];
        payload[1..7].copy_from_slice(b"951753");

        let Some(Event::PairingPasskeyRequest { passkey, .. }) =
            decode(&from_receiver(0x4d, payload))
        else {
            panic!("expected a passkey request");
        };
        assert_eq!(passkey, "951753");
    }

    #[test]
    fn passkey_request_with_invalid_utf8_is_dropped() {
        let mut payload = [0u8; 17];
        payload[1] = 0xff;
        payload[2] = 0xfe;

        assert_eq!(decode(&from_receiver(0x4d, payload)), None);
    }

    #[test]
    fn passkey_press_carries_an_unmodelled_press_type() {
        let mut payload = [0u8; 17];
        payload[0] = 0x33;
        payload[1..7].copy_from_slice(&[1, 2, 3, 4, 5, 6]);

        assert_eq!(
            decode(&from_receiver(0x4e, payload)).unwrap(),
            Event::PairingPasskeyPressed {
                device_address: [1, 2, 3, 4, 5, 6],
                press_type: PairingPasskeyPressType::Other(0x33),
            }
        );
    }

    #[test]
    fn notifications_addressed_elsewhere_are_dropped_except_device_connections() {
        // A device-addressed report is only ever a connection notification;
        // anything else at a device index belongs to that device, not to us.
        assert_eq!(decode(&notification(2, 0x53, [0u8; 17])), None);
        assert!(decode(&notification(2, 0x41, [0u8; 17])).is_some());
    }

    #[test]
    fn unmodelled_sub_id_is_dropped() {
        assert_eq!(decode(&from_receiver(0x42, [0u8; 17])), None);
    }

    #[test]
    fn short_notifications_decode_from_the_zero_padded_payload() {
        // The receiver may answer in either report width; a short report is
        // widened with zeroes, which must not change the decoded event.
        let short = Message::Short(
            MessageHeader {
                device_index: 4,
                sub_id: 0x41,
            },
            [0x00, 0x02, 0x0b, 0x40],
        );

        assert_eq!(
            decode(&short).unwrap(),
            Event::DeviceConnection(DeviceConnection {
                index: 4,
                kind: DeviceKind::Mouse,
                encrypted: false,
                online: true,
                wpid: 0x400b,
            })
        );
    }

    #[test]
    fn discovery_name_with_oversized_length_is_dropped() {
        let mut payload = [0u8; 17];
        payload[3] = 200;

        assert_eq!(discovery_name(&payload), None);
    }

    #[test]
    fn discovery_name_within_bounds_parses() {
        let mut payload = [0u8; 17];
        payload[3] = 4;
        payload[4..8].copy_from_slice(b"Casa");

        assert_eq!(discovery_name(&payload), Some("Casa"));
    }

    #[test]
    fn discovery_name_rejects_invalid_utf8() {
        let mut payload = [0u8; 17];
        payload[3] = 2;
        payload[4] = 0xff;
        payload[5] = 0xfe;

        assert_eq!(discovery_name(&payload), None);
    }
}