9 Commits
Author SHA1 Message Date
Bastian Mäuser f697963705 Document the release checklist: registry upload is separate from release attachments
A release only visible as an attachment does not reach apt; the Debian
registry pool upload is a second, required step. Learned the hard way
when v0.2.1 shipped without it and machines stayed on 0.2.0.
2026-11-12 02:10:34 +01:00
Bastian Mäuser a74b95dca7 Bump version to 0.2.1 2026-11-12 02:06:24 +01:00
Bastian Mäuser 9da7cdb1a5 Ignore the local Gitea push token 2026-11-12 02:01:31 +01:00
Bastian Mäuser dcbe307c4a Bump sd-notify to 0.5 and toml to 1.0
sd-notify 0.5 drops the unset_environment bool from notify() (we always
passed false; the unset variant is a separate function we never used).
toml 1.x is API-compatible for our Config deserialization and its MSRV
is exactly 1.85, matching the project floor. zbus stays on 5.x: v6
requires rustc 1.89, past the Ubuntu 24.04 toolchain this repo commits
to. Resolver locked all updated deps at Rust-1.85-compatible versions.
2026-11-12 01:55:53 +01:00
Bastian Mäuser 4e4bf28508 Document missing_after_secs default as fallback only
The code default stays 30 s for configs that omit the key, but 30 s
false-locks with the companion beacon (event gaps of 25-60 s are
routine). Docs now say explicitly that shipped configs must set 60+.
2026-11-06 15:12:18 +01:00
Bastian Mäuser 923d0fc485 Fix rust-lld path in the arm64 recipe: rustc 1.85 has no rustlib-dir print 2026-11-06 12:27:06 +01:00
Bastian Mäuser e4623f33c3 Bump version to 0.2.0 2026-11-06 12:17:48 +01:00
Bastian Mäuser dcf403200a Fix probe reliability and restore sane missing_after
Two false locks with the phone present: missing_after=30 sat below the
realistic worst-case event gap (beacon counter rotation every 10s times
2-20% duty sampling, with frozen-RSSI dedupe collapsing catches inside
one window), and the connect probe ran while our own discovery
duty-cycling was active, where attempts stall or abort with
le-connection-abort-by-local.

Probe now stops discovery first and retries (2x6s); sample config and
handoff document the sampling math. Local config additionally raises
rssi_lock to -85, where nearby-phone readings were pinning.
2026-11-06 12:17:47 +01:00
Bastian Mäuser 38087583cf Document Debian installation via release and package registry
Option A adds the Gitea Debian registry as an apt source (updates land
with apt upgrade), option B installs a release .deb directly; both share
the same per-user setup steps.
2026-11-05 17:03:06 +01:00
10 changed files with 221 additions and 110 deletions

No files matched your search

