From 8af2aef0282e00a686e832d8262cbbbcf77924dd Mon Sep 17 00:00:00 2001 From: softmaxe <94467584+softmaxe@users.noreply.github.com> Date: Thu, 19 Nov 2026 04:04:43 +0800 Subject: [PATCH 1/5] refactor(hidpp): simplify feature discovery and tighten protocol tests --- src/hidpp.rs | 942 ++------------------------------------------- src/hidpp/tests.rs | 828 +++++++++++++++++++++++++++++++++++++++ src/main.rs | 14 +- 3 files changed, 874 insertions(+), 910 deletions(-) create mode 100644 src/hidpp/tests.rs diff --git a/src/hidpp.rs b/src/hidpp.rs index 9711360..9f82c5b 100644 --- a/src/hidpp.rs +++ b/src/hidpp.rs @@ -28,12 +28,11 @@ const DEVICE_INDEX_CANDIDATES: [u8; 7] = [1, 0xFF, 2, 3, 4, 5, 6]; const REPORT_BUFFER_LEN: usize = 20; const FLUSH_WINDOW: Duration = Duration::from_millis(200); const RESPONSE_TIMEOUT: Duration = Duration::from_millis(1_500); -/// Upper bound for probing every interface and device index. A paired but -/// unavailable index answers with an error report instead of falling silent, so -/// this budget only caps interfaces that never answer at all. +/// Stop starting new probes after this budget. A probe already in progress can +/// finish, and reading a discovered battery feature has its own timeout. const DISCOVERY_BUDGET: Duration = Duration::from_secs(6); -#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[derive(Debug, PartialEq, Eq)] pub struct BatteryStatus { pub level: u8, pub charging: bool, @@ -92,7 +91,7 @@ fn permission_denied(error: &HidError) -> bool { } /// One report read from a HID interface. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[derive(Debug, PartialEq, Eq)] struct Report { buffer: [u8; REPORT_BUFFER_LEN], length: usize, @@ -105,7 +104,7 @@ impl Report { } /// What a single HID++ request produced. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[derive(Debug, PartialEq, Eq)] enum Reply { Response(Report), /// The device index exists but rejected the request. @@ -133,7 +132,7 @@ enum Discovery { } /// What reading the battery through every candidate HID interface found. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[derive(Debug, PartialEq, Eq)] pub enum Reading { Status(BatteryStatus), /// A device index exposed a battery feature, but reading it produced no @@ -141,11 +140,10 @@ pub enum Reading { NoStatus, /// A receiver answered, but reported no connected mouse. Offline, - /// No HID interface answered at any device index. + /// No candidate reported a battery feature or an offline device. NotFound, } -#[derive(Debug, Clone, Copy, PartialEq, Eq)] enum BatteryFeature { Unified(u8), Legacy(u8), @@ -189,12 +187,6 @@ fn ensure_length(response: &[u8], minimum: usize) -> Result<(), HidppError> { Ok(()) } -fn parse_feature_index(response: &[u8]) -> Result, HidppError> { - ensure_length(response, 5)?; - let feature_index = response[4]; - Ok((feature_index != 0).then_some(feature_index)) -} - /// Both battery features report the level in byte 4; only the position of the /// charging flag differs. fn parse_battery(response: &[u8], charging_offset: usize) -> Result { @@ -218,13 +210,6 @@ fn flush(io: &impl RequestIo) -> Result<(), HidppError> { Ok(()) } -/// Remaining time for one request, capped at the per-request timeout. -fn request_timeout(io: &impl RequestIo, deadline: Instant) -> Duration { - deadline - .saturating_duration_since(io.now()) - .min(RESPONSE_TIMEOUT) -} - /// The reply `report` gives to the request, or `None` if it answers something /// else. A HID++ 2.0 reply echoes the request's function and software ID, so /// matching that byte too rejects stale reports and replies meant for another @@ -315,10 +300,14 @@ impl Device<'_, Io> { let [feature_high, feature_low] = feature_id.to_be_bytes(); let reply = self.request(FEATURE_ROOT, 0, [feature_high, feature_low, 0], timeout)?; Ok(match reply { - Reply::Response(report) => match parse_feature_index(report.bytes())? { - Some(feature_index) => FeatureLookup::Index(feature_index), - None => FeatureLookup::Unsupported, - }, + Reply::Response(report) => { + let bytes = report.bytes(); + ensure_length(bytes, 5)?; + match bytes[4] { + 0 => FeatureLookup::Unsupported, + index => FeatureLookup::Index(index), + } + } Reply::DeviceError => FeatureLookup::Unsupported, Reply::Offline => FeatureLookup::Offline, Reply::Silence => FeatureLookup::Silent, @@ -326,9 +315,13 @@ impl Device<'_, Io> { } fn find_battery_feature(&self, deadline: Instant) -> Result { - let unified = - self.lookup_feature(FEATURE_UNIFIED_BATTERY, request_timeout(self.io, deadline))?; - match unified { + let lookup = |feature_id| { + let timeout = deadline + .saturating_duration_since(self.io.now()) + .min(RESPONSE_TIMEOUT); + self.lookup_feature(feature_id, timeout) + }; + match lookup(FEATURE_UNIFIED_BATTERY)? { FeatureLookup::Index(feature_index) => { return Ok(Discovery::Found(BatteryFeature::Unified(feature_index))) } @@ -339,9 +332,7 @@ impl Device<'_, Io> { FeatureLookup::Unsupported => {} } - let legacy = - self.lookup_feature(FEATURE_BATTERY_STATUS, request_timeout(self.io, deadline))?; - Ok(match legacy { + Ok(match lookup(FEATURE_BATTERY_STATUS)? { FeatureLookup::Index(feature_index) => { Discovery::Found(BatteryFeature::Legacy(feature_index)) } @@ -413,29 +404,24 @@ fn candidate_interfaces(api: &HidApi) -> Vec<&hidapi::DeviceInfo> { pub fn read_battery(api: &HidApi) -> Result { let interfaces = candidate_interfaces(api) .into_iter() - .map(|info| move || api.open_path(info.path()).map_err(HidppError::Hid)); + .map(|info| move || api.open_path(info.path())); read_battery_from(interfaces, Instant::now) } /// A HID interface, opened on first use and reused across device indices. -enum Slot { - Unopened(Open), - Open(Io), - Failed, +struct Slot { + opener: Option, + io: Option, } -impl Result, Io> Slot { +impl Result, Io> Slot { /// The open HID interface, or `None` if it failed to open. Only the first /// failed open reports its error; later probes skip the slot. - fn open(&mut self) -> Result, HidppError> { - *self = match std::mem::replace(self, Self::Failed) { - Self::Unopened(open) => Self::Open(open()?), - slot => slot, - }; - Ok(match self { - Self::Open(io) => Some(io), - Self::Unopened(_) | Self::Failed => None, - }) + fn open(&mut self) -> Result, HidError> { + if let Some(open) = self.opener.take() { + self.io = Some(open()?); + } + Ok(self.io.as_ref()) } } @@ -443,12 +429,15 @@ impl Result, Io> Slot { /// before the unlikely ones on the first, then read the first battery feature /// found. `interfaces` open the candidate HID interfaces in probe order. fn read_battery_from( - interfaces: impl IntoIterator Result>, + interfaces: impl IntoIterator Result>, now: impl Fn() -> Instant, ) -> Result { let mut slots = interfaces .into_iter() - .map(Slot::Unopened) + .map(|open| Slot { + opener: Some(open), + io: None, + }) .collect::>(); let deadline = now() + DISCOVERY_BUDGET; let mut offline = false; @@ -462,7 +451,7 @@ fn read_battery_from( Ok(Some(io)) => io, Ok(None) => continue, Err(error) => { - last_error = Some(error); + last_error = Some(error.into()); continue; } }; @@ -494,855 +483,4 @@ fn read_battery_from( } #[cfg(test)] -mod tests { - use std::cell::{Cell, RefCell}; - use std::collections::VecDeque; - use std::iter; - use std::rc::Rc; - - use super::*; - - #[cfg(target_os = "linux")] - #[test] - fn linux_permission_errors_explain_device_access_setup() { - for error in [ - HidError::IoError { - error: std::io::Error::from(std::io::ErrorKind::PermissionDenied), - }, - HidError::HidApiError { - message: String::from( - "failed to open device with path /dev/hidraw4: Permission denied (os error 13)", - ), - }, - ] { - let message = HidppError::Hid(error).to_string(); - assert!(message.contains("sudo /path/to/gbat"), "{message}"); - } - let message = HidppError::Hid(HidError::HidApiError { - message: String::from( - "failed to open device with path /dev/hidraw4: No such file or directory (os error 2)", - ), - }) - .to_string(); - assert!(!message.contains("sudo /path/to/gbat"), "{message}"); - } - - const UNIFIED_LOOKUP: [u8; 7] = unified_lookup(1); - const LEGACY_LOOKUP: [u8; 7] = [REPORT_ID_SHORT, 1, 0, 0x0F, 0x10, 0x00, 0]; - const UNIFIED_QUERY: [u8; 7] = [REPORT_ID_SHORT, 1, 5, 0x1F, 0, 0, 0]; - const LEGACY_QUERY: [u8; 7] = [REPORT_ID_SHORT, 1, 6, 0x0F, 0, 0, 0]; - const UNIFIED_FEATURE: [u8; 7] = [REPORT_ID_SHORT, 1, 0, 0x0F, 5, 0, 0]; - const LEGACY_FEATURE: [u8; 7] = [REPORT_ID_SHORT, 1, 0, 0x0F, 6, 0, 0]; - const LEGACY_STATUS: [u8; 7] = [REPORT_ID_SHORT, 1, 6, 0x0F, 42, 0, 0x81]; - const LEGACY_READING: Reading = Reading::Status(BatteryStatus { - level: 42, - charging: true, - }); - /// A unified status reply that lacks the charging byte. - const INCOMPLETE_UNIFIED: [u8; 7] = [REPORT_ID_SHORT, 1, 5, 0x1F, 99, 0, 0]; - const RECEIVER_OFFLINE: [u8; 7] = receiver_offline(1); - - const fn unified_lookup(device_index: u8) -> [u8; 7] { - [REPORT_ID_SHORT, device_index, 0, 0x0F, 0x10, 0x04, 0] - } - - // Captured from a LIGHTSPEED receiver while its paired mouse was off. - const fn receiver_offline(device_index: u8) -> [u8; 7] { - [REPORT_ID_SHORT, device_index, 0x8F, 0, 0x0F, 0x08, 0] - } - - fn report(bytes: &[u8]) -> Report { - let mut buffer = [0; REPORT_BUFFER_LEN]; - buffer[..bytes.len()].copy_from_slice(bytes); - Report { - buffer, - length: bytes.len(), - } - } - - fn status(level: u8, charging: bool) -> Reading { - Reading::Status(BatteryStatus { level, charging }) - } - - fn ms(millis: u64) -> Duration { - Duration::from_millis(millis) - } - - /// One expected I/O call, its result, and how far it advances the clock. - #[derive(Debug)] - enum ScriptStep { - Read { - timeout_ms: i32, - result: Result, HidError>, - advance: Duration, - }, - Write { - report: Vec, - result: Result<(), HidError>, - advance: Duration, - }, - } - - impl ScriptStep { - fn read(timeout_ms: i32, report: &[u8]) -> Self { - Self::Read { - timeout_ms, - result: Ok(report.to_vec()), - advance: Duration::ZERO, - } - } - - /// A nonblocking read while flushing before a request. - fn flush(report: &[u8]) -> Self { - Self::read(0, report) - } - - fn write(report: &[u8]) -> Self { - Self::Write { - report: report.to_vec(), - result: Ok(()), - advance: Duration::ZERO, - } - } - - fn silence(timeout_ms: i32, advance: Duration) -> Self { - Self::read(timeout_ms, &[]).after(advance) - } - - fn after(mut self, elapsed: Duration) -> Self { - let (Self::Read { advance, .. } | Self::Write { advance, .. }) = &mut self; - *advance = elapsed; - self - } - } - - /// A report read with the full response timeout. - fn reply(report: &[u8]) -> ScriptStep { - ScriptStep::read(1_500, report) - } - - /// The full response timeout passing without a report. - fn no_reply() -> ScriptStep { - ScriptStep::silence(1_500, RESPONSE_TIMEOUT) - } - - /// Flush an empty queue, write `request`, then read `replies`. - fn exchange(request: &[u8], replies: impl IntoIterator) -> Vec { - let mut steps = vec![ScriptStep::flush(&[]), ScriptStep::write(request)]; - steps.extend(replies); - steps - } - - /// Device index 1 reports the unified battery feature at index 5. - fn found_unified() -> Vec { - exchange(&UNIFIED_LOOKUP, [reply(&UNIFIED_FEATURE)]) - } - - fn offline_probe(device_index: u8) -> Vec { - exchange( - &unified_lookup(device_index), - [reply(&receiver_offline(device_index))], - ) - } - - fn silent_probe(device_index: u8) -> Vec { - exchange(&unified_lookup(device_index), [no_reply()]) - } - - /// Plays back an exact sequence of I/O calls on a virtual clock. Any call - /// the script does not expect fails the test, and so does any step still - /// unplayed when the script is dropped. - struct ScriptedIo { - // Sharing this cell keeps every scripted HID interface on one timeline. - clock: Rc>, - steps: RefCell>, - } - - impl ScriptedIo { - fn next_step(&self, call: &str) -> ScriptStep { - self.steps - .borrow_mut() - .pop_front() - .unwrap_or_else(|| panic!("script exhausted during {call}")) - } - } - - impl Drop for ScriptedIo { - fn drop(&mut self) { - if !std::thread::panicking() { - let steps = self.steps.get_mut(); - assert!(steps.is_empty(), "unplayed script steps: {steps:?}"); - } - } - } - - impl RequestIo for ScriptedIo { - fn write(&self, report: &[u8]) -> Result<(), HidError> { - let ScriptStep::Write { - report: expected, - result, - advance, - } = self.next_step("write") - else { - panic!("unexpected write of {report:02X?}"); - }; - assert_eq!(report, expected, "unexpected request bytes"); - self.clock.set(self.now() + advance); - result - } - - fn read_timeout(&self, buffer: &mut [u8], timeout_ms: i32) -> Result { - let ScriptStep::Read { - timeout_ms: expected, - result, - advance, - } = self.next_step("read") - else { - panic!("unexpected read with a {timeout_ms} ms timeout"); - }; - assert_eq!(timeout_ms, expected, "unexpected read timeout"); - self.clock.set(self.now() + advance); - let report = result?; - buffer[..report.len()].copy_from_slice(&report); - Ok(report.len()) - } - - fn now(&self) -> Instant { - self.clock.get() - } - } - - /// A scripted HID interface: the I/O it plays once opened, or the error - /// that opening it fails with. - type Interface = Result, HidError>; - - /// One HID interface that plays `parts` in order. - fn script(parts: impl IntoIterator>) -> Interface { - Ok(parts.into_iter().flatten().collect()) - } - - /// Read the battery through scripted HID interfaces on one virtual clock, - /// returning the outcome and the virtual time it took. - fn read_scripted( - interfaces: impl IntoIterator, - ) -> (Result, Duration) { - let start = Instant::now(); - let clock = Rc::new(Cell::new(start)); - let openers = interfaces.into_iter().map(|interface| { - let clock = Rc::clone(&clock); - move || { - Ok(ScriptedIo { - clock, - steps: RefCell::new(interface?.into()), - }) - } - }); - let result = read_battery_from(openers, || clock.get()); - (result, clock.get() - start) - } - - /// Read the battery through one scripted HID interface. - fn read_one( - parts: impl IntoIterator>, - ) -> (Result, Duration) { - read_scripted([script(parts)]) - } - - fn assert_short_response( - result: Result, - minimum: usize, - actual: usize, - ) { - let Err(error @ HidppError::ShortResponse { .. }) = result else { - panic!("expected a short response error, got {result:?}"); - }; - assert_eq!( - error.to_string(), - format!("short HID++ response: expected at least {minimum} bytes, got {actual}") - ); - } - - #[test] - fn classifies_reports_against_the_request() { - // The request goes to device index 1, feature 5, function 1, software ID 0x0F. - let short_reply = [REPORT_ID_SHORT, 1, 5, 0x1F, 78, 0, 0]; - let long_reply = [REPORT_ID_LONG, 1, 5, 0x1F, 78, 0, 0, 1]; - let cases: [(&[u8], Option); 14] = [ - (&short_reply, Some(Reply::Response(report(&short_reply)))), - (&long_reply, Some(Reply::Response(report(&long_reply)))), - (&[0x12, 1, 5, 0x1F, 78, 0, 0], None), - (&[REPORT_ID_SHORT, 2, 5, 0x1F, 78, 0, 0], None), - (&[REPORT_ID_SHORT, 1, 6, 0x1F, 78, 0, 0], None), - (&[REPORT_ID_SHORT, 1, 5, 0x0F, 78, 0, 0], None), - (&[REPORT_ID_SHORT, 1, 5, 0x1E, 78, 0, 0], None), - (&[REPORT_ID_SHORT, 1], None), - ( - &[REPORT_ID_SHORT, 1, 0x8F, 5, 0x1F, 0x08, 0], - Some(Reply::Offline), - ), - ( - &[REPORT_ID_SHORT, 1, 0x8F, 5, 0x1F, 0x02, 0], - Some(Reply::DeviceError), - ), - // Only the receiver's HID++ 1.0 error means no connected device. - ( - &[REPORT_ID_LONG, 1, 0xFF, 5, 0x1F, 0x08, 0], - Some(Reply::DeviceError), - ), - // Errors must echo the request too. - (&[REPORT_ID_SHORT, 1, 0x8F, 6, 0x1F, 0x08, 0], None), - (&[REPORT_ID_SHORT, 1, 0xFF, 5, 0x0F, 0x02, 0], None), - (&[REPORT_ID_SHORT, 1, 0x8E, 5, 0x1F, 0x02, 0], None), - ]; - for (bytes, expected) in cases { - assert_eq!( - match_report(report(bytes), 1, 5, 0x1F), - expected, - "report {bytes:02X?}" - ); - } - } - - mod discovery { - use super::*; - - #[test] - fn skips_unrelated_reports_and_errors_until_the_matching_reply() { - let (result, _) = read_one([ - exchange( - &UNIFIED_LOOKUP, - [ - reply(&[REPORT_ID_SHORT, 2, 0, 0x0F, 9, 0, 0]), - reply(&[REPORT_ID_SHORT, 1, 0, 0x1F, 9, 0, 0]), - reply(&[REPORT_ID_SHORT, 1, 0x8F, 0, 0x0E, 0x08, 0]), - reply(&UNIFIED_FEATURE), - ], - ), - exchange( - &UNIFIED_QUERY, - [ - reply(&[REPORT_ID_LONG, 1, 5, 0x0F, 12, 0, 0, 0]), - reply(&[REPORT_ID_SHORT, 1, 0xFF, 6, 0x1F, 0x02, 0]), - reply(&[REPORT_ID_LONG, 1, 5, 0x1F, 78, 0, 0, 1]), - ], - ), - ]); - - assert_eq!(result.unwrap(), status(78, true)); - } - - #[test] - fn reads_long_reports_after_flushing_stale_ones() { - for (device_index, feature_index, level, flags, charging) in - [(1, 5, 78, 0x81, true), (0xFF, 9, 42, 0x02, false)] - { - let long_report = |level, flags| { - let mut report = [0; REPORT_BUFFER_LEN]; - report[..8].copy_from_slice(&[ - REPORT_ID_LONG, - device_index, - feature_index, - 0x1F, - level, - 0, - 0, - flags, - ]); - report - }; - // Direct USB is only probed after the receiver slot. - let earlier_probes = if device_index == 1 { - vec![] - } else { - offline_probe(1) - }; - let (result, _) = read_one([ - earlier_probes, - vec![ScriptStep::flush(&[ - REPORT_ID_SHORT, - device_index, - 0, - 0x0F, - 99, - 0, - 0, - ])], - exchange( - &unified_lookup(device_index), - [reply(&[ - REPORT_ID_SHORT, - device_index, - 0, - 0x0F, - feature_index, - 0, - 0, - ])], - ), - vec![ScriptStep::flush(&long_report(8, 0))], - exchange( - &[REPORT_ID_SHORT, device_index, feature_index, 0x1F, 0, 0, 0], - [reply(&long_report(level, flags))], - ), - ]); - - assert_eq!(result.unwrap(), status(level, charging)); - } - } - - #[test] - fn an_unsupported_unified_feature_selects_and_reads_legacy() { - for unified_reply in [ - [REPORT_ID_SHORT, 1, 0, 0x0F, 0, 0, 0], - [REPORT_ID_SHORT, 1, ERROR_MARKER_HIDPP10, 0, 0x0F, 0x02, 0], - [REPORT_ID_SHORT, 1, ERROR_MARKER_HIDPP20, 0, 0x0F, 0x02, 0], - [REPORT_ID_LONG, 1, ERROR_MARKER_HIDPP20, 0, 0x0F, 0x08, 0], - ] { - // Reading the selected legacy feature skips the unified query. - let (result, _) = read_one([ - exchange(&UNIFIED_LOOKUP, [reply(&unified_reply)]), - exchange(&LEGACY_LOOKUP, [reply(&LEGACY_FEATURE)]), - exchange(&LEGACY_QUERY, [reply(&LEGACY_STATUS)]), - ]); - - assert_eq!(result.unwrap(), LEGACY_READING); - } - } - - #[test] - fn an_offline_receiver_ends_each_probe_without_waiting_or_legacy_lookup() { - let reply_delay = ms(17); - let (result, elapsed) = read_one(DEVICE_INDEX_CANDIDATES.map(|device_index| { - exchange( - &unified_lookup(device_index), - [reply(&receiver_offline(device_index)).after(reply_delay)], - ) - })); - - assert!(matches!(result, Ok(Reading::Offline))); - assert_eq!(elapsed, reply_delay * 7); - } - - #[test] - fn continues_from_an_offline_receiver_to_direct_usb() { - let (result, _) = read_one([ - offline_probe(1), - exchange( - &unified_lookup(0xFF), - [reply(&[REPORT_ID_SHORT, 0xFF, 0, 0x0F, 9, 0, 0])], - ), - exchange( - &[REPORT_ID_SHORT, 0xFF, 9, 0x1F, 0, 0, 0], - [reply(&[REPORT_ID_LONG, 0xFF, 9, 0x1F, 53, 0, 0, 1])], - ), - ]); - - assert_eq!(result.unwrap(), status(53, true)); - } - - #[test] - fn checks_likely_indices_on_every_interface_first() { - let (result, _) = read_scripted([ - script([offline_probe(1), offline_probe(0xFF)]), - script([ - offline_probe(1), - exchange( - &unified_lookup(0xFF), - [reply(&[REPORT_ID_SHORT, 0xFF, 0, 0x0F, 9, 0, 0])], - ), - exchange( - &[REPORT_ID_SHORT, 0xFF, 9, 0x1F, 0, 0, 0], - [reply(&[REPORT_ID_LONG, 0xFF, 9, 0x1F, 53, 0, 0, 1])], - ), - ]), - ]); - - assert_eq!(result.unwrap(), status(53, true)); - } - - #[test] - fn offline_outranks_later_errors_while_preserving_candidate_order() { - for offline_first in [true, false] { - let (result, _) = read_one(DEVICE_INDEX_CANDIDATES.map(|device_index| { - let truncated = [REPORT_ID_SHORT, device_index, 0, 0x0F]; - let answer = if offline_first && device_index == 1 { - reply(&RECEIVER_OFFLINE) - } else { - reply(&truncated) - }; - exchange(&unified_lookup(device_index), [answer]) - })); - - if offline_first { - assert!(matches!(result, Ok(Reading::Offline))); - } else { - assert_short_response(result, 5, 4); - } - } - } - - #[test] - fn an_interface_that_fails_to_open_is_skipped() { - let unopenable = || Err(HidError::InitializationError); - - // A later HID interface that finds the battery hides the open error. - let (result, _) = read_scripted([ - unopenable(), - script([ - found_unified(), - exchange( - &UNIFIED_QUERY, - [reply(&[REPORT_ID_LONG, 1, 5, 0x1F, 78, 0, 0, 1])], - ), - ]), - ]); - assert_eq!(result.unwrap(), status(78, true)); - - // So does an offline receiver. - let (result, _) = read_scripted([ - unopenable(), - script(DEVICE_INDEX_CANDIDATES.map(offline_probe)), - ]); - assert!(matches!(result, Ok(Reading::Offline))); - - // Otherwise the open error explains the failure. - let (result, _) = - read_scripted([unopenable(), script([1, 0xFF, 2, 3].map(silent_probe))]); - assert!(matches!( - result, - Err(HidppError::Hid(HidError::InitializationError)) - )); - } - } - - mod request_timing { - use super::*; - - #[test] - fn continuous_queued_reports_stop_flushing_at_the_window_boundary() { - for last_read_ms in [1, 2] { - let stale = [REPORT_ID_SHORT, 1, 5, 0x1F, 8, 0, 0, 0]; - let (result, elapsed) = read_one([ - found_unified(), - vec![ - ScriptStep::flush(&stale).after(ms(100)), - ScriptStep::flush(&stale).after(ms(99)), - ScriptStep::flush(&stale).after(ms(last_read_ms)), - ScriptStep::write(&UNIFIED_QUERY), - reply(&[REPORT_ID_SHORT, 1, 5, 0x1F, 78, 0, 0, 1]), - ], - ]); - - assert_eq!(result.unwrap(), status(78, true)); - assert_eq!(elapsed, ms(199 + last_read_ms)); - } - } - - #[test] - fn unrelated_reports_consume_the_original_response_wait() { - let (result, elapsed) = read_one( - iter::once(exchange( - &UNIFIED_LOOKUP, - [ - ScriptStep::read(1_500, &[REPORT_ID_SHORT, 2, 0, 0x0F, 5, 0, 0]) - .after(ms(500)), - ScriptStep::read(1_000, &[REPORT_ID_SHORT, 1, 0, 0x0E, 5, 0, 0]) - .after(ms(750)), - ScriptStep::silence(250, ms(250)), - ], - )) - .chain( - DEVICE_INDEX_CANDIDATES[1..] - .iter() - .copied() - .map(offline_probe), - ), - ); - - assert!(matches!(result, Ok(Reading::Offline))); - assert_eq!(elapsed, RESPONSE_TIMEOUT); - } - - #[test] - fn fractional_milliseconds_are_truncated_without_ending_the_wait_early() { - let unrelated = [REPORT_ID_SHORT, 2, 0, 0x0F, 5, 0, 0]; - let remaining = Duration::from_micros(2_500); - let (result, elapsed) = read_one([ - // The receiver answers so late that only 2.5 ms of the budget remain. - exchange( - &UNIFIED_LOOKUP, - [reply(&RECEIVER_OFFLINE).after(DISCOVERY_BUDGET - remaining)], - ), - exchange( - &unified_lookup(0xFF), - [ - ScriptStep::read(2, &unrelated).after(Duration::from_micros(1_750)), - ScriptStep::read(0, &unrelated).after(Duration::from_micros(500)), - ScriptStep::silence(0, Duration::from_micros(250)), - ], - ), - ]); - - assert!(matches!(result, Ok(Reading::Offline))); - assert_eq!(elapsed, DISCOVERY_BUDGET); - } - - #[test] - fn a_lookup_with_no_budget_left_ignores_an_unrelated_report() { - let (result, _) = read_one([ - exchange( - &UNIFIED_LOOKUP, - [reply(&[REPORT_ID_SHORT, 1, 0, 0x0F, 0, 0, 0]).after(DISCOVERY_BUDGET)], - ), - exchange( - &LEGACY_LOOKUP, - [ScriptStep::read(0, &[REPORT_ID_SHORT, 2, 0, 0x0F, 5, 0, 0])], - ), - ]); - - assert!(matches!(result, Ok(Reading::NotFound))); - } - - #[test] - fn discovery_overhead_preserves_the_wait_and_later_battery_request_durations() { - let (result, elapsed) = read_scripted([ - // Only 400 ms of the budget remain when the next HID interface - // is probed. - script([exchange( - &UNIFIED_LOOKUP, - [reply(&RECEIVER_OFFLINE).after(ms(5_600))], - )]), - script([ - vec![ - ScriptStep::flush(&[REPORT_ID_SHORT, 1, 0, 0x0F, 99, 0, 0]).after(ms(150)), - ScriptStep::flush(&[]), - ScriptStep::write(&UNIFIED_LOOKUP).after(ms(100)), - ScriptStep::read(400, &UNIFIED_FEATURE).after(ms(400)), - ], - exchange(&UNIFIED_QUERY, [no_reply()]), - exchange(&LEGACY_LOOKUP, [reply(&LEGACY_FEATURE).after(ms(1_500))]), - exchange(&LEGACY_QUERY, [reply(&LEGACY_STATUS).after(ms(1_500))]), - ]), - ]); - - // A matching reply at the response deadline is accepted, and the - // battery requests after it still get their full timeouts. - assert_eq!(result.unwrap(), LEGACY_READING); - assert_eq!(elapsed, ms(5_600 + 650 + 3 * 1_500)); - } - - #[test] - fn silence_skips_the_legacy_lookup_and_the_budget_ends_discovery() { - let (result, elapsed) = read_one([ - exchange( - &UNIFIED_LOOKUP, - [reply(&[REPORT_ID_SHORT, 2, 0, 0x0F, 5, 0, 0]), no_reply()], - ), - silent_probe(0xFF), - silent_probe(2), - silent_probe(3), - ]); - - assert!(matches!(result, Ok(Reading::NotFound))); - assert_eq!(elapsed, DISCOVERY_BUDGET); - } - - #[test] - fn a_probe_can_finish_its_legacy_lookup_after_the_discovery_budget_is_used() { - let (result, elapsed) = read_one([ - silent_probe(1), - silent_probe(0xFF), - silent_probe(2), - exchange( - &unified_lookup(3), - [reply(&[REPORT_ID_SHORT, 3, 0, 0x0F, 0, 0, 0]).after(ms(1_500))], - ), - exchange( - &[REPORT_ID_SHORT, 3, 0, 0x0F, 0x10, 0x00, 0], - [ScriptStep::read(0, &[REPORT_ID_SHORT, 3, 0, 0x0F, 6, 0, 0])], - ), - exchange( - &[REPORT_ID_SHORT, 3, 6, 0x0F, 0, 0, 0], - [reply(&[REPORT_ID_SHORT, 3, 6, 0x0F, 42, 0, 0x81])], - ), - ]); - - assert_eq!(result.unwrap(), LEGACY_READING); - assert_eq!(elapsed, DISCOVERY_BUDGET); - } - } - - mod battery_recovery { - use super::*; - - /// Find the unified feature on device index 1, then read it with `parts`. - fn read_unified( - parts: impl IntoIterator>, - ) -> Result { - read_one(iter::once(found_unified()).chain(parts)).0 - } - - /// Look up the legacy feature, then read its status with `status_reply`. - fn legacy_fallback(status_reply: ScriptStep) -> Vec { - let mut steps = exchange(&LEGACY_LOOKUP, [reply(&LEGACY_FEATURE)]); - steps.extend(exchange(&LEGACY_QUERY, [status_reply])); - steps - } - - #[test] - fn incomplete_unified_replies_recover_with_a_legacy_status() { - // Every matching prefix still lacks the unified charging byte. - for length in 4..=INCOMPLETE_UNIFIED.len() { - let result = read_unified([ - exchange(&UNIFIED_QUERY, [reply(&INCOMPLETE_UNIFIED[..length])]), - legacy_fallback(reply(&LEGACY_STATUS)), - ]); - - assert_eq!(result.unwrap(), LEGACY_READING); - } - } - - #[test] - fn offline_device_error_and_silence_recover_with_a_legacy_status() { - for unified_reply in [ - reply(&[REPORT_ID_SHORT, 1, ERROR_MARKER_HIDPP10, 5, 0x1F, 0x08, 0]), - reply(&[REPORT_ID_LONG, 1, ERROR_MARKER_HIDPP20, 5, 0x1F, 0x02]), - no_reply(), - ] { - let result = read_unified([ - exchange(&UNIFIED_QUERY, [unified_reply]), - legacy_fallback(reply(&LEGACY_STATUS)), - ]); - - assert_eq!(result.unwrap(), LEGACY_READING); - } - } - - #[test] - fn missing_results_from_both_features_return_no_battery_status() { - let result = read_unified([ - exchange(&UNIFIED_QUERY, [no_reply()]), - legacy_fallback(reply(&[ - REPORT_ID_SHORT, - 1, - ERROR_MARKER_HIDPP10, - 6, - 0x0F, - 0x08, - 0, - ])), - ]); - - assert_eq!(result.unwrap(), Reading::NoStatus); - } - - #[test] - fn a_failed_legacy_lookup_preserves_the_unified_short_response() { - for lookup_reply in [ - reply(&[REPORT_ID_SHORT, 1, 0, 0x0F, 0, 0, 0]), - reply(&[REPORT_ID_SHORT, 1, ERROR_MARKER_HIDPP10, 0, 0x0F, 0x08, 0]), - reply(&[REPORT_ID_LONG, 1, ERROR_MARKER_HIDPP20, 0, 0x0F, 0x02]), - reply(&[REPORT_ID_SHORT, 1, 0, 0x0F]), - no_reply(), - ] { - let result = read_unified([ - exchange(&UNIFIED_QUERY, [reply(&INCOMPLETE_UNIFIED)]), - exchange(&LEGACY_LOOKUP, [lookup_reply]), - ]); - - assert_short_response(result, 8, 7); - } - } - - #[test] - fn a_failed_legacy_status_preserves_the_unified_short_response() { - for status_reply in [ - reply(&[REPORT_ID_SHORT, 1, 6, 0x0F, 42, 0]), - reply(&[REPORT_ID_SHORT, 1, ERROR_MARKER_HIDPP10, 6, 0x0F, 0x08, 0]), - reply(&[REPORT_ID_LONG, 1, ERROR_MARKER_HIDPP20, 6, 0x0F, 0x02]), - no_reply(), - ] { - let result = read_unified([ - exchange(&UNIFIED_QUERY, [reply(&INCOMPLETE_UNIFIED)]), - legacy_fallback(status_reply), - ]); - - assert_short_response(result, 8, 7); - } - } - - #[test] - fn a_missing_unified_result_does_not_hide_a_legacy_short_response() { - let result = read_unified([ - exchange(&UNIFIED_QUERY, [no_reply()]), - legacy_fallback(reply(&[REPORT_ID_SHORT, 1, 6, 0x0F, 42, 0])), - ]); - - assert_short_response(result, 7, 6); - } - - #[derive(Debug, Clone, Copy)] - enum IoFailure { - FlushRead, - Write, - ResponseRead, - } - - impl IoFailure { - const ALL: [Self; 3] = [Self::FlushRead, Self::Write, Self::ResponseRead]; - - /// The script for `request` up to and including this failure. - fn steps(self, request: &[u8]) -> Vec { - let failed_read = |timeout_ms| ScriptStep::Read { - timeout_ms, - result: Err(HidError::InitializationError), - advance: Duration::ZERO, - }; - match self { - Self::FlushRead => vec![failed_read(0)], - Self::Write => vec![ - ScriptStep::flush(&[]), - ScriptStep::Write { - report: request.to_vec(), - result: Err(HidError::InitializationError), - advance: Duration::ZERO, - }, - ], - Self::ResponseRead => exchange(request, [failed_read(1_500)]), - } - } - - fn assert_error(self, result: Result) { - assert!( - matches!(result, Err(HidppError::Hid(HidError::InitializationError))), - "{self:?} produced {result:?}" - ); - } - } - - // The scripts end at the failure, so these also check that a failed - // read ends discovery instead of probing the next device index. - #[test] - fn unified_io_failures_stop_without_legacy_recovery() { - for failure in IoFailure::ALL { - failure.assert_error(read_unified([failure.steps(&UNIFIED_QUERY)])); - } - } - - #[test] - fn legacy_io_failures_replace_the_unified_short_response() { - for failure in IoFailure::ALL { - failure.assert_error(read_unified([ - exchange(&UNIFIED_QUERY, [reply(&INCOMPLETE_UNIFIED)]), - failure.steps(&LEGACY_LOOKUP), - ])); - - failure.assert_error(read_unified([ - exchange(&UNIFIED_QUERY, [reply(&INCOMPLETE_UNIFIED)]), - exchange(&LEGACY_LOOKUP, [reply(&LEGACY_FEATURE)]), - failure.steps(&LEGACY_QUERY), - ])); - } - } - } -} +mod tests; diff --git a/src/hidpp/tests.rs b/src/hidpp/tests.rs new file mode 100644 index 0000000..08620eb --- /dev/null +++ b/src/hidpp/tests.rs @@ -0,0 +1,828 @@ +use std::cell::{Cell, RefCell}; +use std::collections::VecDeque; +use std::iter; + +use super::*; + +#[cfg(target_os = "linux")] +#[test] +fn linux_permission_errors_explain_device_access_setup() { + for error in [ + HidError::IoError { + error: std::io::Error::from(std::io::ErrorKind::PermissionDenied), + }, + HidError::HidApiError { + message: String::from( + "failed to open device with path /dev/hidraw4: Permission denied (os error 13)", + ), + }, + ] { + let message = HidppError::Hid(error).to_string(); + assert!(message.contains("sudo /path/to/gbat"), "{message}"); + } + let message = HidppError::Hid(HidError::HidApiError { + message: String::from( + "failed to open device with path /dev/hidraw4: No such file or directory (os error 2)", + ), + }) + .to_string(); + assert!(!message.contains("sudo /path/to/gbat"), "{message}"); +} + +const UNIFIED_LOOKUP: [u8; 7] = unified_lookup(1); +const LEGACY_LOOKUP: [u8; 7] = [REPORT_ID_SHORT, 1, 0, 0x0F, 0x10, 0x00, 0]; +const UNIFIED_QUERY: [u8; 7] = [REPORT_ID_SHORT, 1, 5, 0x1F, 0, 0, 0]; +const LEGACY_QUERY: [u8; 7] = [REPORT_ID_SHORT, 1, 6, 0x0F, 0, 0, 0]; +const UNIFIED_FEATURE: [u8; 7] = [REPORT_ID_SHORT, 1, 0, 0x0F, 5, 0, 0]; +const LEGACY_FEATURE: [u8; 7] = [REPORT_ID_SHORT, 1, 0, 0x0F, 6, 0, 0]; +const LEGACY_STATUS: [u8; 7] = [REPORT_ID_SHORT, 1, 6, 0x0F, 42, 0, 0x81]; +const LEGACY_READING: Reading = Reading::Status(BatteryStatus { + level: 42, + charging: true, +}); +/// A unified status reply that lacks the charging byte. +const INCOMPLETE_UNIFIED: [u8; 7] = [REPORT_ID_SHORT, 1, 5, 0x1F, 99, 0, 0]; +const RECEIVER_OFFLINE: [u8; 7] = receiver_offline(1); + +const fn unified_lookup(device_index: u8) -> [u8; 7] { + [REPORT_ID_SHORT, device_index, 0, 0x0F, 0x10, 0x04, 0] +} + +// Captured from a LIGHTSPEED receiver while its paired mouse was off. +const fn receiver_offline(device_index: u8) -> [u8; 7] { + [REPORT_ID_SHORT, device_index, 0x8F, 0, 0x0F, 0x08, 0] +} + +fn report(bytes: &[u8]) -> Report { + let mut buffer = [0; REPORT_BUFFER_LEN]; + buffer[..bytes.len()].copy_from_slice(bytes); + Report { + buffer, + length: bytes.len(), + } +} + +fn status(level: u8, charging: bool) -> Reading { + Reading::Status(BatteryStatus { level, charging }) +} + +fn ms(millis: u64) -> Duration { + Duration::from_millis(millis) +} + +/// One expected I/O call, its result, and how far it advances the clock. +#[derive(Debug)] +enum ScriptStep { + Read { + timeout_ms: i32, + result: Result, HidError>, + advance: Duration, + }, + Write { + report: Vec, + result: Result<(), HidError>, + advance: Duration, + }, +} + +impl ScriptStep { + fn read(timeout_ms: i32, report: &[u8]) -> Self { + Self::Read { + timeout_ms, + result: Ok(report.to_vec()), + advance: Duration::ZERO, + } + } + + /// A nonblocking read while flushing before a request. + fn flush(report: &[u8]) -> Self { + Self::read(0, report) + } + + fn write(report: &[u8]) -> Self { + Self::Write { + report: report.to_vec(), + result: Ok(()), + advance: Duration::ZERO, + } + } + + fn silence(timeout_ms: i32, advance: Duration) -> Self { + Self::read(timeout_ms, &[]).after(advance) + } + + fn after(mut self, elapsed: Duration) -> Self { + let (Self::Read { advance, .. } | Self::Write { advance, .. }) = &mut self; + *advance = elapsed; + self + } +} + +/// A report read with the full response timeout. +fn reply(report: &[u8]) -> ScriptStep { + ScriptStep::read(1_500, report) +} + +/// The full response timeout passing without a report. +fn no_reply() -> ScriptStep { + ScriptStep::silence(1_500, RESPONSE_TIMEOUT) +} + +/// Flush an empty queue, write `request`, then read `replies`. +fn exchange(request: &[u8], replies: impl IntoIterator) -> Vec { + let mut steps = vec![ScriptStep::flush(&[]), ScriptStep::write(request)]; + steps.extend(replies); + steps +} + +/// Device index 1 reports the unified battery feature at index 5. +fn found_unified() -> Vec { + exchange(&UNIFIED_LOOKUP, [reply(&UNIFIED_FEATURE)]) +} + +fn offline_probe(device_index: u8) -> Vec { + exchange( + &unified_lookup(device_index), + [reply(&receiver_offline(device_index))], + ) +} + +fn silent_probe(device_index: u8) -> Vec { + exchange(&unified_lookup(device_index), [no_reply()]) +} + +/// Plays back an exact sequence of I/O calls on a virtual clock. Any call +/// the script does not expect fails the test, and so does any step still +/// unplayed when the script is dropped. +struct ScriptedIo<'a> { + clock: &'a Cell, + steps: RefCell>, +} + +impl ScriptedIo<'_> { + fn next_step(&self, call: &str) -> ScriptStep { + self.steps + .borrow_mut() + .pop_front() + .unwrap_or_else(|| panic!("script exhausted during {call}")) + } +} + +impl Drop for ScriptedIo<'_> { + fn drop(&mut self) { + if !std::thread::panicking() { + let steps = self.steps.get_mut(); + assert!(steps.is_empty(), "unplayed script steps: {steps:?}"); + } + } +} + +impl RequestIo for ScriptedIo<'_> { + fn write(&self, report: &[u8]) -> Result<(), HidError> { + let ScriptStep::Write { + report: expected, + result, + advance, + } = self.next_step("write") + else { + panic!("unexpected write of {report:02X?}"); + }; + assert_eq!(report, expected, "unexpected request bytes"); + self.clock.set(self.now() + advance); + result + } + + fn read_timeout(&self, buffer: &mut [u8], timeout_ms: i32) -> Result { + let ScriptStep::Read { + timeout_ms: expected, + result, + advance, + } = self.next_step("read") + else { + panic!("unexpected read with a {timeout_ms} ms timeout"); + }; + assert_eq!(timeout_ms, expected, "unexpected read timeout"); + self.clock.set(self.now() + advance); + let report = result?; + buffer[..report.len()].copy_from_slice(&report); + Ok(report.len()) + } + + fn now(&self) -> Instant { + self.clock.get() + } +} + +/// A scripted HID interface: the I/O it plays once opened, or the error +/// that opening it fails with. +type Interface = Result, HidError>; + +/// One HID interface that plays `parts` in order. +fn script(parts: impl IntoIterator>) -> Interface { + Ok(parts.into_iter().flatten().collect()) +} + +/// Read the battery through scripted HID interfaces on one virtual clock, +/// returning the outcome and the virtual time it took. +fn read_scripted( + interfaces: impl IntoIterator, +) -> (Result, Duration) { + let start = Instant::now(); + let clock = Cell::new(start); + let openers = interfaces.into_iter().map(|interface| { + // Keep the script's drop check active even if its opener is skipped. + let scripted = interface.map(|steps| ScriptedIo { + clock: &clock, + steps: RefCell::new(steps.into()), + }); + move || scripted + }); + let result = read_battery_from(openers, || clock.get()); + (result, clock.get() - start) +} + +/// Read the battery through one scripted HID interface. +fn read_one( + parts: impl IntoIterator>, +) -> (Result, Duration) { + read_scripted([script(parts)]) +} + +fn assert_short_response( + result: Result, + minimum: usize, + actual: usize, +) { + let Err(error @ HidppError::ShortResponse { .. }) = result else { + panic!("expected a short response error, got {result:?}"); + }; + assert_eq!( + error.to_string(), + format!("short HID++ response: expected at least {minimum} bytes, got {actual}") + ); +} + +#[test] +fn classifies_reports_against_the_request() { + // The request goes to device index 1, feature 5, function 1, software ID 0x0F. + let short_reply = [REPORT_ID_SHORT, 1, 5, 0x1F, 78, 0, 0]; + let long_reply = [REPORT_ID_LONG, 1, 5, 0x1F, 78, 0, 0, 1]; + let cases: [(&[u8], Option); 14] = [ + (&short_reply, Some(Reply::Response(report(&short_reply)))), + (&long_reply, Some(Reply::Response(report(&long_reply)))), + (&[0x12, 1, 5, 0x1F, 78, 0, 0], None), + (&[REPORT_ID_SHORT, 2, 5, 0x1F, 78, 0, 0], None), + (&[REPORT_ID_SHORT, 1, 6, 0x1F, 78, 0, 0], None), + (&[REPORT_ID_SHORT, 1, 5, 0x0F, 78, 0, 0], None), + (&[REPORT_ID_SHORT, 1, 5, 0x1E, 78, 0, 0], None), + (&[REPORT_ID_SHORT, 1], None), + ( + &[REPORT_ID_SHORT, 1, 0x8F, 5, 0x1F, 0x08, 0], + Some(Reply::Offline), + ), + ( + &[REPORT_ID_SHORT, 1, 0x8F, 5, 0x1F, 0x02, 0], + Some(Reply::DeviceError), + ), + // Only the receiver's HID++ 1.0 error means no connected device. + ( + &[REPORT_ID_LONG, 1, 0xFF, 5, 0x1F, 0x08, 0], + Some(Reply::DeviceError), + ), + // Errors must echo the request too. + (&[REPORT_ID_SHORT, 1, 0x8F, 6, 0x1F, 0x08, 0], None), + (&[REPORT_ID_SHORT, 1, 0xFF, 5, 0x0F, 0x02, 0], None), + (&[REPORT_ID_SHORT, 1, 0x8E, 5, 0x1F, 0x02, 0], None), + ]; + for (bytes, expected) in cases { + assert_eq!( + match_report(report(bytes), 1, 5, 0x1F), + expected, + "report {bytes:02X?}" + ); + } +} + +mod discovery { + use super::*; + + #[test] + fn skips_unrelated_reports_and_errors_until_the_matching_reply() { + let (result, _) = read_one([ + exchange( + &UNIFIED_LOOKUP, + [ + reply(&[REPORT_ID_SHORT, 2, 0, 0x0F, 9, 0, 0]), + reply(&[REPORT_ID_SHORT, 1, 0, 0x1F, 9, 0, 0]), + reply(&[REPORT_ID_SHORT, 1, 0x8F, 0, 0x0E, 0x08, 0]), + reply(&UNIFIED_FEATURE), + ], + ), + exchange( + &UNIFIED_QUERY, + [ + reply(&[REPORT_ID_LONG, 1, 5, 0x0F, 12, 0, 0, 0]), + reply(&[REPORT_ID_SHORT, 1, 0xFF, 6, 0x1F, 0x02, 0]), + reply(&[REPORT_ID_LONG, 1, 5, 0x1F, 78, 0, 0, 1]), + ], + ), + ]); + + assert_eq!(result.unwrap(), status(78, true)); + } + + #[test] + fn reads_long_reports_after_flushing_stale_ones() { + for (device_index, feature_index, level, flags, charging) in + [(1, 5, 78, 0x81, true), (0xFF, 9, 42, 0x02, false)] + { + let long_report = |level, flags| { + let mut report = [0; REPORT_BUFFER_LEN]; + report[..8].copy_from_slice(&[ + REPORT_ID_LONG, + device_index, + feature_index, + 0x1F, + level, + 0, + 0, + flags, + ]); + report + }; + // Direct USB is only probed after the receiver slot. + let earlier_probes = if device_index == 1 { + vec![] + } else { + offline_probe(1) + }; + let (result, _) = read_one([ + earlier_probes, + vec![ScriptStep::flush(&[ + REPORT_ID_SHORT, + device_index, + 0, + 0x0F, + 99, + 0, + 0, + ])], + exchange( + &unified_lookup(device_index), + [reply(&[ + REPORT_ID_SHORT, + device_index, + 0, + 0x0F, + feature_index, + 0, + 0, + ])], + ), + vec![ScriptStep::flush(&long_report(8, 0))], + exchange( + &[REPORT_ID_SHORT, device_index, feature_index, 0x1F, 0, 0, 0], + [reply(&long_report(level, flags))], + ), + ]); + + assert_eq!(result.unwrap(), status(level, charging)); + } + } + + #[test] + fn an_unsupported_unified_feature_selects_and_reads_legacy() { + for unified_reply in [ + [REPORT_ID_SHORT, 1, 0, 0x0F, 0, 0, 0], + [REPORT_ID_SHORT, 1, ERROR_MARKER_HIDPP10, 0, 0x0F, 0x02, 0], + [REPORT_ID_SHORT, 1, ERROR_MARKER_HIDPP20, 0, 0x0F, 0x02, 0], + [REPORT_ID_LONG, 1, ERROR_MARKER_HIDPP20, 0, 0x0F, 0x08, 0], + ] { + // Reading the selected legacy feature skips the unified query. + let (result, _) = read_one([ + exchange(&UNIFIED_LOOKUP, [reply(&unified_reply)]), + exchange(&LEGACY_LOOKUP, [reply(&LEGACY_FEATURE)]), + exchange(&LEGACY_QUERY, [reply(&LEGACY_STATUS)]), + ]); + + assert_eq!(result.unwrap(), LEGACY_READING); + } + } + + #[test] + fn an_offline_receiver_ends_each_probe_without_waiting_or_legacy_lookup() { + let reply_delay = ms(17); + let expected_indices = [1, 0xFF, 2, 3, 4, 5, 6]; + let (result, elapsed) = read_one(expected_indices.map(|device_index| { + exchange( + &unified_lookup(device_index), + [reply(&receiver_offline(device_index)).after(reply_delay)], + ) + })); + + assert!(matches!(result, Ok(Reading::Offline))); + assert_eq!(elapsed, reply_delay * expected_indices.len() as u32); + } + + #[test] + fn checks_likely_indices_on_every_interface_first() { + let (result, _) = read_scripted([ + script([offline_probe(1), offline_probe(0xFF)]), + script([ + offline_probe(1), + exchange( + &unified_lookup(0xFF), + [reply(&[REPORT_ID_SHORT, 0xFF, 0, 0x0F, 9, 0, 0])], + ), + exchange( + &[REPORT_ID_SHORT, 0xFF, 9, 0x1F, 0, 0, 0], + [reply(&[REPORT_ID_LONG, 0xFF, 9, 0x1F, 53, 0, 0, 1])], + ), + ]), + ]); + + assert_eq!(result.unwrap(), status(53, true)); + } + + #[test] + fn offline_outranks_later_errors_while_preserving_candidate_order() { + for offline_first in [true, false] { + let (result, _) = read_one(DEVICE_INDEX_CANDIDATES.map(|device_index| { + let truncated = [REPORT_ID_SHORT, device_index, 0, 0x0F]; + let answer = if offline_first && device_index == 1 { + reply(&RECEIVER_OFFLINE) + } else { + reply(&truncated) + }; + exchange(&unified_lookup(device_index), [answer]) + })); + + if offline_first { + assert!(matches!(result, Ok(Reading::Offline))); + } else { + assert_short_response(result, 5, 4); + } + } + } + + #[test] + fn an_interface_that_fails_to_open_is_skipped() { + let unopenable = || Err(HidError::InitializationError); + + // A later HID interface that finds the battery hides the open error. + let (result, _) = read_scripted([ + unopenable(), + script([ + found_unified(), + exchange( + &UNIFIED_QUERY, + [reply(&[REPORT_ID_LONG, 1, 5, 0x1F, 78, 0, 0, 1])], + ), + ]), + ]); + assert_eq!(result.unwrap(), status(78, true)); + + // So does an offline receiver. + let (result, _) = read_scripted([ + unopenable(), + script(DEVICE_INDEX_CANDIDATES.map(offline_probe)), + ]); + assert!(matches!(result, Ok(Reading::Offline))); + + // Otherwise the open error explains the failure. + let (result, _) = read_scripted([unopenable(), script([1, 0xFF, 2, 3].map(silent_probe))]); + assert!(matches!( + result, + Err(HidppError::Hid(HidError::InitializationError)) + )); + } +} + +mod request_timing { + use super::*; + + #[test] + fn continuous_queued_reports_stop_flushing_at_the_window_boundary() { + for last_read_ms in [1, 2] { + let stale = [REPORT_ID_SHORT, 1, 5, 0x1F, 8, 0, 0, 0]; + let (result, elapsed) = read_one([ + found_unified(), + vec![ + ScriptStep::flush(&stale).after(ms(100)), + ScriptStep::flush(&stale).after(ms(99)), + ScriptStep::flush(&stale).after(ms(last_read_ms)), + ScriptStep::write(&UNIFIED_QUERY), + reply(&[REPORT_ID_SHORT, 1, 5, 0x1F, 78, 0, 0, 1]), + ], + ]); + + assert_eq!(result.unwrap(), status(78, true)); + assert_eq!(elapsed, ms(199 + last_read_ms)); + } + } + + #[test] + fn unrelated_reports_consume_the_original_response_wait() { + let (result, elapsed) = read_one( + iter::once(exchange( + &UNIFIED_LOOKUP, + [ + ScriptStep::read(1_500, &[REPORT_ID_SHORT, 2, 0, 0x0F, 5, 0, 0]).after(ms(500)), + ScriptStep::read(1_000, &[REPORT_ID_SHORT, 1, 0, 0x0E, 5, 0, 0]).after(ms(750)), + ScriptStep::silence(250, ms(250)), + ], + )) + .chain( + DEVICE_INDEX_CANDIDATES[1..] + .iter() + .copied() + .map(offline_probe), + ), + ); + + assert!(matches!(result, Ok(Reading::Offline))); + assert_eq!(elapsed, RESPONSE_TIMEOUT); + } + + #[test] + fn fractional_milliseconds_are_truncated_without_ending_the_wait_early() { + let unrelated = [REPORT_ID_SHORT, 2, 0, 0x0F, 5, 0, 0]; + let remaining = Duration::from_micros(2_500); + let (result, elapsed) = read_one([ + // The receiver answers so late that only 2.5 ms of the budget remain. + exchange( + &UNIFIED_LOOKUP, + [reply(&RECEIVER_OFFLINE).after(DISCOVERY_BUDGET - remaining)], + ), + exchange( + &unified_lookup(0xFF), + [ + ScriptStep::read(2, &unrelated).after(Duration::from_micros(1_750)), + ScriptStep::read(0, &unrelated).after(Duration::from_micros(500)), + ScriptStep::silence(0, Duration::from_micros(250)), + ], + ), + ]); + + assert!(matches!(result, Ok(Reading::Offline))); + assert_eq!(elapsed, DISCOVERY_BUDGET); + } + + #[test] + fn a_lookup_with_no_budget_left_ignores_an_unrelated_report() { + let (result, _) = read_one([ + exchange( + &UNIFIED_LOOKUP, + [reply(&[REPORT_ID_SHORT, 1, 0, 0x0F, 0, 0, 0]).after(DISCOVERY_BUDGET)], + ), + exchange( + &LEGACY_LOOKUP, + [ScriptStep::read(0, &[REPORT_ID_SHORT, 2, 0, 0x0F, 5, 0, 0])], + ), + ]); + + assert!(matches!(result, Ok(Reading::NotFound))); + } + + #[test] + fn discovery_overhead_preserves_the_wait_and_later_battery_request_durations() { + let (result, elapsed) = read_scripted([ + // Only 400 ms of the budget remain when the next HID interface + // is probed. + script([exchange( + &UNIFIED_LOOKUP, + [reply(&RECEIVER_OFFLINE).after(ms(5_600))], + )]), + script([ + vec![ + ScriptStep::flush(&[REPORT_ID_SHORT, 1, 0, 0x0F, 99, 0, 0]).after(ms(150)), + ScriptStep::flush(&[]), + ScriptStep::write(&UNIFIED_LOOKUP).after(ms(100)), + ScriptStep::read(400, &UNIFIED_FEATURE).after(ms(400)), + ], + exchange(&UNIFIED_QUERY, [no_reply()]), + exchange(&LEGACY_LOOKUP, [reply(&LEGACY_FEATURE).after(ms(1_500))]), + exchange(&LEGACY_QUERY, [reply(&LEGACY_STATUS).after(ms(1_500))]), + ]), + ]); + + // A matching reply at the response deadline is accepted, and the + // battery requests after it still get their full timeouts. + assert_eq!(result.unwrap(), LEGACY_READING); + assert_eq!(elapsed, ms(5_600 + 650 + 3 * 1_500)); + } + + #[test] + fn silence_skips_the_legacy_lookup_and_the_budget_ends_discovery() { + let (result, elapsed) = read_one([ + exchange( + &UNIFIED_LOOKUP, + [reply(&[REPORT_ID_SHORT, 2, 0, 0x0F, 5, 0, 0]), no_reply()], + ), + silent_probe(0xFF), + silent_probe(2), + silent_probe(3), + ]); + + assert!(matches!(result, Ok(Reading::NotFound))); + assert_eq!(elapsed, DISCOVERY_BUDGET); + } + + #[test] + fn a_probe_can_finish_its_legacy_lookup_after_the_discovery_budget_is_used() { + let (result, elapsed) = read_one([ + silent_probe(1), + silent_probe(0xFF), + silent_probe(2), + exchange( + &unified_lookup(3), + [reply(&[REPORT_ID_SHORT, 3, 0, 0x0F, 0, 0, 0]).after(ms(1_500))], + ), + exchange( + &[REPORT_ID_SHORT, 3, 0, 0x0F, 0x10, 0x00, 0], + [ScriptStep::read(0, &[REPORT_ID_SHORT, 3, 0, 0x0F, 6, 0, 0])], + ), + exchange( + &[REPORT_ID_SHORT, 3, 6, 0x0F, 0, 0, 0], + [reply(&[REPORT_ID_SHORT, 3, 6, 0x0F, 42, 0, 0x81])], + ), + ]); + + assert_eq!(result.unwrap(), LEGACY_READING); + assert_eq!(elapsed, DISCOVERY_BUDGET); + } +} + +mod battery_recovery { + use super::*; + + /// Find the unified feature on device index 1, then read it with `parts`. + fn read_unified( + parts: impl IntoIterator>, + ) -> Result { + read_one(iter::once(found_unified()).chain(parts)).0 + } + + /// Look up the legacy feature, then read its status with `status_reply`. + fn legacy_fallback(status_reply: ScriptStep) -> Vec { + let mut steps = exchange(&LEGACY_LOOKUP, [reply(&LEGACY_FEATURE)]); + steps.extend(exchange(&LEGACY_QUERY, [status_reply])); + steps + } + + #[test] + fn incomplete_unified_replies_recover_with_a_legacy_status() { + // Every matching prefix still lacks the unified charging byte. + for length in 4..=INCOMPLETE_UNIFIED.len() { + let result = read_unified([ + exchange(&UNIFIED_QUERY, [reply(&INCOMPLETE_UNIFIED[..length])]), + legacy_fallback(reply(&LEGACY_STATUS)), + ]); + + assert_eq!(result.unwrap(), LEGACY_READING); + } + } + + #[test] + fn offline_device_error_and_silence_recover_with_a_legacy_status() { + for unified_reply in [ + reply(&[REPORT_ID_SHORT, 1, ERROR_MARKER_HIDPP10, 5, 0x1F, 0x08, 0]), + reply(&[REPORT_ID_LONG, 1, ERROR_MARKER_HIDPP20, 5, 0x1F, 0x02]), + no_reply(), + ] { + let result = read_unified([ + exchange(&UNIFIED_QUERY, [unified_reply]), + legacy_fallback(reply(&LEGACY_STATUS)), + ]); + + assert_eq!(result.unwrap(), LEGACY_READING); + } + } + + #[test] + fn missing_results_from_both_features_return_no_battery_status() { + let result = read_unified([ + exchange(&UNIFIED_QUERY, [no_reply()]), + legacy_fallback(reply(&[ + REPORT_ID_SHORT, + 1, + ERROR_MARKER_HIDPP10, + 6, + 0x0F, + 0x08, + 0, + ])), + ]); + + assert_eq!(result.unwrap(), Reading::NoStatus); + } + + #[test] + fn a_failed_legacy_lookup_preserves_the_unified_short_response() { + for lookup_reply in [ + reply(&[REPORT_ID_SHORT, 1, 0, 0x0F, 0, 0, 0]), + reply(&[REPORT_ID_SHORT, 1, ERROR_MARKER_HIDPP10, 0, 0x0F, 0x08, 0]), + reply(&[REPORT_ID_LONG, 1, ERROR_MARKER_HIDPP20, 0, 0x0F, 0x02]), + reply(&[REPORT_ID_SHORT, 1, 0, 0x0F]), + no_reply(), + ] { + let result = read_unified([ + exchange(&UNIFIED_QUERY, [reply(&INCOMPLETE_UNIFIED)]), + exchange(&LEGACY_LOOKUP, [lookup_reply]), + ]); + + assert_short_response(result, 8, 7); + } + } + + #[test] + fn a_failed_legacy_status_preserves_the_unified_short_response() { + for status_reply in [ + reply(&[REPORT_ID_SHORT, 1, 6, 0x0F, 42, 0]), + reply(&[REPORT_ID_SHORT, 1, ERROR_MARKER_HIDPP10, 6, 0x0F, 0x08, 0]), + reply(&[REPORT_ID_LONG, 1, ERROR_MARKER_HIDPP20, 6, 0x0F, 0x02]), + no_reply(), + ] { + let result = read_unified([ + exchange(&UNIFIED_QUERY, [reply(&INCOMPLETE_UNIFIED)]), + legacy_fallback(status_reply), + ]); + + assert_short_response(result, 8, 7); + } + } + + #[test] + fn a_missing_unified_result_does_not_hide_a_legacy_short_response() { + let result = read_unified([ + exchange(&UNIFIED_QUERY, [no_reply()]), + legacy_fallback(reply(&[REPORT_ID_SHORT, 1, 6, 0x0F, 42, 0])), + ]); + + assert_short_response(result, 7, 6); + } + + #[derive(Debug, Clone, Copy)] + enum IoFailure { + FlushRead, + Write, + ResponseRead, + } + + impl IoFailure { + const ALL: [Self; 3] = [Self::FlushRead, Self::Write, Self::ResponseRead]; + + /// The script for `request` up to and including this failure. + fn steps(self, request: &[u8]) -> Vec { + let failed_read = |timeout_ms| ScriptStep::Read { + timeout_ms, + result: Err(HidError::InitializationError), + advance: Duration::ZERO, + }; + match self { + Self::FlushRead => vec![failed_read(0)], + Self::Write => vec![ + ScriptStep::flush(&[]), + ScriptStep::Write { + report: request.to_vec(), + result: Err(HidError::InitializationError), + advance: Duration::ZERO, + }, + ], + Self::ResponseRead => exchange(request, [failed_read(1_500)]), + } + } + + fn assert_error(self, result: Result) { + assert!( + matches!(result, Err(HidppError::Hid(HidError::InitializationError))), + "{self:?} produced {result:?}" + ); + } + } + + // The scripts end at the failure, so these also check that a failed + // read ends discovery instead of probing the next device index. + #[test] + fn unified_io_failures_stop_without_legacy_recovery() { + for failure in IoFailure::ALL { + failure.assert_error(read_unified([failure.steps(&UNIFIED_QUERY)])); + } + } + + #[test] + fn legacy_io_failures_replace_the_unified_short_response() { + for failure in IoFailure::ALL { + failure.assert_error(read_unified([ + exchange(&UNIFIED_QUERY, [reply(&INCOMPLETE_UNIFIED)]), + failure.steps(&LEGACY_LOOKUP), + ])); + + failure.assert_error(read_unified([ + exchange(&UNIFIED_QUERY, [reply(&INCOMPLETE_UNIFIED)]), + exchange(&LEGACY_LOOKUP, [reply(&LEGACY_FEATURE)]), + failure.steps(&LEGACY_QUERY), + ])); + } + } +} diff --git a/src/main.rs b/src/main.rs index 5e007a2..2363793 100644 --- a/src/main.rs +++ b/src/main.rs @@ -15,8 +15,11 @@ fn main() -> ExitCode { return ExitCode::SUCCESS; } - match run() { - Ok(()) => ExitCode::SUCCESS, + match read_status() { + Ok(status) => { + println!("{}", format_status(status)); + ExitCode::SUCCESS + } Err(message) => { eprintln!("{message}"); ExitCode::FAILURE @@ -24,16 +27,11 @@ fn main() -> ExitCode { } } -fn run() -> Result<(), String> { +fn read_status() -> Result { let api = HidApi::new().map_err(|error| format!("Could not initialize HID access: {error}"))?; let reading = read_battery(&api).map_err(|error| format!("Could not read battery level: {error}"))?; - println!("{}", format_status(battery_status(reading)?)); - Ok(()) -} - -fn battery_status(reading: Reading) -> Result { match reading { Reading::Status(status) => Ok(status), Reading::NoStatus => Err(String::from( From 7d6c139ce769b85cf8b6b73ef3765c6e936f4d7e Mon Sep 17 00:00:00 2001 From: softmaxe <94467584+softmaxe@users.noreply.github.com> Date: Thu, 19 Nov 2026 04:04:43 +0800 Subject: [PATCH 2/5] fix(raycast): require an executable file when selecting gbat --- raycast/mouse-battery.sh | 38 ++++++++++++++++---------------------- 1 file changed, 16 insertions(+), 22 deletions(-) diff --git a/raycast/mouse-battery.sh b/raycast/mouse-battery.sh index 5d0e413..3053a07 100755 --- a/raycast/mouse-battery.sh +++ b/raycast/mouse-battery.sh @@ -9,30 +9,24 @@ set -euo pipefail -script_dir="${0:A:h}" -project_dir="${script_dir:h}" - if [[ -n "${GBAT_BINARY:-}" ]]; then - binary_path="$GBAT_BINARY" -elif binary_path="$(command -v gbat 2>/dev/null)" && [[ -x "$binary_path" ]]; then - : + candidates=("$GBAT_BINARY") else - binary_path="" - for candidate in \ - "/opt/homebrew/bin/gbat" \ - "/usr/local/bin/gbat" \ - "$HOME/.local/bin/gbat" \ - "$project_dir/target/release/gbat"; do - if [[ -x "$candidate" ]]; then - binary_path="$candidate" - break - fi - done + candidates=( + "${commands[gbat]:-}" + /opt/homebrew/bin/gbat + /usr/local/bin/gbat + "$HOME/.local/bin/gbat" + "${0:A:h:h}/target/release/gbat" + ) fi -if [[ -z "$binary_path" || ! -x "$binary_path" ]]; then - print -u2 "gbat binary not found. Build it with: cargo build --release" - exit 1 -fi +for candidate in "${candidates[@]}"; do + if [[ -f "$candidate" && -x "$candidate" ]]; then + [[ "$candidate" == */* ]] || candidate="./$candidate" + exec "$candidate" + fi +done -exec "$binary_path" +print -u2 "gbat binary not found. Build it with: cargo build --release" +exit 1 From 81d767bf86674468ce0048d28d321fa5819c9d07 Mon Sep 17 00:00:00 2001 From: softmaxe <94467584+softmaxe@users.noreply.github.com> Date: Thu, 19 Nov 2026 04:04:44 +0800 Subject: [PATCH 3/5] fix(verification): detect scratch changes and reject invalid timeouts --- .agents/skills/verify-gbat/SKILL.md | 185 +++++------------- .agents/skills/verify-gbat/features/README.md | 42 ---- .../skills/verify-gbat/features/raycast.md | 17 +- .agents/skills/verify-gbat/scripts/capture.py | 46 +++-- 4 files changed, 85 insertions(+), 205 deletions(-) delete mode 100644 .agents/skills/verify-gbat/features/README.md diff --git a/.agents/skills/verify-gbat/SKILL.md b/.agents/skills/verify-gbat/SKILL.md index 92fe03e..a906b61 100644 --- a/.agents/skills/verify-gbat/SKILL.md +++ b/.agents/skills/verify-gbat/SKILL.md @@ -1,25 +1,21 @@ --- name: verify-gbat -description: Verify gbat's real macOS/Linux battery CLI and macOS Raycast script with isolated PTY runs, version checks, hardware-aware feature journeys, and retained command evidence. Use after changing CLI output, HID behavior, or Raycast integration. +description: Verify gbat's real macOS/Linux battery CLI and macOS Raycast script with isolated PTY runs and retained evidence. Use after changing CLI output, HID behavior, or Raycast integration. --- # Verify gbat -Read [the feature map](features/README.md), then the relevant journey. The primary -surface is a one-shot Rust CLI; the secondary surface is the macOS Raycast Script -Command `Logitech Mouse Battery`. No service, port, login, database, migrations, -or seed data is involved. An empty working directory is sufficient for version -checks; successful battery reads require a real awake Logitech mouse. +Choose the journey that covers the change: -## Launch +- [Version identity](features/version.md) covers the checkout and installed executables. +- [Battery and charging](features/battery.md) covers receiver, direct USB, and charging state. +- [Failure and recovery](features/failure-recovery.md) covers absent devices, offline mice, Linux permissions, and recovery. +- [Raycast integration](features/raycast.md) covers binary selection, missing executables, and the native Script Command. -Run from this checkout using Rust/rustup (the version is pinned in -`rust-toolchain.toml`) and `uv`. The helper uses Python 3.12, provisioned by `uv` -if necessary; Python is a verification dependency, not an app dependency. -On Linux the native hidraw backend needs a C compiler/linker, not `libudev-dev` -or `libusb`. Build as your regular user. +## Launch -Keep these variables in one shell across launch, doctor, drive, and cleanup: +Build as the regular user with the pinned Rust toolchain. The [PTY helper](scripts/capture.py) +uses Python 3.12 through `uv`. Keep these variables in one shell: ```sh REPO="$(git rev-parse --show-toplevel)" @@ -30,28 +26,13 @@ HARNESS="$REPO/.agents/skills/verify-gbat/scripts/capture.py" mkdir -p "$REPO/target/verification-evidence" EVIDENCE="$(mktemp -d "$REPO/target/verification-evidence/run.XXXXXX")" SCRATCH="$(mktemp -d "${TMPDIR:-/tmp}/gbat-verify.XXXXXX")" -printf 'Evidence: %s\nScratch: %s\n' "$EVIDENCE" "$SCRATCH" trap 'rmdir -- "$SCRATCH"' EXIT ``` -The build must succeed before driving. A successful doctor below establishes -CLI readiness and the manifest version. It does not establish hardware -readiness. There is no persistent app process: start each action with the helper -in its own PTY, which exits and is reaped before the next action. Teardown is -the Cleanup section; run it after failures too. - -Hardware queries cannot be isolated by working directory: interfaces are shared, -requests use one software ID, and input reports are flushed. Never run two -battery queries concurrently against the same receiver, including Raycast -refreshes or another agent's run. If another driver is active, defer the query; -do not kill or commandeer it. Version-only runs can coexist. There is no device -selector: multiple Logitech devices can make the reading belong to another -device. Establish the intended device/connection before claiming GPW2 proof. - ## Doctor -This is the read-only instance check. It invokes the exact local binary without -opening HID, requires the version in `Cargo.toml`, and records its SHA-256: +After a successful build, verify the exact executable against the manifest. +Only `--version` as the first CLI argument skips HID initialization. ```sh uv run --no-project --python 3.12 "$HARNESS" \ @@ -59,121 +40,55 @@ uv run --no-project --python 3.12 "$HARNESS" \ --feature version-local --expect version -- "$BINARY" --version ``` -Require helper exit `0`, `result.json` `passed: true`, exact version stdout, -and empty stderr. The helper records a binary hash on every action: compare it -with the doctor hash to detect a build replaced during verification. Version -alone cannot establish freshness, so always build this checkout first. If -anything looks off, repeat this check in a new evidence directory, retaining -the failed attempt. On Linux this command needs no `sudo`. +Require helper exit `0` and `passed: true` in `result.json`. Compare the binary +SHA-256 in subsequent actions with the doctor's hash for the same executable. ## Drive -The executable [PTY helper](scripts/capture.py) accepts exact commands after -`--`; it never runs them through a shell. Every invocation requires a new -evidence subdirectory and an existing, disposable scratch directory. Stdout and -stdin use a private controlling PTY; stderr is redirected to its own proof file -so channel assertions remain possible. It supplies no interactive input. The -default deadline is 30 seconds, not the internal six-second discovery budget; -use `--timeout 60` only for a justified slow host. - -For a real battery read on macOS: - -```sh -uv run --no-project --python 3.12 "$HARNESS" \ - --evidence "$EVIDENCE/battery-terminal" --cwd "$SCRATCH" --binary "$BINARY" \ - --feature battery-terminal --expect battery -- "$BINARY" -``` - -For the corresponding Linux action, use `-- sudo -n "$BINARY"` instead. -Build first as a regular user. If `sudo -n` needs authentication, use the -environment's secret-delivery mechanism; do not put passwords into commands, -artifacts, or this skill. A sudo error is a failed prerequisite, not a gbat -failure-path pass. Do not change udev rules or device permissions for a run. - -Follow the map for charging, offline/recovery, and Raycast actions. A missing -mouse or required charging state is a failed journey with its unmet precondition, -not a successful substitute. Only the first CLI argument exactly equal to -`--version` avoids HID. There is no `--help`, dry-run, or device-list mode; -unknown arguments execute a battery query. The Raycast script does not forward -arguments, so `mouse-battery.sh --version` also queries hardware. +Run each relevant journey with a fresh evidence subdirectory per action. The +helper launches the argv after `--` in a private PTY, captures stderr separately, +and enforces a 30-second deadline by default. To inspect all options, run +`uv run --no-project --python 3.12 "$HARNESS" --help`. + +For successful battery queries, identify the intended awake GPW2 and connection. +The CLI can select any responding Logitech device. Serialize queries on the same +receiver, including Raycast refreshes. They send HID++ requests using a shared +software ID and flush input reports. On Linux, use `-- sudo -n "$BINARY"` in +battery examples when elevated device access is needed. Handle authentication +outside the capture. Keep device permissions unchanged. + +`--expect battery` checks the percentage and allows an optional charging suffix. +Check the suffix against the observed charging state. `--expect error` checks a +family of CLI errors. Inspect stderr for the specific failure in the selected +journey. Record unavailable hardware or permissions as unmet preconditions. +Native Raycast verification requires the visible Script Command invocation and +result. The terminal wrapper ignores arguments, including `--version`. ## Evidence -Keep proof in `$REPO/target/verification-evidence/run.XXXXXX`, outside scratch. -`target/` is already ignored by Git. Copy evidence elsewhere before `cargo clean` -or deleting the checkout. Each action contains: - -- `action.json`: feature/entry-point ID, exact argv, working directory, UTC time, - platform, binary path/hash, manifest version, expected behavior, scratch before. -- `terminal.bin` and `events.jsonl`: raw stdout PTY bytes and timed output chunks. -- `stdout.txt` and `stderr.txt`: stdout with terminal CRLF normalized to LF and - separately captured stderr. -- `result.json`: actual app exit code, timeout/interruption/capture error, - assertion result, scratch after, - and whether scratch files stayed unchanged. Helper exit `0` means all its - checks passed; app exit code is recorded separately. - -Record connection mode, intended device identity, wake/charging conditions, -manual actions, and feature outcomes in `$EVIDENCE/notes.md`. Capture the action -and resulting state through the real user entry point. For hardware queries, -compare charging suffix with independently observed cable/charging conditions; -do not require an exact historical battery percentage. A command that merely -prints a plausible battery line cannot prove device identity or charging state. - -Observe relevant side effects alongside output: the helper compares scratch -file contents; it does not audit the whole filesystem or network. gbat has no -documented state files, network calls, or browser launches, but battery queries -send real HID++ writes before reading replies. Do not call them pure device -reads. `--version` returns before HID initialization. No mock battery provider, -replacement executable, or internal test setter proves real hardware behavior. -Existing protocol tests are useful supplementary checks, not CLI/hardware proof. - -For Raycast UI proof, retain the actual invocation and visible compact result -using available native-app capture tooling; terminal execution of its script is -a separate path. Do not reuse the historical README GIF/WebP as fresh evidence. -Do not run `docs/record-demo.sh` for routine verification: it replaces -`assets/demo.gif`. - -## Cleanup +Keep evidence under the ignored `target/verification-evidence/` directory. +Use a new directory for retries so earlier outcomes remain available. -The helper waits for its child and closes its PTY. On timeout, SIGINT, or SIGTERM -it kills only the process group it created and reaps the child. Never kill by -process name. No server remains to stop. Close only UI windows opened by the -run and restore any device state changed specifically for a journey. +- `action.json` records argv, working directory, timestamp, platform, binary path + and hash, manifest version, expectation, and the initial scratch snapshot. +- `terminal.bin` and `events.jsonl` hold raw PTY output and timed chunks. + `stdout.txt` normalizes terminal CRLF to LF. `stderr.txt` captures stderr. +- `result.json` records the child exit code, timeout, interruption, capture + errors, assertion, and final scratch snapshot. A pass requires the expected + exit and output, a completed capture, and unchanged scratch entries. +- Record the device identity, connection, wake/charging conditions, manual + actions, and feature outcomes in `$EVIDENCE/notes.md`. -After every attempt, including a failed one, remove only that run's scratch: - -```sh -rmdir -- "$SCRATCH" -trap - EXIT -test ! -e "$SCRATCH" -test -s "$EVIDENCE/doctor/action.json" -test -s "$EVIDENCE/doctor/result.json" -test -s "$EVIDENCE/doctor/stdout.txt" -printf 'Retained proof: %s\n' "$EVIDENCE" -``` - -Also confirm the driven feature's `action.json`, `result.json`, stdout/stderr, -and terminal evidence survive. Never remove `$EVIDENCE` in cleanup. For a failed -build before scratch exists, no instance was launched and there is nothing to -terminate. Scratch should be empty: if `rmdir` fails, inspect it and remove only -the run-created files before retrying; do not recursively delete an uninspected -path. Do not erase failed evidence when retrying. SIGKILL or machine termination -cannot be handled; such runs may retain partial evidence and need inspection. - -## Helpers +## Cleanup -All invocations above run `scripts/capture.py` through `uv`; it is also directly -executable. Inspect its options without touching HID with: +The helper reaps its child when it exits. After successes and failures, restore +device state changed for the journey, close windows opened for the run, and +remove the empty scratch directory: ```sh -uv run --no-project --python 3.12 "$HARNESS" --help +rmdir -- "$SCRATCH" && trap - EXIT ``` -`--expect version` requires the current manifest version; `battery` requires one -valid `Battery: N%` line with an optional charging suffix; `error` requires app -exit `1`, empty stdout, and a known gbat error prefix; `missing-binary` requires -the Raycast wrapper's exact missing-executable message. Every expectation also -requires no timeout and unchanged scratch file contents. `error` recognizes a -family of failures: read stderr to assert the specific scenario in the map. -The helper cannot certify hardware setup or native Raycast UI behavior. +If scratch contains unexpected entries, inspect them against the captured +snapshot before removal. Retain the action and result files, including failed +runs. Copy evidence elsewhere before cleaning the Cargo target directory. diff --git a/.agents/skills/verify-gbat/features/README.md b/.agents/skills/verify-gbat/features/README.md deleted file mode 100644 index fc74360..0000000 --- a/.agents/skills/verify-gbat/features/README.md +++ /dev/null @@ -1,42 +0,0 @@ -# gbat verification map - -This is the maintained map of gbat's user-facing behavior. Read the matching -feature file before driving it. Every listed entry point needs its own outcome; -a terminal script run does not cover the native Raycast entry point. - -## Baseline preconditions - -- Follow Launch and Doctor in [the skill](../SKILL.md) from a fresh scratch dir. -- Use the absolute release binary built from this checkout with `--locked`. -- Keep `$REPO`, `$BINARY`, `$HARNESS`, `$EVIDENCE`, and `$SCRATCH` in the shell. -- Use macOS or Linux. Raycast and its zsh script are macOS-only product paths. -- For battery journeys, connect a real awake GPW2 via LIGHTSPEED or USB, identify - the device, and ensure no competing query is using its shared HID interface. -- No fixture can seed hardware state. Missing connection, charging state, - permission, or Raycast installation fails the dependent journey; record the - reason and retain the attempt rather than substituting canned output. - -## Driving conventions - -- Use `capture.py` with a unique evidence subdirectory per action, serially. -- Commands in features assume the Launch variables. On Linux only, replace - battery `-- "$BINARY"` with `-- sudo -n "$BINARY"` after arranging access. -- Match one stdout battery line and exit status, never README percentages. -- Restore physical states changed during testing; preserve evidence in `target/`. - -## Proof and coverage - -Each action needs argv, stdout, stderr, exit code, binary identity, and its -result. For battery/charging record the real device preconditions and observed -physical actions too. Native UI proof needs the actual UI invocation/result. -The initial generated-skill smoke run may prove only one feature; name every -unexercised journey as unverified. Successful unit tests do not fill those gaps. - -## Features - -- [Version identity](version.md): local CLI and installed CLI version reporting. -- [Battery and charging](battery.md): receiver, direct USB, charging suffix. -- [Failure and recovery](failure-recovery.md): offline, absent device, - permissions, recovery through the same CLI path. -- [Raycast integration](raycast.md): explicit binary, automatic discovery, - missing executable, native Script Command. diff --git a/.agents/skills/verify-gbat/features/raycast.md b/.agents/skills/verify-gbat/features/raycast.md index 7730ac9..046bf42 100644 --- a/.agents/skills/verify-gbat/features/raycast.md +++ b/.agents/skills/verify-gbat/features/raycast.md @@ -31,18 +31,19 @@ Preconditions: Require valid battery stdout, empty stderr and app exit `0`. - **Automatic discovery entry.** Run `uv run --no-project --python 3.12 "$HARNESS" --evidence "$EVIDENCE/raycast-discovery" --cwd "$SCRATCH" --binary "$BINARY" --feature raycast-discovery --expect battery -- env -u GBAT_BINARY PATH="$REPO/target/release:$PATH" "$REPO/raycast/mouse-battery.sh"`. - This proves the PATH entry with this checkout's build. Search order after PATH - is `/opt/homebrew/bin/gbat`, `/usr/local/bin/gbat`, `$HOME/.local/bin/gbat`, then - the repository's `target/release/gbat`. When modifying fallback discovery, - exercise each affected location on an appropriately configured host; do not - overwrite installed binaries or claim all fallbacks from the PATH case. + This exercises the PATH entry with this checkout's build. When modifying + fallback discovery, exercise each affected location in the + [documented order](../../../../README.md#raycast) on an appropriately + configured host. Preserve the user's installed binaries. - **Missing configured executable.** Confirm `test ! -e "$SCRATCH/no-gbat"`. Run `uv run --no-project --python 3.12 "$HARNESS" --evidence "$EVIDENCE/raycast-missing" --cwd "$SCRATCH" --binary "$BINARY" --feature raycast-missing --expect missing-binary -- env GBAT_BINARY="$SCRATCH/no-gbat" "$REPO/raycast/mouse-battery.sh"`. Require app exit `1`, empty stdout and exact stderr `gbat binary not found. Build it with: cargo build --release` plus a newline. - A bad explicit override must not fall back to an installed binary. This case - requires no hardware and invokes the real script without a fake executable. + Repeat with `GBAT_BINARY="$SCRATCH"` and `raycast-directory` as the evidence + directory and feature. A searchable directory also has its execute bit set. + Both cases should reach the same missing-executable diagnostic even when + a working gbat is on PATH. - **Native UI entry.** Using available native-app control, open Raycast, search the exact command `Logitech Mouse Battery`, and execute it. Capture the action and visible compact battery result in `$EVIDENCE/raycast-ui/`, with connection @@ -58,5 +59,3 @@ Preconditions: - The script ignores its arguments, including `--version`; it queries hardware. - Invalid `GBAT_BINARY` takes precedence even when a working gbat is on PATH. -- Linux CLI support does not imply Raycast support; Linux cannot prove this map. -- The original Raycast WebP is historical evidence, not proof of the current build. diff --git a/.agents/skills/verify-gbat/scripts/capture.py b/.agents/skills/verify-gbat/scripts/capture.py index c50042d..9de59c3 100755 --- a/.agents/skills/verify-gbat/scripts/capture.py +++ b/.agents/skills/verify-gbat/scripts/capture.py @@ -1,18 +1,18 @@ #!/usr/bin/env -S uv run --no-project --python 3.12 """Capture a short-lived real command in a private PTY and retain its proof.""" -from __future__ import annotations - import argparse import errno import hashlib import json +import math import os import platform import pty import re import select import signal +import stat import sys import time import tomllib @@ -22,17 +22,22 @@ def digest(path: Path) -> str: - return hashlib.sha256(path.read_bytes()).hexdigest() + with path.open("rb") as stream: + return hashlib.file_digest(stream, "sha256").hexdigest() def snapshot(directory: Path) -> dict[str, str]: - return { - str(path.relative_to(directory)): ( - f"symlink:{os.readlink(path)}" if path.is_symlink() else digest(path) - ) - for path in sorted(directory.rglob("*")) - if path.is_symlink() or path.is_file() - } + entries: dict[str, str] = {} + for path in sorted(directory.rglob("*")): + mode = path.lstat().st_mode + if stat.S_ISLNK(mode): + value = f"symlink:{os.readlink(path)}" + elif stat.S_ISREG(mode): + value = digest(path) + else: + value = stat.filemode(mode)[0] + entries[str(path.relative_to(directory))] = value + return entries def write_json(path: Path, data: object) -> None: @@ -135,12 +140,14 @@ def main() -> int: command: list[str] = args.command if command[:1] == ["--"]: command = command[1:] - if not command or args.timeout <= 0: - parser.error("Provide a command after -- and a positive timeout") + if not command or not math.isfinite(args.timeout) or args.timeout <= 0: + parser.error("Provide a command after -- and a finite positive timeout") cwd = args.cwd.resolve(strict=True) binary = args.binary.resolve(strict=True) evidence = args.evidence.resolve() - if evidence == cwd or cwd in evidence.parents: + if not cwd.is_dir() or not binary.is_file(): + parser.error("--cwd must be a directory and --binary must be a file") + if evidence.is_relative_to(cwd): parser.error("Evidence must be outside the scratch working directory") repo = Path(__file__).resolve().parents[4] version = tomllib.loads((repo / "Cargo.toml").read_text())["package"]["version"] @@ -212,13 +219,14 @@ def main() -> int: ) ) ) - after = snapshot(cwd) - passed = bool( + after = snapshot(cwd) if cwd.is_dir() and not cwd.is_symlink() else None + scratch_unchanged = before == after + passed = ( matched and not timed_out and not interrupted - and not capture_error - and before == after + and capture_error is None + and scratch_unchanged ) result = { "feature": args.feature, @@ -226,8 +234,8 @@ def main() -> int: "timed_out": timed_out, "interrupted": interrupted, "capture_error": capture_error, - "expectation_matched": bool(matched), - "scratch_unchanged": before == after, + "expectation_matched": matched, + "scratch_unchanged": scratch_unchanged, "scratch_after": after, "passed": passed, } From 4ba2659bec58a52b0ade9233e557a1fc9b9af6da Mon Sep 17 00:00:00 2001 From: softmaxe <94467584+softmaxe@users.noreply.github.com> Date: Thu, 19 Nov 2026 04:04:44 +0800 Subject: [PATCH 4/5] ci: check CLI exit status and simplify release metadata --- .github/dependabot.yml | 3 +-- .github/workflows/ci.yml | 6 ++--- .github/workflows/release.yml | 41 +++++++++++++---------------------- Cargo.toml | 5 +---- 4 files changed, 20 insertions(+), 35 deletions(-) diff --git a/.github/dependabot.yml b/.github/dependabot.yml index fe45601..9366fdc 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -1,10 +1,10 @@ version: 2 +# Give new releases a week to age before opening routine update PRs. updates: - package-ecosystem: github-actions directory: / schedule: interval: monthly - # Let new releases age before adopting them, so a compromised version is likely yanked first. cooldown: default-days: 7 groups: @@ -17,7 +17,6 @@ updates: directory: / schedule: interval: monthly - # Let new releases age before adopting them, so a compromised version is likely yanked first. cooldown: default-days: 7 groups: diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index cc5e01f..c03dee2 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -48,9 +48,9 @@ jobs: run: | set -euo pipefail cargo build --release --locked - version="$(sed -n 's/^version = "\([^"]*\)"/\1/p' Cargo.toml | head -n 1)" - test -n "$version" - test "$(./target/release/gbat --version)" = "gbat $version" + version="$(cargo metadata --locked --no-deps --format-version 1 | jq -er '.packages[] | select(.name == "gbat") | .version')" + reported_version="$(./target/release/gbat --version)" + test "$reported_version" = "gbat $version" check: name: Check diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 2c6a626..674e0a8 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -22,6 +22,7 @@ concurrency: env: CARGO_TERM_COLOR: always MACOSX_DEPLOYMENT_TARGET: "11.0" + TARGET: aarch64-apple-darwin jobs: build: @@ -30,18 +31,13 @@ jobs: # macos-15 is arm64; release archives remain macOS-only. Linux is built from source. runs-on: macos-15 timeout-minutes: 30 - env: - TARGET: aarch64-apple-darwin outputs: - tag: ${{ steps.version.outputs.tag }} version: ${{ steps.version.outputs.version }} sha256: ${{ steps.package.outputs.sha256 }} steps: - name: Check out source uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: - # No step here uses git, and cargo build scripts are third-party code - # that would otherwise be able to read the token out of .git/config. persist-credentials: false - name: Require the tag to point at a commit on main @@ -61,17 +57,11 @@ jobs: id: version run: | set -euo pipefail - version="$(sed -n 's/^version = "\([^"]*\)"/\1/p' Cargo.toml | head -n 1)" - test -n "$version" - tag="" - if [[ "$GITHUB_EVENT_NAME" == "push" ]]; then - tag="$GITHUB_REF_NAME" - test "$tag" = "v$version" || { - echo "Tag $tag does not match Cargo version $version" >&2 - exit 1 - } + version="$(cargo metadata --locked --no-deps --format-version 1 | jq -er '.packages[] | select(.name == "gbat") | .version')" + if [[ "$GITHUB_EVENT_NAME" == "push" && "$GITHUB_REF_NAME" != "v$version" ]]; then + echo "Tag $GITHUB_REF_NAME does not match Cargo version $version" >&2 + exit 1 fi - echo "tag=$tag" >> "$GITHUB_OUTPUT" echo "version=$version" >> "$GITHUB_OUTPUT" # No tests here: the tag must point at main, and every commit on main passed "Check". @@ -92,7 +82,8 @@ jobs: echo "Expected minimum macOS $MACOSX_DEPLOYMENT_TARGET, got $minos" >&2 exit 1 } - test "$("$binary" --version)" = "gbat $VERSION" + reported_version="$("$binary" --version)" + test "$reported_version" = "gbat $VERSION" package_dir="$RUNNER_TEMP/package" mkdir -p "$package_dir" dist @@ -126,12 +117,13 @@ jobs: - name: Download release files uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 with: - pattern: release-* + name: release-${{ env.TARGET }} path: dist - merge-multiple: true - name: Attest release archives - uses: actions/attest-build-provenance@4d101475d8b20a2381f78447822ac1eab6504dd8 # v4.2.2 + uses: actions/attest@1e69f48acb82d1966a394da916b4c1698aa569d6 # v4.2.2 + env: + NODE_OPTIONS: --max-http-header-size=32768 with: subject-path: dist/*.tar.gz @@ -141,7 +133,7 @@ jobs: env: GH_TOKEN: ${{ github.token }} GH_REPO: ${{ github.repository }} - TAG: ${{ needs.build.outputs.tag }} + TAG: ${{ github.ref_name }} run: gh release create "$TAG" dist/* --verify-tag --generate-notes --title "$TAG" formula-test: @@ -159,8 +151,7 @@ jobs: contents: read attestations: read env: - TAG: ${{ needs.build.outputs.tag || inputs.formula_tag }} - VERSION: ${{ needs.build.outputs.version }} + TAG: ${{ inputs.formula_tag || github.ref_name }} SHA256: ${{ needs.build.outputs.sha256 }} steps: - name: Verify published release for formula retest @@ -173,21 +164,19 @@ jobs: echo "Invalid release tag: $TAG" >&2 exit 1 } - version="${TAG#v}" - archive="gbat-$TAG-aarch64-apple-darwin.tar.gz" + archive="gbat-$TAG-$TARGET.tar.gz" release_dir="$RUNNER_TEMP/published-release" gh release download "$TAG" --repo "$GITHUB_REPOSITORY" \ --pattern "$archive" --pattern "$archive.sha256" --dir "$release_dir" (cd "$release_dir" && shasum -a 256 -c "$archive.sha256") gh attestation verify "$release_dir/$archive" --repo "$GITHUB_REPOSITORY" \ --source-ref "refs/tags/$TAG" - echo "VERSION=$version" >> "$GITHUB_ENV" echo "SHA256=$(shasum -a 256 "$release_dir/$archive" | awk '{ print $1 }')" >> "$GITHUB_ENV" - name: Generate formula run: | set -euo pipefail - archive="gbat-v$VERSION-aarch64-apple-darwin.tar.gz" + archive="gbat-$TAG-$TARGET.tar.gz" cat > "$RUNNER_TEMP/gbat.rb" < Date: Thu, 19 Nov 2026 04:04:44 +0800 Subject: [PATCH 5/5] docs: align bilingual usage and simplify demo recording --- README.md | 41 ++++++++++++++++------------------------- README.zh-CN.md | 38 ++++++++++++++++---------------------- docs/record-demo.sh | 20 +++++--------------- docs/recording.md | 41 ++++++++++------------------------------- 4 files changed, 47 insertions(+), 93 deletions(-) diff --git a/README.md b/README.md index 9d190b6..e8fa651 100644 --- a/README.md +++ b/README.md @@ -22,7 +22,7 @@ G HUB, Python, or a background process. ## Requirements -- macOS 11 Big Sur or later, or Linux with hidraw and udev +- macOS 11 Big Sur or later, or Linux with hidraw and sysfs - A Logitech G Pro Wireless 2 connected through its LIGHTSPEED receiver or USB - A mouse that is awake when `gbat` runs @@ -85,9 +85,8 @@ reports that the mouse is offline, turn it on or move it, then retry. gbat version, battery output, and Raycast script demo

