openlogi-cli 0.8.14

Implementation library for the OpenLogi CLI (the `openlogi` binary).
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
use std::{
    fmt::{self, Write as _},
    process::ExitCode,
};

use anyhow::{Context, Result};
use clap::Args;
use openlogi_camera::Camera;
use openlogi_core::device::{BatteryInfo, DeviceInventory, DeviceModelInfo, PairedDevice};
use openlogi_ipc::client::ConnectError;
use openlogi_ipc::{AgentSnapshot, AgentStatus};

#[derive(Debug, Args)]
pub struct ListArgs {}

/// Exit status for "the scan succeeded, but nothing is connected" — distinct
/// from the failure status a real enumeration error produces.
const NOTHING_FOUND: u8 = 2;

/// Print every connected receiver, paired device and Logitech webcam.
///
/// Reads the running agent's inventory when one is reachable — the agent is
/// the process that actually holds device permissions, so its answer is the
/// GUI's answer and no second identity opens the same HID nodes. Falls back
/// to direct enumeration (this process's own permission identity) when no
/// agent responds; the provenance goes to stderr so scripts keep parsing
/// stdout.
///
/// Returns the `NOTHING_FOUND` status when neither a HID++ device nor a webcam
/// is present, so scripts can tell "no hardware" apart from a failed
/// enumeration.
pub async fn run(_args: ListArgs) -> Result<ExitCode> {
    let (inventories, agent_status) = if let Some(snapshot) = agent_snapshot().await {
        eprintln!("(inventory read from the running agent)");
        (snapshot.inventory, Some(snapshot.status))
    } else {
        eprintln!(
            "(no agent reachable — reading hardware directly; macOS judges this \
             process's Input Monitoring grant, not the agent's)"
        );
        let inventories = openlogi_hid::enumerate()
            .await
            .context("failed to enumerate HID++ devices")?;
        (inventories, None)
    };
    let cameras = openlogi_camera::enumerate_cameras();

    if inventories.is_empty() && cameras.is_empty() {
        println!("No Logitech HID++ devices or webcams found.");
        println!();
        print_empty_notes(agent_status.as_ref());
        return Ok(ExitCode::from(NOTHING_FOUND));
    }

    for (i, inv) in inventories.iter().enumerate() {
        if i != 0 {
            println!();
        }
        print_inventory(inv);
    }

    if !cameras.is_empty() {
        if !inventories.is_empty() {
            println!();
        }
        print_cameras(&cameras);
    }

    Ok(ExitCode::SUCCESS)
}

/// One agent snapshot, or `None` when the CLI should read hardware itself:
/// no agent listening, a hung handshake, a protocol mismatch, or a stalled
/// snapshot call.
async fn agent_snapshot() -> Option<AgentSnapshot> {
    let client = match crate::agent::connect().await {
        Ok(client) => client,
        Err(ConnectError::Skew(skew)) => {
            eprintln!("note: {skew} — reading hardware directly");
            return None;
        }
        Err(_) => return None,
    };
    crate::agent::snapshot(&client).await.ok()
}

/// Why the list is empty. With an agent status in hand the reason is known;
/// without one, fall back to the generic checklist.
fn print_empty_notes(status: Option<&AgentStatus>) {
    match status {
        Some(status) if !status.input_monitoring_granted => {
            println!("Notes:");
            println!(
                "  - The agent does not hold Input Monitoring. Grant it to OpenLogi Agent: \
                 System Settings → Privacy & Security → Input Monitoring (the + picker \
                 cannot browse into the app bundle — use Go to Folder)."
            );
        }
        // Off macOS there is no Input Monitoring gate, so a failed open on
        // Linux is almost always missing hidraw access, not a stale session.
        Some(status) if status.hid_open_failures && cfg!(target_os = "linux") => {
            println!("Notes:");
            println!(
                "  - The agent's device opens keep failing. On Linux, HID++ access needs \
                 OpenLogi's udev rules (shipped by the packages; for a source build see \
                 docs/INSTALL-linux.md)."
            );
        }
        Some(status) if status.hid_open_failures => {
            println!("Notes:");
            println!(
                "  - Input Monitoring is granted, but the agent's device opens keep \
                 failing — another app may hold the devices (quit Logi Options+), or \
                 macOS is serving a stale permission session: log out and back in."
            );
        }
        _ => {
            println!("Notes:");
            println!("  - On macOS, quit Logi Options+ first — both apps fight over HID++ access.");
            println!(
                "  - A Bluetooth-direct mouse (e.g. Lift, Signature) needs Input Monitoring \
                 permission: System Settings → Privacy & Security → Input Monitoring."
            );
            println!(
                "  - On Linux, HID++ access needs OpenLogi's udev rules (shipped by the \
                 packages; for a source build see docs/INSTALL-linux.md)."
            );
        }
    }
}

