Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -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"
Expand Down
2 changes: 1 addition & 1 deletion res/resmon.manifest
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
<assemblyIdentity type="win32" name="ResourceMonitor" version="2.33.0.0"/>
<assemblyIdentity type="win32" name="ResourceMonitor" version="2.34.0.0"/>
<trustInfo xmlns="urn:schemas-microsoft-com:asm.v3">
<security><requestedPrivileges>
<requestedExecutionLevel level="asInvoker" uiAccess="false"/>
Expand Down
2 changes: 1 addition & 1 deletion setup.iss
Original file line number Diff line number Diff line change
@@ -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"
Expand Down
257 changes: 232 additions & 25 deletions src/modbt/main.rs
Original file line number Diff line number Diff line change
@@ -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")]
Expand All @@ -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.
Expand Down Expand Up @@ -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<u8>,
right: Option<u8>,
case: Option<u8>,
/// One battery (headphones, speakers).
single: Option<u8>,
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<u8>, 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<Fp> {
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<u64, (Fp, Instant)>,
}

impl SeenFp {
fn offer(&mut self, addr: u64, p: Fp, name: &str, rssi: i16) -> Option<String> {
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<u16, (Pods, Instant)>,
Expand Down Expand Up @@ -148,68 +253,147 @@ 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<String> = 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::<u64>().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<Mutex<HashMap<(u64, u64), Instant>>> = Arc::default();
println_flush("{\"v\":1,\"kind\":\"hello\"}");
fn bytes(buf: &IBuffer) -> windows::core::Result<Vec<u8>> {
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<BluetoothLEAdvertisementWatcher> {
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<BluetoothLEAdvertisementReceivedEventArgs>| {
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<u8>> = Vec::new();
let mut fast: Vec<Vec<u8>> = 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()?;
Ok(w)
};
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));
}
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::<Vec<_>>().join(" ")
}

#[cfg(not(windows))]
fn main() {}

Expand Down Expand Up @@ -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];
Expand Down
Loading
Loading