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
use openlogi_core::device::{
    Capabilities, DeviceInventory, DeviceKind, PairedDevice, ReceiverInfo,
};
use openlogi_fixture::{
    CassetteExchange, FIXTURE_SCHEMA_VERSION, HidCassette, ReportSupport, RequestMatch,
};

use crate::replay::{
    ChannelConnection, NodePresence, OpenOutcome, RawWriterAvailability, ReceiverLinkState,
    ReceiverSlot, ReceiverSlotState, ReplayChannel, ReplayNode,
};
use crate::{DeviceRoute, NodeId, NodeInfo};

pub(super) const DIRECT_CHANNEL: &str = "scenario-direct";
pub(super) const BOLT_CHANNEL: &str = "scenario-bolt";
pub(super) const BOLT_UID: &str = "A1B2C3D4E5F60708";

pub(super) struct DirectFixture {
    pub(super) node_id: NodeId,
    pub(super) inventory: DeviceInventory,
    pub(super) node: ReplayNode,
    pub(super) channel: ReplayChannel,
    pub(super) cassette: HidCassette,
}

pub(super) fn direct_fixture(open_outcome: OpenOutcome, probe_count: usize) -> DirectFixture {
    let node_id = NodeId::from("scenario-direct-node".to_string());
    let product_id = 0xb35b;
    let name = "Scenario Direct Mouse";
    let inventory = DeviceInventory {
        receiver: ReceiverInfo {
            name: name.to_string(),
            vendor_id: 0x046d,
            product_id,
            unique_id: None,
        },
        paired: vec![PairedDevice {
            slot: crate::DIRECT_DEVICE_INDEX,
            codename: Some(name.to_string()),
            wpid: None,
            kind: DeviceKind::Unknown,
            online: true,
            battery: None,
            model_info: None,
            capabilities: Some(Capabilities {
                pointer: true,
                ..Capabilities::default()
            }),
            settings_revision: 0,
        }],
    };
    let mut exchanges = Vec::new();
    for _ in 0..probe_count {
        exchanges.extend(direct_probe_exchanges());
    }
    DirectFixture {
        node_id: node_id.clone(),
        inventory,
        node: ReplayNode {
            info: node_info(node_id, product_id, name),
            presence: NodePresence::Present,
            open_outcome,
            channel: Some(DIRECT_CHANNEL.to_string()),
            raw_writer: RawWriterAvailability::Unavailable,
            receiver_slots: Vec::new(),
        },
        channel: replay_channel(DIRECT_CHANNEL),
        cassette: cassette("scenario-direct-probes", DIRECT_CHANNEL, exchanges),
    }
}

fn direct_probe_exchanges() -> Vec<CassetteExchange> {
    vec![
        h20(
            short(0xff, 0x00, 0x10, [0, 0, 0]),
            short(0xff, 0x00, 0x10, [4, 0, 0]),
        ),
        h20(
            short(0xff, 0x00, 0x00, [0x00, 0x01, 0]),
            short(0xff, 0x00, 0x00, [0x01, 0, 0]),
        ),
        h20(
            short(0xff, 0x01, 0x00, [0, 0, 0]),
            short(0xff, 0x01, 0x00, [2, 0, 0]),
        ),
        h20(
            short(0xff, 0x01, 0x10, [1, 0, 0]),
            short(0xff, 0x01, 0x10, [0x00, 0x01, 0]),
        ),
        h20(
            short(0xff, 0x01, 0x10, [2, 0, 0]),
            short(0xff, 0x01, 0x10, [0x22, 0x01, 0]),
        ),
    ]
}

pub(super) const HEADSET_CHANNEL: &str = "scenario-headset";

pub(super) struct HeadsetFixture {
    pub(super) node: ReplayNode,
    pub(super) channel: ReplayChannel,
    pub(super) cassette: HidCassette,
}