fn print_cameras(cameras: &[Camera]) {
    println!("Cameras ({} Logitech UVC)", cameras.len());
    let last = cameras.len() - 1;
    for (i, cam) in cameras.iter().enumerate() {
        let prefix = if i == last { "  └─" } else { "  ├─" };
        println!(
            "{prefix} ● {} (camera, vid={:04x} pid={:04x}{caps}, id={})",
            cam.name,
            cam.vendor_id,
            cam.product_id,
            cam.unique_id,
            caps = CameraCapabilitiesDisplay {
                resolution: cam.max_resolution,
                fps: cam.max_fps,
            },
        );
    }
}

struct CameraCapabilitiesDisplay {
    resolution: Option<(u32, u32)>,
    fps: Option<u32>,
}

impl fmt::Display for CameraCapabilitiesDisplay {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match (self.resolution, self.fps) {
            (Some((width, height)), Some(fps)) => {
                write!(f, ", up to {width}x{height}@{fps}")
            }
            (Some((width, height)), None) => write!(f, ", up to {width}x{height}"),
            _ => Ok(()),
        }
    }
}

fn print_inventory(inv: &DeviceInventory) {
    let uid = inv.receiver.unique_id.as_deref().unwrap_or("—");
    println!(
        "{} ({}, vid={:04x} pid={:04x})",
        inv.receiver.name, uid, inv.receiver.vendor_id, inv.receiver.product_id
    );

    if inv.paired.is_empty() {
        println!("  └─ no paired devices");
        return;
    }

    let last = inv.paired.len() - 1;
    for (i, d) in inv.paired.iter().enumerate() {
        let prefix = if i == last { "  └─" } else { "  ├─" };
        println!("{prefix} {}", PairedDeviceDisplay(d));
        if let Some(model) = d.model_info.as_ref() {
            let cont = if i == last { "     " } else { "  │  " };
            println!("{cont}{}", DeviceModelDisplay(model));
        }
    }
}

struct PairedDeviceDisplay<'a>(&'a PairedDevice);

impl fmt::Display for PairedDeviceDisplay<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let device = self.0;
        let dot = if device.online { "●" } else { "○" };
        let codename = device.codename.as_deref().unwrap_or("Unknown device");
        write!(
            f,
            "slot {} {dot} {codename} ({}, ",
            device.slot,
            LowercaseDebug(device.kind)
        )?;
        match device.wpid {
            Some(wpid) => write!(f, "wpid={wpid:04x}, ")?,
            None => write!(f, "wpid=?, ")?,
        }
        match device.battery.as_ref() {
            Some(battery) => write!(f, "{}", BatteryDisplay(battery))?,
            None => write!(f, "battery=—")?,
        }
        write!(f, ")")
    }
}

struct BatteryDisplay<'a>(&'a BatteryInfo);

impl fmt::Display for BatteryDisplay<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let battery = self.0;
        write!(f, "battery=")?;
        // A device without a state-of-charge gauge reports only its level.
        if let Some(percentage) = battery.percentage {
            write!(f, "{percentage}% ")?;
        }
        write!(
            f,
            "{} ({})",
            LowercaseDebug(battery.level),
            LowercaseDebug(battery.status)
        )
    }
}

struct DeviceModelDisplay<'a>(&'a DeviceModelInfo);

impl fmt::Display for DeviceModelDisplay<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let model = self.0;
        write!(f, "     model_ids=[")?;
        let mut separator = "";
        for id in model.model_ids {
            write!(f, "{separator}{id:04x}")?;
            separator = ",";
        }
        write!(
            f,
            "] ext={:02x} serial={} unit_id=",
            model.extended_model_id,
            model.serial_number.as_deref().unwrap_or("—")
        )?;
        for byte in model.unit_id {
            write!(f, "{byte:02x}")?;
        }
        write!(f, " transports=")?;

        separator = "";
        for (enabled, name) in [
            (model.transports.usb, "usb"),
            (model.transports.equad, "equad"),
            (model.transports.btle, "btle"),
            (model.transports.bluetooth, "bt"),
        ] {
            if enabled {
                write!(f, "{separator}{name}")?;
                separator = "+";
            }
        }
        if separator.is_empty() {
            write!(f, "—")?;
        }

        Ok(())
    }
}

/// The CLI historically rendered these enums by lowercasing their `Debug`
/// names. Keep that exact spelling without allocating an intermediate string.
struct LowercaseDebug<T>(T);

impl<T: fmt::Debug> fmt::Display for LowercaseDebug<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(LowercaseWriter(f), "{:?}", self.0)
    }
}

struct LowercaseWriter<'a, 'b>(&'a mut fmt::Formatter<'b>);

