diff --git a/src/hidpp.rs b/src/hidpp.rs index 06f67dd..b59b001 100644 --- a/src/hidpp.rs +++ b/src/hidpp.rs @@ -3,15 +3,15 @@ use std::time::{Duration, Instant}; use hidapi::{HidApi, HidDevice, HidError}; -pub const LOGITECH_VID: u16 = 0x046D; -pub const HIDPP_USAGE_PAGE: u16 = 0xFF00; +const LOGITECH_VID: u16 = 0x046D; +const HIDPP_USAGE_PAGE: u16 = 0xFF00; -pub const FEATURE_ROOT: u16 = 0x0000; -pub const FEATURE_BATTERY_STATUS: u16 = 0x1000; -pub const FEATURE_UNIFIED_BATTERY: u16 = 0x1004; +const FEATURE_ROOT: u8 = 0x00; +const FEATURE_BATTERY_STATUS: u16 = 0x1000; +const FEATURE_UNIFIED_BATTERY: u16 = 0x1004; -pub const REPORT_ID_SHORT: u8 = 0x10; -pub const REPORT_ID_LONG: u8 = 0x11; +const REPORT_ID_SHORT: u8 = 0x10; +const REPORT_ID_LONG: u8 = 0x11; /// Error markers in the third byte of a short or long report: receivers use /// the HID++ 1.0 marker and HID++ 2.0 devices use their own. const ERROR_MARKER_HIDPP10: u8 = 0x8F; @@ -19,11 +19,11 @@ const ERROR_MARKER_HIDPP20: u8 = 0xFF; /// HID++ 1.0 error code a receiver returns for a device index with no /// connected device. const ERROR_CODE_UNKNOWN_DEVICE: u8 = 0x08; -pub const DEFAULT_SW_ID: u8 = 0x0F; +const SW_ID: u8 = 0x0F; /// Receiver-paired devices answer on 1..=6 and a directly connected device on /// 0xFF, so probe both common slots before the rarely used ones. -pub const DEVICE_INDEX_CANDIDATES: &[u8] = &[1, 0xFF, 2, 3, 4, 5, 6]; +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); @@ -39,43 +39,34 @@ pub struct BatteryStatus { pub charging: bool, } -/// A reply that matched the request but cannot be decoded. `match_report` -/// already checked the report ID, device index, feature index, and function -/// byte, and turned error reports into their own outcomes. -#[derive(Debug, Clone, PartialEq, Eq)] -pub enum ProtocolError { - ShortResponse { minimum: usize, actual: usize }, -} - -impl fmt::Display for ProtocolError { - fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - Self::ShortResponse { minimum, actual } => write!( - formatter, - "short HID++ response: expected at least {minimum} bytes, got {actual}" - ), - } - } -} - -impl std::error::Error for ProtocolError {} - #[derive(Debug)] pub enum HidppError { Hid(HidError), - Protocol(ProtocolError), - ShortWrite { expected: usize, actual: usize }, + ShortWrite { + expected: usize, + actual: usize, + }, + /// A reply matched the request but is too short to decode. `match_report` + /// already checked the report ID, device index, feature index, and function + /// byte, and turned error reports into their own outcomes. + ShortResponse { + minimum: usize, + actual: usize, + }, } impl fmt::Display for HidppError { fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Self::Hid(error) => write!(formatter, "HID access failed: {error}"), - Self::Protocol(error) => error.fmt(formatter), Self::ShortWrite { expected, actual } => write!( formatter, "short HID++ write: expected {expected} bytes, wrote {actual}" ), + Self::ShortResponse { minimum, actual } => write!( + formatter, + "short HID++ response: expected at least {minimum} bytes, got {actual}" + ), } } } @@ -88,12 +79,6 @@ impl From for HidppError { } } -impl From for HidppError { - fn from(error: ProtocolError) -> Self { - Self::Protocol(error) - } -} - /// What a single HID++ request produced. enum Reply { Response { @@ -116,14 +101,8 @@ enum FeatureLookup { Silent, } -/// What probing one device index on one interface found. -enum ProbeOutcome { - Found(D), - Offline, - Absent, -} - -/// What probing every interface and device index found. +/// What probing one device index, or every interface and device index, found. +#[derive(Debug)] pub enum Discovery { Found(D), /// A receiver answered, but reported no connected mouse. @@ -131,9 +110,21 @@ pub enum Discovery { NotFound, } +impl Discovery { + fn map(self, found: impl FnOnce(D) -> E) -> Discovery { + match self { + Self::Found(value) => Discovery::Found(found(value)), + Self::Offline => Discovery::Offline, + Self::NotFound => Discovery::NotFound, + } + } +} + +/// An open HID++ interface with the device index and battery feature that +/// discovery selected. pub struct HidppTransport { device: HidDevice, - pub device_index: u8, + device_index: u8, battery_feature: BatteryFeature, } @@ -143,12 +134,6 @@ enum BatteryFeature { Legacy(u8), } -trait BatteryDevice { - fn selected_feature(&self) -> BatteryFeature; - fn discover_feature(&self, feature_id: u16) -> Result, HidppError>; - fn query_feature(&self, feature: BatteryFeature) -> Result, HidppError>; -} - /// Report I/O and the monotonic timeline used by a request. trait RequestIo { fn write(&self, report: &[u8]) -> Result; @@ -170,38 +155,25 @@ impl RequestIo for HidDevice { } } -/// A borrowed device with the feature selected by discovery. -struct BatterySession<'a, I> { - io: &'a I, - device_index: u8, - battery_feature: BatteryFeature, -} - -impl HidppTransport { - fn session(&self) -> BatterySession<'_, HidDevice> { - BatterySession { - io: &self.device, - device_index: self.device_index, - battery_feature: self.battery_feature, - } +fn ensure_length(response: &[u8], minimum: usize) -> Result<(), HidppError> { + if response.len() < minimum { + return Err(HidppError::ShortResponse { + minimum, + actual: response.len(), + }); } + Ok(()) } -pub fn parse_feature_index(response: &[u8]) -> Result, ProtocolError> { +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)) } -pub fn parse_unified_battery(response: &[u8]) -> Result { - parse_battery(response, 7) -} - -pub fn parse_battery_status(response: &[u8]) -> Result { - parse_battery(response, 6) -} - -fn parse_battery(response: &[u8], charging_offset: usize) -> Result { +/// 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 { ensure_length(response, charging_offset + 1)?; Ok(BatteryStatus { level: response[4], @@ -209,16 +181,6 @@ fn parse_battery(response: &[u8], charging_offset: usize) -> Result Result<(), ProtocolError> { - if response.len() < minimum_length { - return Err(ProtocolError::ShortResponse { - minimum: minimum_length, - actual: response.len(), - }); - } - Ok(()) -} - /// Discard reports that arrived before the current request. Queued reports are /// already available, so this never waits for new ones. fn flush(device: &impl RequestIo) -> Result<(), HidppError> { @@ -232,10 +194,6 @@ fn flush(device: &impl RequestIo) -> Result<(), HidppError> { Ok(()) } -fn function_byte(function: u8, sw_id: u8) -> u8 { - ((function & 0x0F) << 4) | (sw_id & 0x0F) -} - /// Remaining time for one request, capped at the per-request timeout. fn request_timeout(device: &impl RequestIo, deadline: Instant) -> Duration { deadline @@ -243,22 +201,7 @@ fn request_timeout(device: &impl RequestIo, deadline: Instant) -> Duration { .min(RESPONSE_TIMEOUT) } -fn send_short( - device: &impl RequestIo, - device_index: u8, - feature_index: u8, - function_byte: u8, - payload: [u8; 3], -) -> Result<(), HidppError> { - let report = [ - REPORT_ID_SHORT, - device_index, - feature_index, - function_byte, - payload[0], - payload[1], - payload[2], - ]; +fn send_short(device: &impl RequestIo, report: [u8; 7]) -> Result<(), HidppError> { let actual = device.write(&report)?; if actual != report.len() { return Err(HidppError::ShortWrite { @@ -269,10 +212,6 @@ fn send_short( Ok(()) } -fn is_error_marker(byte: u8) -> bool { - matches!(byte, ERROR_MARKER_HIDPP10 | ERROR_MARKER_HIDPP20) -} - /// How a received report relates to the request awaiting a reply. #[derive(Debug, Clone, Copy, PartialEq, Eq)] enum ReportMatch { @@ -306,8 +245,8 @@ fn match_report( [feature, function, ..] if feature == feature_index && function == function_byte => { ReportMatch::Reply } - [marker, feature, function, code, ..] - if is_error_marker(marker) && feature == feature_index && function == function_byte => + [marker @ (ERROR_MARKER_HIDPP10 | ERROR_MARKER_HIDPP20), feature, function, code, ..] + if feature == feature_index && function == function_byte => { if marker == ERROR_MARKER_HIDPP10 && code == ERROR_CODE_UNKNOWN_DEVICE { ReportMatch::Offline @@ -357,30 +296,39 @@ fn request( device_index: u8, feature_index: u8, function: u8, - sw_id: u8, payload: [u8; 3], timeout: Duration, ) -> Result { - let function_byte = function_byte(function, sw_id); + let function_byte = (function << 4) | SW_ID; flush(device)?; - send_short(device, device_index, feature_index, function_byte, payload)?; + send_short( + device, + [ + REPORT_ID_SHORT, + device_index, + feature_index, + function_byte, + payload[0], + payload[1], + payload[2], + ], + )?; read_response(device, device_index, feature_index, function_byte, timeout) } -fn get_feature_index_on_device( +fn lookup_feature( device: &impl RequestIo, device_index: u8, - sw_id: u8, feature_id: u16, timeout: Duration, ) -> Result { + let [feature_high, feature_low] = feature_id.to_be_bytes(); let reply = request( device, device_index, - FEATURE_ROOT as u8, + FEATURE_ROOT, 0, - sw_id, - [(feature_id >> 8) as u8, feature_id as u8, 0], + [feature_high, feature_low, 0], timeout, )?; Ok(match reply { @@ -394,105 +342,63 @@ fn get_feature_index_on_device( }) } -fn query_battery_on_device( +fn query_feature( device: &impl RequestIo, device_index: u8, - sw_id: u8, - feature_index: u8, - function: u8, - parse_response: fn(&[u8]) -> Result, + feature: BatteryFeature, ) -> Result, HidppError> { + // Unified Battery reads its status with function 1, Battery Status with + // function 0. + let (feature_index, function, charging_offset) = match feature { + BatteryFeature::Unified(index) => (index, 0x01, 7), + BatteryFeature::Legacy(index) => (index, 0x00, 6), + }; let reply = request( device, device_index, feature_index, function, - sw_id, [0; 3], RESPONSE_TIMEOUT, )?; match reply { - Reply::Response { buffer, length } => Ok(Some(parse_response(&buffer[..length])?)), + Reply::Response { buffer, length } => { + Ok(Some(parse_battery(&buffer[..length], charging_offset)?)) + } Reply::DeviceError | Reply::Offline | Reply::Silence => Ok(None), } } -pub fn get_feature_index( - transport: &HidppTransport, - feature_id: u16, -) -> Result, HidppError> { - transport.session().discover_feature(feature_id) -} - -impl BatteryDevice for HidppTransport { - fn selected_feature(&self) -> BatteryFeature { - self.battery_feature - } - - fn discover_feature(&self, feature_id: u16) -> Result, HidppError> { - get_feature_index(self, feature_id) - } - - fn query_feature(&self, feature: BatteryFeature) -> Result, HidppError> { - self.session().query_feature(feature) - } -} - -impl BatteryDevice for BatterySession<'_, I> { - fn selected_feature(&self) -> BatteryFeature { - self.battery_feature - } - - fn discover_feature(&self, feature_id: u16) -> Result, HidppError> { - let lookup = get_feature_index_on_device( - self.io, - self.device_index, - DEFAULT_SW_ID, - feature_id, - RESPONSE_TIMEOUT, - )?; - Ok(match lookup { - FeatureLookup::Index(feature_index) => Some(feature_index), - FeatureLookup::Unsupported | FeatureLookup::Offline | FeatureLookup::Silent => None, - }) - } - - fn query_feature(&self, feature: BatteryFeature) -> Result, HidppError> { - let (feature_index, function, parser) = match feature { - BatteryFeature::Unified(index) => (index, 0x01, parse_unified_battery as _), - BatteryFeature::Legacy(index) => (index, 0x00, parse_battery_status as _), - }; - query_battery_on_device( - self.io, - self.device_index, - DEFAULT_SW_ID, - feature_index, - function, - parser, - ) - } -} - -fn read_battery_from(transport: &T) -> Result, HidppError> { - let selected_feature = transport.selected_feature(); - if matches!(selected_feature, BatteryFeature::Legacy(_)) { - return transport.query_feature(selected_feature); +/// Read the discovered feature. A unified read that fails to produce a status +/// falls back to the legacy feature, unless the transport failed. +fn read_battery_from( + device: &impl RequestIo, + device_index: u8, + feature: BatteryFeature, +) -> Result, HidppError> { + if matches!(feature, BatteryFeature::Legacy(_)) { + return query_feature(device, device_index, feature); } - let unified_result = transport.query_feature(selected_feature); - let query_legacy = || { - let Some(feature_index) = transport.discover_feature(FEATURE_BATTERY_STATUS)? else { - return Ok(None); - }; - transport.query_feature(BatteryFeature::Legacy(feature_index)) + let unified_result = query_feature(device, device_index, feature); + let query_legacy = || match lookup_feature( + device, + device_index, + FEATURE_BATTERY_STATUS, + RESPONSE_TIMEOUT, + )? { + FeatureLookup::Index(index) => { + query_feature(device, device_index, BatteryFeature::Legacy(index)) + } + FeatureLookup::Unsupported | FeatureLookup::Offline | FeatureLookup::Silent => Ok(None), }; match unified_result { Ok(Some(status)) => Ok(Some(status)), Ok(None) => query_legacy(), - Err(error @ HidppError::Protocol(_)) => match query_legacy() { + Err(error @ HidppError::ShortResponse { .. }) => match query_legacy() { Ok(Some(status)) => Ok(Some(status)), - Ok(None) | Err(HidppError::Protocol(_)) => Err(error), + Ok(None) | Err(HidppError::ShortResponse { .. }) => Err(error), Err(legacy_error @ (HidppError::Hid(_) | HidppError::ShortWrite { .. })) => { Err(legacy_error) } @@ -502,7 +408,11 @@ fn read_battery_from(transport: &T) -> Result Result, HidppError> { - read_battery_from(transport) + read_battery_from( + &transport.device, + transport.device_index, + transport.battery_feature, + ) } fn candidate_interfaces(api: &HidApi) -> Vec<&hidapi::DeviceInfo> { @@ -524,38 +434,36 @@ fn find_battery_feature( device: &impl RequestIo, device_index: u8, deadline: Instant, -) -> Result, HidppError> { - let unified = get_feature_index_on_device( +) -> Result, HidppError> { + let unified = lookup_feature( device, device_index, - DEFAULT_SW_ID, FEATURE_UNIFIED_BATTERY, request_timeout(device, deadline), )?; match unified { FeatureLookup::Index(feature_index) => { - return Ok(ProbeOutcome::Found(BatteryFeature::Unified(feature_index))) + return Ok(Discovery::Found(BatteryFeature::Unified(feature_index))) } - FeatureLookup::Offline => return Ok(ProbeOutcome::Offline), + FeatureLookup::Offline => return Ok(Discovery::Offline), // Every HID++ 2.0 device answers root feature lookups, so silence means // this index is absent and the legacy lookup would only wait again. - FeatureLookup::Silent => return Ok(ProbeOutcome::Absent), + FeatureLookup::Silent => return Ok(Discovery::NotFound), FeatureLookup::Unsupported => {} } - let legacy = get_feature_index_on_device( + let legacy = lookup_feature( device, device_index, - DEFAULT_SW_ID, FEATURE_BATTERY_STATUS, request_timeout(device, deadline), )?; Ok(match legacy { FeatureLookup::Index(feature_index) => { - ProbeOutcome::Found(BatteryFeature::Legacy(feature_index)) + Discovery::Found(BatteryFeature::Legacy(feature_index)) } - FeatureLookup::Offline => ProbeOutcome::Offline, - FeatureLookup::Unsupported | FeatureLookup::Silent => ProbeOutcome::Absent, + FeatureLookup::Offline => Discovery::Offline, + FeatureLookup::Unsupported | FeatureLookup::Silent => Discovery::NotFound, }) } @@ -600,19 +508,19 @@ fn discover( interface_count: usize, deadline: Instant, now: impl Fn() -> Instant, - mut probe: impl FnMut(usize, u8) -> Result, HidppError>, + mut probe: impl FnMut(usize, u8) -> Result, HidppError>, ) -> Result, HidppError> { let mut offline = false; let mut last_error = None; - 'probe: for &device_index in DEVICE_INDEX_CANDIDATES { + 'probe: for device_index in DEVICE_INDEX_CANDIDATES { for interface in 0..interface_count { if now() >= deadline { break 'probe; } match probe(interface, device_index) { - Ok(ProbeOutcome::Found(found)) => return Ok(Discovery::Found(found)), - Ok(ProbeOutcome::Offline) => offline = true, - Ok(ProbeOutcome::Absent) => {} + Ok(Discovery::Found(found)) => return Ok(Discovery::Found(found)), + Ok(Discovery::Offline) => offline = true, + Ok(Discovery::NotFound) => {} Err(error) => last_error = Some(error), } } @@ -641,27 +549,21 @@ pub fn open_first_working_transport(api: &HidApi) -> Result { - let ProbeSlot::Open(device) = - std::mem::replace(&mut slots[interface], ProbeSlot::Failed) - else { - return Ok(ProbeOutcome::Absent); - }; - ProbeOutcome::Found(HidppTransport { - device, - device_index, - battery_feature, - }) + let outcome = find_battery_feature(device, device_index, deadline)?; + Ok(outcome.map(|battery_feature| { + let ProbeSlot::Open(device) = std::mem::replace(slot, ProbeSlot::Failed) else { + unreachable!("a found battery feature comes from an open interface"); + }; + HidppTransport { + device, + device_index, + battery_feature, } - ProbeOutcome::Offline => ProbeOutcome::Offline, - ProbeOutcome::Absent => ProbeOutcome::Absent, - }; - Ok(outcome) + })) }, ) } @@ -674,18 +576,34 @@ mod tests { use super::*; - #[derive(Debug, Clone, Copy, PartialEq, Eq)] - enum ReadPhase { - Flush, - Response, + 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_LEVEL: BatteryStatus = 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]; + // Captured from a LIGHTSPEED receiver while its paired mouse was off. + const RECEIVER_OFFLINE: [u8; 7] = [REPORT_ID_SHORT, 1, 0x8F, 0, 0x0F, 0x08, 0]; + + const fn unified_lookup(device_index: u8) -> [u8; 7] { + [REPORT_ID_SHORT, device_index, 0, 0x0F, 0x10, 0x04, 0] } - /// An ordered script gates response reports behind their request's write. - /// The phase is explicit because both phases can use a zero read timeout. + 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 { - phase: ReadPhase, timeout_ms: i32, result: Result, HidError>, advance: Duration, @@ -698,15 +616,19 @@ mod tests { } impl ScriptStep { - fn flush(report: &[u8]) -> Self { + fn read(timeout_ms: i32, report: &[u8]) -> Self { Self::Read { - phase: ReadPhase::Flush, - timeout_ms: 0, + 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(), @@ -715,113 +637,84 @@ mod tests { } } - fn response(timeout_ms: i32, report: &[u8]) -> Self { - Self::Read { - phase: ReadPhase::Response, - timeout_ms, - result: Ok(report.to_vec()), - advance: Duration::ZERO, - } + fn silence(timeout_ms: i32, advance: Duration) -> Self { + Self::read(timeout_ms, &[]).after(advance) } - fn silence(timeout_ms: i32, advance: Duration) -> Self { - Self::Read { - phase: ReadPhase::Response, - timeout_ms, - result: Ok(Vec::new()), - advance, - } + fn after(mut self, elapsed: Duration) -> Self { + let (Self::Read { advance, .. } | Self::Write { advance, .. }) = &mut self; + *advance = elapsed; + self } } - #[derive(Debug, Clone, PartialEq, Eq)] - enum IoCall { - Read(i32), - Write(Vec), + /// 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 + } + + /// 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 multiple scripted interfaces on one timeline. clock: Rc>, + start: Instant, steps: RefCell>, - calls: RefCell>, } impl ScriptedIo { - fn new(steps: Vec) -> Self { - let mut after_write = false; - for step in &steps { - match step { - ScriptStep::Write { .. } => after_write = true, - ScriptStep::Read { - phase: ReadPhase::Flush, - timeout_ms, - .. - } => { - assert_eq!(*timeout_ms, 0, "flush reads must be nonblocking"); - after_write = false; - } - ScriptStep::Read { - phase: ReadPhase::Response, - result, - advance, - .. - } => { - assert!( - after_write, - "a scripted response requires a preceding write" - ); - if matches!(result, Ok(report) if report.is_empty()) { - assert!( - !advance.is_zero(), - "scripted silence must advance virtual time" - ); - } - } - } - } + fn new>(parts: impl IntoIterator) -> Self { + let start = Instant::now(); Self { - clock: Rc::new(Cell::new(Instant::now())), - steps: RefCell::new(steps.into()), - calls: RefCell::new(Vec::new()), + clock: Rc::new(Cell::new(start)), + start, + steps: RefCell::new(parts.into_iter().flatten().collect()), } } - fn assert_finished(&self) { - assert!( - self.steps.borrow().is_empty(), - "unconsumed script steps: {:?}", - self.steps.borrow() - ); + fn elapsed(&self) -> Duration { + self.now() - self.start } - fn writes(&self) -> Vec> { - self.calls - .borrow() - .iter() - .filter_map(|call| match call { - IoCall::Write(report) => Some(report.clone()), - IoCall::Read(_) => None, - }) - .collect() + 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 { - self.calls.borrow_mut().push(IoCall::Write(report.to_vec())); - let step = self - .steps - .borrow_mut() - .pop_front() - .expect("script exhausted during write"); let ScriptStep::Write { report: expected, result, advance, - } = step + } = self.next_step("write") else { - panic!("unexpected write; expected {step:?}"); + panic!("unexpected write of {report:02X?}"); }; assert_eq!(report, expected, "unexpected request bytes"); self.clock.set(self.now() + advance); @@ -829,28 +722,17 @@ mod tests { } fn read_timeout(&self, buffer: &mut [u8], timeout_ms: i32) -> Result { - self.calls.borrow_mut().push(IoCall::Read(timeout_ms)); - let step = self - .steps - .borrow_mut() - .pop_front() - .expect("script exhausted during read"); let ScriptStep::Read { timeout_ms: expected, result, advance, - .. - } = step + } = self.next_step("read") else { - panic!("unexpected read; expected {step:?}"); + 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?; - assert!( - report.len() <= buffer.len(), - "scripted report exceeds buffer" - ); buffer[..report.len()].copy_from_slice(&report); Ok(report.len()) } @@ -860,249 +742,257 @@ mod tests { } } - #[derive(Debug, Clone, Copy, PartialEq, Eq)] - enum TransportCall { - Discover(u16), - Query(BatteryFeature), + /// Discover the battery feature on `device_index`, then read it. + fn probe_and_read( + io: &ScriptedIo, + device_index: u8, + ) -> Result, HidppError> { + let Ok(Discovery::Found(battery_feature)) = + find_battery_feature(io, device_index, io.now() + DISCOVERY_BUDGET) + else { + panic!("a battery feature should be found on device index {device_index}"); + }; + read_battery_from(io, device_index, battery_feature) } - struct FakeTransport { - selected_feature: BatteryFeature, - feature_results: RefCell, HidppError>>>, - query_results: RefCell, HidppError>>>, - calls: RefCell>, + /// Discover on a single interface. + fn discover_single( + io: &ScriptedIo, + deadline: Instant, + ) -> Result, HidppError> { + discover( + 1, + deadline, + || io.now(), + |_, device_index| find_battery_feature(io, device_index, deadline), + ) } - impl FakeTransport { - fn new( - selected_feature: BatteryFeature, - feature_results: Vec, HidppError>>, - query_results: Vec, HidppError>>, - ) -> Self { - Self { - selected_feature, - feature_results: RefCell::new(feature_results.into()), - query_results: RefCell::new(query_results.into()), - calls: RefCell::new(Vec::new()), - } - } - - fn calls(&self) -> Vec { - self.calls.borrow().clone() - } + 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}") + ); } - impl BatteryDevice for FakeTransport { - fn selected_feature(&self) -> BatteryFeature { - self.selected_feature - } - - fn discover_feature(&self, feature_id: u16) -> Result, HidppError> { - self.calls - .borrow_mut() - .push(TransportCall::Discover(feature_id)); - self.feature_results - .borrow_mut() - .pop_front() - .expect("fake feature result should be configured") - } - - fn query_feature( - &self, - feature: BatteryFeature, - ) -> Result, HidppError> { - self.calls.borrow_mut().push(TransportCall::Query(feature)); - self.query_results - .borrow_mut() - .pop_front() - .expect("fake query result should be configured") + #[test] + fn classifies_reports_against_the_request() { + // The request goes to device index 1, feature 5, function 1, software ID 0x0F. + let cases: [(&[u8], ReportMatch); 14] = [ + (&[REPORT_ID_SHORT, 1, 5, 0x1F, 78, 0, 0], ReportMatch::Reply), + ( + &[REPORT_ID_LONG, 1, 5, 0x1F, 78, 0, 0, 1], + ReportMatch::Reply, + ), + (&[0x12, 1, 5, 0x1F, 78, 0, 0], ReportMatch::Unrelated), + ( + &[REPORT_ID_SHORT, 2, 5, 0x1F, 78, 0, 0], + ReportMatch::Unrelated, + ), + ( + &[REPORT_ID_SHORT, 1, 6, 0x1F, 78, 0, 0], + ReportMatch::Unrelated, + ), + ( + &[REPORT_ID_SHORT, 1, 5, 0x0F, 78, 0, 0], + ReportMatch::Unrelated, + ), + ( + &[REPORT_ID_SHORT, 1, 5, 0x1E, 78, 0, 0], + ReportMatch::Unrelated, + ), + (&[REPORT_ID_SHORT, 1], ReportMatch::Unrelated), + ( + &[REPORT_ID_SHORT, 1, 0x8F, 5, 0x1F, 0x08, 0], + ReportMatch::Offline, + ), + ( + &[REPORT_ID_SHORT, 1, 0x8F, 5, 0x1F, 0x02, 0], + ReportMatch::DeviceError, + ), + // Only the receiver's HID++ 1.0 error means no connected device. + ( + &[REPORT_ID_LONG, 1, 0xFF, 5, 0x1F, 0x08, 0], + ReportMatch::DeviceError, + ), + // Errors must echo the request too. + ( + &[REPORT_ID_SHORT, 1, 0x8F, 6, 0x1F, 0x08, 0], + ReportMatch::Unrelated, + ), + ( + &[REPORT_ID_SHORT, 1, 0xFF, 5, 0x0F, 0x02, 0], + ReportMatch::Unrelated, + ), + ( + &[REPORT_ID_SHORT, 1, 0x8E, 5, 0x1F, 0x02, 0], + ReportMatch::Unrelated, + ), + ]; + for (report, expected) in cases { + assert_eq!( + match_report(report, 1, 5, 0x1F), + expected, + "report {report:02X?}" + ); } } - mod report_matching { + mod discovery { use super::*; - const UNIFIED_LOOKUP: [u8; 7] = [REPORT_ID_SHORT, 1, 0, 0x0F, 0x10, 0x04, 0]; - 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]; - // Captured from a LIGHTSPEED receiver while its paired mouse was off. - const RECEIVER_OFFLINE: [u8; 7] = [REPORT_ID_SHORT, 1, 0x8F, 0, 0x0F, 0x08, 0]; - - fn exchange(report: &[u8], replies: &[&[u8]]) -> Vec { - let mut steps = vec![ScriptStep::flush(&[]), ScriptStep::write(report)]; - steps.extend( - replies - .iter() - .map(|reply| ScriptStep::response(1_500, reply)), + #[test] + fn skips_unrelated_reports_and_errors_until_the_matching_reply() { + let io = ScriptedIo::new([ + 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!( + probe_and_read(&io, 1).unwrap(), + Some(BatteryStatus { + level: 78, + charging: true, + }) ); - steps } #[test] - fn ordinary_replies_must_match_every_request_field() { - for (field, discovery_value, battery_value) in - [(1, 2, 2), (2, 9, 9), (3, 0x1F, 0x0F), (3, 0x0E, 0x1E)] + 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 feature_reply = [REPORT_ID_SHORT, 1, 0, 0x0F, 5, 0, 0]; - let battery_reply = [REPORT_ID_LONG, 1, 5, 0x1F, 78, 0, 0, 1]; - let mut unrelated_feature = [REPORT_ID_SHORT, 1, 0, 0x0F, 9, 0, 0]; - unrelated_feature[field] = discovery_value; - let mut unrelated_battery = [REPORT_ID_LONG, 1, 5, 0x1F, 12, 0, 0, 0]; - unrelated_battery[field] = battery_value; - let mut steps = exchange(&UNIFIED_LOOKUP, &[&unrelated_feature, &feature_reply]); - steps.extend(exchange( - &UNIFIED_QUERY, - &[&unrelated_battery, &battery_reply], - )); - let io = ScriptedIo::new(steps); - - let ProbeOutcome::Found(battery_feature) = - find_battery_feature(&io, 1, io.now() + DISCOVERY_BUDGET).unwrap() - else { - panic!("the matching feature reply should select unified battery"); - }; - assert_eq!(battery_feature, BatteryFeature::Unified(5)); - let session = BatterySession { - io: &io, - device_index: 1, - battery_feature, + 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 }; + let io = ScriptedIo::new([ + 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!( - read_battery_from(&session).unwrap(), - Some(BatteryStatus { - level: 78, - charging: true, - }) + probe_and_read(&io, device_index).unwrap(), + Some(BatteryStatus { level, charging }) ); - assert_eq!(io.writes(), vec![UNIFIED_LOOKUP, UNIFIED_QUERY]); - io.assert_finished(); } } #[test] - fn errors_echoing_other_requests_do_not_hide_matching_replies() { - for marker in [ERROR_MARKER_HIDPP10, ERROR_MARKER_HIDPP20] { - for (field, discovery_value, battery_value) in - [(1, 2, 2), (3, 9, 9), (4, 0x1F, 0x0F), (4, 0x0E, 0x1E)] - { - let mut discovery_error = [REPORT_ID_SHORT, 1, marker, 0, 0x0F, 0x08, 0]; - discovery_error[field] = discovery_value; - let mut battery_error = [REPORT_ID_SHORT, 1, marker, 5, 0x1F, 0x08, 0]; - battery_error[field] = battery_value; - let mut steps = exchange( - &UNIFIED_LOOKUP, - &[&discovery_error, &[REPORT_ID_SHORT, 1, 0, 0x0F, 5, 0, 0]], - ); - steps.extend(exchange( - &UNIFIED_QUERY, - &[&battery_error, &[REPORT_ID_LONG, 1, 5, 0x1F, 64, 0, 0, 0]], - )); - let io = ScriptedIo::new(steps); - - let ProbeOutcome::Found(battery_feature) = - find_battery_feature(&io, 1, io.now() + DISCOVERY_BUDGET).unwrap() - else { - panic!("an unrelated error must not end feature discovery"); - }; - let session = BatterySession { - io: &io, - device_index: 1, - battery_feature, - }; - assert_eq!( - read_battery_from(&session).unwrap(), - Some(BatteryStatus { - level: 64, - charging: false, - }) - ); - assert_eq!(io.writes(), vec![UNIFIED_LOOKUP, UNIFIED_QUERY]); - io.assert_finished(); - } + 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 io = ScriptedIo::new([ + exchange(&UNIFIED_LOOKUP, [reply(&unified_reply)]), + exchange(&LEGACY_LOOKUP, [reply(&LEGACY_FEATURE)]), + exchange(&LEGACY_QUERY, [reply(&LEGACY_STATUS)]), + ]); + + assert_eq!(probe_and_read(&io, 1).unwrap(), Some(LEGACY_LEVEL)); } } #[test] - fn matching_device_errors_allow_legacy_feature_discovery() { - for (marker, code) in [(0x8F, 0x02), (0xFF, 0x02), (0xFF, 0x08)] { - let mut steps = exchange( - &UNIFIED_LOOKUP, - &[&[REPORT_ID_SHORT, 1, marker, 0, 0x0F, code, 0]], - ); - steps.extend(exchange( - &LEGACY_LOOKUP, - &[&[REPORT_ID_SHORT, 1, 0, 0x0F, 6, 0, 0]], - )); - steps.extend(exchange( - &LEGACY_QUERY, - &[&[REPORT_ID_SHORT, 1, 6, 0x0F, 42, 0, 1]], - )); - let io = ScriptedIo::new(steps); - - let ProbeOutcome::Found(battery_feature) = - find_battery_feature(&io, 1, io.now() + DISCOVERY_BUDGET).unwrap() - else { - panic!("a device error should permit the legacy feature lookup"); - }; - assert_eq!(battery_feature, BatteryFeature::Legacy(6)); - let session = BatterySession { - io: &io, - device_index: 1, - battery_feature, - }; - assert_eq!( - read_battery_from(&session).unwrap(), - Some(BatteryStatus { - level: 42, - charging: true, - }) - ); - assert_eq!( - io.writes(), - vec![UNIFIED_LOOKUP, LEGACY_LOOKUP, LEGACY_QUERY] - ); - io.assert_finished(); - } + fn receiver_offline_ends_the_probe_without_waiting_or_legacy_lookup() { + let reply_delay = ms(17); + let io = ScriptedIo::new([exchange( + &UNIFIED_LOOKUP, + [reply(&RECEIVER_OFFLINE).after(reply_delay)], + )]); + + let result = find_battery_feature(&io, 1, io.now() + DISCOVERY_BUDGET); + + assert!(matches!(result, Ok(Discovery::Offline))); + assert_eq!(io.elapsed(), reply_delay); } #[test] - fn receiver_offline_ends_discovery_without_waiting_or_legacy_lookup() { - let reply_delay = Duration::from_millis(17); - let io = ScriptedIo::new(vec![ - ScriptStep::flush(&[]), - ScriptStep::write(&UNIFIED_LOOKUP), - ScriptStep::Read { - phase: ReadPhase::Response, - timeout_ms: 1_500, - result: Ok(RECEIVER_OFFLINE.to_vec()), - advance: reply_delay, - }, - ]); - let start = io.now(); + fn silence_after_an_unmatched_reply_skips_legacy_lookup() { + let io = ScriptedIo::new([exchange( + &UNIFIED_LOOKUP, + [reply(&[REPORT_ID_SHORT, 2, 0, 0x0F, 5, 0, 0]), no_reply()], + )]); - let result = find_battery_feature(&io, 1, start + DISCOVERY_BUDGET); + let result = find_battery_feature(&io, 1, io.now() + DISCOVERY_BUDGET); - assert!(matches!(result, Ok(ProbeOutcome::Offline))); - assert_eq!(io.now().duration_since(start), reply_delay); - assert_eq!(io.writes(), vec![UNIFIED_LOOKUP]); - io.assert_finished(); + assert!(matches!(result, Ok(Discovery::NotFound))); + assert_eq!(io.elapsed(), RESPONSE_TIMEOUT); } #[test] - fn discovery_continues_from_offline_receiver_to_direct_usb() { - let usb_lookup = [REPORT_ID_SHORT, 0xFF, 0, 0x0F, 0x10, 0x04, 0]; - let usb_query = [REPORT_ID_SHORT, 0xFF, 9, 0x1F, 0, 0, 0]; - let mut steps = exchange(&UNIFIED_LOOKUP, &[&RECEIVER_OFFLINE]); - steps.extend(exchange( - &usb_lookup, - &[&[REPORT_ID_SHORT, 0xFF, 0, 0x0F, 9, 0, 0]], - )); - steps.extend(exchange( - &usb_query, - &[&[REPORT_ID_LONG, 0xFF, 9, 0x1F, 53, 0, 0, 1]], - )); - let io = ScriptedIo::new(steps); + fn continues_from_an_offline_receiver_to_direct_usb() { + let io = ScriptedIo::new([ + exchange(&UNIFIED_LOOKUP, [reply(&RECEIVER_OFFLINE)]), + 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])], + ), + ]); let deadline = io.now() + DISCOVERY_BUDGET; let found = discover( @@ -1110,53 +1000,40 @@ mod tests { deadline, || io.now(), |_, device_index| { - Ok(match find_battery_feature(&io, device_index, deadline)? { - ProbeOutcome::Found(battery_feature) => { - ProbeOutcome::Found(BatterySession { - io: &io, - device_index, - battery_feature, - }) - } - ProbeOutcome::Offline => ProbeOutcome::Offline, - ProbeOutcome::Absent => ProbeOutcome::Absent, - }) + Ok(find_battery_feature(&io, device_index, deadline)? + .map(|battery_feature| (device_index, battery_feature))) }, - ) - .unwrap(); + ); - let Discovery::Found(session) = found else { + let Ok(Discovery::Found((device_index, battery_feature))) = found else { panic!("discovery should continue to the direct USB candidate"); }; - assert_eq!(session.device_index, 0xFF); - assert_eq!(session.battery_feature, BatteryFeature::Unified(9)); assert_eq!( - read_battery_from(&session).unwrap(), + read_battery_from(&io, device_index, battery_feature).unwrap(), Some(BatteryStatus { level: 53, charging: true, }) ); - assert_eq!(io.writes(), vec![UNIFIED_LOOKUP, usb_lookup, usb_query]); - io.assert_finished(); } #[test] - fn discovery_checks_likely_indices_on_every_interface_first() { - let usb_lookup = [REPORT_ID_SHORT, 0xFF, 0, 0x0F, 0x10, 0x04, 0]; - let mut first_steps = exchange(&UNIFIED_LOOKUP, &[&RECEIVER_OFFLINE]); - first_steps.extend(exchange( - &usb_lookup, - &[&[REPORT_ID_SHORT, 0xFF, 0x8F, 0, 0x0F, 0x08, 0]], - )); - let first = ScriptedIo::new(first_steps); - let mut second_steps = exchange(&UNIFIED_LOOKUP, &[&RECEIVER_OFFLINE]); - second_steps.extend(exchange( - &usb_lookup, - &[&[REPORT_ID_SHORT, 0xFF, 0, 0x0F, 9, 0, 0]], - )); - let mut second = ScriptedIo::new(second_steps); - second.clock = Rc::clone(&first.clock); + fn checks_likely_indices_on_every_interface_first() { + let first = ScriptedIo::new([ + exchange(&UNIFIED_LOOKUP, [reply(&RECEIVER_OFFLINE)]), + exchange( + &unified_lookup(0xFF), + [reply(&[REPORT_ID_SHORT, 0xFF, 0x8F, 0, 0x0F, 0x08, 0])], + ), + ]); + let mut second = ScriptedIo::new([ + exchange(&UNIFIED_LOOKUP, [reply(&RECEIVER_OFFLINE)]), + exchange( + &unified_lookup(0xFF), + [reply(&[REPORT_ID_SHORT, 0xFF, 0, 0x0F, 9, 0, 0])], + ), + ]); + second.clock = Rc::clone(&first.clock); let interfaces = [first, second]; let deadline = interfaces[0].now() + DISCOVERY_BUDGET; @@ -1173,889 +1050,286 @@ mod tests { result, Ok(Discovery::Found(BatteryFeature::Unified(9))) )); - for io in &interfaces { - assert_eq!(io.writes(), vec![UNIFIED_LOOKUP, usb_lookup]); - io.assert_finished(); - } } #[test] fn offline_outranks_later_errors_while_preserving_candidate_order() { for offline_first in [true, false] { - let mut steps = Vec::new(); - let mut expected_writes = Vec::new(); - for device_index in [1, 0xFF, 2, 3, 4, 5, 6] { - let lookup = [REPORT_ID_SHORT, device_index, 0, 0x0F, 0x10, 0x04, 0]; - if offline_first && device_index == 1 { - steps.extend(exchange(&lookup, &[&RECEIVER_OFFLINE])); + let io = ScriptedIo::new([1, 0xFF, 2, 3, 4, 5, 6].map(|device_index| { + let truncated = [REPORT_ID_SHORT, device_index, 0, 0x0F]; + let answer = if offline_first && device_index == 1 { + reply(&RECEIVER_OFFLINE) } else { - steps.extend(exchange( - &lookup, - &[&[REPORT_ID_SHORT, device_index, 0, 0x0F]], - )); - } - expected_writes.push(lookup); - } - let io = ScriptedIo::new(steps); - let deadline = io.now() + DISCOVERY_BUDGET; + reply(&truncated) + }; + exchange(&unified_lookup(device_index), [answer]) + })); - let result = discover( - 1, - deadline, - || io.now(), - |_, device_index| find_battery_feature(&io, device_index, deadline), - ); + let result = discover_single(&io, io.now() + DISCOVERY_BUDGET); if offline_first { assert!(matches!(result, Ok(Discovery::Offline))); } else { - let Err(error) = result else { - panic!("a malformed matching feature reply should retain its error"); - }; - assert_eq!( - error.to_string(), - "short HID++ response: expected at least 5 bytes, got 4" - ); + assert_short_response(result, 5, 4); } - assert_eq!(io.writes(), expected_writes); - io.assert_finished(); } } - - #[test] - fn unmatched_feature_reply_then_silence_skips_legacy_lookup() { - let mut steps = exchange(&UNIFIED_LOOKUP, &[&[REPORT_ID_SHORT, 2, 0, 0x0F, 5, 0, 0]]); - steps.push(ScriptStep::silence(1_500, RESPONSE_TIMEOUT)); - let io = ScriptedIo::new(steps); - let start = io.now(); - - let result = find_battery_feature(&io, 1, start + DISCOVERY_BUDGET); - - assert!(matches!(result, Ok(ProbeOutcome::Absent))); - assert_eq!(io.now().duration_since(start), RESPONSE_TIMEOUT); - assert_eq!(io.writes(), vec![UNIFIED_LOOKUP]); - io.assert_finished(); - } - - #[test] - fn offline_during_battery_read_still_uses_legacy_fallback() { - let mut steps = exchange(&UNIFIED_LOOKUP, &[&[REPORT_ID_SHORT, 1, 0, 0x0F, 5, 0, 0]]); - steps.extend(exchange( - &UNIFIED_QUERY, - &[&[REPORT_ID_SHORT, 1, 0x8F, 5, 0x1F, 0x08, 0]], - )); - steps.extend(exchange( - &LEGACY_LOOKUP, - &[&[REPORT_ID_SHORT, 1, 0, 0x0F, 6, 0, 0]], - )); - steps.extend(exchange( - &LEGACY_QUERY, - &[&[REPORT_ID_SHORT, 1, 6, 0x0F, 31, 0, 0]], - )); - let io = ScriptedIo::new(steps); - - let ProbeOutcome::Found(battery_feature) = - find_battery_feature(&io, 1, io.now() + DISCOVERY_BUDGET).unwrap() - else { - panic!("the unified feature should be discovered before the mouse goes offline"); - }; - let session = BatterySession { - io: &io, - device_index: 1, - battery_feature, - }; - assert_eq!( - read_battery_from(&session).unwrap(), - Some(BatteryStatus { - level: 31, - charging: false, - }) - ); - assert_eq!( - io.writes(), - vec![UNIFIED_LOOKUP, UNIFIED_QUERY, LEGACY_LOOKUP, LEGACY_QUERY] - ); - io.assert_finished(); - } - } - - fn short_response_error() -> HidppError { - HidppError::Protocol(ProtocolError::ShortResponse { - minimum: 8, - actual: 7, - }) - } - - #[test] - fn parses_root_feature_index_from_byte_four() { - let response = [REPORT_ID_SHORT, 1, 0, 0x0F, 7, 0, 0]; - assert_eq!(parse_feature_index(&response), Ok(Some(7))); - } - - #[test] - fn treats_zero_root_feature_index_as_not_supported() { - let response = [REPORT_ID_LONG, 1, 0, 0x0F, 0, 0]; - assert_eq!(parse_feature_index(&response), Ok(None)); - } - - #[test] - fn parses_unified_battery_level_and_charging_bit() { - let response = [REPORT_ID_SHORT, 1, 5, 0x1F, 78, 0, 0, 1]; - assert_eq!( - parse_unified_battery(&response), - Ok(BatteryStatus { - level: 78, - charging: true, - }) - ); - } - - #[test] - fn parses_legacy_battery_level_and_charging_bit() { - let response = [REPORT_ID_SHORT, 1, 6, 0x0F, 42, 0, 1]; - assert_eq!( - parse_battery_status(&response), - Ok(BatteryStatus { - level: 42, - charging: true, - }) - ); - } - - #[test] - fn rejects_unified_battery_response_missing_charging_byte() { - let response = [REPORT_ID_SHORT, 1, 5, 0x1F, 78, 0, 0]; - assert_eq!( - parse_unified_battery(&response), - Err(ProtocolError::ShortResponse { - minimum: 8, - actual: 7, - }) - ); - } - - #[test] - fn rejects_legacy_battery_response_missing_charging_byte() { - let response = [REPORT_ID_SHORT, 1, 6, 0x0F, 42, 0]; - assert_eq!( - parse_battery_status(&response), - Err(ProtocolError::ShortResponse { - minimum: 7, - actual: 6, - }) - ); - } - - #[test] - fn rejects_response_for_another_device_index() { - let response = [REPORT_ID_SHORT, 2, 5, 0x1F, 78, 0, 0, 1]; - assert_eq!(match_report(&response, 1, 5, 0x1F), ReportMatch::Unrelated); - assert_eq!(match_report(&response, 2, 5, 0x1F), ReportMatch::Reply); - } - - #[test] - fn rejects_response_echoing_another_function_or_software_id() { - let response = [REPORT_ID_SHORT, 1, 5, 0x1F, 78, 0, 0, 1]; - assert_eq!(match_report(&response, 1, 5, 0x0F), ReportMatch::Unrelated); - assert_eq!(match_report(&response, 1, 5, 0x1E), ReportMatch::Unrelated); } mod request_timing { use super::*; - fn after(mut step: ScriptStep, elapsed: Duration) -> ScriptStep { - match &mut step { - ScriptStep::Read { advance, .. } | ScriptStep::Write { advance, .. } => { - *advance = elapsed; - } - } - step - } - - fn silent_probe(device_index: u8) -> [ScriptStep; 3] { - [ - ScriptStep::flush(&[]), - ScriptStep::write(&[REPORT_ID_SHORT, device_index, 0, 0x0F, 0x10, 0x04, 0]), - ScriptStep::silence(1_500, Duration::from_millis(1_500)), - ] + fn silent_probe(device_index: u8) -> Vec { + exchange(&unified_lookup(device_index), [no_reply()]) } #[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 battery_request = [REPORT_ID_SHORT, 1, 5, 0x1F, 0, 0, 0]; - let io = ScriptedIo::new(vec![ - after(ScriptStep::flush(&stale), Duration::from_millis(100)), - after(ScriptStep::flush(&stale), Duration::from_millis(99)), - after( - ScriptStep::flush(&stale), - Duration::from_millis(last_read_ms), - ), - ScriptStep::write(&battery_request), - ScriptStep::response(1_500, &[REPORT_ID_SHORT, 1, 5, 0x1F, 78, 0, 0, 1]), - ]); - let start = io.now(); - let session = BatterySession { - io: &io, - device_index: 1, - battery_feature: BatteryFeature::Unified(5), - }; + let io = ScriptedIo::new([[ + 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!( - read_battery_from(&session).unwrap(), + read_battery_from(&io, 1, BatteryFeature::Unified(5)).unwrap(), Some(BatteryStatus { level: 78, charging: true, }) ); - assert_eq!( - io.now().duration_since(start), - Duration::from_millis(199 + last_read_ms) - ); - assert_eq!(io.writes(), vec![battery_request]); - io.assert_finished(); + assert_eq!(io.elapsed(), ms(199 + last_read_ms)); } } #[test] fn unrelated_reports_consume_the_original_response_wait() { - let io = ScriptedIo::new(vec![ - ScriptStep::flush(&[]), - ScriptStep::write(&[REPORT_ID_SHORT, 1, 0, 0x0F, 0x10, 0x04, 0]), - after( - ScriptStep::response(1_500, &[REPORT_ID_SHORT, 2, 0, 0x0F, 5, 0, 0]), - Duration::from_millis(500), - ), - after( - ScriptStep::response(1_000, &[REPORT_ID_SHORT, 1, 0, 0x0E, 5, 0, 0]), - Duration::from_millis(750), - ), - ScriptStep::silence(250, Duration::from_millis(250)), - ]); - let start = io.now(); + let io = ScriptedIo::new([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)), + ], + )]); - let result = get_feature_index_on_device( - &io, - 1, - DEFAULT_SW_ID, - FEATURE_UNIFIED_BATTERY, - RESPONSE_TIMEOUT, - ); + let result = lookup_feature(&io, 1, FEATURE_UNIFIED_BATTERY, RESPONSE_TIMEOUT); assert!(matches!(result, Ok(FeatureLookup::Silent))); - assert_eq!(io.now().duration_since(start), Duration::from_millis(1_500)); - io.assert_finished(); + assert_eq!(io.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 io = ScriptedIo::new(vec![ - ScriptStep::flush(&[]), - ScriptStep::write(&[REPORT_ID_SHORT, 1, 0, 0x0F, 0x10, 0x04, 0]), - after( - ScriptStep::response(2, &unrelated), - Duration::from_micros(1_750), - ), - after( - ScriptStep::response(0, &unrelated), - Duration::from_micros(500), - ), - ScriptStep::silence(0, Duration::from_micros(250)), - ]); - let start = io.now(); + let io = ScriptedIo::new([exchange( + &UNIFIED_LOOKUP, + [ + 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)), + ], + )]); - let result = get_feature_index_on_device( + let result = lookup_feature( &io, 1, - DEFAULT_SW_ID, FEATURE_UNIFIED_BATTERY, Duration::from_micros(2_500), ); assert!(matches!(result, Ok(FeatureLookup::Silent))); - assert_eq!(io.now().duration_since(start), Duration::from_micros(2_500)); - io.assert_finished(); + assert_eq!(io.elapsed(), Duration::from_micros(2_500)); } #[test] fn zero_duration_ignores_an_unrelated_report_and_returns_silence() { - let discovery_request = [REPORT_ID_SHORT, 1, 0, 0x0F, 0x10, 0x04, 0]; - let io = ScriptedIo::new(vec![ - ScriptStep::flush(&[]), - ScriptStep::write(&discovery_request), - ScriptStep::response(0, &[REPORT_ID_SHORT, 2, 0, 0x0F, 5, 0, 0]), - ]); + let io = ScriptedIo::new([exchange( + &UNIFIED_LOOKUP, + [ScriptStep::read(0, &[REPORT_ID_SHORT, 2, 0, 0x0F, 5, 0, 0])], + )]); - let result = get_feature_index_on_device( - &io, - 1, - DEFAULT_SW_ID, - FEATURE_UNIFIED_BATTERY, - Duration::ZERO, - ); + let result = lookup_feature(&io, 1, FEATURE_UNIFIED_BATTERY, Duration::ZERO); assert!(matches!(result, Ok(FeatureLookup::Silent))); - assert_eq!(io.writes(), vec![discovery_request]); - io.assert_finished(); } #[test] fn discovery_overhead_preserves_the_wait_and_later_battery_request_durations() { - let unified_lookup = [REPORT_ID_SHORT, 1, 0, 0x0F, 0x10, 0x04, 0]; - let unified_query = [REPORT_ID_SHORT, 1, 5, 0x1F, 0, 0, 0]; - let legacy_lookup = [REPORT_ID_SHORT, 1, 0, 0x0F, 0x10, 0, 0]; - let legacy_query = [REPORT_ID_SHORT, 1, 6, 0x0F, 0, 0, 0]; - let io = ScriptedIo::new(vec![ - after( - ScriptStep::flush(&[REPORT_ID_SHORT, 1, 0, 0x0F, 99, 0, 0]), - Duration::from_millis(150), - ), - ScriptStep::flush(&[]), - after( - ScriptStep::write(&unified_lookup), - Duration::from_millis(100), - ), - after( - ScriptStep::response(400, &[REPORT_ID_SHORT, 1, 0, 0x0F, 5, 0, 0]), - Duration::from_millis(400), - ), - ScriptStep::flush(&[]), - ScriptStep::write(&unified_query), - ScriptStep::silence(1_500, Duration::from_millis(1_500)), - ScriptStep::flush(&[]), - ScriptStep::write(&legacy_lookup), - after( - ScriptStep::response(1_500, &[REPORT_ID_SHORT, 1, 0, 0x0F, 6, 0, 0]), - Duration::from_millis(1_500), - ), - ScriptStep::flush(&[]), - ScriptStep::write(&legacy_query), - after( - ScriptStep::response(1_500, &[REPORT_ID_SHORT, 1, 6, 0x0F, 42, 0, 1]), - Duration::from_millis(1_500), - ), + let io = ScriptedIo::new([ + 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))]), ]); - let start = io.now(); // Only 400 ms remain for discovery when this candidate starts. - let deadline = start + Duration::from_millis(400); - let result = discover( - 1, - deadline, - || io.now(), - |_, device_index| find_battery_feature(&io, device_index, deadline), - ); - let Ok(Discovery::Found(battery_feature)) = result else { + let deadline = io.now() + ms(400); + + let Ok(Discovery::Found(battery_feature)) = discover_single(&io, deadline) else { panic!("a matching reply at the response deadline should be accepted"); }; assert_eq!(battery_feature, BatteryFeature::Unified(5)); - assert_eq!(io.now().duration_since(start), Duration::from_millis(650)); - assert!(io.now() > deadline); + assert_eq!(io.elapsed(), ms(650)); - let session = BatterySession { - io: &io, - device_index: 1, - battery_feature, - }; assert_eq!( - read_battery_from(&session).unwrap(), - Some(BatteryStatus { - level: 42, - charging: true, - }) - ); - assert_eq!( - io.writes(), - vec![unified_lookup, unified_query, legacy_lookup, legacy_query] + read_battery_from(&io, 1, battery_feature).unwrap(), + Some(LEGACY_LEVEL) ); - assert_eq!(io.now().duration_since(start), Duration::from_millis(5_150)); - io.assert_finished(); + assert_eq!(io.elapsed(), ms(5_150)); } #[test] fn discovery_stops_before_the_next_candidate_after_six_seconds_of_silence() { - let io = ScriptedIo::new([1, 0xFF, 2, 3].into_iter().flat_map(silent_probe).collect()); - let start = io.now(); - let deadline = start + DISCOVERY_BUDGET; + let io = ScriptedIo::new([1, 0xFF, 2, 3].map(silent_probe)); - let result = discover( - 1, - deadline, - || io.now(), - |_, device_index| find_battery_feature(&io, device_index, deadline), - ); + let result = discover_single(&io, io.now() + DISCOVERY_BUDGET); assert!(matches!(result, Ok(Discovery::NotFound))); - assert_eq!(io.now().duration_since(start), Duration::from_secs(6)); - assert_eq!( - io.writes(), - [1, 0xFF, 2, 3].map(|device_index| [ - REPORT_ID_SHORT, - device_index, - 0, - 0x0F, - 0x10, - 0x04, - 0 - ]) - ); - io.assert_finished(); + assert_eq!(io.elapsed(), DISCOVERY_BUDGET); } #[test] fn a_probe_can_finish_its_legacy_lookup_after_the_discovery_budget_is_used() { - let mut steps = [1, 0xFF, 2] - .into_iter() - .flat_map(silent_probe) - .collect::>(); - let unified_lookup = [REPORT_ID_SHORT, 3, 0, 0x0F, 0x10, 0x04, 0]; - let legacy_lookup = [REPORT_ID_SHORT, 3, 0, 0x0F, 0x10, 0, 0]; - steps.extend([ - ScriptStep::flush(&[]), - ScriptStep::write(&unified_lookup), - after( - ScriptStep::response(1_500, &[REPORT_ID_SHORT, 3, 0, 0x0F, 0, 0, 0]), - Duration::from_millis(1_500), + let io = ScriptedIo::new([ + 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])], ), - ScriptStep::flush(&[]), - ScriptStep::write(&legacy_lookup), - ScriptStep::response(0, &[REPORT_ID_SHORT, 3, 0, 0x0F, 6, 0, 0]), ]); - let io = ScriptedIo::new(steps); - let deadline = io.now() + DISCOVERY_BUDGET; - let result = discover( - 1, - deadline, - || io.now(), - |_, device_index| find_battery_feature(&io, device_index, deadline), - ); + let result = discover_single(&io, io.now() + DISCOVERY_BUDGET); assert!(matches!( result, Ok(Discovery::Found(BatteryFeature::Legacy(6))) )); - assert_eq!(io.now(), deadline); - assert_eq!(io.writes().last(), Some(&legacy_lookup.to_vec())); - io.assert_finished(); + assert_eq!(io.elapsed(), DISCOVERY_BUDGET); } - - #[test] - fn discovery_budget_retains_offline_and_error_precedence() { - for offline in [true, false] { - let first_reply = if offline { - after( - ScriptStep::response(1_500, &[REPORT_ID_SHORT, 1, 0x8F, 0, 0x0F, 0x08, 0]), - Duration::from_millis(1_500), - ) - } else { - ScriptStep::silence(1_500, Duration::from_millis(1_500)) - }; - let mut steps = vec![ - ScriptStep::flush(&[]), - ScriptStep::write(&[REPORT_ID_SHORT, 1, 0, 0x0F, 0x10, 0x04, 0]), - first_reply, - ScriptStep::flush(&[]), - ScriptStep::write(&[REPORT_ID_SHORT, 0xFF, 0, 0x0F, 0x10, 0x04, 0]), - after( - ScriptStep::response(1_500, &[REPORT_ID_SHORT, 0xFF, 0, 0x0F]), - Duration::from_millis(1_500), - ), - ]; - steps.extend([2, 3].into_iter().flat_map(silent_probe)); - let io = ScriptedIo::new(steps); - let deadline = io.now() + DISCOVERY_BUDGET; - - let result = discover( - 1, - deadline, - || io.now(), - |_, device_index| find_battery_feature(&io, device_index, deadline), - ); - - if offline { - assert!(matches!(result, Ok(Discovery::Offline))); - } else { - assert!(matches!( - result, - Err(HidppError::Protocol(ProtocolError::ShortResponse { - minimum: 5, - actual: 4, - })) - )); - } - assert_eq!(io.now(), deadline); - io.assert_finished(); - } - } - } - - #[test] - fn caps_request_timeout_at_the_response_timeout() { - let io = ScriptedIo::new(Vec::new()); - assert_eq!( - request_timeout(&io, io.now() + DISCOVERY_BUDGET), - RESPONSE_TIMEOUT - ); - assert_eq!(request_timeout(&io, io.now()), Duration::ZERO); - } - - #[test] - fn offline_outranks_an_error_on_another_interface() { - let io = ScriptedIo::new(Vec::new()); - let result = discover::<()>( - 2, - io.now() + DISCOVERY_BUDGET, - || io.now(), - |interface, _| match interface { - 0 => Ok(ProbeOutcome::Offline), - _ => Err(HidppError::Hid(HidError::InitializationError)), - }, - ); - assert!(matches!(result, Ok(Discovery::Offline))); - } - - #[test] - fn keeps_probing_past_an_offline_index() { - let io = ScriptedIo::new(Vec::new()); - let result = discover( - 2, - io.now() + DISCOVERY_BUDGET, - || io.now(), - |interface, device_index| { - Ok(match (interface, device_index) { - (1, 0xFF) => ProbeOutcome::Found("usb"), - (0, _) => ProbeOutcome::Offline, - _ => ProbeOutcome::Absent, - }) - }, - ); - assert!(matches!(result, Ok(Discovery::Found("usb")))); - } - - #[test] - fn reports_offline_for_receiver_unknown_device_error() { - // Captured from a LIGHTSPEED receiver while its paired mouse was off. - let response = [REPORT_ID_SHORT, 1, 0x8F, 0x00, 0x0F, 0x08, 0x00]; - assert_eq!(match_report(&response, 1, 0x00, 0x0F), ReportMatch::Offline); - } - - #[test] - fn recognizes_hidpp20_error_for_the_request() { - let response = [ - REPORT_ID_LONG, - 0xFF, - 0xFF, - 0x05, - 0x1F, - 0x02, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - ]; - assert_eq!( - match_report(&response, 0xFF, 0x05, 0x1F), - ReportMatch::DeviceError - ); - } - - #[test] - fn ignores_error_echoing_another_request() { - let response = [REPORT_ID_SHORT, 1, 0x8F, 0x00, 0x0F, 0x08, 0x00]; - assert_eq!( - match_report(&response, 1, 0x05, 0x0F), - ReportMatch::Unrelated - ); - assert_eq!( - match_report(&response, 1, 0x00, 0x1F), - ReportMatch::Unrelated - ); } mod battery_recovery { use super::*; - const UNIFIED_LOOKUP: [u8; 7] = [REPORT_ID_SHORT, 1, 0, 0x0F, 0x10, 0x04, 0]; - const UNIFIED_QUERY: [u8; 7] = [REPORT_ID_SHORT, 1, 5, 0x1F, 0, 0, 0]; - const LEGACY_LOOKUP: [u8; 7] = [REPORT_ID_SHORT, 1, 0, 0x0F, 0x10, 0, 0]; - const LEGACY_QUERY: [u8; 7] = [REPORT_ID_SHORT, 1, 6, 0x0F, 0, 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 INCOMPLETE_UNIFIED: [u8; 7] = [REPORT_ID_SHORT, 1, 5, 0x1F, 99, 0, 0]; - - fn exchange(report: &[u8], reply: ScriptStep) -> Vec { - vec![ScriptStep::flush(&[]), ScriptStep::write(report), reply] - } - - fn legacy_discovery() -> Vec { - exchange(&LEGACY_LOOKUP, ScriptStep::response(1_500, &LEGACY_FEATURE)) - } - fn read_unified(io: &ScriptedIo) -> Result, HidppError> { - read_battery_from(&BatterySession { - io, - device_index: 1, - battery_feature: BatteryFeature::Unified(5), - }) - } - - fn assert_unified_protocol_error(result: Result, HidppError>) { - assert!(matches!( - result, - Err(HidppError::Protocol(ProtocolError::ShortResponse { - minimum: 8, - actual: 7, - })) - )); + read_battery_from(io, 1, BatteryFeature::Unified(5)) } - #[test] - fn unsupported_unified_discovery_selects_and_reads_legacy() { - for reply in [ - vec![REPORT_ID_SHORT, 1, 0, 0x0F, 0, 0, 0], - vec![REPORT_ID_LONG, 1, ERROR_MARKER_HIDPP20, 0, 0x0F, 2], - ] { - let mut steps = exchange(&UNIFIED_LOOKUP, ScriptStep::response(1_500, &reply)); - steps.extend(legacy_discovery()); - steps.extend(exchange( - &LEGACY_QUERY, - ScriptStep::response(1_500, &LEGACY_STATUS), - )); - let io = ScriptedIo::new(steps); - - let ProbeOutcome::Found(battery_feature) = - find_battery_feature(&io, 1, io.now() + DISCOVERY_BUDGET).unwrap() - else { - panic!("legacy battery feature should be discovered"); - }; - let session = BatterySession { - io: &io, - device_index: 1, - battery_feature, - }; - - assert_eq!( - read_battery_from(&session).unwrap(), - Some(BatteryStatus { - level: 42, - charging: true, - }) - ); - assert_eq!( - io.writes(), - vec![UNIFIED_LOOKUP, LEGACY_LOOKUP, LEGACY_QUERY] - ); - io.assert_finished(); - } + /// 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 mut steps = exchange( - &UNIFIED_QUERY, - ScriptStep::response(1_500, &INCOMPLETE_UNIFIED[..length]), - ); - steps.extend(legacy_discovery()); - steps.extend(exchange( - &LEGACY_QUERY, - ScriptStep::response(1_500, &LEGACY_STATUS), - )); - let io = ScriptedIo::new(steps); + let io = ScriptedIo::new([ + exchange(&UNIFIED_QUERY, [reply(&INCOMPLETE_UNIFIED[..length])]), + legacy_fallback(reply(&LEGACY_STATUS)), + ]); - assert_eq!( - read_unified(&io).unwrap(), - Some(BatteryStatus { - level: 42, - charging: true, - }) - ); - assert_eq!( - io.writes(), - vec![UNIFIED_QUERY, LEGACY_LOOKUP, LEGACY_QUERY] - ); - io.assert_finished(); + assert_eq!(read_unified(&io).unwrap(), Some(LEGACY_LEVEL)); } } #[test] fn offline_device_error_and_silence_recover_with_a_legacy_status() { - for reply in [ - ScriptStep::response( - 1_500, - &[ - REPORT_ID_SHORT, - 1, - ERROR_MARKER_HIDPP10, - 5, - 0x1F, - ERROR_CODE_UNKNOWN_DEVICE, - 0, - ], - ), - ScriptStep::response( - 1_500, - &[REPORT_ID_LONG, 1, ERROR_MARKER_HIDPP20, 5, 0x1F, 2], - ), - ScriptStep::silence(1_500, RESPONSE_TIMEOUT), + 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 mut steps = exchange(&UNIFIED_QUERY, reply); - steps.extend(legacy_discovery()); - steps.extend(exchange( - &LEGACY_QUERY, - ScriptStep::response(1_500, &LEGACY_STATUS), - )); - let io = ScriptedIo::new(steps); + let io = ScriptedIo::new([ + exchange(&UNIFIED_QUERY, [unified_reply]), + legacy_fallback(reply(&LEGACY_STATUS)), + ]); - assert_eq!( - read_unified(&io).unwrap(), - Some(BatteryStatus { - level: 42, - charging: true, - }) - ); - assert_eq!( - io.writes(), - vec![UNIFIED_QUERY, LEGACY_LOOKUP, LEGACY_QUERY] - ); - io.assert_finished(); + assert_eq!(read_unified(&io).unwrap(), Some(LEGACY_LEVEL)); } } #[test] fn missing_results_from_both_features_return_no_battery_status() { - let mut steps = exchange(&UNIFIED_QUERY, ScriptStep::silence(1_500, RESPONSE_TIMEOUT)); - steps.extend(legacy_discovery()); - steps.extend(exchange( - &LEGACY_QUERY, - ScriptStep::response( - 1_500, - &[REPORT_ID_SHORT, 1, ERROR_MARKER_HIDPP10, 6, 0x0F, 8, 0], - ), - )); - let io = ScriptedIo::new(steps); + let io = ScriptedIo::new([ + exchange(&UNIFIED_QUERY, [no_reply()]), + legacy_fallback(reply(&[ + REPORT_ID_SHORT, + 1, + ERROR_MARKER_HIDPP10, + 6, + 0x0F, + 0x08, + 0, + ])), + ]); assert_eq!(read_unified(&io).unwrap(), None); - assert_eq!( - io.writes(), - vec![UNIFIED_QUERY, LEGACY_LOOKUP, LEGACY_QUERY] - ); - io.assert_finished(); } #[test] - fn unavailable_legacy_feature_preserves_the_unified_protocol_error() { - for reply in [ - ScriptStep::response(1_500, &[REPORT_ID_SHORT, 1, 0, 0x0F, 0, 0, 0]), - ScriptStep::response( - 1_500, - &[REPORT_ID_SHORT, 1, ERROR_MARKER_HIDPP10, 0, 0x0F, 8, 0], - ), - ScriptStep::response( - 1_500, - &[REPORT_ID_LONG, 1, ERROR_MARKER_HIDPP20, 0, 0x0F, 2], - ), - ScriptStep::silence(1_500, RESPONSE_TIMEOUT), + 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 mut steps = exchange( - &UNIFIED_QUERY, - ScriptStep::response(1_500, &INCOMPLETE_UNIFIED), - ); - steps.extend(exchange(&LEGACY_LOOKUP, reply)); - let io = ScriptedIo::new(steps); + let io = ScriptedIo::new([ + exchange(&UNIFIED_QUERY, [reply(&INCOMPLETE_UNIFIED)]), + exchange(&LEGACY_LOOKUP, [lookup_reply]), + ]); - assert_unified_protocol_error(read_unified(&io)); - assert_eq!(io.writes(), vec![UNIFIED_QUERY, LEGACY_LOOKUP]); - io.assert_finished(); + assert_short_response(read_unified(&io), 8, 7); } } #[test] - fn malformed_legacy_lookup_preserves_the_unified_protocol_error() { - let mut steps = exchange( - &UNIFIED_QUERY, - ScriptStep::response(1_500, &INCOMPLETE_UNIFIED), - ); - steps.extend(exchange( - &LEGACY_LOOKUP, - ScriptStep::response(1_500, &[REPORT_ID_SHORT, 1, 0, 0x0F]), - )); - let io = ScriptedIo::new(steps); - - assert_unified_protocol_error(read_unified(&io)); - assert_eq!(io.writes(), vec![UNIFIED_QUERY, LEGACY_LOOKUP]); - io.assert_finished(); - } - - #[test] - fn malformed_or_missing_legacy_status_preserves_the_unified_protocol_error() { - for reply in [ - ScriptStep::response(1_500, &[REPORT_ID_SHORT, 1, 6, 0x0F, 42, 0]), - ScriptStep::response( - 1_500, - &[REPORT_ID_SHORT, 1, ERROR_MARKER_HIDPP10, 6, 0x0F, 8, 0], - ), - ScriptStep::response( - 1_500, - &[REPORT_ID_LONG, 1, ERROR_MARKER_HIDPP20, 6, 0x0F, 2], - ), - ScriptStep::silence(1_500, RESPONSE_TIMEOUT), + 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 mut steps = exchange( - &UNIFIED_QUERY, - ScriptStep::response(1_500, &INCOMPLETE_UNIFIED), - ); - steps.extend(legacy_discovery()); - steps.extend(exchange(&LEGACY_QUERY, reply)); - let io = ScriptedIo::new(steps); + let io = ScriptedIo::new([ + exchange(&UNIFIED_QUERY, [reply(&INCOMPLETE_UNIFIED)]), + legacy_fallback(status_reply), + ]); - assert_unified_protocol_error(read_unified(&io)); - assert_eq!( - io.writes(), - vec![UNIFIED_QUERY, LEGACY_LOOKUP, LEGACY_QUERY] - ); - io.assert_finished(); + assert_short_response(read_unified(&io), 8, 7); } } #[test] - fn a_missing_unified_result_does_not_hide_a_legacy_protocol_error() { - let mut steps = exchange(&UNIFIED_QUERY, ScriptStep::silence(1_500, RESPONSE_TIMEOUT)); - steps.extend(legacy_discovery()); - steps.extend(exchange( - &LEGACY_QUERY, - ScriptStep::response(1_500, &[REPORT_ID_SHORT, 1, 6, 0x0F, 42, 0]), - )); - let io = ScriptedIo::new(steps); + fn a_missing_unified_result_does_not_hide_a_legacy_short_response() { + let io = ScriptedIo::new([ + exchange(&UNIFIED_QUERY, [no_reply()]), + legacy_fallback(reply(&[REPORT_ID_SHORT, 1, 6, 0x0F, 42, 0])), + ]); - assert!(matches!( - read_unified(&io), - Err(HidppError::Protocol(ProtocolError::ShortResponse { - minimum: 7, - actual: 6, - })) - )); - assert_eq!( - io.writes(), - vec![UNIFIED_QUERY, LEGACY_LOOKUP, LEGACY_QUERY] - ); - io.assert_finished(); + assert_short_response(read_unified(&io), 7, 6); } - #[derive(Clone, Copy)] + #[derive(Debug, Clone, Copy)] enum IoFailure { FlushRead, Write, @@ -2063,429 +1337,80 @@ mod tests { ResponseRead, } - const IO_FAILURES: [IoFailure; 4] = [ - IoFailure::FlushRead, - IoFailure::Write, - IoFailure::ShortWrite, - IoFailure::ResponseRead, - ]; - impl IoFailure { - fn steps(self, report: &[u8]) -> Vec { - let read_failure = |phase, timeout_ms| ScriptStep::Read { - phase, + const ALL: [Self; 4] = [ + Self::FlushRead, + Self::Write, + Self::ShortWrite, + 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, }; + let write = |result| ScriptStep::Write { + report: request.to_vec(), + result, + advance: Duration::ZERO, + }; match self { - Self::FlushRead => vec![read_failure(ReadPhase::Flush, 0)], - Self::Write | Self::ShortWrite => vec![ + Self::FlushRead => vec![failed_read(0)], + Self::Write => vec![ ScriptStep::flush(&[]), - ScriptStep::Write { - report: report.to_vec(), - result: match self { - Self::ShortWrite => Ok(3), - _ => Err(HidError::InitializationError), - }, - advance: Duration::ZERO, - }, + write(Err(HidError::InitializationError)), ], - Self::ResponseRead => { - exchange(report, read_failure(ReadPhase::Response, 1_500)) - } + Self::ShortWrite => vec![ScriptStep::flush(&[]), write(Ok(3))], + Self::ResponseRead => exchange(request, [failed_read(1_500)]), } } fn assert_error(self, result: Result, HidppError>) { - match self { - Self::ShortWrite => assert!(matches!( - result, + match (self, result) { + ( + Self::ShortWrite, Err(HidppError::ShortWrite { expected: 7, actual: 3, - }) - )), - _ => assert!(matches!( - result, - Err(HidppError::Hid(HidError::InitializationError)) - )), + }), + ) + | ( + Self::FlushRead | Self::Write | Self::ResponseRead, + Err(HidppError::Hid(HidError::InitializationError)), + ) => {} + (failure, result) => panic!("{failure:?} produced {result:?}"), } } } #[test] fn unified_io_failures_stop_without_legacy_recovery() { - for failure in IO_FAILURES { - let io = ScriptedIo::new(failure.steps(&UNIFIED_QUERY)); + for failure in IoFailure::ALL { + let io = ScriptedIo::new([failure.steps(&UNIFIED_QUERY)]); failure.assert_error(read_unified(&io)); - let expected_calls = match failure { - IoFailure::FlushRead => vec![IoCall::Read(0)], - IoFailure::Write | IoFailure::ShortWrite => { - vec![IoCall::Read(0), IoCall::Write(UNIFIED_QUERY.to_vec())] - } - IoFailure::ResponseRead => vec![ - IoCall::Read(0), - IoCall::Write(UNIFIED_QUERY.to_vec()), - IoCall::Read(1_500), - ], - }; - assert_eq!(*io.calls.borrow(), expected_calls); - io.assert_finished(); } } #[test] - fn legacy_lookup_and_query_io_failures_replace_the_unified_protocol_error() { - for failed_report in [LEGACY_LOOKUP, LEGACY_QUERY] { - for failure in IO_FAILURES { - let mut steps = exchange( - &UNIFIED_QUERY, - ScriptStep::response(1_500, &INCOMPLETE_UNIFIED), - ); - let mut expected_writes = vec![UNIFIED_QUERY]; - if failed_report == LEGACY_QUERY { - steps.extend(legacy_discovery()); - expected_writes.push(LEGACY_LOOKUP); - } - steps.extend(failure.steps(&failed_report)); - if !matches!(failure, IoFailure::FlushRead) { - expected_writes.push(failed_report); - } - let io = ScriptedIo::new(steps); - - failure.assert_error(read_unified(&io)); - assert_eq!(io.writes(), expected_writes); - io.assert_finished(); - } - } - } - } - - #[test] - fn uses_the_discovered_feature_without_rediscovery() { - let status = BatteryStatus { - level: 78, - charging: true, - }; - for selected_feature in [BatteryFeature::Unified(5), BatteryFeature::Legacy(6)] { - let transport = - FakeTransport::new(selected_feature, Vec::new(), vec![Ok(Some(status))]); - - let result = read_battery_from(&transport); - - assert!(matches!(result, Ok(Some(found)) if found == status)); - assert_eq!( - transport.calls(), - vec![TransportCall::Query(selected_feature)] - ); - } - } - - #[test] - fn unified_protocol_error_discovers_and_queries_legacy() { - let status = BatteryStatus { - level: 42, - charging: false, - }; - let transport = FakeTransport::new( - BatteryFeature::Unified(5), - vec![Ok(Some(6))], - vec![Err(short_response_error()), Ok(Some(status))], - ); - - let result = read_battery_from(&transport); - - assert!(matches!(result, Ok(Some(found)) if found == status)); - assert_eq!( - transport.calls(), - vec![ - TransportCall::Query(BatteryFeature::Unified(5)), - TransportCall::Discover(FEATURE_BATTERY_STATUS), - TransportCall::Query(BatteryFeature::Legacy(6)), - ] - ); - } - - #[test] - fn missing_unified_response_discovers_and_queries_legacy() { - let transport = FakeTransport::new( - BatteryFeature::Unified(5), - vec![Ok(Some(6))], - vec![Ok(None), Ok(None)], - ); - - let result = read_battery_from(&transport); - - assert!(matches!(result, Ok(None))); - assert_eq!( - transport.calls(), - vec![ - TransportCall::Query(BatteryFeature::Unified(5)), - TransportCall::Discover(FEATURE_BATTERY_STATUS), - TransportCall::Query(BatteryFeature::Legacy(6)), - ] - ); - } - - #[test] - fn preserves_unified_protocol_error_when_legacy_is_unavailable() { - let transport = FakeTransport::new( - BatteryFeature::Unified(5), - vec![Ok(None)], - vec![Err(short_response_error())], - ); - - let result = read_battery_from(&transport); - - assert!(matches!( - result, - Err(HidppError::Protocol(ProtocolError::ShortResponse { - minimum: 8, - actual: 7, - })) - )); - assert_eq!( - transport.calls(), - vec![ - TransportCall::Query(BatteryFeature::Unified(5)), - TransportCall::Discover(FEATURE_BATTERY_STATUS), - ] - ); - } - - #[test] - fn preserves_unified_protocol_error_over_a_legacy_protocol_error() { - let transport = FakeTransport::new( - BatteryFeature::Unified(5), - vec![Ok(Some(6))], - vec![ - Err(short_response_error()), - Err(HidppError::Protocol(ProtocolError::ShortResponse { - minimum: 7, - actual: 6, - })), - ], - ); - - let result = read_battery_from(&transport); - - assert!(matches!( - result, - Err(HidppError::Protocol(ProtocolError::ShortResponse { - minimum: 8, - actual: 7, - })) - )); - assert_eq!( - transport.calls(), - vec![ - TransportCall::Query(BatteryFeature::Unified(5)), - TransportCall::Discover(FEATURE_BATTERY_STATUS), - TransportCall::Query(BatteryFeature::Legacy(6)), - ] - ); - } - - /// Transport failures that are not protocol errors; `HidppError` is not - /// `Clone`, so each case builds a fresh one. - const TRANSPORT_FAILURES: [fn() -> HidppError; 2] = [ - || HidppError::Hid(HidError::InitializationError), - || HidppError::ShortWrite { - expected: 7, - actual: 3, - }, - ]; - - #[test] - fn returns_legacy_transport_failure_after_unified_protocol_error() { - for failure in TRANSPORT_FAILURES { - let transport = FakeTransport::new( - BatteryFeature::Unified(5), - vec![Ok(Some(6))], - vec![Err(short_response_error()), Err(failure())], - ); - - let result = read_battery_from(&transport); - - assert_eq!( - result.map_err(|error| error.to_string()), - Err(failure().to_string()) - ); - assert_eq!( - transport.calls(), - vec![ - TransportCall::Query(BatteryFeature::Unified(5)), - TransportCall::Discover(FEATURE_BATTERY_STATUS), - TransportCall::Query(BatteryFeature::Legacy(6)), - ] - ); - } - } - - #[test] - fn does_not_fall_back_after_unified_transport_failure() { - for failure in TRANSPORT_FAILURES { - let transport = - FakeTransport::new(BatteryFeature::Unified(5), Vec::new(), vec![Err(failure())]); - - let result = read_battery_from(&transport); - - assert_eq!( - result.map_err(|error| error.to_string()), - Err(failure().to_string()) - ); - assert_eq!( - transport.calls(), - vec![TransportCall::Query(BatteryFeature::Unified(5))] - ); - } - } - - mod scripted_success { - use super::*; - - #[test] - fn discovers_and_reads_unified_battery_from_raw_reports() { - for (device_index, feature_index, level, charging_byte, charging) in - [(1, 5, 78, 0x81, true), (0xFF, 9, 42, 0x02, false)] - { - let discover_report = [REPORT_ID_SHORT, device_index, 0, 0x0F, 0x10, 0x04, 0]; - let battery_report = [REPORT_ID_SHORT, device_index, feature_index, 0x1F, 0, 0, 0]; - let mut stale_battery = [0; REPORT_BUFFER_LEN]; - stale_battery[..8].copy_from_slice(&[ - REPORT_ID_LONG, - device_index, - feature_index, - 0x1F, - 8, - 0, - 0, - 0, - ]); - let mut battery_response = [0; REPORT_BUFFER_LEN]; - battery_response[..8].copy_from_slice(&[ - REPORT_ID_LONG, - device_index, - feature_index, - 0x1F, - level, - 0, - 0, - charging_byte, - ]); - let io = ScriptedIo::new(vec![ - ScriptStep::flush(&[REPORT_ID_SHORT, device_index, 0, 0x0F, 99, 0, 0]), - ScriptStep::flush(&[]), - ScriptStep::write(&discover_report), - ScriptStep::response( - 1_500, - &[REPORT_ID_SHORT, device_index, 0, 0x0F, feature_index, 0, 0], - ), - ScriptStep::flush(&stale_battery), - ScriptStep::flush(&[]), - ScriptStep::write(&battery_report), - ScriptStep::response(1_500, &battery_response), + fn legacy_io_failures_replace_the_unified_short_response() { + for failure in IoFailure::ALL { + let lookup_failure = ScriptedIo::new([ + exchange(&UNIFIED_QUERY, [reply(&INCOMPLETE_UNIFIED)]), + failure.steps(&LEGACY_LOOKUP), ]); + failure.assert_error(read_unified(&lookup_failure)); - let ProbeOutcome::Found(battery_feature) = - find_battery_feature(&io, device_index, io.now() + DISCOVERY_BUDGET).unwrap() - else { - panic!("battery feature should be discovered"); - }; - let session = BatterySession { - io: &io, - device_index, - battery_feature, - }; - assert_eq!( - read_battery_from(&session).unwrap(), - Some(BatteryStatus { level, charging }) - ); - assert_eq!(io.writes(), vec![discover_report, battery_report]); - io.assert_finished(); + let query_failure = ScriptedIo::new([ + exchange(&UNIFIED_QUERY, [reply(&INCOMPLETE_UNIFIED)]), + exchange(&LEGACY_LOOKUP, [reply(&LEGACY_FEATURE)]), + failure.steps(&LEGACY_QUERY), + ]); + failure.assert_error(read_unified(&query_failure)); } } - - #[test] - fn zero_timeout_response_is_available_after_its_write() { - let response = [REPORT_ID_SHORT, 1, 0, 0x0F, 5, 0, 0]; - let io = ScriptedIo::new(vec![ - ScriptStep::flush(&[]), - ScriptStep::write(&[REPORT_ID_SHORT, 1, 0, 0x0F, 0x10, 0x04, 0]), - ScriptStep::response(0, &response), - ]); - - let result = get_feature_index_on_device( - &io, - 1, - DEFAULT_SW_ID, - FEATURE_UNIFIED_BATTERY, - Duration::ZERO, - ); - - assert!(matches!(result, Ok(FeatureLookup::Index(5)))); - assert_eq!(io.calls.borrow().first(), Some(&IoCall::Read(0))); - assert_eq!(io.calls.borrow().last(), Some(&IoCall::Read(0))); - io.assert_finished(); - } - - #[test] - fn expected_silence_advances_virtual_time() { - let timeout = Duration::from_millis(10); - let io = ScriptedIo::new(vec![ - ScriptStep::flush(&[]), - ScriptStep::write(&[REPORT_ID_SHORT, 1, 0, 0x0F, 0x10, 0x04, 0]), - ScriptStep::silence(10, timeout), - ]); - let start = io.now(); - - let result = get_feature_index_on_device( - &io, - 1, - DEFAULT_SW_ID, - FEATURE_UNIFIED_BATTERY, - timeout, - ); - - assert!(matches!(result, Ok(FeatureLookup::Silent))); - assert_eq!(io.now().duration_since(start), timeout); - io.assert_finished(); - } - - #[test] - #[should_panic(expected = "script exhausted during read")] - fn an_exhausted_script_fails_instead_of_inventing_silence() { - let io = ScriptedIo::new(vec![ - ScriptStep::flush(&[]), - ScriptStep::write(&[REPORT_ID_SHORT, 1, 0, 0x0F, 0x10, 0x04, 0]), - ]); - let _ = find_battery_feature(&io, 1, io.now() + DISCOVERY_BUDGET); - } - - #[test] - #[should_panic(expected = "unexpected read; expected Write")] - fn an_unexpected_io_operation_fails_explicitly() { - let io = ScriptedIo::new(vec![ScriptStep::write(&[ - REPORT_ID_SHORT, - 1, - 0, - 0x0F, - 0x10, - 0x04, - 0, - ])]); - let _ = find_battery_feature(&io, 1, io.now() + DISCOVERY_BUDGET); - } - - #[test] - #[should_panic(expected = "a scripted response requires a preceding write")] - fn a_script_cannot_expose_a_response_before_its_write() { - let _ = ScriptedIo::new(vec![ScriptStep::response( - 0, - &[REPORT_ID_SHORT, 1, 0, 0x0F, 5, 0, 0], - )]); - } } } diff --git a/src/lib.rs b/src/lib.rs deleted file mode 100644 index abb6ca8..0000000 --- a/src/lib.rs +++ /dev/null @@ -1 +0,0 @@ -pub mod hidpp; diff --git a/src/main.rs b/src/main.rs index c03b64c..d3a7af0 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,7 +1,9 @@ +mod hidpp; + use std::process::ExitCode; -use gbat::hidpp::{open_first_working_transport, read_battery, BatteryStatus, Discovery}; use hidapi::HidApi; +use hidpp::{open_first_working_transport, read_battery, BatteryStatus, Discovery}; fn main() -> ExitCode { if std::env::args().nth(1).as_deref() == Some("--version") { @@ -58,8 +60,7 @@ fn format_status(status: BatteryStatus) -> String { #[cfg(test)] mod tests { - use super::format_status; - use gbat::hidpp::BatteryStatus; + use super::{format_status, BatteryStatus}; #[test] fn formats_battery_status_for_terminal_and_raycast() {