first commit
This commit is contained in:
1 parent
2dc85ba948
commit
57a8357dd7
11 files changed
+2062
No files matched your search
@@ -0,0 +1 @@
|
||||
/target
|
||||
Generated
+1083
File diff suppressed because it is too large.
Load diff
+22
@@ -0,0 +1,22 @@
|
||||
[package]
|
||||
name = "btle-proximity"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
description = "BLE proximity screen locker: locks the desktop session when your phone leaves Bluetooth range"
|
||||
license = "MIT"
|
||||
|
||||
[dependencies]
|
||||
anyhow = "1"
|
||||
clap = { version = "4", features = ["derive"] }
|
||||
sd-notify = "0.4"
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
tokio = { version = "1", features = ["macros", "process", "rt-multi-thread", "signal", "time"] }
|
||||
tokio-stream = "0.1"
|
||||
toml = "0.8"
|
||||
tracing = "0.1"
|
||||
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
|
||||
zbus = { version = "5", default-features = false, features = ["tokio"] }
|
||||
|
||||
[profile.release]
|
||||
lto = true
|
||||
strip = true
|
||||
@@ -0,0 +1,38 @@
|
||||
# MAC address of the paired phone to watch.
|
||||
# Run `btle-proximity list-paired` to see candidates.
|
||||
device_mac = "AA:BB:CC:DD:EE:FF"
|
||||
|
||||
# Bluetooth adapter to use, e.g. "hci0". First available if unset.
|
||||
#adapter = "hci0"
|
||||
|
||||
# Lock the session after this long without strong evidence of presence.
|
||||
missing_after_secs = 30
|
||||
|
||||
# Advertisement updates newer than this count as "recently seen".
|
||||
presence_timeout_secs = 15
|
||||
|
||||
# Discovery only reports devices at or above this RSSI (dBm).
|
||||
rssi_floor = -90
|
||||
|
||||
# At or below this RSSI the device counts as out of range (dBm).
|
||||
rssi_lock = -80
|
||||
|
||||
# Scan duty cycle per state: radio on for window_ms, then rest until
|
||||
# interval_ms has elapsed. window_ms/interval_ms is the radio duty cycle.
|
||||
[duty.present]
|
||||
window_ms = 100 # ~2% radio duty while the phone is around
|
||||
interval_ms = 5000
|
||||
|
||||
[duty.suspect]
|
||||
window_ms = 200 # aggressive probing while confirming absence
|
||||
interval_ms = 1000
|
||||
|
||||
[duty.locked]
|
||||
window_ms = 100 # rarely polling for the phone's return
|
||||
interval_ms = 30000
|
||||
|
||||
# Optional: command to run instead of `loginctl lock-session`.
|
||||
#lock_command = "swaylock -f"
|
||||
|
||||
# Optional: log lock actions instead of executing them (for testing).
|
||||
#dry_run = false
|
||||
+158
@@ -0,0 +1,158 @@
|
||||
use anyhow::{ensure, Context, Result};
|
||||
use serde::Deserialize;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::Duration;
|
||||
|
||||
fn presence_timeout_secs() -> u64 {
|
||||
15
|
||||
}
|
||||
fn missing_after_secs() -> u64 {
|
||||
30
|
||||
}
|
||||
fn rssi_floor() -> i16 {
|
||||
-90
|
||||
}
|
||||
fn rssi_lock() -> i16 {
|
||||
-80
|
||||
}
|
||||
|
||||
fn present_duty() -> Duty {
|
||||
Duty {
|
||||
window_ms: 100,
|
||||
interval_ms: 5000,
|
||||
}
|
||||
}
|
||||
fn suspect_duty() -> Duty {
|
||||
Duty {
|
||||
window_ms: 200,
|
||||
interval_ms: 1000,
|
||||
}
|
||||
}
|
||||
fn locked_duty() -> Duty {
|
||||
Duty {
|
||||
window_ms: 100,
|
||||
interval_ms: 30_000,
|
||||
}
|
||||
}
|
||||
|
||||
/// One scan duty cycle: radio on for `window_ms`, then rest until `interval_ms`.
|
||||
#[derive(Debug, Clone, Copy, Deserialize)]
|
||||
pub struct Duty {
|
||||
pub window_ms: u64,
|
||||
pub interval_ms: u64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, Deserialize)]
|
||||
pub struct DutyConfig {
|
||||
#[serde(default = "present_duty")]
|
||||
pub present: Duty,
|
||||
#[serde(default = "suspect_duty")]
|
||||
pub suspect: Duty,
|
||||
#[serde(default = "locked_duty")]
|
||||
pub locked: Duty,
|
||||
}
|
||||
|
||||
impl Default for DutyConfig {
|
||||
fn default() -> Self {
|
||||
DutyConfig {
|
||||
present: present_duty(),
|
||||
suspect: suspect_duty(),
|
||||
locked: locked_duty(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
pub struct Config {
|
||||
/// Identity MAC address of the paired phone to watch.
|
||||
pub device_mac: String,
|
||||
/// Bluetooth adapter to use, e.g. "hci0". First available if unset.
|
||||
#[serde(default)]
|
||||
pub adapter: Option<String>,
|
||||
/// Command to run instead of `loginctl lock-session`.
|
||||
#[serde(default)]
|
||||
pub lock_command: Option<String>,
|
||||
/// Advertisement updates newer than this count as "recently seen".
|
||||
#[serde(default = "presence_timeout_secs")]
|
||||
pub presence_timeout_secs: u64,
|
||||
/// Lock the session after this long without strong evidence of presence.
|
||||
#[serde(default = "missing_after_secs")]
|
||||
pub missing_after_secs: u64,
|
||||
/// Discovery filter: only devices at or above this RSSI are reported (dBm).
|
||||
#[serde(default = "rssi_floor")]
|
||||
pub rssi_floor: i16,
|
||||
/// At or below this RSSI the device counts as out of range (dBm).
|
||||
#[serde(default = "rssi_lock")]
|
||||
pub rssi_lock: i16,
|
||||
#[serde(default)]
|
||||
pub duty: DutyConfig,
|
||||
/// Log lock actions instead of executing them.
|
||||
#[serde(default)]
|
||||
pub dry_run: bool,
|
||||
}
|
||||
|
||||
impl Config {
|
||||
pub fn load(path: &Path) -> Result<Self> {
|
||||
let raw = std::fs::read_to_string(path)
|
||||
.with_context(|| format!("reading config file {}", path.display()))?;
|
||||
let cfg: Config = toml::from_str(&raw)
|
||||
.with_context(|| format!("parsing config file {}", path.display()))?;
|
||||
cfg.validate()?;
|
||||
Ok(cfg)
|
||||
}
|
||||
|
||||
pub fn validate(&self) -> Result<()> {
|
||||
ensure!(
|
||||
self.normalized_mac().len() == 12,
|
||||
"device_mac must be a MAC address (got {:?})",
|
||||
self.device_mac
|
||||
);
|
||||
ensure!(
|
||||
self.missing_after_secs > self.presence_timeout_secs,
|
||||
"missing_after_secs must be greater than presence_timeout_secs"
|
||||
);
|
||||
ensure!(
|
||||
self.rssi_lock > self.rssi_floor,
|
||||
"rssi_lock must be greater than rssi_floor"
|
||||
);
|
||||
for (name, d) in [
|
||||
("present", &self.duty.present),
|
||||
("suspect", &self.duty.suspect),
|
||||
("locked", &self.duty.locked),
|
||||
] {
|
||||
ensure!(d.window_ms > 0, "{name}.window_ms must be > 0");
|
||||
ensure!(
|
||||
d.interval_ms >= d.window_ms,
|
||||
"{name}.interval_ms must be >= {name}.window_ms"
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn normalized_mac(&self) -> String {
|
||||
normalize_mac(&self.device_mac)
|
||||
}
|
||||
|
||||
pub fn presence_timeout(&self) -> Duration {
|
||||
Duration::from_secs(self.presence_timeout_secs)
|
||||
}
|
||||
|
||||
pub fn missing_after(&self) -> Duration {
|
||||
Duration::from_secs(self.missing_after_secs)
|
||||
}
|
||||
}
|
||||
|
||||
/// Uppercase hex digits only, separators removed: "aa:bb:cc" -> "AABBCC".
|
||||
pub fn normalize_mac(s: &str) -> String {
|
||||
s.chars()
|
||||
.filter(|c| c.is_ascii_hexdigit())
|
||||
.map(|c| c.to_ascii_uppercase())
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub fn default_path() -> Option<PathBuf> {
|
||||
let base = std::env::var_os("XDG_CONFIG_HOME")
|
||||
.map(PathBuf::from)
|
||||
.or_else(|| std::env::var_os("HOME").map(|h| PathBuf::from(h).join(".config")))?;
|
||||
Some(base.join("btle-proximity").join("config.toml"))
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
use anyhow::{bail, Context, Result};
|
||||
use tracing::{info, warn};
|
||||
|
||||
/// Lock the desktop session. Tries, in order:
|
||||
/// 1. `lock_command` from config, if set
|
||||
/// 2. `loginctl lock-session` (logind notifies the session's screen locker)
|
||||
/// 3. org.freedesktop.login1.Manager.Lock over the system bus
|
||||
pub async fn lock_screen(lock_command: Option<&str>, dry_run: bool) -> Result<()> {
|
||||
if dry_run {
|
||||
info!("dry-run: would lock the screen now");
|
||||
return Ok(());
|
||||
}
|
||||
if let Some(cmd) = lock_command {
|
||||
return run_shell(cmd).await;
|
||||
}
|
||||
match loginctl_lock().await {
|
||||
Ok(()) => {
|
||||
info!("screen locked via loginctl lock-session");
|
||||
Ok(())
|
||||
}
|
||||
Err(e) => {
|
||||
warn!("loginctl failed ({e:#}), falling back to logind D-Bus");
|
||||
logind_dbus_lock().await
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn run_shell(cmd: &str) -> Result<()> {
|
||||
let out = tokio::process::Command::new("sh")
|
||||
.arg("-c")
|
||||
.arg(cmd)
|
||||
.stdout(std::process::Stdio::piped())
|
||||
.stderr(std::process::Stdio::piped())
|
||||
.output()
|
||||
.await
|
||||
.with_context(|| format!("spawning lock command {cmd:?}"))?;
|
||||
if out.status.success() {
|
||||
info!(command = cmd, "screen locked");
|
||||
Ok(())
|
||||
} else {
|
||||
bail!(
|
||||
"lock command {cmd:?} failed: {}",
|
||||
String::from_utf8_lossy(&out.stderr).trim()
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
async fn loginctl_lock() -> Result<()> {
|
||||
let out = tokio::process::Command::new("loginctl")
|
||||
.arg("lock-session")
|
||||
.output()
|
||||
.await
|
||||
.context("spawning loginctl")?;
|
||||
if out.status.success() {
|
||||
Ok(())
|
||||
} else {
|
||||
bail!(
|
||||
"loginctl lock-session failed: {}",
|
||||
String::from_utf8_lossy(&out.stderr).trim()
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
async fn logind_dbus_lock() -> Result<()> {
|
||||
let conn = zbus::Connection::system()
|
||||
.await
|
||||
.context("connecting to the system D-Bus")?;
|
||||
let proxy = zbus::Proxy::new(
|
||||
&conn,
|
||||
"org.freedesktop.login1",
|
||||
"/org/freedesktop/login1",
|
||||
"org.freedesktop.login1.Manager",
|
||||
)
|
||||
.await?;
|
||||
proxy
|
||||
.call::<_, _, ()>("Lock", &())
|
||||
.await
|
||||
.context("calling org.freedesktop.login1.Manager.Lock")?;
|
||||
info!("screen locked via logind D-Bus");
|
||||
Ok(())
|
||||
}
|
||||
+79
@@ -0,0 +1,79 @@
|
||||
mod config;
|
||||
mod locker;
|
||||
mod policy;
|
||||
mod scanner;
|
||||
|
||||
use anyhow::{Context, Result};
|
||||
use clap::{Parser, Subcommand};
|
||||
|
||||
#[derive(Parser)]
|
||||
#[command(
|
||||
name = "btle-proximity",
|
||||
version,
|
||||
about = "Locks the desktop session when your phone leaves Bluetooth range"
|
||||
)]
|
||||
struct Cli {
|
||||
/// Path to the TOML config file
|
||||
#[arg(long, short, value_name = "FILE")]
|
||||
config: Option<std::path::PathBuf>,
|
||||
/// Log lock actions instead of executing them
|
||||
#[arg(long)]
|
||||
dry_run: bool,
|
||||
#[command(subcommand)]
|
||||
command: Option<Command>,
|
||||
}
|
||||
|
||||
#[derive(Subcommand)]
|
||||
enum Command {
|
||||
/// Run the daemon (default)
|
||||
Run,
|
||||
/// List paired Bluetooth devices and exit
|
||||
ListPaired,
|
||||
}
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<()> {
|
||||
let cli = Cli::parse();
|
||||
|
||||
tracing_subscriber::fmt()
|
||||
.with_env_filter(
|
||||
tracing_subscriber::EnvFilter::try_from_default_env()
|
||||
.unwrap_or_else(|_| tracing_subscriber::EnvFilter::new("info")),
|
||||
)
|
||||
.init();
|
||||
|
||||
match cli.command.as_ref().unwrap_or(&Command::Run) {
|
||||
Command::ListPaired => {
|
||||
for dev in scanner::list_paired().await? {
|
||||
println!(
|
||||
"{} {:20} {}",
|
||||
dev.address,
|
||||
dev.alias,
|
||||
if dev.connected { "connected" } else { "" }
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
Command::Run => run(cli).await,
|
||||
}
|
||||
}
|
||||
|
||||
async fn run(cli: Cli) -> Result<()> {
|
||||
let path = cli.config.or_else(config::default_path).context(
|
||||
"no config file found: pass --config or install one at \
|
||||
$XDG_CONFIG_HOME/btle-proximity/config.toml",
|
||||
)?;
|
||||
let mut cfg = config::Config::load(&path)?;
|
||||
if cli.dry_run {
|
||||
cfg.dry_run = true;
|
||||
}
|
||||
scanner::run(cfg).await
|
||||
}
|
||||
|
||||
pub fn notify_ready() {
|
||||
let _ = sd_notify::notify(false, &[sd_notify::NotifyState::Ready]);
|
||||
}
|
||||
|
||||
pub fn notify_stopping() {
|
||||
let _ = sd_notify::notify(false, &[sd_notify::NotifyState::Stopping]);
|
||||
}
|
||||
+265
@@ -0,0 +1,265 @@
|
||||
use crate::config::{Duty, DutyConfig};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum State {
|
||||
/// Started, waiting for the first sighting of the target device.
|
||||
Bootstrapping,
|
||||
/// Fresh, strong evidence that the device is nearby.
|
||||
Present,
|
||||
/// No fresh strong evidence; probing aggressively.
|
||||
Suspect,
|
||||
/// Screen has been locked; waiting for the device to return.
|
||||
Locked,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Action {
|
||||
Lock,
|
||||
}
|
||||
|
||||
pub struct Policy {
|
||||
presence_timeout: Duration,
|
||||
missing_after: Duration,
|
||||
rssi_lock: i16,
|
||||
state: State,
|
||||
last_event: Option<Instant>,
|
||||
last_rssi: Option<i16>,
|
||||
connected: bool,
|
||||
weak_since: Option<Instant>,
|
||||
}
|
||||
|
||||
impl Policy {
|
||||
pub fn new(presence_timeout: Duration, missing_after: Duration, rssi_lock: i16) -> Self {
|
||||
Policy {
|
||||
presence_timeout,
|
||||
missing_after,
|
||||
rssi_lock,
|
||||
state: State::Bootstrapping,
|
||||
last_event: None,
|
||||
last_rssi: None,
|
||||
connected: false,
|
||||
weak_since: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn state(&self) -> State {
|
||||
self.state
|
||||
}
|
||||
|
||||
pub fn last_rssi(&self) -> Option<i16> {
|
||||
self.last_rssi
|
||||
}
|
||||
|
||||
/// Feed an observed update about the target device (advertisement
|
||||
/// property change, connect/disconnect, ...).
|
||||
pub fn note_event(&mut self, now: Instant, rssi: Option<i16>, connected: Option<bool>) {
|
||||
if let Some(c) = connected {
|
||||
self.connected = c;
|
||||
}
|
||||
if let Some(r) = rssi {
|
||||
self.last_rssi = Some(r);
|
||||
}
|
||||
self.last_event = Some(now);
|
||||
}
|
||||
|
||||
/// The screen was locked successfully.
|
||||
pub fn mark_locked(&mut self) {
|
||||
if self.state == State::Suspect {
|
||||
self.state = State::Locked;
|
||||
}
|
||||
}
|
||||
|
||||
/// Evaluate the state machine. Returns Some(Action::Lock) for as long as
|
||||
/// the screen should be locked; call mark_locked() once it succeeded.
|
||||
pub fn on_tick(&mut self, now: Instant) -> Option<Action> {
|
||||
let fresh = self
|
||||
.last_event
|
||||
.is_some_and(|t| now.duration_since(t) <= self.presence_timeout);
|
||||
let strong = self.last_rssi.is_some_and(|r| r > self.rssi_lock);
|
||||
|
||||
if self.state == State::Bootstrapping {
|
||||
// Arming: never lock before the target was seen at least once,
|
||||
// so the daemon can start with the phone already away.
|
||||
if fresh {
|
||||
self.state = State::Present;
|
||||
}
|
||||
return None;
|
||||
}
|
||||
|
||||
let present = self.connected || (fresh && strong);
|
||||
if present {
|
||||
self.state = State::Present;
|
||||
self.weak_since = None;
|
||||
return None;
|
||||
}
|
||||
|
||||
if self.state == State::Present {
|
||||
self.state = State::Suspect;
|
||||
}
|
||||
if self.state != State::Suspect {
|
||||
return None;
|
||||
}
|
||||
|
||||
// Word from the device stopped arriving entirely.
|
||||
let stale = self
|
||||
.last_event
|
||||
.is_none_or(|t| now.duration_since(t) >= self.missing_after);
|
||||
if stale {
|
||||
return Some(Action::Lock);
|
||||
}
|
||||
|
||||
// Word still arriving, but the signal is too weak to trust.
|
||||
if !strong {
|
||||
let since = *self.weak_since.get_or_insert(now);
|
||||
if now.duration_since(since) >= self.missing_after {
|
||||
return Some(Action::Lock);
|
||||
}
|
||||
} else {
|
||||
self.weak_since = None;
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
pub fn duty(&self, cfg: &DutyConfig) -> Duty {
|
||||
match self.state {
|
||||
State::Bootstrapping | State::Suspect => cfg.suspect,
|
||||
State::Present => cfg.present,
|
||||
State::Locked => cfg.locked,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::time::Duration;
|
||||
|
||||
fn policy() -> Policy {
|
||||
Policy::new(Duration::from_secs(15), Duration::from_secs(30), -80)
|
||||
}
|
||||
|
||||
fn t(secs: u64) -> Instant {
|
||||
Instant::now() + Duration::from_secs(secs)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn never_locks_before_first_sighting() {
|
||||
let mut p = policy();
|
||||
for s in 0..300 {
|
||||
assert_eq!(p.on_tick(t(s)), None);
|
||||
}
|
||||
assert_eq!(p.state(), State::Bootstrapping);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn arms_on_first_sighting() {
|
||||
let mut p = policy();
|
||||
p.note_event(t(10), Some(-50), None);
|
||||
p.on_tick(t(11));
|
||||
assert_eq!(p.state(), State::Present);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stays_present_while_events_fresh_and_strong() {
|
||||
let mut p = policy();
|
||||
p.note_event(t(0), Some(-50), None);
|
||||
for s in 1..=60 {
|
||||
p.note_event(t(s), Some(-52), None);
|
||||
assert_eq!(p.on_tick(t(s)), None, "locked at {s}s");
|
||||
assert_eq!(p.state(), State::Present);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn locks_after_signal_goes_stale() {
|
||||
let mut p = policy();
|
||||
p.note_event(t(0), Some(-50), None);
|
||||
assert_eq!(p.on_tick(t(1)), None);
|
||||
assert_eq!(p.state(), State::Present);
|
||||
// Last event at t=0: presence expires at 15s, lock at 30s.
|
||||
assert_eq!(p.on_tick(t(20)), None);
|
||||
assert_eq!(p.state(), State::Suspect);
|
||||
assert_eq!(p.on_tick(t(29)), None);
|
||||
assert_eq!(p.on_tick(t(30)), Some(Action::Lock));
|
||||
p.mark_locked();
|
||||
assert_eq!(p.state(), State::Locked);
|
||||
assert_eq!(p.on_tick(t(300)), None);
|
||||
assert_eq!(p.state(), State::Locked);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lock_is_retried_until_confirmed() {
|
||||
let mut p = policy();
|
||||
p.note_event(t(0), Some(-50), None);
|
||||
p.on_tick(t(1)); // armed by the first sighting
|
||||
assert_eq!(p.on_tick(t(30)), Some(Action::Lock));
|
||||
assert_eq!(p.state(), State::Suspect);
|
||||
assert_eq!(p.on_tick(t(31)), Some(Action::Lock));
|
||||
p.mark_locked();
|
||||
assert_eq!(p.on_tick(t(32)), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn weak_signal_locks_only_after_missing_after() {
|
||||
let mut p = policy();
|
||||
p.note_event(t(0), Some(-50), None);
|
||||
p.on_tick(t(1)); // armed
|
||||
for s in 2..31 {
|
||||
p.note_event(t(s), Some(-90), None);
|
||||
assert_eq!(p.on_tick(t(s)), None, "locked at {s}s");
|
||||
assert_eq!(p.state(), State::Suspect);
|
||||
}
|
||||
// Weak continuously since t=2 -> locks at t=32.
|
||||
p.note_event(t(31), Some(-90), None);
|
||||
assert_eq!(p.on_tick(t(31)), None);
|
||||
p.note_event(t(32), Some(-90), None);
|
||||
assert_eq!(p.on_tick(t(32)), Some(Action::Lock));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn strong_signal_recovers_from_suspect() {
|
||||
let mut p = policy();
|
||||
p.note_event(t(0), Some(-50), None);
|
||||
p.on_tick(t(1));
|
||||
p.note_event(t(20), Some(-95), None);
|
||||
p.on_tick(t(20));
|
||||
assert_eq!(p.state(), State::Suspect);
|
||||
p.note_event(t(25), Some(-55), None);
|
||||
p.on_tick(t(25));
|
||||
assert_eq!(p.state(), State::Present);
|
||||
// Weak/stale clocks were reset by the recovery.
|
||||
p.note_event(t(40), Some(-90), None);
|
||||
p.on_tick(t(40));
|
||||
assert_eq!(p.on_tick(t(50)), None);
|
||||
p.note_event(t(70), Some(-90), None);
|
||||
assert_eq!(p.on_tick(t(70)), Some(Action::Lock));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn connected_device_counts_as_present() {
|
||||
let mut p = policy();
|
||||
p.note_event(t(0), None, Some(true));
|
||||
p.on_tick(t(1));
|
||||
assert_eq!(p.state(), State::Present);
|
||||
assert_eq!(p.on_tick(t(400)), None);
|
||||
assert_eq!(p.state(), State::Present);
|
||||
p.note_event(t(401), None, Some(false));
|
||||
assert_eq!(p.on_tick(t(402)), None);
|
||||
assert_eq!(p.state(), State::Suspect);
|
||||
assert_eq!(p.on_tick(t(431)), Some(Action::Lock));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resight_after_lock_returns_to_present_without_unlock() {
|
||||
let mut p = policy();
|
||||
p.note_event(t(0), Some(-50), None);
|
||||
p.on_tick(t(1));
|
||||
assert_eq!(p.on_tick(t(30)), Some(Action::Lock));
|
||||
p.mark_locked();
|
||||
assert_eq!(p.state(), State::Locked);
|
||||
p.note_event(t(100), Some(-50), None);
|
||||
p.on_tick(t(100));
|
||||
assert_eq!(p.state(), State::Present);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,318 @@
|
||||
use crate::config::{normalize_mac, Config};
|
||||
use crate::policy::{Action, Policy};
|
||||
use crate::{notify_ready, notify_stopping};
|
||||
use anyhow::{Context, Result};
|
||||
use std::collections::HashMap;
|
||||
use std::time::{Duration, Instant};
|
||||
use tokio_stream::StreamExt;
|
||||
use tracing::{debug, error, info, warn};
|
||||
use zbus::message::Type as MsgType;
|
||||
use zbus::zvariant::{OwnedObjectPath, OwnedValue, Value};
|
||||
use zbus::{Connection, MatchRule, Message, MessageStream, Proxy};
|
||||
|
||||
const BLUEZ: &str = "org.bluez";
|
||||
const DEVICE_IFACE: &str = "org.bluez.Device1";
|
||||
const ADAPTER_IFACE: &str = "org.bluez.Adapter1";
|
||||
const PROPS_IFACE: &str = "org.freedesktop.DBus.Properties";
|
||||
const OBJMGR_IFACE: &str = "org.freedesktop.DBus.ObjectManager";
|
||||
const OBJMGR_PATH: &str = "/";
|
||||
|
||||
type Props = HashMap<String, OwnedValue>;
|
||||
type InterfacesAndProps = HashMap<String, Props>;
|
||||
type ManagedObjects = HashMap<OwnedObjectPath, InterfacesAndProps>;
|
||||
|
||||
pub struct PairedDevice {
|
||||
pub address: String,
|
||||
pub alias: String,
|
||||
pub connected: bool,
|
||||
}
|
||||
|
||||
pub async fn list_paired() -> Result<Vec<PairedDevice>> {
|
||||
let conn = connect().await?;
|
||||
let objects = managed_objects(&conn).await?;
|
||||
let mut devices = Vec::new();
|
||||
for (path, ifaces) in objects {
|
||||
let Some(props) = ifaces.get(DEVICE_IFACE) else {
|
||||
continue;
|
||||
};
|
||||
if !get_bool(props, "Paired").unwrap_or(false) {
|
||||
continue;
|
||||
}
|
||||
devices.push(PairedDevice {
|
||||
address: get_str(props, "Address").unwrap_or_else(|| path.as_str().to_owned()),
|
||||
alias: get_str(props, "Alias").unwrap_or_default(),
|
||||
connected: get_bool(props, "Connected").unwrap_or(false),
|
||||
});
|
||||
}
|
||||
devices.sort_by(|a, b| a.alias.cmp(&b.alias));
|
||||
Ok(devices)
|
||||
}
|
||||
|
||||
pub async fn run(cfg: Config) -> Result<()> {
|
||||
let conn = connect().await?;
|
||||
let objects = managed_objects(&conn).await?;
|
||||
|
||||
let adapter_path = find_adapter(&objects, cfg.adapter.as_deref())
|
||||
.context("no usable Bluetooth adapter found")?;
|
||||
let adapter = Proxy::new(&conn, BLUEZ, adapter_path.clone(), ADAPTER_IFACE).await?;
|
||||
ensure_powered(&adapter).await?;
|
||||
set_discovery_filter(&adapter, cfg.rssi_floor).await?;
|
||||
|
||||
let target_mac = cfg.normalized_mac();
|
||||
// A device object may already exist from pairing or an earlier scan. We
|
||||
// only use its path to route signal events; presence is decided from live
|
||||
// events only (cached properties like RSSI go stale).
|
||||
let target = find_device_path(&objects, &target_mac).map(|path| Target { path });
|
||||
if let Some(t) = &target {
|
||||
debug!(path = %t.path, "target device object known to BlueZ");
|
||||
}
|
||||
let mut target = target;
|
||||
|
||||
info!(adapter = %adapter_path, device = %cfg.device_mac, "watching for device");
|
||||
|
||||
// PropertiesChanged from any BlueZ object (filtered to the target in
|
||||
// code), plus InterfacesAdded so the target is recognized the first time
|
||||
// it advertises after daemon start.
|
||||
let props_rule = MatchRule::builder()
|
||||
.msg_type(MsgType::Signal)
|
||||
.sender(BLUEZ)?
|
||||
.path_namespace(OBJMGR_PATH)?
|
||||
.interface(PROPS_IFACE)?
|
||||
.member("PropertiesChanged")?
|
||||
.build();
|
||||
let added_rule = MatchRule::builder()
|
||||
.msg_type(MsgType::Signal)
|
||||
.sender(BLUEZ)?
|
||||
.path(OBJMGR_PATH)?
|
||||
.interface(OBJMGR_IFACE)?
|
||||
.member("InterfacesAdded")?
|
||||
.build();
|
||||
let mut props_stream = MessageStream::for_match_rule(props_rule, &conn, None).await?;
|
||||
let mut added_stream = MessageStream::for_match_rule(added_rule, &conn, None).await?;
|
||||
|
||||
let mut policy = Policy::new(cfg.presence_timeout(), cfg.missing_after(), cfg.rssi_lock);
|
||||
let mut last_state = policy.state();
|
||||
let mut radio_on = false;
|
||||
// Fire immediately: open the first scan window right away.
|
||||
let mut next_toggle = tokio::time::Instant::now();
|
||||
|
||||
let mut tick = tokio::time::interval(Duration::from_secs(1));
|
||||
tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
|
||||
let mut term = tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())?;
|
||||
|
||||
notify_ready();
|
||||
|
||||
loop {
|
||||
tokio::select! {
|
||||
_ = tokio::time::sleep_until(next_toggle) => {
|
||||
if radio_on {
|
||||
stop_discovery(&adapter).await;
|
||||
radio_on = false;
|
||||
let d = policy.duty(&cfg.duty);
|
||||
let off = Duration::from_millis(d.interval_ms - d.window_ms);
|
||||
next_toggle = tokio::time::Instant::now() + off;
|
||||
} else {
|
||||
if let Err(e) = start_discovery(&adapter).await {
|
||||
warn!("StartDiscovery failed: {e:#}; re-checking adapter power");
|
||||
if let Err(e) = ensure_powered(&adapter).await {
|
||||
error!("adapter is unusable: {e:#}");
|
||||
}
|
||||
}
|
||||
radio_on = true;
|
||||
let window = Duration::from_millis(policy.duty(&cfg.duty).window_ms);
|
||||
next_toggle = tokio::time::Instant::now() + window;
|
||||
}
|
||||
}
|
||||
Some(msg) = props_stream.next() => match msg {
|
||||
Ok(m) => handle_props_changed(&mut policy, &mut target, &target_mac, m),
|
||||
Err(e) => warn!("D-Bus signal error: {e}"),
|
||||
},
|
||||
Some(msg) = added_stream.next() => match msg {
|
||||
Ok(m) => handle_interfaces_added(&mut policy, &mut target, &target_mac, m),
|
||||
Err(e) => warn!("D-Bus signal error: {e}"),
|
||||
},
|
||||
_ = tick.tick() => {
|
||||
if let Some(Action::Lock) = policy.on_tick(Instant::now()) {
|
||||
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:#}"),
|
||||
}
|
||||
}
|
||||
let s = policy.state();
|
||||
if s != last_state {
|
||||
info!(state = ?s, rssi = ?policy.last_rssi(), "state change");
|
||||
last_state = s;
|
||||
}
|
||||
}
|
||||
_ = tokio::signal::ctrl_c() => break,
|
||||
_ = term.recv() => break,
|
||||
}
|
||||
}
|
||||
|
||||
stop_discovery(&adapter).await;
|
||||
notify_stopping();
|
||||
info!("bye");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
struct Target {
|
||||
path: OwnedObjectPath,
|
||||
}
|
||||
|
||||
/// Extract the MAC from a device object path such as
|
||||
/// "/org/bluez/hci0/dev_AA_BB_CC_DD_EE_FF".
|
||||
fn path_mac(path: &str) -> Option<String> {
|
||||
let idx = path.rfind("dev_")?;
|
||||
Some(normalize_mac(&path[idx + 4..]))
|
||||
}
|
||||
|
||||
fn handle_props_changed(
|
||||
policy: &mut Policy,
|
||||
target: &mut Option<Target>,
|
||||
target_mac: &str,
|
||||
msg: Message,
|
||||
) {
|
||||
let Ok((iface, changed, _invalidated)) =
|
||||
msg.body().deserialize::<(String, Props, Vec<String>)>()
|
||||
else {
|
||||
return;
|
||||
};
|
||||
if iface != DEVICE_IFACE {
|
||||
return;
|
||||
}
|
||||
let header = msg.header();
|
||||
let Some(path) = header.path() else {
|
||||
return;
|
||||
};
|
||||
let known = target
|
||||
.as_ref()
|
||||
.is_some_and(|t| t.path.as_str() == path.as_str());
|
||||
if !known {
|
||||
if path_mac(path.as_str()).as_deref() != Some(target_mac) {
|
||||
return;
|
||||
}
|
||||
*target = Some(Target {
|
||||
path: path.to_owned().into(),
|
||||
});
|
||||
}
|
||||
let rssi = get_i16(&changed, "RSSI");
|
||||
let connected = get_bool(&changed, "Connected");
|
||||
debug!(path = %path, ?rssi, ?connected, "target update");
|
||||
policy.note_event(Instant::now(), rssi, connected);
|
||||
}
|
||||
|
||||
fn handle_interfaces_added(
|
||||
policy: &mut Policy,
|
||||
target: &mut Option<Target>,
|
||||
target_mac: &str,
|
||||
msg: Message,
|
||||
) {
|
||||
let Ok((path, ifaces)) = msg
|
||||
.body()
|
||||
.deserialize::<(OwnedObjectPath, InterfacesAndProps)>()
|
||||
else {
|
||||
return;
|
||||
};
|
||||
let Some(props) = ifaces.get(DEVICE_IFACE) else {
|
||||
return;
|
||||
};
|
||||
if path_mac(path.as_str()).as_deref() != Some(target_mac) {
|
||||
return;
|
||||
}
|
||||
*target = Some(Target { path: path.clone() });
|
||||
let rssi = get_i16(props, "RSSI");
|
||||
let connected = get_bool(props, "Connected");
|
||||
debug!(path = %path, ?rssi, ?connected, "target appeared");
|
||||
policy.note_event(Instant::now(), rssi, connected);
|
||||
}
|
||||
|
||||
async fn connect() -> Result<Connection> {
|
||||
Connection::system()
|
||||
.await
|
||||
.context("connecting to the system D-Bus (is BlueZ running?)")
|
||||
}
|
||||
|
||||
async fn managed_objects(conn: &Connection) -> Result<ManagedObjects> {
|
||||
let om = Proxy::new(conn, BLUEZ, OBJMGR_PATH, OBJMGR_IFACE).await?;
|
||||
om.call("GetManagedObjects", &())
|
||||
.await
|
||||
.context("calling org.bluez ObjectManager.GetManagedObjects")
|
||||
}
|
||||
|
||||
fn find_adapter(objects: &ManagedObjects, wanted: Option<&str>) -> Option<OwnedObjectPath> {
|
||||
let mut adapters: Vec<&OwnedObjectPath> = objects
|
||||
.iter()
|
||||
.filter(|(_, ifaces)| ifaces.contains_key(ADAPTER_IFACE))
|
||||
.map(|(path, _)| path)
|
||||
.collect();
|
||||
if let Some(w) = wanted {
|
||||
let suffix = format!("/{}", w.trim_start_matches('/'));
|
||||
adapters.retain(|p| p.as_str().ends_with(&suffix));
|
||||
}
|
||||
adapters.into_iter().next().cloned()
|
||||
}
|
||||
|
||||
fn find_device_path(objects: &ManagedObjects, target_mac: &str) -> Option<OwnedObjectPath> {
|
||||
objects
|
||||
.iter()
|
||||
.find(|(path, ifaces)| {
|
||||
ifaces.contains_key(DEVICE_IFACE)
|
||||
&& path_mac(path.as_str()).as_deref() == Some(target_mac)
|
||||
})
|
||||
.map(|(path, _)| path.clone())
|
||||
}
|
||||
|
||||
async fn ensure_powered(adapter: &Proxy<'_>) -> Result<()> {
|
||||
let powered: bool = adapter.get_property("Powered").await.unwrap_or(false);
|
||||
if !powered {
|
||||
info!("powering on Bluetooth adapter");
|
||||
adapter
|
||||
.set_property("Powered", true)
|
||||
.await
|
||||
.context("failed to power on the Bluetooth adapter")?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn set_discovery_filter(adapter: &Proxy<'_>, rssi_floor: i16) -> Result<()> {
|
||||
let mut filter: HashMap<&str, Value<'static>> = HashMap::new();
|
||||
filter.insert("Transport", Value::from("le"));
|
||||
filter.insert("DuplicateData", Value::from(true));
|
||||
filter.insert("RSSI", Value::from(rssi_floor));
|
||||
adapter
|
||||
.call::<_, _, ()>("SetDiscoveryFilter", &(&filter,))
|
||||
.await
|
||||
.context("setting the BLE discovery filter")?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn start_discovery(adapter: &Proxy<'_>) -> Result<()> {
|
||||
adapter
|
||||
.call::<_, _, ()>("StartDiscovery", &())
|
||||
.await
|
||||
.context("StartDiscovery")?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn stop_discovery(adapter: &Proxy<'_>) {
|
||||
if let Err(e) = adapter.call::<_, _, ()>("StopDiscovery", &()).await {
|
||||
debug!("StopDiscovery failed: {e:#}");
|
||||
}
|
||||
}
|
||||
|
||||
fn get_str(props: &Props, key: &str) -> Option<String> {
|
||||
props
|
||||
.get(key)
|
||||
.and_then(|v| String::try_from(v.clone()).ok())
|
||||
}
|
||||
|
||||
fn get_bool(props: &Props, key: &str) -> Option<bool> {
|
||||
props.get(key).and_then(|v| bool::try_from(v.clone()).ok())
|
||||
}
|
||||
|
||||
fn get_i16(props: &Props, key: &str) -> Option<i16> {
|
||||
props.get(key).and_then(|v| i16::try_from(v.clone()).ok())
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
pub mod bluez;
|
||||
|
||||
pub use bluez::{list_paired, run};
|
||||
@@ -0,0 +1,14 @@
|
||||
[Unit]
|
||||
Description=BLE proximity screen locker
|
||||
Wants=bluetooth.service
|
||||
After=bluetooth.service
|
||||
PartOf=graphical-session.target
|
||||
|
||||
[Service]
|
||||
Type=notify
|
||||
ExecStart=%h/.cargo/bin/btle-proximity --config %h/.config/btle-proximity/config.toml
|
||||
Restart=on-failure
|
||||
RestartSec=5s
|
||||
|
||||
[Install]
|
||||
WantedBy=graphical-session.target
|
||||
Reference in new issue
Block a user