/// A G733-style headset dongle: its feature table is `FeatureSet` plus
/// `0x1F20` at index 2 and nothing else, so the battery feature is the only
/// evidence that a device sits behind the node. `adc_answers` scripts each
/// successive `getAdcMeasurement` answer (see [`adc_reading`] /
/// [`adc_error`]): the first rides the full probe, each later one a cache-hit
/// battery re-read.
pub(super) fn headset_fixture(adc_answers: &[Vec<u8>]) -> HeadsetFixture {
    battery_only_fixture(
        0x1f20,
        HEADSET_PRODUCT_ID,
        "G733 Gaming Headset",
        adc_answers,
    )
}

/// The product id [`headset_fixture`] lists its dongle under.
pub(super) const HEADSET_PRODUCT_ID: u16 = 0x0ab5;

/// A node whose feature table is `FeatureSet` plus one battery feature
/// (`feature_id`) at index 2 and nothing else. `answers` scripts each
/// successive function-`0` read of that feature: the first rides the full
/// probe, each later one a cache-hit battery re-read.
pub(super) fn battery_only_fixture(
    feature_id: u16,
    product_id: u16,
    name: &str,
    answers: &[Vec<u8>],
) -> HeadsetFixture {
    let node_id = NodeId::from("scenario-headset-node".to_string());
    let [feature_high, feature_low] = feature_id.to_be_bytes();
    let mut exchanges = vec![
        h20(
            short(0xff, 0x00, 0x10, [0, 0, 0]),
            short(0xff, 0x00, 0x10, [4, 0, 0]),
        ),
        h20(
            short(0xff, 0x00, 0x00, [0x00, 0x01, 0]),
            short(0xff, 0x00, 0x00, [0x01, 0, 0]),
        ),
        h20(
            short(0xff, 0x01, 0x00, [0, 0, 0]),
            short(0xff, 0x01, 0x00, [2, 0, 0]),
        ),
        h20(
            short(0xff, 0x01, 0x10, [1, 0, 0]),
            short(0xff, 0x01, 0x10, [0x00, 0x01, 0]),
        ),
        h20(
            short(0xff, 0x01, 0x10, [2, 0, 0]),
            short(0xff, 0x01, 0x10, [feature_high, feature_low, 0]),
        ),
    ];
    exchanges.extend(
        answers
            .iter()
            .map(|answer| h20(short(0xff, 0x02, 0x00, [0, 0, 0]), answer.clone())),
    );
    HeadsetFixture {
        node: ReplayNode {
            info: node_info(node_id, product_id, name),
            presence: NodePresence::Present,
            open_outcome: OpenOutcome::Hidpp,
            channel: Some(HEADSET_CHANNEL.to_string()),
            raw_writer: RawWriterAvailability::Unavailable,
            receiver_slots: Vec::new(),
        },
        channel: replay_channel(HEADSET_CHANNEL),
        cassette: cassette("scenario-headset-probes", HEADSET_CHANNEL, exchanges),
    }
}