impl fmt::Write for LowercaseWriter<'_, '_> {
    fn write_str(&mut self, value: &str) -> fmt::Result {
        for character in value.chars().flat_map(char::to_lowercase) {
            self.0.write_char(character)?;
        }
        Ok(())
    }
}

#[cfg(test)]
mod format_tests {
    use openlogi_core::device::{BatteryLevel, BatteryStatus, DeviceKind, DeviceTransports};

    use super::{
        BatteryDisplay, CameraCapabilitiesDisplay, DeviceModelDisplay, PairedDevice,
        PairedDeviceDisplay,
    };
    use super::{BatteryInfo, DeviceModelInfo};

    fn base_device() -> PairedDevice {
        PairedDevice {
            slot: 1,
            codename: Some("MX Master 3S".to_string()),
            wpid: Some(0x4082),
            kind: DeviceKind::Mouse,
            online: true,
            battery: None,
            model_info: None,
            capabilities: None,
            settings_revision: 0,
        }
    }

    #[test]
    fn online_device_uses_filled_dot_and_reports_fields() {
        let d = base_device();
        let out = PairedDeviceDisplay(&d).to_string();
        assert_eq!(out, "slot 1 ● MX Master 3S (mouse, wpid=4082, battery=—)");
    }

    #[test]
    fn offline_device_uses_hollow_dot() {
        let mut d = base_device();
        d.online = false;
        let out = PairedDeviceDisplay(&d).to_string();
        assert!(out.starts_with("slot 1 ○ "));
    }

    #[test]
    fn missing_codename_and_wpid_fall_back_to_placeholders() {
        let mut d = base_device();
        d.codename = None;
        d.wpid = None;
        let out = PairedDeviceDisplay(&d).to_string();
        assert_eq!(out, "slot 1 ● Unknown device (mouse, wpid=?, battery=—)");
    }

    #[test]
    fn battery_info_is_embedded_when_present() {
        let mut d = base_device();
        d.battery = Some(BatteryInfo {
            percentage: Some(42),
            level: BatteryLevel::Low,
            status: BatteryStatus::Discharging,
        });
        let out = PairedDeviceDisplay(&d).to_string();
        assert!(out.contains("battery=42% low (discharging)"));
    }

    #[test]
    fn a_level_only_battery_prints_no_percentage() {
        let b = BatteryInfo {
            percentage: None,
            level: BatteryLevel::Good,
            status: BatteryStatus::Discharging,
        };
        assert_eq!(BatteryDisplay(&b).to_string(), "battery=good (discharging)");
    }

    #[test]
    fn battery_status_debug_names_are_lowercased_verbatim() {
        // `ChargingSlow`'s Debug form has no separator; lowercasing alone
        // yields "chargingslow", not "charging_slow" or "charging slow".
        let b = BatteryInfo {
            percentage: Some(10),
            level: BatteryLevel::Critical,
            status: BatteryStatus::ChargingSlow,
        };
        assert_eq!(
            BatteryDisplay(&b).to_string(),
            "battery=10% critical (chargingslow)"
        );
    }

    #[test]
    fn camera_capabilities_include_resolution_and_optional_fps() {
        assert_eq!(
            CameraCapabilitiesDisplay {
                resolution: Some((1920, 1080)),
                fps: Some(60),
            }
            .to_string(),
            ", up to 1920x1080@60"
        );
        assert_eq!(
            CameraCapabilitiesDisplay {
                resolution: Some((1920, 1080)),
                fps: None,
            }
            .to_string(),
            ", up to 1920x1080"
        );
        assert_eq!(
            CameraCapabilitiesDisplay {
                resolution: None,
                fps: Some(60),
            }
            .to_string(),
            ""
        );
    }

    fn base_model() -> DeviceModelInfo {
        DeviceModelInfo {
            entity_count: 1,
            serial_number: None,
            unit_id: [0x00, 0x01, 0x02, 0x03],
            transports: DeviceTransports::default(),
            model_ids: [0xb042, 0, 0],
            extended_model_id: 0x02,
        }
    }

    #[test]
    fn model_with_no_transports_shows_placeholder_and_missing_serial() {
        let m = base_model();
        let out = DeviceModelDisplay(&m).to_string();
        assert_eq!(
            out,
            "     model_ids=[b042,0000,0000] ext=02 serial=— unit_id=00010203 transports=—"
        );
    }

    #[test]
    fn model_transports_join_in_declared_field_order() {
        let mut m = base_model();
        m.transports = DeviceTransports {
            usb: true,
            equad: false,
            btle: true,
            bluetooth: true,
        };
        m.serial_number = Some("SN123".to_string());
        let out = DeviceModelDisplay(&m).to_string();
        assert!(out.contains("transports=usb+btle+bt"));
        assert!(out.contains("serial=SN123"));
    }
}