+3
View File
@@ -1 +1,4 @@
/target /target
# local Gitea API token (never commit)
.gitea-push-token
+11 -2
View File
@@ -66,9 +66,18 @@ rearms monitoring. See README.md for the full design.
during a pause the phone is both undetectable and unconnectable. during a pause the phone is both undetectable and unconnectable.
- `DuplicateData = true` in the discovery filter does not bypass the - `DuplicateData = true` in the discovery filter does not bypass the
RSSI dedupe at the `Device1` property level. RSSI dedupe at the `Device1` property level.
- **Sampling math**: the beacon rotates its counter every 10 s, but the
daemon only hears it a fraction of the time (2-20% duty), and frozen
RSSI dedupes catches within one rotation window — event gaps of
25-60 s are routine. `missing_after_secs` must be well above that
(30 s false-locked twice; 60 s is the sane floor). The code default
stays 30 as a conservative fallback for configs that omit the key —
shipped configs (config.toml.example) must set 60 explicitly.
- `Device1.Connect` is the only reliable "is it actually there" oracle, - `Device1.Connect` is the only reliable "is it actually there" oracle,
and it works whenever the phone advertises. Scan-based checks cannot and it works whenever the phone advertises — but connection attempts
distinguish "silent but present" from "gone". stall or abort (`le-connection-abort-by-local`) while our own
discovery duty-cycling is active. Stop discovery before probing and
retry; do not run a single long attempt under scan contention.
- The long-term fix for all of the above is the AdvertisementMonitor - The long-term fix for all of the above is the AdvertisementMonitor
roadmap (controller-offloaded patterns, BlueZ ≥ 5.65 + Experimental). roadmap (controller-offloaded patterns, BlueZ ≥ 5.65 + Experimental).
Generated
+27 -47
View File
@@ -115,7 +115,7 @@ checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"
[[package]] [[package]]
name = "btle-proximity" name = "btle-proximity"
version = "0.1.0" version = "0.2.1"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"clap", "clap",
@@ -469,7 +469,7 @@ version = "3.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e67ba7e9b2b56446f1d419b1d807906278ffa1a658a8a5d8a39dcb1f5a78614f" checksum = "e67ba7e9b2b56446f1d419b1d807906278ffa1a658a8a5d8a39dcb1f5a78614f"
dependencies = [ dependencies = [
"toml_edit 0.25.18+spec-1.1.0", "toml_edit",
] ]
[[package]] [[package]]
@@ -534,9 +534,9 @@ checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f"
[[package]] [[package]]
name = "sd-notify" name = "sd-notify"
version = "0.4.5" version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b943eadf71d8b69e661330cb0e2656e31040acf21ee7708e2c238a0ec6af2bf4" checksum = "3e4ef7359e694bfaf1dd27a30f9d760b54c00dfae9f19bd0c05a39bc9128fe76"
dependencies = [ dependencies = [
"libc", "libc",
] ]
@@ -584,11 +584,11 @@ dependencies = [
[[package]] [[package]]
name = "serde_spanned" name = "serde_spanned"
version = "0.6.9" version = "1.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bf41e0cfaf7226dca15e8197172c295a782857fcb97fad1808a166870dee75a3" checksum = "9c187e0a369471c550af028cba56d4f4fa2a489ad28151ae95a4d340a2a8b782"
dependencies = [ dependencies = [
"serde", "serde_core",
] ]
[[package]] [[package]]
@@ -723,46 +723,26 @@ dependencies = [
[[package]] [[package]]
name = "toml" name = "toml"
version = "0.8.23" version = "1.2.1+spec-1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dc1beb996b9d83529a9e75c17a1686767d148d70663143c7854d8b4a09ced362" checksum = "d5755c51863cdac711f1956baf8eb9588e060755f7d3c4c979e70ea1e1f32cd7"
dependencies = [
"serde",
"serde_spanned",
"toml_datetime 0.6.11",
"toml_edit 0.22.27",
]
[[package]]
name = "toml_datetime"
version = "0.6.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "22cddaf88f4fbc13c51aebbf5f8eceb5c7c5a9da2ac40a13519eb5b0a0e8f11c"
dependencies = [
"serde",
]
[[package]]
name = "toml_datetime"
version = "1.1.2+spec-1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2b86d767906c6c42421dcba507eb9d203e779497710a47782a224bb871653053"
dependencies = [
"serde_core",
]
[[package]]
name = "toml_edit"
version = "0.22.27"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "41fe8c660ae4257887cf66394862d21dbca4a6ddd26f04a3560410406a2f819a"
dependencies = [ dependencies = [
"indexmap", "indexmap",
"serde", "serde_core",
"serde_spanned", "serde_spanned",
"toml_datetime 0.6.11", "toml_datetime",
"toml_write", "toml_parser",
"winnow 0.7.15", "toml_writer",
"winnow 1.0.5",
]
[[package]]
name = "toml_datetime"
version = "1.1.3+spec-1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "173f25c883cd2176a2d8212155638c0a60d484a9d84546d270866f40f56b6e49"
dependencies = [
"serde_core",
] ]
[[package]] [[package]]
@@ -772,7 +752,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1ec6e78bd70db9420d8d212fa9dc97f116448a1ceff5d00eabb991d407e21396" checksum = "1ec6e78bd70db9420d8d212fa9dc97f116448a1ceff5d00eabb991d407e21396"
dependencies = [ dependencies = [
"indexmap", "indexmap",
"toml_datetime 1.1.2+spec-1.1.0", "toml_datetime",
"toml_parser", "toml_parser",
"winnow 1.0.5", "winnow 1.0.5",
] ]
@@ -787,10 +767,10 @@ dependencies = [
] ]
[[package]] [[package]]
name = "toml_write" name = "toml_writer"
version = "0.1.2" version = "1.2.0+spec-1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5d99f8c9a7727884afe522e9bd5edbfc91a3312b36a77b5fb8926e4c31a41801" checksum = "009dbb7700f11c55ef83aebbe4c0e9cf1f1ac0844bd8d6f00dc38f302026e13a"
[[package]] [[package]]
name = "tracing" name = "tracing"
+3 -3
View File
@@ -1,6 +1,6 @@
[package] [package]
name = "btle-proximity" name = "btle-proximity"
version = "0.1.0" version = "0.2.1"
edition = "2021" edition = "2021"
rust-version = "1.85" rust-version = "1.85"
resolver = "3" resolver = "3"
@@ -31,11 +31,11 @@ assets = [
[dependencies] [dependencies]
anyhow = "1" anyhow = "1"
clap = { version = "4", features = ["derive"] } clap = { version = "4", features = ["derive"] }
sd-notify = "0.4" sd-notify = "0.5"
serde = { version = "1", features = ["derive"] } serde = { version = "1", features = ["derive"] }
tokio = { version = "1", features = ["macros", "process", "rt-multi-thread", "signal", "time"] } tokio = { version = "1", features = ["macros", "process", "rt-multi-thread", "signal", "time"] }
tokio-stream = "0.1" tokio-stream = "0.1"
toml = "0.8" toml = "1"
tracing = "0.1" tracing = "0.1"
tracing-subscriber = { version = "0.3", features = ["env-filter"] } tracing-subscriber = { version = "0.3", features = ["env-filter"] }
zbus = { version = "5", default-features = false, features = ["tokio"] } zbus = { version = "5", default-features = false, features = ["tokio"] }
+77 -14
View File
@@ -59,7 +59,57 @@ proof of absence.
factor; OS-generated advertisements (Fast Pair, Continuity) are too factor; OS-generated advertisements (Fast Pair, Continuity) are too
intermittent to rely on. intermittent to rely on.
## Build & install ## Install (Debian packages)
Prebuilt `.deb` packages for amd64 and arm64 are attached to the
[releases](https://git.netz.org/bmaeuser/btle-proximity/releases) and
available through the Gitea Debian package registry.
### Option A — apt repository (recommended, delivers updates)
```sh
sudo install -d /etc/apt/keyrings
curl -fsSL https://git.netz.org/api/packages/bmaeuser/debian/repository.key \
| sudo gpg --dearmor -o /etc/apt/keyrings/btle-proximity.gpg
echo "deb [signed-by=/etc/apt/keyrings/btle-proximity.gpg] https://git.netz.org/api/packages/bmaeuser/debian stable main" \
| sudo tee /etc/apt/sources.list.d/btle-proximity.list
sudo apt update
sudo apt install btle-proximity
```
Future releases land with the usual `apt upgrade`.
### Option B — manual .deb from a release
```sh
curl -fLO https://git.netz.org/bmaeuser/btle-proximity/releases/download/v0.1.0/btle-proximity_0.1.0-1_amd64.deb
sudo apt install ./btle-proximity_0.1.0-1_amd64.deb
# arm64: btle-proximity_0.1.0-1_arm64.deb (fully static musl binary)
```
Both options install the binary to `/usr/bin`, the user unit to
`/usr/lib/systemd/user/`, a man page and the config example to
`/usr/share/doc/btle-proximity/`.
### Per-user setup
```sh
mkdir -p ~/.config/btle-proximity
cp /usr/share/doc/btle-proximity/examples/config.toml ~/.config/btle-proximity/config.toml
btle-proximity list-paired # pick your phone's MAC, edit config.toml
systemctl --user enable --now btle-proximity
journalctl --user -u btle-proximity -f
```
Coming from the `cargo install` flow? Remove that copy first
(`cargo uninstall btle-proximity`) and the unit copied to
`~/.config/systemd/user/`, so neither shadows the package.
The Android app (`btle-proximity-beacon-release.apk`) is attached to the
same releases; Obtainium can track the repo for automatic updates — see
`android/README.md`.
## Build & install from source
```sh ```sh
cargo install --path . # installs to ~/.cargo/bin cargo install --path . # installs to ~/.cargo/bin
@@ -83,24 +133,15 @@ RUST_LOG=debug btle-proximity --dry-run
``` ```
Tune `rssi_lock` / `presence_timeout_secs` / `missing_after_secs` to your Tune `rssi_lock` / `presence_timeout_secs` / `missing_after_secs` to your
room. Then install the user service (runs inside your session, Type=notify): room.
### Debian package ### Building the Debian packages
```sh ```sh
cargo install cargo-deb --version 2.12.1 # 3.x needs rustc > 1.85 cargo install cargo-deb --version 2.12.1 # 3.x needs rustc > 1.85
cargo deb # -> target/debian/btle-proximity_*.deb cargo deb # -> target/debian/btle-proximity_*.deb
sudo apt install ./target/debian/btle-proximity_0.1.0-1_amd64.deb
systemctl --user enable --now btle-proximity
``` ```
Installs the binary to `/usr/bin`, the user unit to
`/usr/lib/systemd/user/`, a man page and the config example to
`/usr/share/doc/btle-proximity/`. Per-user config still lives at
`~/.config/btle-proximity/config.toml`. If you previously installed via
`cargo install`, remove that copy (`cargo uninstall btle-proximity`) to
avoid PATH shadowing.
#### arm64 (aarch64) #### arm64 (aarch64)
Cross-built as a **static musl binary**, so no cross-gcc/sysroot is needed Cross-built as a **static musl binary**, so no cross-gcc/sysroot is needed
@@ -111,7 +152,7 @@ an isolated rustup under `/tmp` so the distro cargo is not touched:
export RUSTUP_HOME=/tmp/rustup CARGO_HOME=/tmp/rustup-cargo PATH=/tmp/rustup-cargo/bin:$PATH export RUSTUP_HOME=/tmp/rustup CARGO_HOME=/tmp/rustup-cargo PATH=/tmp/rustup-cargo/bin:$PATH
curl -sSf https://sh.rustup.rs | sh -s -- -y --default-toolchain 1.85.0 --profile minimal --no-modify-path curl -sSf https://sh.rustup.rs | sh -s -- -y --default-toolchain 1.85.0 --profile minimal --no-modify-path
rustup target add aarch64-unknown-linux-musl rustup target add aarch64-unknown-linux-musl
mkdir -p /tmp/lld-bin && ln -sf "$(rustc --print rustlib-dir)"/x86_64-unknown-linux-gnu/bin/rust-lld /tmp/lld-bin/ld.lld mkdir -p /tmp/lld-bin && ln -sf "$(rustc --print sysroot)"/lib/rustlib/x86_64-unknown-linux-gnu/bin/rust-lld /tmp/lld-bin/ld.lld
export CARGO_TARGET_AARCH64_UNKNOWN_LINUX_MUSL_LINKER=/tmp/lld-bin/ld.lld export CARGO_TARGET_AARCH64_UNKNOWN_LINUX_MUSL_LINKER=/tmp/lld-bin/ld.lld
~/.cargo/bin/cargo-deb --target aarch64-unknown-linux-musl --no-strip ~/.cargo/bin/cargo-deb --target aarch64-unknown-linux-musl --no-strip
# -> target/aarch64-unknown-linux-musl/debian/btle-proximity_*_arm64.deb # -> target/aarch64-unknown-linux-musl/debian/btle-proximity_*_arm64.deb
@@ -120,8 +161,30 @@ export CARGO_TARGET_AARCH64_UNKNOWN_LINUX_MUSL_LINKER=/tmp/lld-bin/ld.lld
The `--no-strip` matters: the release profile already strips via the The `--no-strip` matters: the release profile already strips via the
linker, and the host `strip` cannot read aarch64 objects. linker, and the host `strip` cannot read aarch64 objects.
#### Publishing a release (checklist)
A release is visible in two **separate** places, and both must be fed or
`apt upgrade` silently stays on the old version:
1. **Release attachments** (manual downloads):
`POST /api/v1/repos/bmaeuser/btle-proximity/releases` with the tag, then
upload the debs (and the beacon APK) as release assets.
2. **Debian package registry** (what `apt update` actually reads):
```sh
curl --upload-file btle-proximity_0.2.1-1_amd64.deb \
-u bmaeuser:<token> \
https://git.netz.org/api/packages/bmaeuser/debian/pool/stable/main/upload
# repeat for arm64; then verify the new version appears in:
curl https://git.netz.org/api/packages/bmaeuser/debian/dists/stable/main/binary-amd64/Packages
curl https://git.netz.org/api/packages/bmaeuser/debian/dists/stable/main/binary-arm64/Packages
```
### Manual install (dev flow) ### Manual install (dev flow)
The unit in `systemd/` runs the cargo-installed binary
(`%h/.cargo/bin/btle-proximity`); the packaged variant under
`packaging/` points at `/usr/bin` instead.
```sh ```sh
cp systemd/btle-proximity.service ~/.config/systemd/user/ cp systemd/btle-proximity.service ~/.config/systemd/user/
systemctl --user daemon-reload systemctl --user daemon-reload
@@ -135,7 +198,7 @@ See `config.toml.example`; every knob is documented there. Highlights:
| key | default | meaning | | key | default | meaning |
| ---------------------- | ------- | ------------------------------------------ | | ---------------------- | ------- | ------------------------------------------ |
| `device_mac` | — | identity MAC of the paired phone | | `device_mac` | — | identity MAC of the paired phone |
| `missing_after_secs` | 30 | absence confirmation before locking | | `missing_after_secs` | 30 (use 60+) | absence confirmation; 30 is only the fallback, false-locks with the companion app |
| `presence_timeout_secs`| 15 | how fresh an update must be to count | | `presence_timeout_secs`| 15 | how fresh an update must be to count |
| `rssi_floor` / `rssi_lock` | -90/-80 | discovery floor / out-of-range threshold | | `rssi_floor` / `rssi_lock` | -90/-80 | discovery floor / out-of-range threshold |
| `duty.*` | see file| per-state scan window/interval | | `duty.*` | see file| per-state scan window/interval |
+12 -8
View File
@@ -6,14 +6,15 @@ device_mac = "AA:BB:CC:DD:EE:FF"
#adapter = "hci0" #adapter = "hci0"
# Lock the session after this long without strong evidence of presence. # Lock the session after this long without strong evidence of presence.
# Before locking, the daemon additionally probes the phone with a 10s # Before locking, the daemon additionally probes the phone with a short
# connection attempt, which cancels the lock if the phone answers. # connection attempt (2 tries, discovery paused), which cancels the lock
# 30s is safe with the companion beacon app (android/): it advertises # if the phone answers. Keep in mind the sampling math: the beacon
# reliably from a foreground service and rotates its payload so the # rotates its counter every 10 s, but the daemon only hears it a fraction
# daemon always sees fresh evidence. Third-party beacon apps pause # of the time (2-20% duty), so event gaps of 25-60 s are routine when
# advertising while the phone sits still — with those, raise this to # the RSSI is frozen — 30 s false-locked in practice. 60 s is a sane
# 120s or expect occasional false locks. # default with the companion app; third-party beacon apps that pause
missing_after_secs = 30 # advertising warrant 120 s.
missing_after_secs = 60
# Advertisement updates newer than this count as "recently seen". # Advertisement updates newer than this count as "recently seen".
# Once updates stall past half of this, the radio steps up to the # Once updates stall past half of this, the radio steps up to the
@@ -24,6 +25,9 @@ presence_timeout_secs = 15
rssi_floor = -90 rssi_floor = -90
# At or below this RSSI the device counts as out of range (dBm). # At or below this RSSI the device counts as out of range (dBm).
# Watch your desk readings (sighting reports in the journal): if a
# nearby phone pins at the threshold, raise this — e.g. -85 when
# readings hover around -80.
rssi_lock = -80 rssi_lock = -80
# Scan duty cycle per state: radio on for window_ms, then rest until # Scan duty cycle per state: radio on for window_ms, then rest until
+40
View File
@@ -4,6 +4,46 @@ Dated notes for picking this project back up: what happened, what was
learned, and which threads are still open. AGENTS.md carries the distilled learned, and which threads are still open. AGENTS.md carries the distilled
rules; this file carries the history behind them. rules; this file carries the history behind them.
## 2026-11-06 — two more false locks: sampling math and probe contention
**Symptoms.** Two false locks while the user was present: 11:24:24 (RSSI
-64, strong, phone advertising) and 11:57:30 (RSSI -82 after 10 minutes
pinned at -78..-82).
**Root causes.**
1. *`missing_after = 30` sat below the realistic worst-case event gap.*
The beacon rotates its ServiceData counter every 10 s, but the daemon
only *samples* the radio (2-20% duty). When the RSSI is frozen (BlueZ
dedupe), catches within one rotation window dedupe to nothing, so
event gaps of 25-60 s are routine — e.g. 11:56:32 → 11:57:30 (58 s
gap) reached `missing_after` and triggered a probe.
2. *The connect probe ran while our own discovery duty-cycling was
active.* With the phone in range and advertising, the probe still
stalled for its whole window and BlueZ returned
`le-connection-abort-by-local` — controller contention between our
scan windows and the connection attempt. The probe is the last line
of defense and was not reliable under load.
**Fixes shipped.**
- Probe: 2 attempts × 6 s with a 1 s pause, and discovery is stopped
before probing so the connection attempt gets a clean radio.
- `missing_after = 60` with the companion app (30 s is not enough given
the sampling math; third-party beacons still warrant 120 s).
- Local config: `rssi_lock = -85` — nearby-phone readings pinned at
-78..-82 dBm sat exactly on the -80 threshold and made the weak-signal
path flap constantly. Watch desk readings via the sighting reports.
**Lingering observations.**
- Desk RSSI varies hugely day to day (-44..-65 one day, -52..-86 the
next): interference, phone position, TX power. The `rssi_lock`
threshold needs headroom against this variance.
- `le-connection-abort-by-local` at probe time is now expected only when
our 6 s timeout cancels the attempt (zbus drops the call → bluetoothd
aborts); the retry covers the transient case.
## 2026-11-05 — false-lock debugging session ## 2026-11-05 — false-lock debugging session
**Symptoms.** The daemon flipped Present⇄Suspect every minute or so and **Symptoms.** The daemon flipped Present⇄Suspect every minute or so and
+2
View File
@@ -6,6 +6,8 @@ use std::time::Duration;
fn presence_timeout_secs() -> u64 { fn presence_timeout_secs() -> u64 {
15 15
} }
/// Fallback for configs that omit the key. 30 s false-locks with the
/// companion beacon (see config.toml.example); real configs should set 60.
fn missing_after_secs() -> u64 { fn missing_after_secs() -> u64 {
30 30
} }
+2 -2
View File
@@ -83,9 +83,9 @@ async fn run(cli: Cli) -> Result<()> {
} }
pub fn notify_ready() { pub fn notify_ready() {
let _ = sd_notify::notify(false, &[sd_notify::NotifyState::Ready]); let _ = sd_notify::notify(&[sd_notify::NotifyState::Ready]);
} }
pub fn notify_stopping() { pub fn notify_stopping() {
let _ = sd_notify::notify(false, &[sd_notify::NotifyState::Stopping]); let _ = sd_notify::notify(&[sd_notify::NotifyState::Stopping]);
} }
+44 -34
View File
@@ -152,7 +152,13 @@ pub async fn run(cfg: Config) -> Result<()> {
// LE connection attempt. A phone in range accepts it even // LE connection attempt. A phone in range accepts it even
// when advertisement updates have gone quiet (BlueZ // when advertisement updates have gone quiet (BlueZ
// dedupes identical RSSI values), so silence alone is not // dedupes identical RSSI values), so silence alone is not
// proof of absence. // proof of absence. Stop scanning first: a connection
// attempt does not complete reliably while our own
// discovery duty-cycling contends with it.
if radio_on {
stop_discovery(&adapter).await;
radio_on = false;
}
if probe_reachable(&conn, target.as_ref()).await { if probe_reachable(&conn, target.as_ref()).await {
info!("connect probe: phone in range, not locking"); info!("connect probe: phone in range, not locking");
policy.note_event(Instant::now(), None, Some(true)); policy.note_event(Instant::now(), None, Some(true));
@@ -207,11 +213,13 @@ struct Target {
path: OwnedObjectPath, path: OwnedObjectPath,
} }
/// How long to wait for the connect probe before concluding the phone is /// The probe runs while our own discovery duty-cycling is active, and on
/// gone. The controller scans for the phone's advertisements for this whole /// this controller a connection attempt can stall or be aborted under that
/// window, so slow or intermittent advertising still gets caught; aborting /// contention ("le-connection-abort-by-local"). So: keep each attempt short,
/// cancels BlueZ's connection attempt. /// retry before concluding absence, and let the caller stop discovery first.
const PROBE_TIMEOUT: Duration = Duration::from_secs(10); const PROBE_ATTEMPTS: usize = 2;
const PROBE_TIMEOUT: Duration = Duration::from_secs(6);
const PROBE_RETRY_PAUSE: Duration = Duration::from_secs(1);
/// Attempt a short LE connection to the paired phone. Returns true if the /// 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 /// device accepted the connection (it is in range); the connection is closed
@@ -227,37 +235,39 @@ async fn probe_reachable(conn: &Connection, target: Option<&Target>) -> bool {
return false; return false;
} }
}; };
match tokio::time::timeout(PROBE_TIMEOUT, proxy.call::<_, _, ()>("Connect", &())).await { for attempt in 0..PROBE_ATTEMPTS {
Ok(Ok(())) => { if attempt > 0 {
if let Err(e) = tokio::time::timeout( tokio::time::sleep(PROBE_RETRY_PAUSE).await;
Duration::from_secs(1), }
proxy.call::<_, _, ()>("Disconnect", &()), match tokio::time::timeout(PROBE_TIMEOUT, proxy.call::<_, _, ()>("Connect", &())).await {
) Ok(Ok(())) => {
.await if let Err(e) = tokio::time::timeout(
{ Duration::from_secs(1),
debug!("probe: disconnect failed: {e:#}"); proxy.call::<_, _, ()>("Disconnect", &()),
)
.await
{
debug!("probe: disconnect failed: {e:#}");
}
return true;
}
Ok(Err(e)) => {
info!("probe: connect rejected (attempt {attempt}): {e:#}");
}
Err(_) => {
info!("probe: attempt {attempt} 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;
} }
true
}
Ok(Err(e)) => {
info!("probe: connect rejected: {e:#}");
false
}
Err(_) => {
warn!(
"probe: no connection within {}s, treating phone as out of range",
PROBE_TIMEOUT.as_secs()
);
// 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
} }
} }
warn!("probe: no connection after {PROBE_ATTEMPTS} attempts, treating phone as out of range");
false
} }
/// Extract the MAC from a device object path such as /// Extract the MAC from a device object path such as