/// A battery-powered keyboard or mouse: `FeatureSet`, the legacy `0x1000`
/// battery at index 2, and one settings feature (`feature_id`, such as
/// `0x40a3` or `0x2202`) at index 3 that the inventory probe lists but never
/// reads. The battery answers 50 % to each of `battery_reads` reads: the
/// first rides the full probe, each later one a cache-hit re-read.
pub(super) fn setting_fixture(
    feature_id: u16,
    product_id: u16,
    name: &str,
    battery_reads: usize,
) -> HeadsetFixture {
    let node_id = NodeId::from("scenario-settings-node".to_string());
    let [feature_high, feature_low] = feature_id.to_be_bytes();
    let mut exchanges = vec![
        h20(
            short(0xff, 0x00, 0x10, [0, 0, 0]),
            short(0xff, 0x00, 0x10, [4, 0, 0]),
        ),
        h20(
            short(0xff, 0x00, 0x00, [0x00, 0x01, 0]),
            short(0xff, 0x00, 0x00, [0x01, 0, 0]),
        ),
        h20(
            short(0xff, 0x01, 0x00, [0, 0, 0]),
            short(0xff, 0x01, 0x00, [3, 0, 0]),
        ),
        h20(
            short(0xff, 0x01, 0x10, [1, 0, 0]),
            short(0xff, 0x01, 0x10, [0x00, 0x01, 0]),
        ),
        h20(
            short(0xff, 0x01, 0x10, [2, 0, 0]),
            short(0xff, 0x01, 0x10, [0x10, 0x00, 0]),
        ),
        h20(
            short(0xff, 0x01, 0x10, [3, 0, 0]),
            short(0xff, 0x01, 0x10, [feature_high, feature_low, 0]),
        ),
    ];
    exchanges.extend((0..battery_reads).map(|_| {
        h20(
            short(0xff, 0x02, 0x00, [0, 0, 0]),
            short(0xff, 0x02, 0x00, [50, 20, 0x00]),
        )
    }));
    HeadsetFixture {
        node: ReplayNode {
            info: node_info(node_id, product_id, name),
            presence: NodePresence::Present,
            open_outcome: OpenOutcome::Hidpp,
            channel: Some(HEADSET_CHANNEL.to_string()),
            raw_writer: RawWriterAvailability::Unavailable,
            receiver_slots: Vec::new(),
        },
        channel: replay_channel(HEADSET_CHANNEL),
        cassette: cassette("scenario-settings-probes", HEADSET_CHANNEL, exchanges),
    }
}

/// A linked `getAdcMeasurement` answer.
pub(super) fn adc_reading(voltage_mv: u16, flags: u8) -> Vec<u8> {
    let [high, low] = voltage_mv.to_be_bytes();
    short(0xff, 0x02, 0x00, [high, low, flags])
}

/// A HID++ 2.0 error answer to `getAdcMeasurement`.
pub(super) fn adc_error(code: u8) -> Vec<u8> {
    vec![0x10, 0xff, 0xff, 0x02, 0x00, code, 0]
}

/// A `0x1001` `getBatteryInfo` answer for [`battery_only_fixture`]: the
/// voltage as big-endian millivolts, then the charging flags.
pub(super) fn voltage_reading(voltage_mv: u16, flags: u8) -> Vec<u8> {
    let [high, low] = voltage_mv.to_be_bytes();
    short(0xff, 0x02, 0x00, [high, low, flags])
}

#[derive(Clone, Copy)]
pub(super) struct BoltSlot {
    pub(super) slot: u8,
    pub(super) online: bool,
}

pub(super) struct BoltFixture {
    pub(super) node_id: NodeId,
    pub(super) inventory: DeviceInventory,
    pub(super) node: ReplayNode,
    pub(super) channel: ReplayChannel,
    pub(super) cassette: HidCassette,
}

pub(super) fn bolt_fixture(tag: &str, slots: &[BoltSlot], pass_count: usize) -> BoltFixture {
    // Register locks are host-wide. Independent replay scenarios must not
    // contend for the same synthetic receiver, including across test processes.
    let node_id = NodeId::from(format!("scenario-bolt-node-{}-{tag}", std::process::id()));
    let product_id = 0xc548;
    let mut exchanges = Vec::new();
    for _ in 0..pass_count {
        exchanges.extend(bolt_pass_exchanges(slots));
    }
    BoltFixture {
        node_id: node_id.clone(),
        inventory: DeviceInventory {
            receiver: ReceiverInfo {
                name: "Logi Bolt Receiver".to_string(),
                vendor_id: 0x046d,
                product_id,
                unique_id: Some(BOLT_UID.to_string()),
            },
            paired: slots
                .iter()
                .map(|spec| PairedDevice {
                    slot: spec.slot,
                    codename: Some(slot_name(spec.slot)),
                    wpid: None,
                    kind: DeviceKind::Mouse,
                    online: spec.online,
                    battery: None,
                    model_info: None,
                    capabilities: None,
                    settings_revision: 0,
                })
                .collect(),
        },
        node: ReplayNode {
            info: node_info(node_id, product_id, "Scenario Bolt Receiver"),
            presence: NodePresence::Present,
            open_outcome: OpenOutcome::Hidpp,
            channel: Some(BOLT_CHANNEL.to_string()),
            raw_writer: RawWriterAvailability::Unavailable,
            receiver_slots: slots
                .iter()
                .map(|spec| ReceiverSlot {
                    slot: spec.slot,
                    state: ReceiverSlotState::Paired(if spec.online {
                        ReceiverLinkState::Online
                    } else {
                        ReceiverLinkState::Offline
                    }),
                })
                .collect(),
        },
        channel: replay_channel(BOLT_CHANNEL),
        cassette: cassette("scenario-bolt-probes", BOLT_CHANNEL, exchanges),
    }
}