-This terminal demo shows real battery readings from `gbat 0.0.1`. It is a -historical recording, so its version may differ from the current release. -See [recording details](docs/recording.md) for its source and update instructions. +The demo shows a real battery reading. See the [recording details](docs/recording.md) +for the captured version and instructions for recording a new demo. ## Raycast @@ -147,12 +146,6 @@ On Linux, use `sudo "$HOME/.local/bin/gbat"`; `sudo` may use a different `PATH`. ### Linux and sudo -Use `sudo` for battery queries on Linux: - -```sh -sudo ./target/release/gbat -``` - Linux exposes the receiver and mouse through `/dev/hidraw*`. These device nodes are normally accessible only to root. Reading battery status requires opening the appropriate node for both reading and writing: `gbat` sends a HID++ battery @@ -191,21 +184,19 @@ xattr -dr com.apple.quarantine "$(brew --prefix gbat)" ## How it works -`gbat` opens Logitech HID++ interfaces in shared mode on macOS and through hidraw -on Linux. It checks receiver device -indices `1` through `6` and the direct USB index `0xFF`, trying `1` and `0xFF` -first. It uses the first interface and device index that reports a supported -battery feature. It filters only by Logitech's vendor ID, so with several -Logitech HID++ devices connected it may read another mouse, keyboard, or -headset. There is no device selector. - -It reads `UNIFIED_BATTERY` at `0x1004` and falls back to `BATTERY_STATUS` at -`0x1000` when the unified feature is unavailable, does not answer, or returns an -incomplete response. Once a battery feature is found, HID access errors stop the -read. During discovery, an interface that fails is skipped; its error is -reported only if no other interface finds the mouse or reports it offline. -If neither feature yields a battery status, the command reports an error -instead of inventing a `0%` reading. +`gbat` selects interfaces with Logitech's vendor ID and HID++ usage page +`0xFF00`. It opens them in shared mode on macOS and through hidraw on Linux. +It probes each interface at receiver index `1`, then at direct USB index +`0xFF`, then at receiver indices `2` through `6`. The first device that +reports a supported battery feature supplies the reading. There is no device +selector, so the reading can come from another mouse, keyboard, or headset. + +During discovery, a silent `UNIFIED_BATTERY` (`0x1004`) lookup skips that +interface and index. If the device answers that the feature is unsupported, +`gbat` looks up `BATTERY_STATUS` (`0x1000`). It also tries the legacy feature +when a discovered unified feature yields no usable status. A HID access error +during a status read ends the query. Discovery errors are reported only if +no candidate exposes a battery feature or reports the mouse offline. ## License diff --git a/README.zh-CN.md b/README.zh-CN.md index 0aecd84..878d24f 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -9,8 +9,7 @@ 简体中文

