From 32703d719dd3ab4a44d503646a7bd849d23b37a7 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 17:59:15 +0000 Subject: [PATCH 1/2] 2.34.0: Bluetooth levels live, case kept, nearby earbuds - Sony: read the support list and ask the battery types the model has (set 2 threshold types 9 / 10 / 8: WF-C710N answered none of 1 / 2 / 0). Channel open for every connected Sony device, asked every 20 s. - Last levels kept per device with their time; case level kept while both buds are out of the case. Saved across restarts. - Helper module: Google Fast Pair battery field (1 % steps) next to Apple's; runs whenever the Bluetooth page reads, paired or not. Unpaired devices heard nearby are listed last. - --scan mode in mod_bluetooth.exe and a section 9 in --bt-debug. - Page re-read every 5 s (overview 15 s). --- Cargo.lock | 2 +- Cargo.toml | 2 +- res/resmon.manifest | 2 +- setup.iss | 2 +- src/modbt/main.rs | 257 ++++++++++++++++++++++++++++++---- src/modules.rs | 10 +- src/modules_ui.rs | 6 +- src/monitor/btpage.rs | 74 ++++++++-- src/sensors/deep/bluetooth.rs | 211 +++++++++++++++++++++++++--- src/sensors/deep/btmod.rs | 162 +++++++++++++++++++-- src/sensors/deep/live.rs | 10 +- src/sensors/deep/sony.rs | 100 +++++++++++-- 12 files changed, 732 insertions(+), 106 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 744195f..0d9a2aa 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -92,7 +92,7 @@ dependencies = [ [[package]] name = "resmon" -version = "2.33.0" +version = "2.34.0" dependencies = [ "embed-resource", "windows", diff --git a/Cargo.toml b/Cargo.toml index b89784b..7e406f8 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "resmon" -version = "2.33.0" +version = "2.34.0" edition = "2021" authors = ["Emulsion Labs"] description = "Ultra-light taskbar resource monitor for Windows 10/11" diff --git a/res/resmon.manifest b/res/resmon.manifest index 14b22d6..632d0b0 100644 --- a/res/resmon.manifest +++ b/res/resmon.manifest @@ -1,6 +1,6 @@ - + diff --git a/setup.iss b/setup.iss index 6be0007..c26d907 100644 --- a/setup.iss +++ b/setup.iss @@ -1,6 +1,6 @@ ; Inno Setup script. Build the exe first: cargo build --release #define MyAppName "Resource Monitor" -#define MyAppVersion "2.33.0" +#define MyAppVersion "2.34.0" #define MyAppPublisher "Emulsion Labs" #define MyAppURL "https://github.com/rajhansgithub/Windows_Resource_Monitoring_Tool" #define MyAppExeName "ResourceMonitor.exe" diff --git a/src/modbt/main.rs b/src/modbt/main.rs index 7106831..819abe5 100644 --- a/src/modbt/main.rs +++ b/src/modbt/main.rs @@ -1,14 +1,21 @@ //! `mod_bluetooth.exe`: the optional Bluetooth helper module of Resource Monitor. //! //! Listens to Bluetooth LE advertisements (passive, no pairing, no connection) for what -//! Windows itself never reads: AirPods and Beats broadcast each bud's and the case's level -//! and charging state in Apple's "proximity pairing" advertisement (manufacturer data, -//! company 0x004C, type 0x07). The levels come in steps of 10 %. +//! Windows itself never reads, from devices near this PC whether or not they are connected: +//! * AirPods and Beats broadcast each bud's and the case's level and charging state in +//! Apple's "proximity pairing" advertisement (manufacturer data, company 0x004C, type +//! 0x07). The levels come in steps of 10 %. +//! * Google Fast Pair earbuds and headphones (Sony, Pixel Buds, JBL, Jabra and others that +//! were set up with an Android phone) add left, right and case levels to their Fast Pair +//! advertisement (service data 0xFE2C, battery field), in 1 % steps. //! //! Output: one JSON object per line on stdout, at most every 2 s per device and whenever //! a value changes. The core app draws them; this process holds no UI. It exits when its //! stdin closes (the app quit), and the app also keeps it in a kill-on-close job object. //! +//! `mod_bluetooth.exe --scan [seconds]` prints every advertisement it hears instead (raw +//! manufacturer and service data, decoded levels), for finding what a device sends. +//! //! WinRT stays in this process, out of the taskbar app (see the module-system notes). #![cfg_attr(not(test), windows_subsystem = "windows")] @@ -20,6 +27,8 @@ use std::time::{Duration, Instant}; /// Apple's Bluetooth SIG company id. const APPLE: u16 = 0x004C; +/// Google Fast Pair's 16-bit service UUID. +const FAST_PAIR: u16 = 0xFE2C; /// Weaker than this is someone else's AirPods across the room. const MIN_RSSI: i16 = -72; /// A device's line is repeated at most this often when nothing changes. @@ -119,6 +128,102 @@ fn json(p: &Pods, rssi: i16) -> String { ) } +/// Levels from a Fast Pair advertisement's battery field. +#[derive(Clone, Debug, PartialEq)] +struct Fp { + left: Option, + right: Option, + case: Option, + /// One battery (headphones, speakers). + single: Option, + charging_left: bool, + charging_right: bool, + charging_case: bool, +} + +/// One battery byte: bit 7 charging, bits 0..=6 the level, 0x7F unknown. +fn fp_level(b: u8) -> (Option, bool) { + let v = b & 0x7F; + ((v <= 100).then_some(v), b & 0x80 != 0) +} + +/// Decodes Fast Pair service data (UUID already stripped). Only the account-data form (the +/// one a device that was set up sends) carries levels: a version byte, then fields of +/// `length << 4 | type`; type 3 (shown) or 4 (hidden) is the battery field, one byte per +/// battery: left, right, case. A 3-byte payload is the discoverable model id: no levels. +fn decode_fast_pair(b: &[u8]) -> Option { + if b.len() <= 3 || b[0] >> 4 != 0 { + return None; + } + let mut i = 1; + while i < b.len() { + let (len, ty) = (usize::from(b[i] >> 4), b[i] & 0x0F); + i += 1; + let field = b.get(i..i + len)?; + if matches!(ty, 3 | 4) && !field.is_empty() { + let mut fp = Fp { left: None, right: None, case: None, single: None, charging_left: false, charging_right: false, charging_case: false }; + if field.len() == 1 { + let (v, c) = fp_level(field[0]); + fp.single = v; + fp.charging_left = c; + } else { + (fp.left, fp.charging_left) = fp_level(field[0]); + (fp.right, fp.charging_right) = fp_level(field[1]); + if let Some(&c) = field.get(2) { + (fp.case, fp.charging_case) = fp_level(c); + } + } + return (fp.left.is_some() || fp.right.is_some() || fp.case.is_some() || fp.single.is_some()).then_some(fp); + } + i += len; + } + None +} + +fn fp_json(p: &Fp, addr: u64, name: &str, rssi: i16) -> String { + format!( + "{{\"v\":1,\"kind\":\"fastpair\",\"key\":\"{addr:012x}\",\"model\":\"{}\",\"left\":{},\"right\":{},\"case\":{},\"single\":{},\"charging_left\":{},\"charging_right\":{},\"charging_case\":{},\"rssi\":{}}}", + clean(name), + opt(p.left), + opt(p.right), + opt(p.case), + opt(p.single), + p.charging_left, + p.charging_right, + p.charging_case, + rssi + ) +} + +/// A name safe inside a JSON string (quotes, backslashes and control characters dropped). +fn clean(s: &str) -> String { + s.chars().filter(|c| !c.is_control() && *c != '"' && *c != '\\').take(48).collect() +} + +/// Throttles Fast Pair lines per address, as `Seen` does for Apple models. +#[derive(Default)] +struct SeenFp { + last: HashMap, +} + +impl SeenFp { + fn offer(&mut self, addr: u64, p: Fp, name: &str, rssi: i16) -> Option { + let now = Instant::now(); + let due = match self.last.get(&addr) { + Some((old, t)) => (old != &p && now.duration_since(*t) >= MIN_GAP) || now.duration_since(*t) >= REPEAT, + None => true, + }; + if !due { + return None; + } + let line = fp_json(&p, addr, name, rssi); + self.last.insert(addr, (p, now)); + // Rotating addresses: forget the ones not heard for a while. + self.last.retain(|_, v| now.duration_since(v.1) < Duration::from_secs(300)); + Some(line) + } +} + #[derive(Default)] struct Seen { last: HashMap, @@ -148,48 +253,113 @@ fn main() { BluetoothLEScanningMode, }; use windows::Foundation::TypedEventHandler; - use windows::Storage::Streams::DataReader; + use windows::Storage::Streams::{DataReader, IBuffer}; use windows::Win32::System::Com::{CoInitializeEx, COINIT_MULTITHREADED}; - // The app closing our stdin (or dying) ends us. - std::thread::spawn(|| { - let mut sink = String::new(); - while std::io::stdin().read_line(&mut sink).map_or(false, |n| n > 0) { - sink.clear(); - } - std::process::exit(0); - }); + let args: Vec = std::env::args().collect(); + // `--scan [seconds]`: print everything heard, then exit. + let scan = args.iter().position(|a| a.eq_ignore_ascii_case("--scan")).map(|i| args.get(i + 1).and_then(|v| v.parse::().ok()).unwrap_or(30)); + if scan.is_none() { + // The app closing our stdin (or dying) ends us. + std::thread::spawn(|| { + let mut sink = String::new(); + while std::io::stdin().read_line(&mut sink).map_or(false, |n| n > 0) { + sink.clear(); + } + std::process::exit(0); + }); + } // SAFETY: once, for this thread; the watcher's callbacks run on the MTA pool. let _ = unsafe { CoInitializeEx(None, COINIT_MULTITHREADED) }; let seen = Arc::new(Mutex::new(Seen::default())); + let seen_fp = Arc::new(Mutex::new(SeenFp::default())); + let raw_seen: Arc>> = Arc::default(); println_flush("{\"v\":1,\"kind\":\"hello\"}"); + fn bytes(buf: &IBuffer) -> windows::core::Result> { + let n = buf.Length()? as usize; + let mut v = vec![0u8; n.min(255)]; + if !v.is_empty() { + DataReader::FromBuffer(buf)?.ReadBytes(&mut v)?; + } + Ok(v) + } loop { let run = || -> windows::core::Result { let w = BluetoothLEAdvertisementWatcher::new()?; - w.SetScanningMode(BluetoothLEScanningMode::Passive)?; - let seen = seen.clone(); + // The scan asks for scan responses too (names); the helper only listens. + w.SetScanningMode(if scan.is_some() { BluetoothLEScanningMode::Active } else { BluetoothLEScanningMode::Passive })?; + let (seen, seen_fp, raw_seen) = (seen.clone(), seen_fp.clone(), raw_seen.clone()); w.Received(&TypedEventHandler::new(move |_, args: &Option| { let Some(a) = args else { return Ok(()) }; let rssi = a.RawSignalStrengthInDBm()?; + let addr = a.BluetoothAddress()?; + let adv = a.Advertisement()?; + let name = adv.LocalName().map(|h| h.to_string()).unwrap_or_default(); + let mut apple: Vec> = Vec::new(); + let mut fast: Vec> = Vec::new(); + let mut raw = String::new(); + let sections = adv.DataSections()?; + for i in 0..sections.Size()? { + let sec = sections.GetAt(i)?; + let ty = sec.DataType()?; + let d = bytes(&sec.Data()?)?; + if scan.is_some() && !matches!(ty, 0x01 | 0x08 | 0x09) { + raw.push_str(&format!(" | {ty:02x}: {}", hex(&d))); + } + match ty { + 0xFF if d.len() > 2 && u16::from_le_bytes([d[0], d[1]]) == APPLE => apple.push(d[2..].to_vec()), + 0x16 if d.len() > 2 && u16::from_le_bytes([d[0], d[1]]) == FAST_PAIR => fast.push(d[2..].to_vec()), + _ => {} + } + } + if scan.is_some() { + // Each address and payload once every 5 s. + let h = raw.bytes().fold(0xcbf2_9ce4_8422_2325u64, |h, b| (h ^ u64::from(b)).wrapping_mul(0x0100_0000_01b3)); + let due = raw_seen.lock().map(|mut m| { + let now = Instant::now(); + let fresh = m.get(&(addr, h)).is_some_and(|t| now.duration_since(*t) < Duration::from_secs(5)); + if !fresh { + m.insert((addr, h), now); + } + !fresh + }); + if due.unwrap_or(false) { + let mut line = format!("{addr:012x} {rssi:>4} dBm \"{}\"{raw}", clean(&name)); + for b in &apple { + if let Some(p) = decode(b) { + line.push_str(&format!(" => apple {} L {:?} R {:?} case {:?}", model_name(p.model_id), p.left, p.right, p.case)); + } + } + for b in &fast { + match decode_fast_pair(b) { + Some(p) => line.push_str(&format!(" => fast pair L {:?} R {:?} case {:?} one {:?}", p.left, p.right, p.case, p.single)), + None if b.len() == 3 => line.push_str(&format!(" => fast pair model {:06x}", u32::from_be_bytes([0, b[0], b[1], b[2]]))), + None => {} + } + } + println_flush(&line); + } + return Ok(()); + } if rssi < MIN_RSSI { return Ok(()); } - let list = a.Advertisement()?.GetManufacturerDataByCompanyId(APPLE)?; - for i in 0..list.Size()? { - let buf = list.GetAt(i)?.Data()?; - let n = buf.Length()? as usize; - if n == 0 || n > 64 { - continue; - } - let mut bytes = vec![0u8; n]; - DataReader::FromBuffer(&buf)?.ReadBytes(&mut bytes)?; - if let Some(p) = decode(&bytes) { + for b in &apple { + if let Some(p) = decode(b) { let line = seen.lock().ok().and_then(|mut s| s.offer(p, rssi)); if let Some(line) = line { println_flush(&line); } } } + for b in &fast { + if let Some(p) = decode_fast_pair(b) { + let line = seen_fp.lock().ok().and_then(|mut s| s.offer(addr, p, &name, rssi)); + if let Some(line) = line { + println_flush(&line); + } + } + } Ok(()) }))?; w.Start()?; @@ -197,6 +367,11 @@ fn main() { }; match run() { Ok(w) => { + if let Some(secs) = scan { + std::thread::sleep(Duration::from_secs(secs)); + let _ = w.Stop(); + return; + } // Runs until Bluetooth is turned off (status Aborted); then start again. while w.Status().map_or(false, |s| s == BluetoothLEAdvertisementWatcherStatus::Started || s == BluetoothLEAdvertisementWatcherStatus::Created) { std::thread::sleep(Duration::from_secs(5)); @@ -204,12 +379,21 @@ fn main() { let _ = w.Stop(); println_flush("{\"v\":1,\"kind\":\"radio_off\"}"); } - Err(e) => println_flush(&format!("{{\"v\":1,\"kind\":\"error\",\"code\":{}}}", e.code().0)), + Err(e) => { + println_flush(&format!("{{\"v\":1,\"kind\":\"error\",\"code\":{}}}", e.code().0)); + if scan.is_some() { + return; + } + } } std::thread::sleep(Duration::from_secs(30)); } } +fn hex(b: &[u8]) -> String { + b.iter().map(|x| format!("{x:02x}")).collect::>().join(" ") +} + #[cfg(not(windows))] fn main() {} @@ -259,6 +443,29 @@ mod tests { assert!(s.offer(decode(&b).unwrap(), -50).is_none()); } + /// Fast Pair account data: empty-ish filter, salt, then shown battery: left 72 %, + /// right 68 % charging, case 41 %. + #[test] + fn fast_pair_battery() { + let b = [0x00, 0x40, 0x11, 0x22, 0x33, 0x44, 0x11, 0x5A, 0x33, 72, 0x80 | 68, 41]; + let p = decode_fast_pair(&b).unwrap(); + assert_eq!((p.left, p.right, p.case, p.single), (Some(72), Some(68), Some(41), None)); + assert!(p.charging_right && !p.charging_left && !p.charging_case); + // Hidden battery field (type 4), unknown case. + let b = [0x00, 0x00, 0x34, 100, 99, 0x7F]; + let p = decode_fast_pair(&b).unwrap(); + assert_eq!((p.left, p.right, p.case), (Some(100), Some(99), None)); + // One battery. + let p = decode_fast_pair(&[0x00, 0x00, 0x13, 0x80 | 55]).unwrap(); + assert_eq!((p.single, p.charging_left), (Some(55), true)); + // Discoverable model id, no battery field, truncated field. + assert!(decode_fast_pair(&[0x2C, 0x00, 0x1A]).is_none()); + assert!(decode_fast_pair(&[0x00, 0x40, 0x11, 0x22]).is_none()); + assert!(decode_fast_pair(&[0x00, 0x00, 0x11, 0x5A]).is_none()); + let l = fp_json(&decode_fast_pair(&[0x00, 0x00, 0x33, 72, 68, 41]).unwrap(), 0x1234, "WF-\"X", -60); + assert!(l.contains("\"kind\":\"fastpair\"") && l.contains("\"left\":72") && l.contains("\"model\":\"WF-X\"")); + } + #[test] fn line() { let b = [0x07, 0x19, 0x01, 0x0E, 0x20, 0x2B, 0x79, 0x45, 0x00]; diff --git a/src/modules.rs b/src/modules.rs index 0fffc3f..2c39049 100644 --- a/src/modules.rs +++ b/src/modules.rs @@ -12,7 +12,7 @@ use crate::sensors::deep::addons::Addon; pub enum Id { /// Built in: paired Bluetooth devices and their batteries (`Settings::mod_bluetooth`). Bluetooth, - /// Add-on `mod_bluetooth.exe`: AirPods and Beats per-bud levels (`Settings::mod_bt_extras`). + /// Add-on `mod_bluetooth.exe`: per-bud, case and nearby levels from BLE advertisements (`Settings::mod_bt_extras`). BtExtras, /// Built in: the readings Windows only gives an elevated app (SATA SMART, per-app network /// bytes, busiest apps per drive). @@ -65,11 +65,11 @@ pub const MODULES: [Module; 7] = [ }, Module { id: Id::BtExtras, - name: "AirPods and Beats", + name: "Earbuds nearby", kind: Kind::AddOn, needs: Needs::AppleDevice, - blurb: "Left, right and case levels for AirPods and Beats, from their Bluetooth signal.", - reads: "The Bluetooth LE advertisements AirPods and Beats send near this PC: left, right and case levels and charging. A separate small program, so its Windows Runtime code never loads into the app. Runs only while an Apple or Beats device is paired.", + blurb: "Left, right and case levels for AirPods, Beats and Fast Pair earbuds near this PC, paired or not.", + reads: "The Bluetooth LE advertisements AirPods and Beats send near this PC: left, right and case levels and charging. A separate small program, so its Windows Runtime code never loads into the app. Also Google Fast Pair battery fields (Sony, Pixel Buds, JBL and others set up with an Android phone). Listens only, never connects; runs while the Monitor page is open.", exe: "mod_bluetooth.exe", }, Module { @@ -286,7 +286,7 @@ impl State { State::On => "On".into(), State::Off => "Off".into(), State::Running => "Running".into(), - State::Waiting => "On, waiting for AirPods".into(), + State::Waiting => "On, listening soon".into(), State::Paused => "Needs Bluetooth devices on".into(), State::Shelf => "Not installed".into(), State::Downloading(Some(f)) => format!("Downloading {}%", (f * 100.0).round() as i32), diff --git a/src/modules_ui.rs b/src/modules_ui.rs index 503a6bc..bb66bd7 100644 --- a/src/modules_ui.rs +++ b/src/modules_ui.rs @@ -276,7 +276,7 @@ impl ModPage { .map(|d| [d.left, d.case, d.right]) .next(); BtFacts { - paired: list.len(), + paired: list.iter().filter(|d| !d.nearby).count(), connected: list.iter().filter(|d| d.connected).count(), lowest, pods, @@ -918,11 +918,11 @@ fn reading(m: &modules::Module, st: &State, s: &Snap) -> (String, String, String let f = |x: Option| x.map_or("--".to_string(), |v| format!("{v}%")); (pct(v), format!("Left {} \u{00B7} Right {} \u{00B7} Case {}", f(l), f(r), f(c))) } - None => (("On".into(), String::new()), "Running. Levels show when the AirPods case opens near this PC.".into()), + None => (("On".into(), String::new()), "Listening. Levels show when earbuds near this PC open their case or play.".into()), }, (Id::BtExtras, State::Waiting) => ( ("On".into(), String::new()), - if bt.apple { "Starts with the next Bluetooth read.".into() } else { "Starts when AirPods or Beats are paired.".into() }, + "Starts with the next Bluetooth read.".into(), ), (Id::BtExtras, State::Paused) => (("Paused".into(), String::new()), "Turn on Bluetooth devices: this add-on reads through it.".into()), (Id::BtExtras, State::Off) => (("Off".into(), String::new()), "Installed, switched off. It does not run.".into()), diff --git a/src/monitor/btpage.rs b/src/monitor/btpage.rs index cd82cbf..cdc3866 100644 --- a/src/monitor/btpage.rs +++ b/src/monitor/btpage.rs @@ -51,8 +51,14 @@ fn per_bud(d: &BtDevice) -> bool { d.left.is_some() || d.right.is_some() } +/// The levels shown are live: connected, heard nearby now, or per-bud levels the helper +/// hears from the open case. Last-read levels (`levels_at`) are not. +fn fresh(d: &BtDevice) -> bool { + d.levels_at.is_none() && (d.connected || d.nearby || per_bud(d)) +} + fn is_low(d: &BtDevice) -> bool { - d.connected && level(d).is_some_and(|l| l <= LOW_PCT) + fresh(d) && level(d).is_some_and(|l| l <= LOW_PCT) } fn kind_label(k: Kind) -> &'static str { @@ -89,6 +95,21 @@ fn ago(unix: u64) -> String { /// Connection state in words. fn state(d: &BtDevice) -> String { + let s = state_only(d); + // Earbuds report the case only while a bud is in it: say how old the case level is. + match d.case_at { + Some(t) if d.levels_at.is_none() && d.case.is_some() => format!("{s} \u{00B7} case {}", ago(t)), + _ => s, + } +} + +fn state_only(d: &BtDevice) -> String { + if d.nearby { + return if d.charging == Some(true) { "Nearby \u{00B7} charging".into() } else { "Nearby \u{00B7} not paired".into() }; + } + if let (Some(t), false) = (d.levels_at, d.connected) { + return format!("Last read {}", ago(t)); + } if d.connected { if d.charging == Some(true) { "Charging".into() @@ -101,6 +122,9 @@ fn state(d: &BtDevice) -> String { } else { "Connected".into() } + } else if per_bud(d) { + // Heard from the open case near this PC. + "In the case, nearby".into() } else { match d.last_seen { Some(t) => format!("Seen {}", ago(t)), @@ -254,13 +278,14 @@ impl Monitor { pub(super) fn bt_module_label(&self) -> Option<&'static str> { use crate::sensors::deep::btmod::{available, is_apple, Get}; // Switched off on the Modules page: nothing to offer here. - if !self.bt().iter().any(is_apple) || available() || !crate::sensors::deep::btmod::enabled() { + // Earbuds or headphones paired: the helper hears their case and nearby buds. + if !self.bt().iter().any(|d| is_apple(d) || is_audio(d)) || available() || !crate::sensors::deep::btmod::enabled() { return None; } match self.bt_get.lock().map(|g| g.clone()).unwrap_or_default() { Get::Working => Some("Downloading\u{2026}"), Get::Done => None, - Get::Idle | Get::Failed(..) => Some("AirPods L / R levels"), + Get::Idle | Get::Failed(..) => Some("Case + nearby levels"), } } @@ -307,20 +332,24 @@ impl Monitor { Get::Working => return (Tone::Info, "Getting the Bluetooth extras module\u{2026}".into(), "About 500 KB from this version's GitHub release, checked against its built-in checksum.".into()), Get::Failed(e, at) if at.elapsed().as_secs() < 60 => return (Tone::Bad, "The Bluetooth extras module did not download.".into(), e), Get::Done if !self.bt().iter().any(|d| d.left.is_some() || d.right.is_some()) => { - return (Tone::Good, "Bluetooth extras installed.".into(), "AirPods and Beats show left, right and case once their case lid opens or they are in use near this PC.".into()) + return (Tone::Good, "Bluetooth extras installed.".into(), "AirPods, Beats and Fast Pair earbuds show left, right and case once their case opens or they are in use near this PC.".into()) } _ => {} } } let b = self.bt(); let on = b.iter().filter(|d| d.connected).count(); - let sub = format!("{on} connected \u{00B7} {} paired \u{00B7} levels as Windows reports them", b.len()); - if let Some(d) = b.iter().filter(|d| is_low(d)).min_by_key(|d| level(d)) { + let paired = b.iter().filter(|d| !d.nearby).count(); + let near = b.len() - paired; + let near_t = if near > 0 { format!(" \u{00B7} {near} nearby") } else { String::new() }; + let sub = format!("{on} connected \u{00B7} {paired} paired{near_t} \u{00B7} whole percents, as the devices send them"); + // Someone else's buds nearby are not a reason to warn. + if let Some(d) = b.iter().filter(|d| is_low(d) && !d.nearby).min_by_key(|d| level(d)) { let l = level(d).unwrap_or(0); return (Tone::Bad, format!("{} is at {l}%. Charge it soon.", d.name), sub); } if on == 0 { - return (Tone::Info, "No Bluetooth device is connected.".into(), format!("{} paired. Levels shown are the last Windows saw.", b.len())); + return (Tone::Info, "No Bluetooth device is connected.".into(), format!("{paired} paired{near_t}. Dim levels are the last ones read.")); } match b.iter().filter(|d| d.connected).filter_map(|d| level(d).map(|l| (l, d))).min_by_key(|x| x.0) { Some((l, d)) => (Tone::Good, "Every connected device has charge.".into(), format!("Lowest: {} at {l}% \u{00B7} {sub}", d.name)), @@ -493,7 +522,7 @@ impl Monitor { impl Draw<'_> { /// Battery colour: low red, charging green, else the accent; dim when disconnected. fn bt_col(&self, d: &BtDevice) -> Rgba { - if !d.connected { + if !fresh(d) { self.col.dim } else if is_low(d) { self.col.crit @@ -549,14 +578,14 @@ impl Draw<'_> { cv.fill_rect(Rect { l, t, r: rr, b: t + 1 }, self.col.line); } let cy = t + rh / 2; - let ic = if d.connected { self.col.fg } else { self.col.dim }; + let ic = if fresh(d) { self.col.fg } else { self.col.dim }; bt_icon(cv, d.kind, (l + self.s(12)) as f32, cy as f32, self.sf(22.0), ic); let nx = l + self.s(36); let nm = cv.ellipsize(self.f.semi, &d.name, name_w - self.s(40)); cv.text(self.f.semi, &nm, nx, cy - self.s(17), ic); let sub = format!("{} \u{00B7} {}", note(d).to_uppercase(), kind_label(d.kind)); let sub = cv.ellipsize(self.f.tiny, &sub, name_w - self.s(40)); - cv.text(self.f.tiny, &sub, nx, cy + self.s(3), if d.connected { self.bt_col(d) } else { self.col.dim }); + cv.text(self.f.tiny, &sub, nx, cy + self.s(3), self.bt_col(d)); // Level: big number on the right, segmented bars between. let c = self.bt_col(d); let pt = pct_text(level(d)); @@ -674,7 +703,7 @@ impl Draw<'_> { let iy = (y0 + y1 - ch * k) / 2.0 - f[1] * k; (ix, iy, k) }; - let on = d.connected; + let on = fresh(d); let numc = |v: Option| match v { None => self.col.dim, Some(_) if !on => self.col.dim, @@ -713,7 +742,9 @@ impl Draw<'_> { let xs = dev.cols(); for (i, (lab, v)) in [("L", d.left), ("CASE", d.case), ("R", d.right)].iter().enumerate() { let x = (ix + xs[i] * k) as i32; - mid(cv, &pct_text(*v), x, ny, numc(*v), true); + // A case level from earlier (buds out of the case) is drawn dim. + let c = if i == 1 && d.case_at.is_some() { self.col.dim } else { numc(*v) }; + mid(cv, &pct_text(*v), x, ny, c, true); let (lw, lh) = cv.measure(self.f.tiny, lab); cv.text(self.f.tiny, lab, x - lw / 2, sy - self.s(2) - lh / 2, self.col.dim); } @@ -747,7 +778,7 @@ impl Draw<'_> { let m = self.m; let b = m.bt(); let on = b.iter().filter(|d| d.connected).count(); - let low = b.iter().filter(|d| is_low(d)).count(); + let low = b.iter().filter(|d| is_low(d) && !d.nearby).count(); let pw = if low > 0 { self.pill(cv, r, &format!("{low} low"), self.col.crit, true) } else { 0 }; let y = self.header(cv, r, "Bluetooth", &format!("{on} connected"), pw + self.s(8)); let (l, rr) = (r.l + self.s(16), r.r - self.s(16)); @@ -893,6 +924,23 @@ mod tests { assert_eq!(level(&dev(None, None, None)), None); } + #[test] + fn old_levels_say_when() { + let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_secs(); + let mut d = dev(None, Some(78), Some(80)); + d.kind = Kind::Earbuds; + d.case = Some(60); + d.case_at = Some(now - 1200); + assert_eq!(state(&d), "Connected \u{00B7} case 20 min ago"); + d.connected = false; + d.levels_at = Some(now - 7200); + assert_eq!(state(&d), "Last read 2 h ago"); + assert!(!fresh(&d) && !is_low(&d)); + let n = BtDevice { nearby: true, left: Some(10), right: Some(30), ..Default::default() }; + assert!(fresh(&n) && is_low(&n)); + assert_eq!(state(&n), "Nearby \u{00B7} not paired"); + } + #[test] fn low_only_when_connected() { let mut d = dev(Some(15), None, None); diff --git a/src/sensors/deep/bluetooth.rs b/src/sensors/deep/bluetooth.rs index f272c2c..2f539ce 100644 --- a/src/sensors/deep/bluetooth.rs +++ b/src/sensors/deep/bluetooth.rs @@ -96,6 +96,13 @@ pub struct BtDevice { pub hands_free_idle: bool, /// Sony's own channel (its RFCOMM service id), for left / right / case levels. pub sony: Option, + /// Not paired: heard nearby (its BLE advertisement carries levels; the helper module). + pub nearby: bool, + /// The levels shown are the last ones read (not live), at this time (unix seconds). + pub levels_at: Option, + /// The case level shown is the last one read, at this time (unix seconds): earbuds report + /// the case only while a bud sits in it. + pub case_at: Option, } // ---- property keys (from the Windows SDK headers: devpkey.h, devpropdef.h, BluetoothAEP) ---- @@ -658,10 +665,13 @@ fn apply_sony(list: &mut [BtDevice], levels: &HashMap) if l.left.is_some() || l.right.is_some() { d.left = l.left; d.right = l.right; - d.case = l.case; - } else if d.battery.is_none() { + } else if l.single.is_some() { + // Sony's own reading is newer than the level Windows keeps. d.battery = l.single; } + if l.case.is_some() { + d.case = l.case; + } if d.charging.is_none() { d.charging = l.charging; } @@ -727,8 +737,9 @@ fn fnv(s: &str) -> u64 { fn sort(out: &mut [BtDevice]) { out.sort_by(|a, b| { - b.connected - .cmp(&a.connected) + a.nearby + .cmp(&b.nearby) + .then(b.connected.cmp(&a.connected)) .then((a.kind as u8).cmp(&(b.kind as u8))) .then_with(|| a.name.to_lowercase().cmp(&b.name.to_lowercase())) .then_with(|| a.id.cmp(&b.id)) @@ -1125,8 +1136,8 @@ pub fn write_watch() -> Option { fn watch_line(d: &BtDevice) -> String { format!( - "{} | connected {} | battery {:?} | left {:?} | right {:?} | case {:?} | charging {:?} | receiver {}", - d.name, d.connected, d.battery, d.left, d.right, d.case, d.charging, d.receiver + "{} | connected {} | battery {:?} | left {:?} | right {:?} | case {:?} | charging {:?} | receiver {} | nearby {} | levels_at {:?} | case_at {:?}", + d.name, d.connected, d.battery, d.left, d.right, d.case, d.charging, d.receiver, d.nearby, d.levels_at, d.case_at ) } @@ -1173,7 +1184,7 @@ pub fn debug_report() -> String { } // The page also gets Sony's own levels (the reader thread's workers): the same here. - let wanted: Vec<(u64, u128)> = shown.iter().filter(|d| d.connected && d.battery.is_none()).filter_map(|d| Some((d.addr?, d.sony?))).collect(); + let wanted: Vec<(u64, u128)> = shown.iter().filter(|d| d.connected).filter_map(|d| Some((d.addr?, d.sony?))).collect(); if !wanted.is_empty() { let mut sony = super::sony::Sony::default(); sony.tick(&wanted); @@ -1312,6 +1323,8 @@ pub fn debug_report() -> String { let _ = writeln!(o, "{} | {addr:012x} | service {}", d.name, guid_string(svc)); o.push_str(&super::sony::probe(addr, svc)); } + let _ = writeln!(o, "\n== 9. Nearby BLE advertisements (helper module, 20 s) =="); + o.push_str(&super::btmod::scan_report(20)); o } @@ -1619,6 +1632,8 @@ fn to_line(d: &BtDevice) -> String { b(d.mic_off).into(), b(d.hands_free_idle).into(), d.sony.map_or(String::new(), |v| format!("{v:032x}")), + d.levels_at.map_or(String::new(), |v| v.to_string()), + d.case_at.map_or(String::new(), |v| v.to_string()), ] .join("\t") } @@ -1649,6 +1664,9 @@ fn from_line(l: &str) -> Option { mic_off: b(f[15]), hands_free_idle: b(f[16]), sony: f.get(17).and_then(|v| u128::from_str_radix(v, 16).ok()), + nearby: false, + levels_at: f.get(18).and_then(|v| v.parse().ok()), + case_at: f.get(19).and_then(|v| v.parse().ok()), }) } @@ -1757,6 +1775,11 @@ fn spawn() -> Shared { ); } let demo_env = std::env::var_os("RESMON_BT_DEMO").is_some(); + // Last levels read per device, so a level that stops coming (earbuds back in the + // closed case, the case with both buds out, a device switched off) stays on screen + // with its time instead of going blank. Seeded from the saved list. + let mut kept: HashMap = if demo_env { HashMap::new() } else { seed_kept(&load_cache(), cache_age()) }; + let mut saved_at = std::time::Instant::now(); // The last read before the helper's levels went in, and what was published from it: // new AirPods levels go out within seconds instead of waiting for the next read. let mut base: Vec = Vec::new(); @@ -1785,9 +1808,7 @@ fn spawn() -> Shared { helper.tick(false); sony.tick(&[]); } else { - let mut list = base.clone(); - super::btmod::apply(&mut list, &helper.readings()); - apply_sony(&mut list, &sony.levels()); + let list = finish(base.clone(), &helper.readings(), &sony.levels(), &mut kept); if list != shown { shown = list.clone(); m.lock().unwrap_or_else(|e| e.into_inner()).done = Some(Arc::new(list)); @@ -1809,18 +1830,22 @@ fn spawn() -> Shared { let list = if demo_env { demo() } else { - let mut list = read_with(&mut logi); - helper.tick(list.iter().any(super::btmod::is_apple)); - let wanted: Vec<(u64, u128)> = - list.iter().filter(|d| d.connected && d.battery.is_none()).filter_map(|d| Some((d.addr?, d.sony?))).collect(); + let list = read_with(&mut logi); + // Always listen while the page reads: nearby earbuds (AirPods, Fast Pair) are + // heard whether or not they are paired. + helper.tick(true); + // Every connected Sony device: its channel also has the case. + let wanted: Vec<(u64, u128)> = list.iter().filter(|d| d.connected).filter_map(|d| Some((d.addr?, d.sony?))).collect(); sony.tick(&wanted); base = list.clone(); - super::btmod::apply(&mut list, &helper.readings()); - apply_sony(&mut list, &sony.levels()); + let list = finish(list, &helper.readings(), &sony.levels(), &mut kept); // An empty read can be the radio still starting: keep the last list then. - if !list.is_empty() && list != saved { - save_cache(&list); - saved = list.clone(); + // Also once a minute while levels are live, so their times stay current. + let paired: Vec = list.iter().filter(|d| !d.nearby).cloned().collect(); + if !paired.is_empty() && (paired != saved || saved_at.elapsed().as_secs() >= 60) { + save_cache(&stamped(&paired, &kept)); + saved = paired; + saved_at = std::time::Instant::now(); } shown = list.clone(); list @@ -1836,14 +1861,126 @@ fn spawn() -> Shared { s } +/// What the reader keeps of a device's last levels. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +struct Kept { + battery: Option, + left: Option, + right: Option, + /// When battery / left / right were last read (unix seconds). + at: u64, + case: Option, + case_at: u64, +} + +fn unix_now() -> u64 { + std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_secs()) +} + +/// When the saved list was written (unix seconds), for its entries that carry no time. +fn cache_age() -> u64 { + std::fs::metadata(cache_path()) + .and_then(|m| m.modified()) + .ok() + .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok()) + .map_or(0, |d| d.as_secs()) +} + +/// The kept levels from the saved list. Only levels that came from a live source go in: +/// per-bud levels, or a connected device's level (Windows keeps a stale one for others). +fn seed_kept(list: &[BtDevice], written: u64) -> HashMap { + let mut m = HashMap::new(); + for d in list.iter().filter(|d| !d.nearby && !d.receiver) { + let lr = d.left.is_some() || d.right.is_some(); + let mut k = Kept::default(); + if lr || (d.connected && d.battery.is_some()) || d.levels_at.is_some() { + k.battery = d.battery; + k.left = d.left; + k.right = d.right; + k.at = d.levels_at.unwrap_or(written); + } + if let Some(c) = d.case { + k.case = Some(c); + k.case_at = d.case_at.unwrap_or(written); + } + if k != Kept::default() { + m.insert(d.id.clone(), k); + } + } + m +} + +/// Live levels go into `kept`; a level that is not live now comes back from `kept` with the +/// time it was read (`levels_at`, `case_at`). +fn remember(list: &mut [BtDevice], kept: &mut HashMap, now: u64) { + for d in list.iter_mut().filter(|d| !d.nearby && !d.receiver) { + let k = kept.entry(d.id.clone()).or_default(); + let lr = d.left.is_some() || d.right.is_some(); + // Windows keeps the last level of a device that went away: not live. + let live = lr || (d.connected && d.battery.is_some()); + if live { + (k.battery, k.left, k.right, k.at) = (d.battery, d.left, d.right, now); + } else if k.at > 0 && (k.left.is_some() || k.right.is_some() || k.battery.is_some()) { + // Per-bud levels beat Windows' stale single level; a single level only fills a gap. + if k.left.is_some() || k.right.is_some() || d.battery.is_none() { + d.left = k.left; + d.right = k.right; + d.battery = k.battery.or(d.battery); + d.levels_at = Some(k.at); + } else if d.battery == k.battery { + // Windows' kept level is the one read then: say when. + d.levels_at = Some(k.at); + } + } + if let Some(c) = d.case { + (k.case, k.case_at) = (Some(c), now); + } else if let Some(c) = k.case { + d.case = Some(c); + d.case_at = Some(k.case_at); + } + } +} + +/// The list as saved: each level with the time it was read. +fn stamped(list: &[BtDevice], kept: &HashMap) -> Vec { + list.iter() + .map(|d| { + let mut d = d.clone(); + if let Some(k) = kept.get(&d.id) { + if k.at > 0 { + d.levels_at = Some(k.at); + } + if d.case.is_some() && k.case_at > 0 { + d.case_at = Some(k.case_at); + } + } + d + }) + .collect() +} + +/// A read with everything the reader thread adds: the helper's and Sony's levels, the last +/// levels of devices that went quiet, and the unpaired devices heard nearby (listed last). +fn finish(mut list: Vec, readings: &[super::btmod::Reading], sony: &HashMap, kept: &mut HashMap) -> Vec { + // Sony first: Fast Pair readings are matched against the levels it put on. + apply_sony(&mut list, sony); + let used = super::btmod::apply(&mut list, readings); + let near = super::btmod::nearby(&list, readings, &used); + remember(&mut list, kept, unix_now()); + list.extend(near); + sort(&mut list); + list +} + /// The helper module stops when no read was asked for this long. const IDLE_STOP: std::time::Duration = std::time::Duration::from_secs(120); /// While the helper runs, its new levels are published this often between reads. const HELPER_POLL: std::time::Duration = std::time::Duration::from_secs(2); -/// A Bluetooth read slower than this is logged to diagnostics.log. -const SLOW_READ_MS: f32 = 500.0; +/// A Bluetooth read slower than this is logged to diagnostics.log (a sleeping Logitech +/// mouse alone takes 0.5-2 s to not answer; that is normal and off the sensor thread). +const SLOW_READ_MS: f32 = 3000.0; #[cfg(test)] mod tests { @@ -1874,6 +2011,38 @@ mod tests { } /// The cache brings back every field the page and the fix button use. + /// A case level read once stays, with its time, while the buds are out of the case; a + /// device that went quiet keeps its last per-bud levels with their time. + #[test] + fn levels_are_kept_with_their_time() { + let mut kept = HashMap::new(); + let buds = |l: Option, c: Option| BtDevice { id: "{buds}".into(), name: "WF-C710N".into(), kind: Kind::Earbuds, connected: true, left: l, right: l, case: c, ..Default::default() }; + let mut list = vec![buds(Some(80), Some(60))]; + remember(&mut list, &mut kept, 1000); + assert_eq!((list[0].case, list[0].case_at, list[0].levels_at), (Some(60), None, None)); + // Both buds out: the case answers nothing. + let mut list = vec![buds(Some(78), None)]; + remember(&mut list, &mut kept, 1300); + assert_eq!((list[0].left, list[0].case, list[0].case_at, list[0].levels_at), (Some(78), Some(60), Some(1000), None)); + // Back in the closed case: disconnected, nothing live. + let mut gone = buds(None, None); + gone.connected = false; + let mut list = vec![gone.clone()]; + remember(&mut list, &mut kept, 5000); + assert_eq!((list[0].left, list[0].right, list[0].levels_at, list[0].case), (Some(78), Some(78), Some(1300), Some(60))); + // Saved and read back on the next start: same levels, same times. + let saved = stamped(&list, &kept); + let back = parse_cache(&cache_text(&saved)); + let mut kept2 = seed_kept(&back, 9000); + let mut list = vec![gone]; + remember(&mut list, &mut kept2, 9500); + assert_eq!((list[0].left, list[0].levels_at, list[0].case, list[0].case_at), (Some(78), Some(1300), Some(60), Some(1000))); + // A disconnected device with only Windows' stale level is left alone. + let mut m = vec![BtDevice { id: "{m}".into(), battery: Some(40), ..Default::default() }]; + remember(&mut m, &mut kept, 9500); + assert_eq!((m[0].battery, m[0].levels_at), (Some(40), None)); + } + #[test] fn cache_round_trip() { let a = BtDevice { diff --git a/src/sensors/deep/btmod.rs b/src/sensors/deep/btmod.rs index 55dc1d5..087971e 100644 --- a/src/sensors/deep/btmod.rs +++ b/src/sensors/deep/btmod.rs @@ -27,14 +27,31 @@ const FRESH: Duration = Duration::from_secs(90); /// Wait between restarts of a helper that quit. const RESTART: Duration = Duration::from_secs(60); +/// Where a reading came from. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Src { + /// Apple's proximity pairing advertisement (10 % steps). + Apple, + /// Google Fast Pair's battery field (1 % steps). + FastPair, +} + /// One device's levels from the helper. #[derive(Clone, Debug, PartialEq)] pub struct Reading { + pub src: Src, + /// Apple: the model name; Fast Pair: the (rotating) address. + pub key: String, + /// Apple: the model ("AirPods Pro"); Fast Pair: the advertised name, often empty. pub model: String, pub left: Option, pub right: Option, pub case: Option, + /// One battery (Fast Pair headphones). + pub single: Option, + /// A bud (or the one battery) is charging. pub charging: bool, + pub rssi: i16, pub at: Instant, } @@ -297,6 +314,22 @@ pub fn download_async(st: &GetState) { }); } +/// Runs the helper's `--scan` for the debug report: every advertisement heard in `secs`. +pub fn scan_report(secs: u64) -> String { + let Some(path) = find() else { + return format!("No trusted {EXE} found (looked in {:?}).\n", installed_paths()); + }; + use std::os::windows::process::CommandExt; + const CREATE_NO_WINDOW: u32 = 0x0800_0000; + match Command::new(&path).arg("--scan").arg(secs.to_string()).stdin(Stdio::null()).stderr(Stdio::null()).creation_flags(CREATE_NO_WINDOW).output() { + Ok(out) => { + let t = String::from_utf8_lossy(&out.stdout); + format!("{} ({} lines)\n{t}", path.display(), t.lines().count()) + } + Err(e) => format!("{}: {e}\n", path.display()), + } +} + /// An Apple / Beats device (what the helper reads). pub fn is_apple(d: &BtDevice) -> bool { let n = d.name.to_lowercase(); @@ -326,7 +359,7 @@ pub struct Helper { } impl Helper { - /// Runs the helper while `wanted` (an Apple device is paired) and allowed (switched + /// Runs the helper while `wanted` (the Bluetooth reader is active) and allowed (switched /// on in Settings > Modules, not just removed), stops it otherwise. pub fn tick(&mut self, wanted: bool) { if !wanted || !allowed() { @@ -396,7 +429,7 @@ impl Helper { let Ok(line) = line else { break }; if let Some(r) = parse_line(&line) { if let Ok(mut m) = readings.lock() { - m.insert(r.model.clone(), r); + m.insert(format!("{:?}:{}", r.src, r.key), r); } } } @@ -436,16 +469,22 @@ impl Drop for Helper { /// Puts per-bud levels on the paired Apple devices: by model family in the name /// ("AirPods Pro", "AirPods Max", "Beats Fit Pro", ...), or the only reading to the only device. -pub fn apply(list: &mut [BtDevice], readings: &[Reading]) { +/// Returns which readings went onto a paired device (by index). +pub fn apply(list: &mut [BtDevice], readings: &[Reading]) -> Vec { + let mut used = vec![false; readings.len()]; let apples: Vec = (0..list.len()).filter(|&i| is_apple(&list[i])).collect(); + let apple_reads: Vec = (0..readings.len()).filter(|&k| readings[k].src == Src::Apple).collect(); for i in &apples { let name = list[*i].name.to_lowercase(); - let hit = readings + let hit = apple_reads .iter() - .filter(|r| family_match(&name, &r.model.to_lowercase())) - .max_by_key(|r| r.at) - .or_else(|| (apples.len() == 1 && readings.len() == 1).then(|| &readings[0])); - if let Some(r) = hit { + .copied() + .filter(|&k| family_match(&name, &readings[k].model.to_lowercase())) + .max_by_key(|&k| readings[k].at) + .or_else(|| (apples.len() == 1 && apple_reads.len() == 1).then(|| apple_reads[0])); + if let Some(k) = hit { + used[k] = true; + let r = &readings[k]; let d = &mut list[*i]; d.left = r.left; d.right = r.right; @@ -459,6 +498,63 @@ pub fn apply(list: &mut [BtDevice], readings: &[Reading]) { } } } + // Fast Pair: the address rotates and the advertisement names no paired device, so a + // reading goes onto a paired device only when it is the same buds: a connected device + // whose own channel reports the same left and right (within 2 %). It then adds the case. + for (k, r) in readings.iter().enumerate().filter(|(_, r)| r.src == Src::FastPair) { + let close = |a: Option, b: Option| matches!((a, b), (Some(a), Some(b)) if a.abs_diff(b) <= 2); + let same = list.iter_mut().find(|d| d.connected && close(d.left, r.left) && close(d.right, r.right)); + if let Some(d) = same { + used[k] = true; + if d.case.is_none() { + d.case = r.case; + } + } + } + used +} + +/// Devices heard nearby that are not on the paired list (readings `apply` did not use). +pub fn nearby(list: &[BtDevice], readings: &[Reading], used: &[bool]) -> Vec { + let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_secs()); + let mut out: Vec = Vec::new(); + for (k, r) in readings.iter().enumerate() { + if used.get(k).copied().unwrap_or(false) { + continue; + } + let one = r.left.is_none() && r.right.is_none(); + let name = match r.src { + Src::Apple => r.model.clone(), + Src::FastPair if !r.model.trim().is_empty() => r.model.trim().to_string(), + Src::FastPair if one => "Headphones (Fast Pair)".into(), + Src::FastPair => "Earbuds (Fast Pair)".into(), + }; + // A paired device of the same name is that device (its name came in the advertisement). + if list.iter().any(|d| !d.nearby && d.name.eq_ignore_ascii_case(&name)) && r.src == Src::FastPair { + continue; + } + let kind = if one || name.to_lowercase().contains("max") { Kind::Headphones } else { Kind::Earbuds }; + let battery = match (r.left, r.right) { + (Some(l), Some(rr)) => Some(l.min(rr)), + (l, rr) => l.or(rr).or(r.single), + }; + out.push(BtDevice { + id: format!("{{near-{:?}-{}}}", r.src, r.key).to_lowercase(), + name, + kind, + nearby: true, + battery, + left: r.left, + right: r.right, + case: r.case, + charging: Some(r.charging), + le: true, + last_seen: Some(now), + ..Default::default() + }); + } + out.sort_by(|a, b| a.name.cmp(&b.name).then_with(|| a.id.cmp(&b.id))); + out } /// The paired name belongs to the advertised model family. @@ -477,19 +573,31 @@ fn family_match(name: &str, model: &str) -> bool { } } -/// One helper line: `{"kind":"apple","model":"AirPods Pro","left":95,...}`. +/// One helper line: `{"kind":"apple","model":"AirPods Pro","left":95,...}` or +/// `{"kind":"fastpair","key":"a1b2c3d4e5f6","model":"","left":72,...}`. fn parse_line(line: &str) -> Option { - if json_str(line, "kind")? != "apple" { - return None; - } + let src = match json_str(line, "kind")?.as_str() { + "apple" => Src::Apple, + "fastpair" => Src::FastPair, + _ => return None, + }; let num = |k: &str| json_raw(line, k).and_then(|v| v.parse::().ok()).filter(|&v| v <= 100); let yes = |k: &str| json_raw(line, k) == Some("true"); + let model = json_str(line, "model")?; + let key = match src { + Src::Apple => model.clone(), + Src::FastPair => json_str(line, "key")?, + }; Some(Reading { - model: json_str(line, "model")?, + src, + key, + model, left: num("left"), right: num("right"), case: num("case"), + single: num("single"), charging: yes("charging_left") || yes("charging_right"), + rssi: json_raw(line, "rssi").and_then(|v| v.parse().ok()).unwrap_or(0), at: Instant::now(), }) } @@ -572,8 +680,32 @@ mod tests { #[test] fn applies() { let mut list = vec![BtDevice { name: "AirPods Pro #2".into(), kind: Kind::Earbuds, ..Default::default() }]; - let r = Reading { model: "AirPods Pro".into(), left: Some(95), right: Some(75), case: Some(55), charging: false, at: Instant::now() }; - apply(&mut list, &[r]); + let r = Reading { src: Src::Apple, key: "AirPods Pro".into(), model: "AirPods Pro".into(), left: Some(95), right: Some(75), case: Some(55), single: None, charging: false, rssi: -50, at: Instant::now() }; + let used = apply(&mut list, &[r]); assert_eq!((list[0].left, list[0].right, list[0].case, list[0].battery), (Some(95), Some(75), Some(55), Some(75))); + assert_eq!(used, vec![true]); + } + + fn fp(key: &str, l: Option, r: Option, c: Option) -> Reading { + Reading { src: Src::FastPair, key: key.into(), model: String::new(), left: l, right: r, case: c, single: None, charging: false, rssi: -60, at: Instant::now() } + } + + /// Fast Pair buds that are the connected Sony buds add their case; others show nearby. + #[test] + fn fast_pair_nearby() { + let mut list = vec![BtDevice { id: "{sony}".into(), name: "WF-C710N".into(), kind: Kind::Earbuds, connected: true, left: Some(70), right: Some(64), ..Default::default() }]; + let reads = [fp("aa", Some(71), Some(64), Some(45)), fp("bb", Some(30), Some(35), None)]; + let used = apply(&mut list, &reads); + assert_eq!(used, vec![true, false]); + assert_eq!(list[0].case, Some(45)); + let near = nearby(&list, &reads, &used); + assert_eq!(near.len(), 1); + assert!(near[0].nearby && near[0].name == "Earbuds (Fast Pair)" && near[0].battery == Some(30)); + // Someone's AirPods with no paired Apple device: nearby too. + let a = Reading { src: Src::Apple, key: "AirPods Pro".into(), model: "AirPods Pro".into(), left: Some(85), right: Some(85), case: None, single: None, charging: false, rssi: -55, at: Instant::now() }; + let used = apply(&mut list, std::slice::from_ref(&a)); + assert_eq!(nearby(&list, std::slice::from_ref(&a), &used)[0].name, "AirPods Pro"); + let p = parse_line(r#"{"v":1,"kind":"fastpair","key":"0a1b2c3d4e5f","model":"","left":72,"right":68,"case":null,"single":null,"charging_left":false,"charging_right":true,"charging_case":false,"rssi":-61}"#).unwrap(); + assert_eq!((p.src, p.key.as_str(), p.left, p.right, p.case, p.charging, p.rssi), (Src::FastPair, "0a1b2c3d4e5f", Some(72), Some(68), None, true, -61)); } } diff --git a/src/sensors/deep/live.rs b/src/sensors/deep/live.rs index 3a1616c..e422dd0 100644 --- a/src/sensors/deep/live.rs +++ b/src/sensors/deep/live.rs @@ -14,11 +14,11 @@ use crate::sensors::pdh::{Counter, Query}; const STATIC_SECS: f64 = 60.0; /// Connections and Wi-Fi are re-read this often. const NET_SECS: f64 = 2.0; -/// Paired Bluetooth devices are re-read this often on the overview (battery levels move -/// in 10% steps; Windows itself refreshes them rarely)... -const BT_SECS: f64 = 30.0; -/// ...and this often while the Bluetooth page is open. -const BT_PAGE_SECS: f64 = 10.0; +/// Paired Bluetooth devices are re-read this often on the overview... +const BT_SECS: f64 = 15.0; +/// ...and this often while the Bluetooth page is open. Sony's and the helper's levels land +/// within 2 s of arriving in between (the reader thread publishes them on their own). +const BT_PAGE_SECS: f64 = 5.0; /// Add-ons are re-read this often on the overview (the tab's warning dot)... const ADDON_SECS: f64 = 20.0; /// ...and this often while the Add-ons page is open (mic in use, zone temperatures). diff --git a/src/sensors/deep/sony.rs b/src/sensors/deep/sony.rs index 81e2fca..bf0a829 100644 --- a/src/sensors/deep/sony.rs +++ b/src/sensors/deep/sony.rs @@ -11,10 +11,16 @@ //! byte & !0x10. Type 0C = command, 01 = acknowledgement. Every command is acknowledged; the //! acknowledgement's sequence number is the next one to send. Battery: set 1 asks `10 t`, //! answers `11` / notifies `13`; set 2 asks `22 t`, answers `23` / notifies `25`. Type 0 one -//! battery, 1 left + right, 2 case; each level is 0..=100 then a charging byte. +//! battery, 1 left + right, 2 case; set 2 also has 8 / 9 / 10, the same three "with +//! thresholds", and newer earbuds (WF-C710N, WF-1000XM5) answer only those. Each level is +//! 0..=100 then a charging byte. The support list (`06 00`, answer `07 00 n functions`) says +//! which types a model has (functions 20 / 21 / 22 / 28 / 29 / 2A in set 2, 11 / 15 / 18 in +//! set 1); when it says nothing, every type is asked. //! -//! One worker thread per connected Sony device holds the channel open, asks every 30 s and -//! takes the notifications in between. The Bluetooth reader only reads its results. +//! One worker thread per connected Sony device holds the channel open, asks every 20 s and +//! takes the notifications (each change, at once) in between. The Bluetooth reader only reads +//! its results. The case answers 0 while both buds are out of it: that is "unknown", and the +//! reader keeps the last real case level with its time. use std::collections::HashMap; use std::sync::atomic::{AtomicBool, Ordering}; @@ -32,8 +38,8 @@ const T_ACK: u8 = 0x01; const T_CMD: u8 = 0x0C; const T_CMD2: u8 = 0x0E; -/// Battery asked this often (Sony's app: 30 s). -const ASK_EVERY: Duration = Duration::from_secs(30); +/// Battery asked this often (Sony's app: 30 s); every change also arrives as a notification. +const ASK_EVERY: Duration = Duration::from_secs(20); /// Wait for an acknowledgement, and resends (Sony's app: 750 ms, 10 times). const ACK_WAIT: Duration = Duration::from_millis(750); const RESENDS: u32 = 3; @@ -136,11 +142,39 @@ fn check(b: &[u8]) -> Option { (sum == b[6 + n]).then(|| Frame { kind: b[0], seq: b[1], payload: b[6..6 + n].to_vec() }) } -/// The battery question for set 1 or 2 and a battery type (0 one, 1 left + right, 2 case). +/// The battery question for set 1 or 2 and a battery type (0 one, 1 left + right, 2 case; +/// set 2 also 8 / 9 / 10 with thresholds). fn ask(v2: bool, t: u8) -> [u8; 2] { [if v2 { 0x22 } else { 0x10 }, t] } +/// The support functions question (`06 00`). +const SUPPORT: [u8; 2] = [0x06, 0x00]; + +/// Every battery type of a set, left + right and case first, for a model whose support +/// list was not read. +fn all_types(v2: bool) -> Vec { + if v2 { + vec![1, 9, 2, 10, 0, 8] + } else { + vec![1, 2, 0] + } +} + +/// The battery types a support list (`07 00 n f..`) names, left + right and case first. +/// None when the payload is not a support list or names no battery. +pub fn battery_types(v2: bool, p: &[u8]) -> Option> { + if p.len() < 3 || p[0] != 0x07 || p[1] != 0x00 { + return None; + } + let n = usize::from(p[2]); + // Set 2 lists (function, version) pairs, set 1 one byte per function. + let funcs: Vec = if v2 { p[3..].chunks(2).take(n).map(|c| c[0]).collect() } else { p[3..].iter().take(n).copied().collect() }; + let map: &[(u8, u8)] = if v2 { &[(0x21, 1), (0x29, 9), (0x22, 2), (0x2A, 10), (0x20, 0), (0x28, 8)] } else { &[(0x15, 1), (0x18, 2), (0x11, 0)] }; + let types: Vec = map.iter().filter(|(f, _)| funcs.contains(f)).map(|x| x.1).collect(); + (!types.is_empty()).then_some(types) +} + /// Folds a battery answer or notification into `lv`; false when the payload is none. pub fn take_battery(p: &[u8], lv: &mut Level) -> bool { let (Some(&cmd), Some(&t)) = (p.first(), p.get(1)) else { return false }; @@ -242,14 +276,13 @@ fn session(addr: u64, svc: u128, stop: &AtomicBool, level: &Mutex= next { next = Instant::now() + ASK_EVERY; - // Earbuds answer left + right and the case; headphones one battery. - let types: &[u8] = if lv.left.is_some() || lv.right.is_some() { &[1, 2] } else { &[1, 2, 0] }; - for &t in types { + for &t in &types { // A model without that battery may not answer; the rest still count. let _ = ch.command(&ask(v2, t)); } @@ -287,13 +320,15 @@ pub fn probe(addr: u64, svc: u128) -> String { let v2 = svc == SVC_V2; let mut ch = Chan { s, dec: Decoder::default(), seq: 0, frames: Vec::new() }; let mut lv = Level::default(); - let mut steps: Vec<(&str, Vec)> = vec![("init", vec![0x00, 0x00])]; - for t in [1u8, 2, 0] { - steps.push(("battery", ask(v2, t).to_vec())); - } - for (what, p) in steps { + let r = ch.command(&[0x00, 0x00]); + let _ = writeln!(o, " init 00 00: {}", r.err().unwrap_or_else(|| "acknowledged".into())); + let listed = ch.support(v2); + let _ = writeln!(o, " support 06 00: battery types {listed:?}"); + // Every type, so the report shows which ones this model answers. + for t in all_types(v2) { + let p = ask(v2, t); let r = ch.command(&p); - let _ = writeln!(o, " {what} {}: {}", hex(&p), r.err().unwrap_or_else(|| "acknowledged".into())); + let _ = writeln!(o, " battery {}: {}", hex(&p), r.err().unwrap_or_else(|| "acknowledged".into())); } let until = Instant::now() + Duration::from_secs(4); while Instant::now() < until { @@ -332,6 +367,23 @@ struct Chan { #[cfg(windows)] impl Chan { + /// Ask the support list and wait up to 1.5 s for it: the battery types this model has. + /// The frames that came meanwhile stay for the caller. + fn support(&mut self, v2: bool) -> Option> { + self.command(&SUPPORT).ok()?; + let until = Instant::now() + Duration::from_millis(1500); + loop { + if let Some(t) = self.frames.iter().find_map(|f| battery_types(v2, &f.payload)) { + return Some(t); + } + let left = until.saturating_duration_since(Instant::now()); + if left.is_zero() { + return None; + } + self.pump(left.min(Duration::from_millis(300))).ok()?; + } + } + /// Send one command and wait for its acknowledgement. fn command(&mut self, payload: &[u8]) -> Result<(), String> { let f = encode(T_CMD, self.seq, payload); @@ -498,6 +550,24 @@ mod tests { assert!(!take_battery(&[0x01, 0x00, 0x40, 0x10], &mut lv)); } + #[test] + fn support_lists() { + // Set 2: (function, version) pairs; 29 and 2A = left + right and case with thresholds. + assert_eq!(battery_types(true, &[0x07, 0x00, 4, 0x29, 0x01, 0x2A, 0x01, 0x61, 0x01, 0x58, 0x01]), Some(vec![9, 10])); + assert_eq!(battery_types(true, &[0x07, 0x00, 2, 0x21, 0x00, 0x22, 0x00]), Some(vec![1, 2])); + // Set 1: one byte per function. + assert_eq!(battery_types(false, &[0x07, 0x00, 3, 0x11, 0x62, 0x15]), Some(vec![1, 0])); + // No battery listed, or not a support list. + assert_eq!(battery_types(true, &[0x07, 0x00, 1, 0x61, 0x01]), None); + assert_eq!(battery_types(true, &[0x01, 0x00, 0x03, 0x00]), None); + // Threshold answers carry the same levels first. + let mut lv = Level::default(); + assert!(take_battery(&[0x23, 0x09, 72, 0, 68, 0, 30, 30], &mut lv)); + assert_eq!((lv.left, lv.right), (Some(72), Some(68))); + assert!(take_battery(&[0x25, 0x0A, 55, 1, 30], &mut lv)); + assert_eq!(lv.case, Some(55)); + } + #[test] fn questions() { assert_eq!(ask(true, 1), [0x22, 0x01]); From 54d4bc8ecf53654780ef4fb0b7a22719e0ad728a Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 18:07:56 +0000 Subject: [PATCH 2/2] Unknown Apple model goes onto the paired AirPods only when right next to the PC --- src/sensors/deep/btmod.rs | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/src/sensors/deep/btmod.rs b/src/sensors/deep/btmod.rs index 087971e..a34c1a5 100644 --- a/src/sensors/deep/btmod.rs +++ b/src/sensors/deep/btmod.rs @@ -27,6 +27,9 @@ const FRESH: Duration = Duration::from_secs(90); /// Wait between restarts of a helper that quit. const RESTART: Duration = Duration::from_secs(60); +/// A lone Apple reading of an unknown model counts as the paired device only this close. +const LONE_RSSI: i16 = -60; + /// Where a reading came from. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Src { @@ -481,7 +484,9 @@ pub fn apply(list: &mut [BtDevice], readings: &[Reading]) -> Vec { .copied() .filter(|&k| family_match(&name, &readings[k].model.to_lowercase())) .max_by_key(|&k| readings[k].at) - .or_else(|| (apples.len() == 1 && apple_reads.len() == 1).then(|| apple_reads[0])); + // An unknown model goes onto the only paired Apple device only when it is the only + // one heard and right next to this PC (someone else's buds are farther away). + .or_else(|| (apples.len() == 1 && apple_reads.len() == 1 && readings[apple_reads[0]].rssi >= LONE_RSSI).then(|| apple_reads[0])); if let Some(k) = hit { used[k] = true; let r = &readings[k]; @@ -705,6 +710,12 @@ mod tests { let a = Reading { src: Src::Apple, key: "AirPods Pro".into(), model: "AirPods Pro".into(), left: Some(85), right: Some(85), case: None, single: None, charging: false, rssi: -55, at: Instant::now() }; let used = apply(&mut list, std::slice::from_ref(&a)); assert_eq!(nearby(&list, std::slice::from_ref(&a), &used)[0].name, "AirPods Pro"); + // A paired AirPods and an unknown Apple model: theirs only when right next to the PC. + let mut mine = vec![BtDevice { name: "Rajhans's AirPods Pro #2".into(), kind: Kind::Earbuds, ..Default::default() }]; + let far = Reading { model: "Apple headphones".into(), key: "Apple headphones".into(), rssi: -70, ..a.clone() }; + assert_eq!(apply(&mut mine, std::slice::from_ref(&far)), vec![false]); + let near = Reading { rssi: -48, ..far }; + assert_eq!(apply(&mut mine, std::slice::from_ref(&near)), vec![true]); let p = parse_line(r#"{"v":1,"kind":"fastpair","key":"0a1b2c3d4e5f","model":"","left":72,"right":68,"case":null,"single":null,"charging_left":false,"charging_right":true,"charging_case":false,"rssi":-61}"#).unwrap(); assert_eq!((p.src, p.key.as_str(), p.left, p.right, p.case, p.charging, p.rssi), (Src::FastPair, "0a1b2c3d4e5f", Some(72), Some(68), None, true, -61)); }