From 28b101df3ad1a8b30135918b45f780f856d6f545 Mon Sep 17 00:00:00 2001 From: rajhansgithub Date: Thu, 3 Dec 2026 02:42:48 +0530 Subject: [PATCH] 2.36.0: charging shown for each part of earbuds, with its age when they go silent --- Cargo.lock | 2 +- Cargo.toml | 2 +- res/resmon.manifest | 2 +- setup.iss | 2 +- src/liquid.rs | 64 ++++++++- src/modbt/main.rs | 7 +- src/monitor/btpage.rs | 249 +++++++++++++++++++++++++++++----- src/monitor/hover.rs | 16 ++- src/sensors/deep/bluetooth.rs | 85 ++++++++++-- src/sensors/deep/btmod.rs | 15 +- src/sensors/deep/sony.rs | 24 +++- 11 files changed, 407 insertions(+), 61 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 74bcc7e..4eba4aa 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -92,7 +92,7 @@ dependencies = [ [[package]] name = "resmon" -version = "2.35.2" +version = "2.36.0" dependencies = [ "embed-resource", "windows", diff --git a/Cargo.toml b/Cargo.toml index 362fe31..aefbc51 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "resmon" -version = "2.35.2" +version = "2.36.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 1392a5b..8a9a357 100644 --- a/res/resmon.manifest +++ b/res/resmon.manifest @@ -1,6 +1,6 @@ - + diff --git a/setup.iss b/setup.iss index 13680c5..c2573fb 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.35.2" +#define MyAppVersion "2.36.0" #define MyAppPublisher "Emulsion Labs" #define MyAppURL "https://github.com/rajhansgithub/Windows_Resource_Monitoring_Tool" #define MyAppExeName "ResourceMonitor.exe" diff --git a/src/liquid.rs b/src/liquid.rs index e242212..995f879 100644 --- a/src/liquid.rs +++ b/src/liquid.rs @@ -819,6 +819,12 @@ impl Pen<'_> { } } + /// A charging bolt in a box 12 x 20 units at (0, 0). + fn bolt(&mut self, c: Rgba) { + let p: Vec

= [(7.0, 0.0), (0.0, 12.0), (5.5, 12.0), (4.0, 20.0), (12.0, 8.0), (6.5, 8.0)].to_vec(); + self.fill(&[p], false, c); + } + /// Dots carried along a curve (case into the buds). fn flow(&mut self, p: [f32; 8]) { for i in 0..3 { @@ -837,8 +843,11 @@ impl Pen<'_> { } /// The parts that are not fills: outlines, seams, ports, lights, charge. - fn deco(&mut self, d: Dev, st: St, vals: [f32; 3]) { + fn deco(&mut self, d: Dev, sts: [St; 3]) { + // Earbuds: what is not a fill (the case's light, the cable) belongs to the case. + let st = if d.three() { sts[1] } else { sts[0] }; let chg = st == St::Charging; + let fed = [sts[0] == St::Charging, sts[2] == St::Charging]; match d { Dev::Battery => { self.outline(&rr(7.0, 29.0, 80.0, 42.0, 7.0), 1.0); @@ -890,7 +899,12 @@ impl Pen<'_> { self.line(&[(29.0, 53.0), (71.0, 53.0)], 0.5); if chg { self.cable(50.0, 74.0, 0.0, 1.0, 6.0); + } + // The case charges the bud that says so. + if fed[0] { self.flow([29.0, 61.0, 27.0, 61.5, 25.5, 62.0, 23.5, 62.5]); + } + if fed[1] { self.flow([71.0, 61.0, 73.0, 61.5, 74.5, 62.0, 76.5, 62.5]); } } @@ -912,7 +926,11 @@ impl Pen<'_> { self.disc(50.0, 62.0, 1.5, alpha(led, a)); if chg { self.cable(50.0, 75.0, 0.0, 1.0, 3.0); + } + if fed[0] { self.flow([32.0, 60.0, 30.0, 60.0, 29.0, 62.0, 27.0, 64.0]); + } + if fed[1] { self.flow([68.0, 60.0, 70.0, 60.0, 71.0, 62.0, 73.0, 64.0]); } } @@ -992,10 +1010,15 @@ impl Pen<'_> { } } } - let _ = vals; } } +/// A charging bolt `h` px tall with its top left at (x, y). +pub fn bolt(cv: &mut Canvas, x: f32, y: f32, h: f32, c: Rgba, tk: &Tokens) { + let ink = Ink { fg: tk.fg, panel: tk.panel, track: tk.track, fill: tk.accent_fill, warn: tk.warn, crit: tk.crit, on: tk.on_accent, dots: false }; + Pen { cv, ox: x.round() as i32, oy: y.round() as i32, k: h / 20.0, t: 0.0, th: 1.0, ink }.bolt(c); +} + /// The state one part of `d` is drawn in at level `v` (0..100). A low device's parts go by their /// own level: a full case is not red because the buds are low. pub fn part_state(d: Dev, st: St, v: f32) -> St { @@ -1016,6 +1039,13 @@ fn mask_k(k: f32) -> f32 { /// width in pixels. #[allow(clippy::too_many_arguments)] pub fn draw(cv: &mut Canvas, d: Dev, x: f32, y: f32, k: f32, vals: [f32; 3], st: St, t: f32, tk: &Tokens, th: f32) { + let sts = if d.three() { vals.map(|v| part_state(d, st, v)) } else { [st; 3] }; + draw_parts(cv, d, x, y, k, vals, sts, t, tk, th); +} + +/// `draw` with a state for each part (left, case, right). +#[allow(clippy::too_many_arguments)] +pub fn draw_parts(cv: &mut Canvas, d: Dev, x: f32, y: f32, k: f32, vals: [f32; 3], sts: [St; 3], t: f32, tk: &Tokens, th: f32) { if k <= 0.05 { return; } @@ -1025,10 +1055,10 @@ pub fn draw(cv: &mut Canvas, d: Dev, x: f32, y: f32, k: f32, vals: [f32; 3], st: let regs = regions_of(d); for (i, r) in regs.iter().enumerate() { let v = if d.three() { vals[r.vi] } else { vals[0] }; - p.region(d, i, r, (v / 100.0).clamp(0.0, 1.0), part_state(d, st, v)); + let st = if d.three() { sts[r.vi] } else { sts[0] }; + p.region(d, i, r, (v / 100.0).clamp(0.0, 1.0), st); } - // Earbuds: the parts that are not fills (the case's light) belong to the case. - p.deco(d, if d.three() { part_state(d, st, vals[1]) } else { st }, vals); + p.deco(d, sts); } #[cfg(test)] @@ -1124,6 +1154,30 @@ mod tests { assert_eq!(part_state(Dev::Mouse, St::Low, 90.0), St::Low, "a device with one level is as it was"); } + /// Only the part that charges changes: left bud charging leaves the right bud and the case alone. + #[test] + fn each_part_charges_by_itself() { + let tk = crate::look::tokens_for(crate::look::Look::Lime, true); + for d in [Dev::Earbuds, Dev::Pods] { + let shot = |sts: [St; 3]| { + let mut cv = Canvas::new(); + cv.resize(400, 400); + cv.clear(tk.panel); + draw_parts(&mut cv, d, 0.0, 0.0, 4.0, [50.0, 60.0, 50.0], sts, 0.4, &tk, 1.7); + cv.pixels().to_vec() + }; + let (n, c) = (St::Normal, St::Charging); + let calm = shot([n, n, n]); + let diff = |v: &[u32], x0: usize, x1: usize| (0..400).flat_map(|y| (x0..x1).map(move |x| y * 400 + x)).filter(|&i| v[i] != calm[i]).count(); + let left = shot([c, n, n]); + assert!(diff(&left, 0, 33 * 4) > 0 && diff(&left, 50 * 4, 400) == 0, "{d:?}: left bud"); + let right = shot([n, n, c]); + assert!(diff(&right, 67 * 4, 400) > 0 && diff(&right, 0, 50 * 4) == 0, "{d:?}: right bud"); + let case = shot([n, c, n]); + assert!(diff(&case, 33 * 4, 67 * 4) > 0 && diff(&case, 0, 22 * 4) == 0 && diff(&case, 78 * 4, 400) == 0, "{d:?}: case"); + } + } + #[test] fn only_activity_moves() { assert!(!St::Normal.moves()); diff --git a/src/modbt/main.rs b/src/modbt/main.rs index 819abe5..0f177ce 100644 --- a/src/modbt/main.rs +++ b/src/modbt/main.rs @@ -51,7 +51,9 @@ struct Pods { /// Decodes Apple manufacturer data (company id already stripped): /// `[0x07, len, 0x01, model hi, model lo, status, pods, flags|case, lid, ...]`. fn decode(b: &[u8]) -> Option { - if b.len() < 9 || b[0] != 0x07 { + // `01` = the message with model and levels. Other forms (`07 11 06 ..`, sent by buds away from + // their phone) hold scrambled bytes: read as levels they give random numbers. + if b.len() < 9 || b[0] != 0x07 || b[2] != 0x01 { return None; } let model_id = u16::from_be_bytes([b[3], b[4]]); @@ -433,6 +435,9 @@ mod tests { fn rejects_other_types() { assert!(decode(&[0x10, 0x05, 0x01]).is_none()); assert!(decode(&[0x07, 0x19]).is_none()); + // Heard on a real PC: scrambled, not left 55 % charging, right 85 %, case 100 %. + assert!(decode(&[0x07, 0x11, 0x06, 0x5F, 0x81, 0x5D, 0x58, 0xAA, 0xF8, 0xEE, 0x34]).is_none()); + assert!(decode(&[0x07, 0x11, 0x06, 0x50, 0x50, 0x50, 0x74, 0xAC, 0x2C, 0x39, 0x92]).is_none()); } #[test] diff --git a/src/monitor/btpage.rs b/src/monitor/btpage.rs index 908e886..6fdfafd 100644 --- a/src/monitor/btpage.rs +++ b/src/monitor/btpage.rs @@ -63,6 +63,75 @@ fn is_low(d: &BtDevice) -> bool { fresh(d) && level(d).is_some_and(|l| l <= LOW_PCT) } +/// Charging flags older than this say nothing about now: the buds are full by then. +const CHARGE_KEEP: u64 = 3 * 3600; + +fn now_unix() -> u64 { + std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_secs()) +} + +/// What is known about one part's charging (0 left, 1 case, 2 right). +#[derive(Clone, Copy, Debug, PartialEq)] +enum Chg { + No, + /// It says so now. + Live, + /// It said so in its last message, then went quiet (buds in the closed case). + Was, +} + +fn chg(d: &BtDevice, part: usize) -> Chg { + match (d.parts[part], d.levels_at) { + (Some(true), None) if fresh(d) => Chg::Live, + (Some(true), Some(t)) if now_unix().saturating_sub(t) < CHARGE_KEEP => Chg::Was, + _ => Chg::No, + } +} + +/// A single battery charging now (mouse, keyboard, headphones). +fn chg_one(d: &BtDevice) -> bool { + fresh(d) && d.charging == Some(true) +} + +/// A bud charged in its last message: buds charge only in their case. +fn in_case(d: &BtDevice) -> bool { + !d.connected && d.levels_at.is_some() && (d.parts[0] == Some(true) || d.parts[2] == Some(true)) +} + +/// What charges now, in words ("Buds and case charging"); None = nothing says so. +fn chg_words(d: &BtDevice) -> Option { + let on = |p: usize| chg(d, p) == Chg::Live; + let buds = match (on(0), on(2)) { + (true, true) => "Buds", + (true, false) => "Left bud", + (false, true) => "Right bud", + _ => "", + }; + match (buds, on(1)) { + ("", true) => Some("Case charging".into()), + ("", false) => chg_one(d).then(|| "Charging".into()), + (b, true) => Some(format!("{b} and case charging")), + (b, false) => Some(format!("{b} charging")), + } +} + +/// "20 min ago" -> "20m", "3 h ago" -> "3h": for a narrow cell. +fn ago_short(unix: u64) -> String { + let t = ago(unix); + let t = t.strip_suffix(" ago").unwrap_or("now"); + t.replace(" min", "m").replace(" h", "h").replace(" d", "d") +} + +/// How old the levels on an earbud card are, longest wording first (empty = live). +fn age_words(d: &BtDevice) -> Vec { + let Some(t) = d.levels_at else { return Vec::new() }; + if in_case(d) { + vec![format!("In case \u{00B7} {}", ago(t)), format!("In case {}", ago_short(t)), ago_short(t)] + } else { + vec![format!("Last read {}", ago(t)), ago(t), ago_short(t)] + } +} + /// A part with charge of its own on a device that is low. fn part_calm(d: &BtDevice, v: Option) -> bool { is_low(d) && v.is_some_and(|v| v > LOW_PCT) @@ -112,14 +181,25 @@ fn state(d: &BtDevice) -> String { 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() }; + return match chg_words(d) { + Some(w) => format!("Nearby \u{00B7} {}", w.to_lowercase()), + None => "Nearby \u{00B7} not paired".into(), + }; } if let (Some(t), false) = (d.levels_at, d.connected) { - return format!("Last read {}", ago(t)); + return if in_case(d) { + if chg(d, 0) == Chg::Was || chg(d, 2) == Chg::Was { + format!("In the case, was charging {}", ago(t)) + } else { + format!("In the case {}", ago(t)) + } + } else { + format!("Last read {}", ago(t)) + }; } if d.connected { - if d.charging == Some(true) { - "Charging".into() + if let Some(w) = chg_words(d) { + w } else if d.hands_free_off { "Connected \u{00B7} Hands-Free off, no level".into() } else if d.hands_free_idle { @@ -131,7 +211,7 @@ fn state_only(d: &BtDevice) -> String { } } else if per_bud(d) { // Heard from the open case near this PC. - "In the case, nearby".into() + chg_words(d).map_or("In the case, nearby".into(), |w| format!("In the case \u{00B7} {}", w.to_lowercase())) } else { match d.last_seen { Some(t) => format!("Seen {}", ago(t)), @@ -505,26 +585,36 @@ fn liq_dev(d: &BtDevice) -> Dev { } } -/// Levels (left, case, right for earbuds) and what the device is doing. -fn liq_vals(d: &BtDevice) -> ([f32; 3], St) { +/// Levels (left, case, right for earbuds) and what each part is doing. +fn liq_vals(d: &BtDevice) -> ([f32; 3], [St; 3]) { let f = |v: Option| v.map_or(0.0, f32::from); - let vals = if liq_dev(d).three() { [f(d.left), f(d.case), f(d.right)] } else { [f(level(d)); 3] }; - let st = if !d.connected { - St::Normal - } else if d.charging == Some(true) { - St::Charging - } else if is_low(d) { - St::Low - } else { - St::Normal - }; - (vals, st) + let dev = liq_dev(d); + let low = d.connected && is_low(d); + if !dev.three() { + let st = if d.connected && d.charging == Some(true) { + St::Charging + } else if low { + St::Low + } else { + St::Normal + }; + return ([f(level(d)); 3], [st; 3]); + } + let vals = [f(d.left), f(d.case), f(d.right)]; + let mut sts = vals.map(|v| if low { crate::liquid::part_state(dev, St::Low, v) } else { St::Normal }); + for (p, st) in sts.iter_mut().enumerate() { + // Moves only while the part says it charges now. + if chg(d, p) == Chg::Live { + *st = St::Charging; + } + } + (vals, sts) } impl Monitor { /// A device card on the Bluetooth page moves (charging, low). pub(super) fn bt_moving(&self) -> bool { - self.view == Some(crate::sensors::deep::Dev::Bluetooth) && self.bt_layout != 0 && self.bt().iter().any(|d| liq_vals(d).1.moves()) + self.view == Some(crate::sensors::deep::Dev::Bluetooth) && self.bt_layout != 0 && self.bt().iter().any(|d| liq_vals(d).1.iter().any(|s| s.moves())) } /// The band of device cards on the Bluetooth page (content coordinates). @@ -560,10 +650,11 @@ impl Draw<'_> { fn bt_col(&self, d: &BtDevice) -> Rgba { if !fresh(d) { self.col.dim + } else if chg_words(d).is_some() { + // Charging says more than low: it is being taken care of. + self.col.good } else if is_low(d) { self.col.crit - } else if d.charging == Some(true) { - self.col.good } else { self.col.accent } @@ -571,12 +662,10 @@ impl Draw<'_> { /// Colour of one part's level (left, right or case): a low device's other parts are not red. fn part_col(&self, d: &BtDevice, v: Option) -> Rgba { - if !part_calm(d, v) { - self.bt_col(d) - } else if d.charging == Some(true) { - self.col.good - } else { + if part_calm(d, v) { self.col.accent + } else { + self.bt_col(d) } } @@ -725,6 +814,17 @@ impl Draw<'_> { let (_, th) = cv.measure(m.num_sm_font, &t); cv.numeral_center(m.num_sm_font, &t, cx as i32, cy as i32 - th / 2 - self.s(5), ink); cv.text_center(self.f.tiny, lab, cx as i32, cy as i32 + self.s(11), dim); + let part = match lab { + "LEFT" => chg(d, 0), + "RIGHT" => chg(d, 2), + "CASE" => chg(d, 1), + _ if chg_one(d) => Chg::Live, + _ => Chg::No, + }; + if part != Chg::No { + let h = self.sf(9.0); + crate::liquid::bolt(cv, cx - h * 0.3, cy + self.sf(23.0), h, ink, &crate::look::tokens(self.dark())); + } cx += step; } } @@ -738,7 +838,7 @@ impl Draw<'_> { self.card(cv, r); let tk = crate::look::tokens(self.dark()); let dev = liq_dev(d); - let (vals, st) = liq_vals(d); + let (vals, sts) = liq_vals(d); let narrow = r.w() < self.s(NARROW_W); let p = tile_pad(m, r.w()); // A little higher in the hover window: Flash's tall digits keep clear of the line below. @@ -779,23 +879,33 @@ impl Draw<'_> { cv.text(self.f.tiny, "%", x + self.s(3), y - h / 2 + self.s(3), self.col.dim); }; let sub = note(d); + // Charging: a bolt, dim when it is what the buds last said. + let bolt_h = self.sf(9.0); + let bolt = |cv: &mut Canvas, x: i32, cy: i32, c: Chg| { + if c != Chg::No { + let col = if c == Chg::Live { self.col.good } else { self.col.dim }; + crate::liquid::bolt(cv, x as f32, cy as f32 - bolt_h / 2.0, bolt_h, col, &tk); + } + }; + let one = if chg_one(d) && !dev.three() { Chg::Live } else { Chg::No }; // A tall shape needs the width for its number beside it; in a narrow cell it goes on top. if dev.tall() && !narrow { let num_w = cv.measure(font, "100").0 + cv.measure(self.f.tiny, "%").0 + self.s(3); let col_w = num_w.max(cv.measure(self.f.small, &sub).0.min(r.w() / 2 - p)); let tx = r.r - p - col_w; let (ix, iy, k) = fit(r.l + p, r.t + p, tx - self.s(12), r.b - self.s(34), true); - crate::liquid::draw(cv, dev, ix, iy, k, vals, st, m.ianim.t, &tk, th); + crate::liquid::draw_parts(cv, dev, ix, iy, k, vals, sts, m.ianim.t, &tk, th); let t = pct_text(level(d)); let w = mid(cv, &t, tx, ny, numc(level(d)), false); if level(d).is_some() { pct_sign(cv, tx + w, ny); + bolt(cv, tx + w + self.s(4) + cv.measure(self.f.tiny, "%").0 + self.s(3), ny, one); } let st = cv.ellipsize(self.f.small, &sub, r.r - p - tx); text_mid(cv, self.f.small, &st, tx, sy, if on { self.bt_col(d) } else { self.col.dim }); } else { let (ix, iy, k) = fit(r.l + p, r.t + p, r.r - p, ny - self.s(22), false); - crate::liquid::draw(cv, dev, ix, iy, k, vals, st, m.ianim.t, &tk, th); + crate::liquid::draw_parts(cv, dev, ix, iy, k, vals, sts, m.ianim.t, &tk, th); if dev.three() { let xs = dev.cols(); for (i, (lab, v)) in [("L", d.left), ("CASE", d.case), ("R", d.right)].iter().enumerate() { @@ -804,7 +914,11 @@ impl Draw<'_> { 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); + // The bolt stands right of the label; both stay centred under the number. + let c = chg(d, i); + let bw = if c == Chg::No { 0 } else { (bolt_h * 0.6) as i32 + self.s(2) }; + cv.text(self.f.tiny, lab, x - (lw + bw) / 2, sy - self.s(2) - lh / 2, self.col.dim); + bolt(cv, x - (lw + bw) / 2 + lw + self.s(2), sy - self.s(2), c); } } else { let t = pct_text(level(d)); @@ -816,8 +930,12 @@ impl Draw<'_> { mid(cv, &t, x, ny, numc(level(d)), false); if has { pct_sign(cv, x + w, ny); + bolt(cv, x + w + sw + self.s(3), ny, one); } - let (sf, st) = cv.fit_text(&[self.f.small, if narrow { self.f.tiny } else { self.f.small }], &sub, r.w() - 2 * p); + // Too long for a narrow cell ("Connected \u{00B7} via receiver"): its first part, whole. + let short = sub.split(" \u{00B7} ").next().unwrap_or(&sub); + let tiny = if narrow { self.f.tiny } else { self.f.small }; + let (sf, st) = cv.fit_first(&[(self.f.small, &sub), (tiny, &sub), (self.f.small, short), (tiny, short)], r.w() - 2 * p); let (sw, _) = cv.measure(sf, &st); text_mid(cv, sf, &st, cx - sw / 2, sy, if on { self.bt_col(d) } else { self.col.dim }); } @@ -826,7 +944,22 @@ impl Draw<'_> { let fy = r.b - self.s(16); let lamp = if on { self.bt_col(d) } else { self.col.off }; cv.fill_disc((r.l + p + self.s(3)) as f32, fy as f32, self.sf(3.5), lamp); - let nm = cv.ellipsize(self.f.cap, &d.name, r.w() - 2 * p - self.s(12)); + // Earbuds have no state line: the age of old levels, or what charges, at the right of the + // name, in the longest wording that leaves the name whole. + let room = r.w() - 2 * p - self.s(12); + let mut words = if dev.three() { age_words(d) } else { Vec::new() }; + if dev.three() && words.is_empty() { + words.extend(chg_words(d)); + } + let name_w = cv.measure(self.f.cap, &d.name).0; + let side = words.iter().find(|t| name_w + self.s(8) + cv.measure(self.f.tiny, t).0 <= room).or(words.last().filter(|_| d.levels_at.is_some())); + let mut used = 0; + if let Some(t) = side { + let w = cv.measure(self.f.tiny, t).0; + used = w + self.s(8); + text_mid(cv, self.f.tiny, t, r.r - p - w, fy, if d.levels_at.is_none() { self.col.good } else { self.col.dim }); + } + let nm = cv.ellipsize(self.f.cap, &d.name, room - used); text_mid(cv, self.f.cap, &nm, r.l + p + self.s(12), fy, if on { self.col.fg } else { self.col.dim }); } @@ -1013,6 +1146,58 @@ mod tests { assert_eq!(f32::from(LOW_PCT), crate::liquid::LOW); } + /// Charging is said only where a flag says so, per part; old flags carry their age. + #[test] + fn charging_words_are_honest() { + let now = now_unix(); + let mut d = dev(None, Some(10), Some(10)); + d.case = Some(100); + assert_eq!(chg_words(&d), None); + d.parts = [Some(true), Some(false), Some(true)]; + assert_eq!(chg_words(&d).as_deref(), Some("Buds charging")); + assert_eq!(state(&d), "Buds charging"); + d.parts = [Some(true), Some(true), Some(false)]; + assert_eq!(chg_words(&d).as_deref(), Some("Left bud and case charging")); + d.parts = [None, Some(true), None]; + assert_eq!(chg_words(&d).as_deref(), Some("Case charging")); + // Lid closed five minutes ago while they charged: in the case, never "charging" now. + d.connected = false; + d.levels_at = Some(now - 300); + d.parts = [Some(true), Some(false), Some(true)]; + assert_eq!(chg_words(&d), None); + assert_eq!((chg(&d, 0), chg(&d, 1), chg(&d, 2)), (Chg::Was, Chg::No, Chg::Was)); + assert_eq!(state(&d), "In the case, was charging 5 min ago"); + assert_eq!(age_words(&d)[0], "In case \u{00B7} 5 min ago"); + assert_eq!(age_words(&d)[2], "5m"); + assert!(liq_vals(&d).1.iter().all(|s| !s.moves()), "old flags do not move"); + // Hours later the flag is worth nothing; being in the case still holds. + d.levels_at = Some(now - 5 * 3600); + assert_eq!(chg(&d, 0), Chg::No); + assert_eq!(state(&d), "In the case 5 h ago"); + // Gone without a charging flag: in the case or out of range, so neither is claimed. + d.parts = [Some(false), Some(false), Some(false)]; + assert_eq!(state(&d), "Last read 5 h ago"); + assert_eq!(age_words(&d).last().map(String::as_str), Some("5h")); + // One battery: its own flag. + let mut m = dev(Some(70), None, None); + m.kind = Kind::Mouse; + m.charging = Some(true); + assert_eq!(state(&m), "Charging"); + assert_eq!(liq_vals(&m).1, [St::Charging; 3]); + m.connected = false; + assert_eq!(chg_words(&m), None); + } + + /// Only the part that charges moves; a low bud that charges is charging, the rest keep theirs. + #[test] + fn parts_move_by_their_own_flag() { + let mut d = dev(None, Some(10), Some(10)); + d.kind = Kind::Earbuds; + d.case = Some(100); + d.parts = [Some(true), Some(false), Some(false)]; + assert_eq!(liq_vals(&d).1, [St::Charging, St::Normal, St::Low]); + } + #[test] fn low_only_when_connected() { let mut d = dev(Some(15), None, None); diff --git a/src/monitor/hover.rs b/src/monitor/hover.rs index 8faac07..63e3cdc 100644 --- a/src/monitor/hover.rs +++ b/src/monitor/hover.rs @@ -1221,10 +1221,13 @@ mod tests { save(&mut cv, format!("hover-{k}")); } // Rows of 1 to 4 cells of every kind. - let kinds: [&[&str]; 7] = [ + let kinds: [&[&str]; 10] = [ &["bt|{buds}"], &["bt|{buds}", "bt|{buds}~"], - &["bt|{buds}", "bt|{mx}"], + &["bt|{old}"], + &["bt|{buds}~"], + &["bt|{old}", "bt|{mx}"], + &["bt|{buds}~", "bt|{old}", "bt|{mx}"], &["bt|{buds}", "bt|{mx}", "bt|{kb}"], &["drive|drive:C", "screen|screen:LG ULTRAGEAR", "net|{aa}", "part|cpu", "vram", "part|gpu", "addon|usb", "addon|privacy", "addon|thermal", "unit|usb|USB drive", "unit|privacy|Microphone"], &["drive|drive:C", "net|{bb}"], @@ -1237,14 +1240,17 @@ mod tests { b.m = machine(); b.m.in_hover = true; let mut bt = (*b.m.det.deep.bt).clone(); - bt.push(BtDevice { id: "{buds}~".into(), name: "WF-C710N".into(), left: Some(10), right: Some(10), case: Some(100), ..bt[0].clone() }); + bt.push(BtDevice { id: "{buds}~".into(), name: "WF-C710N".into(), left: Some(10), right: Some(10), case: Some(100), parts: [Some(true), Some(true), Some(true)], ..bt[0].clone() }); + bt.push(BtDevice { id: "{old}".into(), name: "WF-C510".into(), connected: false, parts: [Some(true), Some(false), Some(true)], levels_at: Some(crate::insights::unix_ms() as u64 / 1000 - 1260), ..bt[0].clone() }); + bt[1].charging = Some(true); + bt[2].receiver = true; b.m.det.deep.bt = Arc::new(bt); - cv.resize(w, 2500); + cv.resize(w, 3600); cv.clear(crate::look::tokens(true).bg); let mut y = 10; for k in kinds { b.layout(&k.iter().map(|x| x.to_string()).collect::>(), 144, 368 * 144 / 96); - b.draw(&mut cv, 18, y, Rect { l: 0, t: 0, r: w, b: 2500 }, true, None); + b.draw(&mut cv, 18, y, Rect { l: 0, t: 0, r: w, b: 3600 }, true, None); y += b.h + 30; } save(&mut cv, format!("rows-{look}")); diff --git a/src/sensors/deep/bluetooth.rs b/src/sensors/deep/bluetooth.rs index 2f539ce..26eb978 100644 --- a/src/sensors/deep/bluetooth.rs +++ b/src/sensors/deep/bluetooth.rs @@ -76,6 +76,9 @@ pub struct BtDevice { pub right: Option, pub case: Option, pub charging: Option, + /// Left, case and right charging, each by its own flag (None = not said). With `levels_at` + /// these are as last read, not now. + pub parts: [Option; 3], /// Has a Bluetooth LE / Classic endpoint. pub le: bool, pub classic: bool, @@ -228,7 +231,8 @@ pub fn demo() -> Vec { ..Default::default() }; let mut buds = d("AirPods Pro", Kind::Earbuds, true, Some(80), 0); - (buds.left, buds.right, buds.case, buds.charging) = (Some(90), Some(80), Some(60), Some(false)); + (buds.left, buds.right, buds.case, buds.charging) = (Some(90), Some(80), Some(60), Some(true)); + buds.parts = [Some(true), Some(true), Some(false)]; let mut pad = d("DualSense", Kind::Gamepad, true, Some(75), 0); pad.charging = Some(true); vec![ @@ -675,6 +679,7 @@ fn apply_sony(list: &mut [BtDevice], levels: &HashMap) if d.charging.is_none() { d.charging = l.charging; } + d.parts = l.parts; } } @@ -1136,8 +1141,8 @@ pub fn write_watch() -> Option { fn watch_line(d: &BtDevice) -> String { format!( - "{} | 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 + "{} | connected {} | battery {:?} | left {:?} | right {:?} | case {:?} | charging {:?} | left/case/right charging {:?} | receiver {} | nearby {} | levels_at {:?} | case_at {:?}", + d.name, d.connected, d.battery, d.left, d.right, d.case, d.charging, d.parts, d.receiver, d.nearby, d.levels_at, d.case_at ) } @@ -1196,7 +1201,7 @@ pub fn debug_report() -> String { apply_sony(&mut page, &sony.levels()); let _ = writeln!(o, "With Sony's channel (after {} ms):", t.elapsed().as_millis()); for d in page.iter().filter(|d| d.sony.is_some()) { - let _ = writeln!(o, "{} | battery {:?} | left {:?} | right {:?} | case {:?} | charging {:?}", d.name, d.battery, d.left, d.right, d.case, d.charging); + let _ = writeln!(o, "{} | battery {:?} | left {:?} | right {:?} | case {:?} | charging {:?} | left/case/right charging {:?}", d.name, d.battery, d.left, d.right, d.case, d.charging, d.parts); } // Workers close their channels before section 8 opens its own. drop(sony); @@ -1601,7 +1606,9 @@ const KINDS: [Kind; 12] = [ ]; /// Cache file format version (first line). -const CACHE_HEAD: &str = "resmon-bt-cache 1"; +const CACHE_HEAD: &str = "resmon-bt-cache 2"; +/// Version 1 could hold random AirPods levels (scrambled messages read as levels). +const CACHE_HEAD_1: &str = "resmon-bt-cache 1"; fn cache_path() -> std::path::PathBuf { crate::util::data_dir().join("bluetooth-devices.txt") @@ -1634,6 +1641,7 @@ fn to_line(d: &BtDevice) -> String { 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()), + d.parts.iter().map(|p| p.map_or('-', |c| if c { '1' } else { '0' })).collect(), ] .join("\t") } @@ -1667,6 +1675,17 @@ fn from_line(l: &str) -> Option { nearby: false, levels_at: f.get(18).and_then(|v| v.parse().ok()), case_at: f.get(19).and_then(|v| v.parse().ok()), + parts: { + let mut p = [None; 3]; + for (p, c) in p.iter_mut().zip(f.get(20).copied().unwrap_or("").chars()) { + *p = match c { + '1' => Some(true), + '0' => Some(false), + _ => None, + }; + } + p + }, }) } @@ -1681,10 +1700,19 @@ fn cache_text(list: &[BtDevice]) -> String { fn parse_cache(t: &str) -> Vec { let mut lines = t.lines(); - if lines.next() != Some(CACHE_HEAD) { - return Vec::new(); + let old = match lines.next() { + Some(CACHE_HEAD) => false, + Some(CACHE_HEAD_1) => true, + _ => return Vec::new(), + }; + let mut v: Vec = lines.filter_map(from_line).collect(); + if old { + for d in v.iter_mut().filter(|d| super::btmod::is_apple(d)) { + (d.left, d.right, d.case, d.battery, d.charging) = (None, None, None, None, None); + (d.levels_at, d.case_at) = (None, None); + } } - lines.filter_map(from_line).collect() + v } /// The list the last run saw (empty when there is none). @@ -1871,6 +1899,8 @@ struct Kept { at: u64, case: Option, case_at: u64, + /// Left, case and right charging at `at`. + parts: [Option; 3], } fn unix_now() -> u64 { @@ -1898,6 +1928,7 @@ fn seed_kept(list: &[BtDevice], written: u64) -> HashMap { k.left = d.left; k.right = d.right; k.at = d.levels_at.unwrap_or(written); + k.parts = d.parts; } if let Some(c) = d.case { k.case = Some(c); @@ -1920,6 +1951,7 @@ fn remember(list: &mut [BtDevice], kept: &mut HashMap, now: u64) { 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); + k.parts = d.parts; } 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() { @@ -1927,6 +1959,7 @@ fn remember(list: &mut [BtDevice], kept: &mut HashMap, now: u64) { d.right = k.right; d.battery = k.battery.or(d.battery); d.levels_at = Some(k.at); + d.parts = k.parts; } else if d.battery == k.battery { // Windows' kept level is the one read then: say when. d.levels_at = Some(k.at); @@ -2066,6 +2099,42 @@ mod tests { assert_eq!((back[1].left, back[1].right, back[1].case, back[1].charging), (Some(85), Some(95), Some(100), Some(false))); assert_eq!(back[2], m); assert!(parse_cache("something else\nx").is_empty()); + // Charging flags of each part survive; a list from before them reads as "not said". + let c = BtDevice { name: "WF-C710N".into(), kind: Kind::Earbuds, left: Some(10), right: Some(10), case: Some(100), levels_at: Some(9), parts: [Some(true), None, Some(false)], ..Default::default() }; + assert_eq!(parse_cache(&cache_text(&[c.clone()]))[0].parts, c.parts); + let old = cache_text(&[c.clone(), b.clone()]).replace(CACHE_HEAD, CACHE_HEAD_1); + let old: String = old.lines().map(|l| l.rsplit_once('\t').map_or(l.to_string(), |x| x.0.to_string())).collect::>().join("\n"); + let back = parse_cache(&old); + assert_eq!((back[0].left, back[0].parts), (Some(10), [None; 3])); + assert_eq!((back[1].left, back[1].case), (None, None), "AirPods levels from before could be random: dropped"); + } + + /// Earbuds that went quiet keep the charging flags of their last message, marked as old. + #[test] + fn charging_flags_are_kept_with_their_time() { + let mut kept = HashMap::new(); + let on = BtDevice { id: "{b}".into(), connected: true, left: Some(10), right: Some(10), case: Some(100), parts: [Some(true), Some(false), Some(true)], ..Default::default() }; + let mut l = vec![on.clone()]; + remember(&mut l, &mut kept, 1000); + assert_eq!((l[0].parts, l[0].levels_at), (on.parts, None), "live"); + // The lid closes: the earbuds drop off. + let mut l = vec![BtDevice { id: "{b}".into(), ..Default::default() }]; + remember(&mut l, &mut kept, 1300); + assert_eq!((l[0].parts, l[0].levels_at, l[0].left), (on.parts, Some(1000), Some(10))); + // Back on, out of the case: the new flags win. + let mut l = vec![BtDevice { parts: [Some(false), None, Some(false)], ..on.clone() }]; + remember(&mut l, &mut kept, 1400); + assert_eq!(l[0].parts, [Some(false), None, Some(false)]); + } + + /// Sony's flags land on their own part. + #[test] + fn sony_flags_per_part() { + let mut l = vec![BtDevice { addr: Some(7), connected: true, ..Default::default() }]; + let lv = super::super::sony::Level { left: Some(50), right: Some(60), case: Some(70), charging: Some(true), parts: [Some(true), Some(true), Some(false)], single: None }; + apply_sony(&mut l, &HashMap::from([(7, lv)])); + assert_eq!(l[0].parts, [Some(true), Some(true), Some(false)]); + assert_eq!((l[0].left, l[0].case, l[0].right), (Some(50), Some(70), Some(60))); } /// Startup guard: the Bluetooth query is narrowed to the two Bluetooth protocols, so it diff --git a/src/sensors/deep/btmod.rs b/src/sensors/deep/btmod.rs index a34c1a5..4b56d44 100644 --- a/src/sensors/deep/btmod.rs +++ b/src/sensors/deep/btmod.rs @@ -54,6 +54,8 @@ pub struct Reading { pub single: Option, /// A bud (or the one battery) is charging. pub charging: bool, + /// Left, case and right charging (None = that part gave no level). + pub parts: [Option; 3], pub rssi: i16, pub at: Instant, } @@ -495,6 +497,7 @@ pub fn apply(list: &mut [BtDevice], readings: &[Reading]) -> Vec { d.right = r.right; d.case = r.case; d.charging = Some(r.charging); + d.parts = r.parts; if d.battery.is_none() { d.battery = match (r.left, r.right) { (Some(l), Some(r)) => Some(l.min(r)), @@ -514,6 +517,10 @@ pub fn apply(list: &mut [BtDevice], readings: &[Reading]) -> Vec { if d.case.is_none() { d.case = r.case; } + // The earbuds' own channel goes first; the advertisement fills what it left out. + for (p, q) in d.parts.iter_mut().zip(r.parts) { + *p = p.or(q); + } } } used @@ -553,6 +560,7 @@ pub fn nearby(list: &[BtDevice], readings: &[Reading], used: &[bool]) -> Vec Option { case: num("case"), single: num("single"), charging: yes("charging_left") || yes("charging_right"), + parts: [num("left").map(|_| yes("charging_left")), num("case").map(|_| yes("charging_case")), num("right").map(|_| yes("charging_right"))], rssi: json_raw(line, "rssi").and_then(|v| v.parse().ok()).unwrap_or(0), at: Instant::now(), }) @@ -685,14 +694,14 @@ mod tests { #[test] fn applies() { let mut list = vec![BtDevice { name: "AirPods Pro #2".into(), kind: Kind::Earbuds, ..Default::default() }]; - 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 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, parts: [None; 3], 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() } + Reading { src: Src::FastPair, key: key.into(), model: String::new(), left: l, right: r, case: c, single: None, charging: false, parts: [None; 3], rssi: -60, at: Instant::now() } } /// Fast Pair buds that are the connected Sony buds add their case; others show nearby. @@ -707,7 +716,7 @@ mod tests { 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 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, parts: [None; 3], 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. diff --git a/src/sensors/deep/sony.rs b/src/sensors/deep/sony.rs index bf0a829..8b9ce22 100644 --- a/src/sensors/deep/sony.rs +++ b/src/sensors/deep/sony.rs @@ -56,7 +56,10 @@ pub struct Level { pub left: Option, pub right: Option, pub case: Option, + /// A bud (or the one battery) is charging. pub charging: Option, + /// Left, case and right charging. + pub parts: [Option; 3], } // --------------------------------------------------------------------------------------------- @@ -192,8 +195,14 @@ pub fn take_battery(p: &[u8], lv: &mut Level) -> bool { lv.left = pct(p[2]); lv.right = pct(p[4]); lv.charging = Some(p[3] == 1 || p[5] == 1); + // A bud with no level said nothing about charging either. + lv.parts[0] = lv.left.map(|_| p[3] == 1); + lv.parts[2] = lv.right.map(|_| p[5] == 1); + } + 2 if p.len() >= 3 => { + lv.case = pct(p[2]); + lv.parts[1] = lv.case.and_then(|_| p.get(3)).map(|c| *c == 1); } - 2 if p.len() >= 3 => lv.case = pct(p[2]), _ => return false, } true @@ -290,7 +299,12 @@ fn session(addr: u64, svc: u128, stop: &AtomicBool, level: &Mutex