-`gbat` reads Logitech G Pro Wireless 2 battery status on macOS and Linux, prints -one line, and exits. +`gbat` 在 macOS 和 Linux 上读取 Logitech G Pro Wireless 2 的电量和充电状态,输出一行结果后退出。 ```text Battery: 78% @@ -21,18 +20,13 @@ Battery: 42% (charging) ## 系统要求 -- macOS 11 Big Sur or later, or Linux with hidraw and udev +- macOS 11 Big Sur 及以上版本,或支持 hidraw 和 sysfs 的 Linux - 通过 LIGHTSPEED 接收器或 USB 连接的 Logitech G Pro Wireless 2 - 运行 `gbat` 时鼠标处于唤醒状态 ## 安装 -On Linux, build the CLI from source and -[run battery queries with sudo](README.md#linux-and-sudo). -Linux builds do not require `libudev-dev` or a separately installed HIDAPI library. -Homebrew packages, release archives, and Raycast integration remain macOS-only. - -Homebrew 软件包和 GitHub Release 归档仅提供 Apple Silicon 的 `arm64` 可执行文件。 +Homebrew 软件包和 GitHub Release 归档仅提供适用于 Apple Silicon 的 macOS `arm64` 可执行文件。Linux 用户请[从源码构建](#从源码构建),并[使用 sudo 查询电量](#linux-设备权限)。Raycast 集成仅适用于 macOS。 使用 Homebrew 安装: @@ -68,13 +62,7 @@ gbat sudo /path/to/gbat ``` -Linux normally restricts `/dev/hidraw*` to root. Battery reads require read/write -access to send a HID++ query and receive its reply. Run the binary with `sudo` -for each battery query; `gbat --version` works without `sudo`. The CLI does not -install udev rules or change device permissions. See -[Linux and sudo](README.md#linux-and-sudo) for details. - -成功时,命令向 stdout 输出一行电池状态,退出码为 `0`。失败时,命令向 stderr 输出错误,退出码为 `1`。运行 `gbat --version` 可查看已安装的版本,不会访问鼠标。 +成功时,命令向 stdout 输出一行电池状态,退出码为 `0`。失败时,命令向 stderr 输出错误,退出码为 `1`。在两个平台上,普通用户都可以运行 `gbat --version` 查看版本,无需访问鼠标。 鼠标闲置后,读取可能需要等待无线模块唤醒。如果接收器报告鼠标离线,打开鼠标电源或移动鼠标后重试。 @@ -82,7 +70,7 @@ install udev rules or change device permissions. See gbat 版本、电量输出和 Raycast 脚本演示

-这段终端演示使用 `gbat 0.0.1` 读取真实鼠标电量。录屏保留了当时的版本,可能与当前 Release 不同。源码版本和更新方法见[录屏说明](docs/recording.md)。 +这段终端演示读取了真实鼠标的电量。录制时的版本和更新方法见[录屏说明](docs/recording.md)。 ## Raycast @@ -127,7 +115,13 @@ cp target/release/gbat "$HOME/.local/bin/gbat" 确认 `$HOME/.local/bin` 已加入 `PATH`,即可在任意目录运行 `gbat`。 -On Linux, run `sudo "$HOME/.local/bin/gbat"`; `sudo` may use a different `PATH`. +在 Linux 上可运行 `sudo "$HOME/.local/bin/gbat"`,因为 `sudo` 使用的 `PATH` 可能与当前 Shell 不同。 + +### Linux 设备权限 + +查询电量时,`gbat` 需要读写对应的 `/dev/hidraw*` 节点,才能发送 HID++ 请求并接收回复。这些节点通常只有 root 能够读写。请使用普通用户构建,在查询电量时运行 `sudo ./target/release/gbat`。`gbat` 不会安装 udev 规则、更改设备权限或配置免密 sudo。 + +Linux 版本使用原生 hidraw 后端,无需 `libudev-dev`、`libusb` 或单独安装的 HIDAPI 库。构建 Rust 依赖仍需 C 编译器和链接器,在 Ubuntu 或 Debian 上可通过 `sudo apt install build-essential` 安装。 ## 故障排查 @@ -136,8 +130,8 @@ On Linux, run `sudo "$HOME/.local/bin/gbat"`; `sudo` may use a different `PATH`. | `No responsive Logitech HID++ interface found` | 连接接收器或 USB 线,唤醒鼠标后重试。 | | `The receiver reports no connected mouse` | 鼠标已离线。打开鼠标电源或移动鼠标后重试。 | | `Could not read battery level` | 鼠标可能在读取时离线,或返回了无法使用的电池响应。移动鼠标后重试。 | -| HID access errors on macOS | Run `gbat` from Terminal and approve any macOS permission prompt. `sudo` is not normally required on macOS. | -| `Permission denied (os error 13)` on Linux | Run `sudo /path/to/gbat`; see [Linux and sudo](README.md#linux-and-sudo). | +| macOS 提示 `Could not initialize HID access` 或 `Could not read battery level: HID access failed` | 从 Terminal 运行一次 `gbat`,若系统弹出权限请求,请允许访问。macOS 通常无需使用 `sudo`。 | +| Linux 提示 `Permission denied (os error 13)` | 运行 `sudo /path/to/gbat`,详见 [Linux 设备权限](#linux-设备权限)。 | | Raycast 提示 `gbat binary not found` | 安装或构建 `gbat`,或在脚本中将 `GBAT_BINARY` 设为它的可执行文件路径。 | | `Battery: 100%` 但没有 `(charging)` | 鼠标充满后可能停止主动充电,这是正常现象。 | | macOS 阻止运行 | 打开 System Settings > Privacy & Security,为 `gbat` 选择 Open Anyway。 | @@ -150,9 +144,9 @@ xattr -dr com.apple.quarantine "$(brew --prefix gbat)" ## 工作原理 -`gbat` 以共享模式打开 Logitech HID++ 接口。它会检查接收器的设备索引 `1` 到 `6` 和 USB 直连索引 `0xFF`,先尝试 `1` 和 `0xFF`,再使用首个报告支持电池功能的接口及设备索引。它只按 Logitech 厂商 ID 筛选,连接多个 Logitech HID++ 设备时,可能读到另一只鼠标、键盘或耳机,且无法指定设备。 +`gbat` 按 Logitech 厂商 ID 和 HID++ 用途页 `0xFF00` 筛选接口,在 macOS 上以共享模式打开,在 Linux 上通过 hidraw 访问。它先在各接口上探测接收器索引 `1`,再尝试 USB 直连索引 `0xFF`,最后依次探测接收器索引 `2` 到 `6`。它会读取首个报告支持电池功能的设备。命令不支持指定设备,连接多个 Logitech 设备时,读数可能来自另一只鼠标、键盘或耳机。 -它优先读取 `0x1004` 的 `UNIFIED_BATTERY`。该功能不可用、未响应或返回不完整响应时,会回退到 `0x1000` 的 `BATTERY_STATUS`。找到电池功能后,HID 访问错误会直接终止读取。探测阶段某个接口出错时会跳过它,只有其他接口都没找到鼠标、也没有报告离线时,才返回该错误。如果两个功能都未返回电池状态,命令会报错,不会将读取失败显示为 `0%`。 +探测时,如果查询 `UNIFIED_BATTERY`(`0x1004`)没有收到回复,`gbat` 会跳过当前接口和索引。如果设备回复不支持该功能,它会继续查找 `BATTERY_STATUS`(`0x1000`)。已找到的 `UNIFIED_BATTERY` 未能返回可用状态时,它也会尝试后者。读取电池状态时遇到 HID 访问错误会结束查询。只有所有候选设备都未报告支持电池功能、也未报告鼠标离线时,才会返回探测阶段的错误。 ## 许可证 diff --git a/docs/record-demo.sh b/docs/record-demo.sh index 3002c75..61fd6fd 100755 --- a/docs/record-demo.sh +++ b/docs/record-demo.sh @@ -2,7 +2,7 @@ # Record the current build and connected mouse without replaying sample output. set -eu -project_root=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd -P) +project_root=$(CDPATH='' cd -- "$(dirname -- "$0")/.." && pwd -P) cd "$project_root" for dependency in cargo vhs ffmpeg; do @@ -12,6 +12,7 @@ for dependency in cargo vhs ffmpeg; do fi done +export CARGO_TARGET_DIR="$project_root/target" cargo build --release --locked binary="$project_root/target/release/gbat" version=$("$binary" --version) @@ -19,26 +20,15 @@ printf 'Recording %s\n' "$version" # Fail before recording if the mouse cannot provide a real battery reading. "$binary" -work_dir=$(mktemp -d "$project_root/target/record-demo.XXXXXX") +work_dir=$(mktemp -d target/record-demo.XXXXXX) trap 'rm -r "$work_dir"' EXIT trap 'exit 1' HUP INT TERM candidate="$work_dir/demo.gif" # Render to a temporary file so a failed recording keeps the published GIF. -awk -v output="$candidate" ' - /^[[:space:]]*Output[[:space:]]/ { - if (!replaced) { - print "Output \"" output "\"" - replaced = 1 - } - next - } - { print } - END { if (!replaced) exit 1 } -' demo.tape > "$work_dir/demo.tape" -vhs "$work_dir/demo.tape" +vhs --output "$candidate" demo.tape test -s "$candidate" ffmpeg -hide_banner -loglevel error -xerror -i "$candidate" -f null - -cp "$candidate" "$project_root/assets/demo.gif" +mv "$candidate" "$project_root/assets/demo.gif" printf 'Recorded %s in %s\n' "$version" "$project_root/assets/demo.gif" diff --git a/docs/recording.md b/docs/recording.md index e198b11..2902029 100644 --- a/docs/recording.md +++ b/docs/recording.md @@ -1,24 +1,13 @@ # README recordings -The terminal animation was captured on October 13, 2026, on macOS 27.0.1 with a -connected Logitech mouse. Its battery readings are live output. -The Raycast animation is the original GitHub asset and is kept unchanged. - -| Asset | Captured version | Source | +| Asset | Capture | Visible output | | --- | --- | --- | -| [`demo.gif`](../assets/demo.gif) | `gbat 0.0.1` | Local release build of `0.0.1` | -| [`raycast-demo.webp`](../assets/raycast-demo.webp) | Original capture; software versions not recorded | Original GitHub asset, retained unchanged | - -The terminal demo shows the binary's own `--version` output and `Battery: 61%`. -A later terminal recording may show a different level or charging state. -The original Raycast animation shows the `Logitech Mouse Battery` command and -`Battery: 86%`. It demonstrates the workflow without identifying a gbat release. - -The logo is static artwork. It contains no software version. +| [`demo.gif`](../assets/demo.gif) | Local release build on macOS 27.0.1, October 13, 2026, with a connected Logitech mouse | `gbat 0.0.1` and `Battery: 61%` | +| [`raycast-demo.webp`](../assets/raycast-demo.webp) | Original GitHub asset. Software versions were not recorded. | `Logitech Mouse Battery` and `Battery: 86%` | ## Record the terminal demo -Install Rust and the recording tools, connect the mouse, and keep it awake: +On macOS, install Rust and the recording tools, connect the mouse, and keep it awake: ```sh brew install vhs ffmpeg ttyd @@ -30,30 +19,20 @@ The script builds with `--locked`, verifies a real battery read, and records sets `GBAT_BINARY` to that same build, so all four commands use it. There is no sample-output wrapper. -The recorder renders to a temporary GIF and checks that FFmpeg can decode it -before replacing `assets/demo.gif`. Temporary files are removed on exit. +The recorder passes a temporary output path to VHS and checks that FFmpeg can +decode the entire GIF before moving it to `assets/demo.gif`. Use VHS `0.12.1` or later: `0.12.0` can exit successfully without rendering, which leaves the existing GIF untouched. The checked-in capture used VHS `0.12.1`, ttyd `1.7.7`, and FFmpeg `9.0.2`. -## Preserve the original Raycast animation - -Keep `assets/raycast-demo.webp` byte-for-byte identical to the original GitHub -asset as it was committed. Do not re-record, -re-encode, or replace it during gbat version updates or README drift checks. -Only change it when the user explicitly requests a replacement. - -The terminal recorder updates only `assets/demo.gif`. Its release version and -recording date do not apply to the Raycast animation. - ## Check before updating the README - Open the terminal animation and check its version, battery output, and readability. A successful recorder exit alone is not enough. -- Verify that the original Raycast animation remains unchanged. +- Preserve the original Raycast animation byte-for-byte during terminal demo + and release updates. Replace it only when explicitly requested. - Check every relative link and image reference in both README files. -- Update the terminal capture's version and tool versions here and its captions - in both README files together. Keep the binary version tied to `Cargo.toml` - and the intended release; do not change it to match an older recording. +- Record the capture date, CLI version, observed output, and tool versions here. + Both README captions link to this file.