fn bolt_pass_exchanges(slots: &[BoltSlot]) -> Vec<CassetteExchange> {
    let mut exchanges = vec![
        exact(
            vec![0x10, 0xff, 0x81, 0x02, 0, 0, 0],
            Some(vec![
                0x10,
                0xff,
                0x81,
                0x02,
                0,
                u8::try_from(slots.len()).expect("at most six synthetic Bolt slots"),
                0,
            ]),
        ),
        exact(
            vec![0x10, 0xff, 0x83, 0xfb, 0, 0, 0],
            Some(unique_id_response()),
        ),
        exact(
            vec![0x10, 0xff, 0x81, 0x00, 0, 0, 0],
            Some(vec![0x10, 0xff, 0x81, 0x00, 0, 1, 0]),
        ),
        exact(
            vec![0x10, 0xff, 0x80, 0x02, 0x02, 0, 0],
            Some(vec![0x10, 0xff, 0x80, 0x02, 0x02, 0, 0]),
        ),
    ];
    for slot in 1..=6 {
        let request = vec![0x10, 0xff, 0x83, 0xb5, 0x50 + slot, 0, 0];
        let response = slots
            .iter()
            .find(|spec| spec.slot == slot)
            .copied()
            .map_or_else(
                || vec![0x10, 0xff, 0x8f, 0x83, 0xb5, 0x02, 0],
                pairing_response,
            );
        exchanges.push(exact(request, Some(response)));
        if slots.iter().any(|spec| spec.slot == slot) {
            exchanges.push(exact(
                vec![0x10, 0xff, 0x83, 0xb5, 0x60 + slot, 0x01, 0],
                Some(codename_response(slot)),
            ));
        }
    }
    for spec in slots.iter().filter(|spec| spec.online) {
        exchanges.push(h20(
            short(spec.slot, 0x00, 0x10, [0, 0, 0]),
            short(spec.slot, 0x00, 0x10, [4, 0, 0]),
        ));
        exchanges.push(h20(
            short(spec.slot, 0x00, 0x00, [0x00, 0x01, 0]),
            short(spec.slot, 0x00, 0x00, [0, 0, 0]),
        ));
    }
    exchanges
}

fn unique_id_response() -> Vec<u8> {
    let mut response = vec![0; 20];
    response[..4].copy_from_slice(&[0x11, 0xff, 0x83, 0xfb]);
    response[4..].copy_from_slice(BOLT_UID.as_bytes());
    response
}

fn pairing_response(spec: BoltSlot) -> Vec<u8> {
    let mut response = vec![0; 20];
    response[..4].copy_from_slice(&[0x11, 0xff, 0x83, 0xb5]);
    response[4] = 0x50 + spec.slot;
    response[5] = 0x02 | u8::from(!spec.online) << 6;
    response[6..8].copy_from_slice(&0xb35b_u16.to_le_bytes());
    response[8..12].copy_from_slice(&[0, 0, 0, spec.slot]);
    response
}

