Fix false locks: escalate duty when updates stall, probe before locking

BlueZ dedupes identical RSSI values, so a stationary phone can go quiet
in the event stream while in range. At the 2% present duty cycle the
~1Hz beacon was caught less often than presence_timeout, causing
Present/Suspect flapping and locks after 60s of silence with the phone
at -60 dBm.

- Present: step up to the Suspect duty once the last sighting ages past
  half of presence_timeout, without leaving Present
- Lock path: attempt a 3s LE connect to the phone first; success cancels
  the lock and returns to Present, failure locks as before
This commit is contained in:
Bastian Mäuser committed 2026-11-05 14:48:10 +01:00
1 parent 426342eb10
commit 43a79d8a43
4 files changed
+133 -18

No files matched your search

+15 -8
View File
@@ -28,14 +28,20 @@ The daemon adapts it to a small state machine:
``` ```
- **Present**: fresh advertisement updates with RSSI above `rssi_lock`, or an - **Present**: fresh advertisement updates with RSSI above `rssi_lock`, or an
active connection to the device. active connection to the device. If updates go quiet — a stationary phone
produces identical RSSI values, which BlueZ dedupes — the radio steps up to
the Suspect duty after half of `presence_timeout_secs`, without leaving
Present.
- **Suspect**: high-duty re-check so a few dropped beacons don't lock you out. - **Suspect**: high-duty re-check so a few dropped beacons don't lock you out.
- **Bootstrapping**: the daemon never locks before it has seen the phone at - **Bootstrapping**: the daemon never locks before it has seen the phone at
least once, so you can boot with the phone in another room. least once, so you can boot with the phone in another room.
- **Locked**: no unlock; the next sighting just returns to Present. - **Locked**: no unlock; the next sighting just returns to Present.
Locking goes through `loginctl lock-session` (works with GNOME, KDE, Sway, Locking goes through `loginctl lock-session` (works with GNOME, KDE, Sway,
...), configurable via `lock_command`. ...), configurable via `lock_command`. Before locking, the daemon attempts a
short (3s) LE connection to the paired phone: a phone in range accepts it,
which cancels the lock — silence in the advertisement stream alone is not
proof of absence.
## Requirements ## Requirements
@@ -112,12 +118,13 @@ See `config.toml.example`; every knob is documented there. Highlights:
## Known trade-offs (v1) ## Known trade-offs (v1)
- Presence is inferred from advertisement property updates. If BlueZ - Presence is inferred from advertisement property updates. BlueZ dedupes
suppresses updates for identical RSSI values (its property cache dedupes), identical RSSI values (its property cache suppresses unchanged values), so
a *perfectly* stationary phone in a perfectly stationary room can look a stationary phone can go quiet in the event stream while in range. Two
absent; the default `presence_timeout_secs = 15` plus real-world RSSI countermeasures: the radio escalates duty while updates are stalled (see
jitter makes this unlikely, but `--dry-run` on your hardware is the Present above), and the lock decision is gated on a 3s LE connect probe.
arbiter. The AdvertisementMonitor roadmap removes this class of problem. `--dry-run` on your hardware remains the arbiter. The AdvertisementMonitor
roadmap removes this class of problem.
- While the screen is locked the daemon keeps low-duty scanning to notice - While the screen is locked the daemon keeps low-duty scanning to notice
the phone's return (rearming only; it never unlocks). the phone's return (rearming only; it never unlocks).
+1 -1
View File
@@ -36,7 +36,7 @@ fn locked_duty() -> Duty {
} }
/// One scan duty cycle: radio on for `window_ms`, then rest until `interval_ms`. /// One scan duty cycle: radio on for `window_ms`, then rest until `interval_ms`.
#[derive(Debug, Clone, Copy, Deserialize)] #[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
pub struct Duty { pub struct Duty {
pub window_ms: u64, pub window_ms: u64,
pub interval_ms: u64, pub interval_ms: u64,
+48 -2
View File
@@ -121,11 +121,24 @@ impl Policy {
None None
} }
pub fn duty(&self, cfg: &DutyConfig) -> Duty { pub fn duty(&self, cfg: &DutyConfig, now: Instant) -> Duty {
match self.state { match self.state {
State::Bootstrapping | State::Suspect => cfg.suspect, State::Bootstrapping | State::Suspect => cfg.suspect,
State::Present => cfg.present,
State::Locked => cfg.locked, State::Locked => cfg.locked,
State::Present => {
// A stationary phone produces identical RSSI values, which
// BlueZ dedupes: updates can legitimately go quiet while the
// phone is in range. Escalate the radio before "fresh"
// expires instead of flipping to Suspect.
let aging = self
.last_event
.is_none_or(|t| now.duration_since(t) >= self.presence_timeout / 2);
if aging {
cfg.suspect
} else {
cfg.present
}
}
} }
} }
} }
@@ -139,6 +152,23 @@ mod tests {
Policy::new(Duration::from_secs(15), Duration::from_secs(30), -80) Policy::new(Duration::from_secs(15), Duration::from_secs(30), -80)
} }
fn duty_cfg() -> DutyConfig {
DutyConfig {
present: Duty {
window_ms: 100,
interval_ms: 5000,
},
suspect: Duty {
window_ms: 200,
interval_ms: 1000,
},
locked: Duty {
window_ms: 100,
interval_ms: 30_000,
},
}
}
fn t(secs: u64) -> Instant { fn t(secs: u64) -> Instant {
Instant::now() + Duration::from_secs(secs) Instant::now() + Duration::from_secs(secs)
} }
@@ -236,6 +266,22 @@ mod tests {
assert_eq!(p.on_tick(t(70)), Some(Action::Lock)); assert_eq!(p.on_tick(t(70)), Some(Action::Lock));
} }
#[test]
fn present_duty_escalates_while_updates_stall() {
let mut p = policy();
let cfg = duty_cfg();
p.note_event(t(0), Some(-50), None);
p.on_tick(t(1));
assert_eq!(p.state(), State::Present);
assert_eq!(p.duty(&cfg, t(5)), cfg.present);
// Past half the presence timeout: listen harder, but stay Present.
assert_eq!(p.duty(&cfg, t(9)), cfg.suspect);
assert_eq!(p.state(), State::Present);
// A fresh sighting de-escalates again.
p.note_event(t(10), Some(-52), None);
assert_eq!(p.duty(&cfg, t(11)), cfg.present);
}
#[test] #[test]
fn connected_device_counts_as_present() { fn connected_device_counts_as_present() {
let mut p = policy(); let mut p = policy();
+69 -7
View File
@@ -105,10 +105,11 @@ pub async fn run(cfg: Config) -> Result<()> {
loop { loop {
tokio::select! { tokio::select! {
_ = tokio::time::sleep_until(next_toggle) => { _ = tokio::time::sleep_until(next_toggle) => {
let now = Instant::now();
if radio_on { if radio_on {
stop_discovery(&adapter).await; stop_discovery(&adapter).await;
radio_on = false; radio_on = false;
let d = policy.duty(&cfg.duty); let d = policy.duty(&cfg.duty, now);
let off = Duration::from_millis(d.interval_ms - d.window_ms); let off = Duration::from_millis(d.interval_ms - d.window_ms);
next_toggle = tokio::time::Instant::now() + off; next_toggle = tokio::time::Instant::now() + off;
} else { } else {
@@ -119,7 +120,7 @@ pub async fn run(cfg: Config) -> Result<()> {
} }
} }
radio_on = true; radio_on = true;
let window = Duration::from_millis(policy.duty(&cfg.duty).window_ms); let window = Duration::from_millis(policy.duty(&cfg.duty, now).window_ms);
next_toggle = tokio::time::Instant::now() + window; next_toggle = tokio::time::Instant::now() + window;
} }
} }
@@ -133,12 +134,24 @@ pub async fn run(cfg: Config) -> Result<()> {
}, },
_ = tick.tick() => { _ = tick.tick() => {
if let Some(Action::Lock) = policy.on_tick(Instant::now()) { if let Some(Action::Lock) = policy.on_tick(Instant::now()) {
match crate::locker::lock_screen(cfg.lock_command.as_deref(), cfg.dry_run).await { // Before locking: actively check the phone with a short
Ok(()) => { // LE connection attempt. A phone in range accepts it even
info!("screen locked"); // when advertisement updates have gone quiet (BlueZ
policy.mark_locked(); // dedupes identical RSSI values), so silence alone is not
// proof of absence.
if probe_reachable(&conn, target.as_ref()).await {
info!("connect probe: phone in range, not locking");
policy.note_event(Instant::now(), None, Some(true));
} else {
match crate::locker::lock_screen(cfg.lock_command.as_deref(), cfg.dry_run)
.await
{
Ok(()) => {
info!("screen locked");
policy.mark_locked();
}
Err(e) => error!("locking the screen failed: {e:#}"),
} }
Err(e) => error!("locking the screen failed: {e:#}"),
} }
} }
let s = policy.state(); let s = policy.state();
@@ -162,6 +175,55 @@ struct Target {
path: OwnedObjectPath, path: OwnedObjectPath,
} }
/// How long to wait for the connect probe before concluding the phone is
/// gone. LE connection setup with the phone in range completes well within
/// this; aborting cancels BlueZ's connection attempt.
const PROBE_TIMEOUT: Duration = Duration::from_secs(3);
/// Attempt a short LE connection to the paired phone. Returns true if the
/// device accepted the connection (it is in range); the connection is closed
/// again immediately, presence monitoring stays scan-based.
async fn probe_reachable(conn: &Connection, target: Option<&Target>) -> bool {
let Some(target) = target else {
return false;
};
let proxy = match Proxy::new(conn, BLUEZ, target.path.clone(), DEVICE_IFACE).await {
Ok(p) => p,
Err(e) => {
debug!("probe: proxy setup failed: {e:#}");
return false;
}
};
match tokio::time::timeout(PROBE_TIMEOUT, proxy.call::<_, _, ()>("Connect", &())).await {
Ok(Ok(())) => {
if let Err(e) = tokio::time::timeout(
Duration::from_secs(1),
proxy.call::<_, _, ()>("Disconnect", &()),
)
.await
{
debug!("probe: disconnect failed: {e:#}");
}
true
}
Ok(Err(e)) => {
debug!("probe: connect rejected: {e:#}");
false
}
Err(_) => {
debug!("probe: timed out");
// Cancel the pending connection attempt so BlueZ does not keep
// paging for the device in the background.
let _ = tokio::time::timeout(
Duration::from_secs(1),
proxy.call::<_, _, ()>("Disconnect", &()),
)
.await;
false
}
}
}
/// Extract the MAC from a device object path such as /// Extract the MAC from a device object path such as
/// "/org/bluez/hci0/dev_AA_BB_CC_DD_EE_FF". /// "/org/bluez/hci0/dev_AA_BB_CC_DD_EE_FF".
fn path_mac(path: &str) -> Option<String> { fn path_mac(path: &str) -> Option<String> {