fn codename_response(slot: u8) -> Vec<u8> {
    let name = slot_name(slot);
    let mut response = vec![0; 20];
    response[..4].copy_from_slice(&[0x11, 0xff, 0x83, 0xb5]);
    response[4] = 0x60 + slot;
    response[5] = 1;
    response[6] = u8::try_from(name.len()).expect("short synthetic codename");
    response[7..7 + name.len()].copy_from_slice(name.as_bytes());
    response
}

fn slot_name(slot: u8) -> String {
    format!("slot-{slot}")
}

pub(super) struct DpiFixture {
    pub(super) node_id: NodeId,
    pub(super) route: DeviceRoute,
    pub(super) node: ReplayNode,
    pub(super) channel: ReplayChannel,
    pub(super) cassette: HidCassette,
    pub(super) held_request: Vec<u8>,
}

pub(super) fn malformed_dpi_fixture() -> DpiFixture {
    let bolt = bolt_fixture(
        "malformed-dpi",
        &[BoltSlot {
            slot: 1,
            online: true,
        }],
        1,
    );
    let held_request = short(1, 0x05, 0x20, [0, 0, 0]);
    let exchanges = vec![
        exact(
            vec![0x10, 0xff, 0x83, 0xfb, 0, 0, 0],
            Some(unique_id_response()),
        ),
        h20(
            short(1, 0x00, 0x10, [0, 0, 0]),
            short(1, 0x00, 0x10, [4, 0, 0]),
        ),
        h20(
            short(1, 0x00, 0x00, [0x22, 0x01, 0]),
            short(1, 0x00, 0x00, [0x05, 0, 0]),
        ),
        h20(
            held_request.clone(),
            vec![0x10, 1, 0xff, 0x05, 0x20, 0xff, 0],
        ),
    ];
    DpiFixture {
        node_id: bolt.node_id,
        route: DeviceRoute::Bolt {
            receiver_uid: BOLT_UID.to_string(),
            slot: 1,
        },
        node: bolt.node,
        channel: bolt.channel,
        cassette: cassette("malformed-late-dpi", BOLT_CHANNEL, exchanges),
        held_request,
    }
}

pub(super) fn connection_notification(slot: u8) -> Vec<u8> {
    let mut report = vec![0; 20];
    report[..3].copy_from_slice(&[0x11, slot, 0x41]);
    report[4] = 0x02;
    report[5..7].copy_from_slice(&0xb35b_u16.to_le_bytes());
    report
}

fn replay_channel(id: &str) -> ReplayChannel {
    ReplayChannel {
        id: id.to_string(),
        connection: ChannelConnection::Connected,
        report_support: ReportSupport::ShortAndLong,
    }
}

fn node_info(id: NodeId, product_id: u16, name: &str) -> NodeInfo {
    NodeInfo {
        id,
        vendor_id: 0x046d,
        product_id,
        usage_page: 0xff00,
        usage_id: 0x0002,
        name: name.to_string(),
        manufacturer: Some("Logitech".to_string()),
        serial_number: None,
    }
}

fn cassette(name: &str, channel: &str, exchanges: Vec<CassetteExchange>) -> HidCassette {
    HidCassette {
        schema_version: FIXTURE_SCHEMA_VERSION,
        name: name.to_string(),
        channel: channel.to_string(),
        report_support: ReportSupport::ShortAndLong,
        exchanges,
    }
}

fn exact(request: Vec<u8>, response: Option<Vec<u8>>) -> CassetteExchange {
    CassetteExchange {
        request_match: RequestMatch::Exact,
        request,
        response,
        required: true,
    }
}

fn h20(request: Vec<u8>, response: Vec<u8>) -> CassetteExchange {
    CassetteExchange {
        request_match: RequestMatch::Hidpp20,
        request,
        response: Some(response),
        required: true,
    }
}

pub(super) fn short(device: u8, feature: u8, function: u8, payload: [u8; 3]) -> Vec<u8> {
    vec![
        0x10, device, feature, function, payload[0], payload[1], payload[2],
    ]
}