From 2d0b3fd5a8fa9a9a47a912f8a84cc375f718cf28 Mon Sep 17 00:00:00 2001 From: pepperstm Date: Thu, 12 Nov 2026 13:31:53 +0000 Subject: [PATCH] Remember sensors and reconnect them at launch Bluetooth sensors are remembered once connected. At launch the app looks for them for three minutes and connects each one as it wakes, and looks again when the Devices page or ride setup opens. The Devices page shows the ones it's still looking for, with Forget. Remove forgets a sensor too. The ANT+ stick is turned on again at launch if it was on, since ANT+ pairs whichever sensors are near rather than a list. --- README.md | 3 +- src-tauri/src/commands.rs | 24 ++++++ src-tauri/src/devices/ble.rs | 151 ++++++++++++++++++++++++++--------- src-tauri/src/devices/mod.rs | 94 +++++++++++++++++++++- src-tauri/src/main.rs | 15 ++++ web/src/bridge.ts | 6 +- web/src/state.ts | 2 +- web/src/types.ts | 2 + web/src/ui/Devices.tsx | 19 ++++- web/src/ui/RideSetup.tsx | 2 + 10 files changed, 272 insertions(+), 46 deletions(-) diff --git a/README.md b/README.md index a667b4f..5b539c9 100644 --- a/README.md +++ b/README.md @@ -134,7 +134,7 @@ To pair a device: 4. It joins the list with its kind (*Smart trainer*, *Power meter*, *Heart rate*, *Cadence*, *Speed* or *Controller*) and *Connected*, with its live readings. A trainer says *controllable* when VeloPopuli can set its resistance, or *read-only* when it can only read it. 5. Add the others the same way. When two devices measure the same thing, the most direct one is used. -If a device drops out (it goes to sleep, the trainer is switched off) it shows *Signal lost — searching…* and reconnects by itself when it's back. **Remove** disconnects it. Devices aren't remembered between launches yet, so add them again after opening the app. +If a device drops out (it goes to sleep, the trainer is switched off) it shows *Signal lost — searching…* and reconnects by itself when it's back. Bluetooth devices are remembered: when you next open the app it looks for them for a few minutes and connects each one as it wakes, and the Devices page shows which it's still looking for. **Remove** disconnects a device and forgets it; **Forget** does the same for one it's still looking for. If the ANT+ stick was on, it's turned on again too. - **macOS:** the first search asks for Bluetooth permission. - **Linux:** needs BlueZ running. @@ -203,7 +203,6 @@ Your browser opens for approval. The key and tokens are stored in the system key - Native renderer: Windows and Linux, and making it the default - More from OpenStreetMap: mapped roof shapes, other land cover (farmland, rock, glaciers), mapped leaf types, squares and car parks - Wahoo legacy protocol and steering; Di2 and Zwift Click/Play controllers as shifters for virtual gears without a bridge -- Remembering devices between launches ### Stretch: self-hosted group-ride servers diff --git a/src-tauri/src/commands.rs b/src-tauri/src/commands.rs index 18052e8..28311ba 100644 --- a/src-tauri/src/commands.rs +++ b/src-tauri/src/commands.rs @@ -194,13 +194,31 @@ pub async fn ble_connect(state: State<'_, AppState>, id: String) -> Res<()> { state.ble.connect(state.devices.clone(), &id).await } +/// Looks for the remembered Bluetooth sensors that aren't connected, for a few minutes. +#[tauri::command] +pub async fn devices_look_for_known(state: State<'_, AppState>) -> Res<()> { + state.ble.look_for_known(state.devices.clone()).await +} + +/// Stops reconnecting a remembered Bluetooth sensor at launch. +#[tauri::command] +pub fn device_forget(state: State, id: String) { + state.devices.change_remembered(|r| { + r.forget_ble(&id); + }); + let pending = state.devices.snapshot().looking_for.into_iter().filter(|k| k.id != id).collect(); + state.devices.set_looking_for(pending); +} + #[tauri::command] pub fn ant_start(state: State) { + state.devices.change_remembered(|r| r.ant = true); state.ant.start(state.devices.clone()); } #[tauri::command] pub fn ant_stop(state: State) { + state.devices.change_remembered(|r| r.ant = false); state.ant.stop(); } @@ -214,9 +232,15 @@ pub fn demo_nudge(state: State, delta: f64) { state.demo.nudge(delta); } +/// Disconnects a device. A Bluetooth one is forgotten too, so it isn't reconnected at launch. #[tauri::command] pub fn device_remove(state: State, id: String) { state.devices.remove(&id); + if let Some(peripheral) = id.strip_prefix("ble:") { + state.devices.change_remembered(|r| { + r.forget_ble(peripheral); + }); + } } // ── Ride ─────────────────────────────────────────────────────────────────── diff --git a/src-tauri/src/devices/ble.rs b/src-tauri/src/devices/ble.rs index 06f0a70..62fa135 100644 --- a/src-tauri/src/devices/ble.rs +++ b/src-tauri/src/devices/ble.rs @@ -31,9 +31,17 @@ pub struct Candidate { #[derive(Default)] pub struct Ble { adapter: OnceCell, + /// The rider is searching for a device to add. scanning: Arc, + /// The app is looking for remembered sensors to connect again. + looking: Arc, } +/// How long to look for remembered sensors after launch: long enough to wake them. +const LOOK_FOR: Duration = Duration::from_secs(180); +/// How soon to try a remembered sensor again after a failed attempt. +const RETRY_AFTER: Duration = Duration::from_secs(15); + /// What a device must advertise to be listed: a cycling sensor, or an OpenBikeControl controller. fn sensor_services() -> [Uuid; 6] { [uuid_from_u16(SVC_FTMS), uuid_from_u16(SVC_CYCLING_POWER), uuid_from_u16(SVC_HEART_RATE), uuid_from_u16(SVC_CSC), Uuid::from_u128(SVC_TACX_FEC), Uuid::from_u128(SVC_OBC)] @@ -71,7 +79,7 @@ impl Ble { if self.scanning.swap(true, Ordering::SeqCst) { return Ok(()); } - let scanning = self.scanning.clone(); + let (scanning, looking) = (self.scanning.clone(), self.looking.clone()); tauri::async_runtime::spawn(async move { let wanted = sensor_services(); let mut sent: Vec = Vec::new(); @@ -105,12 +113,71 @@ impl Ble { } tokio::time::sleep(Duration::from_millis(600)).await; } - let _ = adapter.stop_scan().await; + // Leave the radio on while remembered sensors are still being looked for. + if !looking.load(Ordering::SeqCst) { + let _ = adapter.stop_scan().await; + } diag::event("ble", "scan stopped"); }); Ok(()) } + /// Looks for the remembered sensors for a few minutes and connects each one as it is heard. + /// Does nothing when none are missing or a search is already running. + pub async fn look_for_known(&self, devices: Arc) -> Result<(), String> { + let missing = |devices: &Devices| devices.remembered().ble.into_iter().filter(|k| !devices.contains(&format!("ble:{}", k.id))).collect::>(); + if missing(&devices).is_empty() || self.looking.swap(true, Ordering::SeqCst) { + return Ok(()); + } + let adapter = match self.adapter().await { + Ok(a) => a.clone(), + Err(e) => { + self.looking.store(false, Ordering::SeqCst); + return Err(e); + } + }; + if let Err(e) = adapter.start_scan(ScanFilter::default()).await { + self.looking.store(false, Ordering::SeqCst); + diag::event("ble", format!("scan for remembered sensors failed: {e}")); + return Err(format!("Could not start a Bluetooth scan: {e}")); + } + diag::event("ble", "looking for remembered sensors"); + let (scanning, looking) = (self.scanning.clone(), self.looking.clone()); + tauri::async_runtime::spawn(async move { + let until = tokio::time::Instant::now() + LOOK_FOR; + let mut tried: std::collections::HashMap = std::collections::HashMap::new(); + loop { + let pending = missing(&devices); + devices.set_looking_for(pending.clone()); + if pending.is_empty() || tokio::time::Instant::now() > until { + break; + } + for p in adapter.peripherals().await.unwrap_or_default() { + let pid = p.id().to_string(); + if !pending.iter().any(|k| k.id == pid) || tried.get(&pid).is_some_and(|t| t.elapsed() < RETRY_AFTER) { + continue; + } + tried.insert(pid.clone(), tokio::time::Instant::now()); + diag::event("ble", format!("heard remembered sensor id={pid}, connecting")); + let devices = devices.clone(); + tauri::async_runtime::spawn(async move { + if let Err(e) = open_link(devices, p, &pid).await { + diag::event("ble", format!("remembered sensor id={pid}: {e}")); + } + }); + } + tokio::time::sleep(Duration::from_secs(1)).await; + } + devices.set_looking_for(Vec::new()); + looking.store(false, Ordering::SeqCst); + if !scanning.load(Ordering::SeqCst) { + let _ = adapter.stop_scan().await; + } + diag::event("ble", "stopped looking for remembered sensors"); + }); + Ok(()) + } + pub fn scan_stop(&self) { self.scanning.store(false, Ordering::SeqCst); } @@ -119,44 +186,52 @@ impl Ble { pub async fn connect(&self, devices: Arc, peripheral_id: &str) -> Result<(), String> { let adapter = self.adapter().await?; let peripheral = adapter.peripherals().await.map_err(err)?.into_iter().find(|p| p.id().to_string() == peripheral_id).ok_or("That sensor is no longer in range.")?; - let name = peripheral.properties().await.ok().flatten().and_then(|p| p.local_name).filter(|n| !n.is_empty()).unwrap_or_else(|| "Bluetooth sensor".into()); - let id = format!("ble:{peripheral_id}"); - diag::event("dev", format!("dev={id} name={name:?} connecting")); - - let (control_tx, control_rx) = mpsc::unbounded_channel::(); - let (stop_tx, stop_rx) = watch::channel(false); - let info = DeviceInfo { id: id.clone(), name, transport: Transport::Ble, kind: DeviceKind::Hr, status: DeviceStatus::Connecting, controllable: false, readings: Readings::default() }; - let handle = Handle { - control: Some(Box::new(move |cmd| { - let _ = control_tx.send(cmd); - })), - stop: Box::new(move || { - let _ = stop_tx.send(true); - }), - }; - if !devices.add(info, handle) { - return Ok(()); - } + open_link(devices, peripheral, peripheral_id).await + } +} - let mut link = Link { peripheral, devices: devices.clone(), id: id.clone(), control_rx, stop_rx }; - let first = match tokio::time::timeout(Duration::from_secs(25), link.open()).await { - Ok(Ok(session)) => session, - Ok(Err(e)) => { - diag::event("dev", format!("dev={id} first connection failed: {e}")); - devices.remove(&id); - let _ = link.peripheral.disconnect().await; - return Err(e); - } - Err(_) => { - diag::event("dev", format!("dev={id} first connection failed: timed out after 25 s")); - devices.remove(&id); - let _ = link.peripheral.disconnect().await; - return Err("Timed out connecting to the sensor.".into()); - } - }; - tauri::async_runtime::spawn(link.run(first)); - Ok(()) +/// Connects to a peripheral, remembers it once the first connection works, and keeps it +/// connected until it is removed. +async fn open_link(devices: Arc, peripheral: Peripheral, peripheral_id: &str) -> Result<(), String> { + let name = peripheral.properties().await.ok().flatten().and_then(|p| p.local_name).filter(|n| !n.is_empty()).unwrap_or_else(|| "Bluetooth sensor".into()); + let id = format!("ble:{peripheral_id}"); + diag::event("dev", format!("dev={id} name={name:?} connecting")); + + let (control_tx, control_rx) = mpsc::unbounded_channel::(); + let (stop_tx, stop_rx) = watch::channel(false); + let info = DeviceInfo { id: id.clone(), name, transport: Transport::Ble, kind: DeviceKind::Hr, status: DeviceStatus::Connecting, controllable: false, readings: Readings::default() }; + let handle = Handle { + control: Some(Box::new(move |cmd| { + let _ = control_tx.send(cmd); + })), + stop: Box::new(move || { + let _ = stop_tx.send(true); + }), + }; + if !devices.add(info, handle) { + return Ok(()); } + + let mut link = Link { peripheral, devices: devices.clone(), id: id.clone(), control_rx, stop_rx }; + let first = match tokio::time::timeout(Duration::from_secs(25), link.open()).await { + Ok(Ok(session)) => session, + Ok(Err(e)) => { + diag::event("dev", format!("dev={id} first connection failed: {e}")); + devices.remove(&id); + let _ = link.peripheral.disconnect().await; + return Err(e); + } + Err(_) => { + diag::event("dev", format!("dev={id} first connection failed: timed out after 25 s")); + devices.remove(&id); + let _ = link.peripheral.disconnect().await; + return Err("Timed out connecting to the sensor.".into()); + } + }; + let name = devices.snapshot().devices.into_iter().find(|d| d.id == id).map(|d| d.name).unwrap_or_default(); + devices.change_remembered(|r| r.add_ble(peripheral_id, &name)); + tauri::async_runtime::spawn(link.run(first)); + Ok(()) } /// What a connected peripheral offers, resolved once per connection. diff --git a/src-tauri/src/devices/mod.rs b/src-tauri/src/devices/mod.rs index b93f5cf..48ace3c 100644 --- a/src-tauri/src/devices/mod.rs +++ b/src-tauri/src/devices/mod.rs @@ -7,7 +7,7 @@ pub mod sim; use std::collections::HashMap; use std::sync::Mutex; -use serde::Serialize; +use serde::{Deserialize, Serialize}; use tauri::{AppHandle, Emitter, Manager}; use velopopuli_core::devices::obc; use velopopuli_core::devices::{DeviceInfo, DeviceStatus, Hub, Readings, Telemetry, TrainerCommand}; @@ -28,25 +28,94 @@ pub struct AntStatus { } #[derive(Clone, Serialize)] +#[serde(rename_all = "camelCase")] pub struct DevicesSnapshot { pub devices: Vec, pub ant: AntStatus, + /// Remembered Bluetooth sensors not connected yet, while the app looks for them. + pub looking_for: Vec, } +/// A Bluetooth sensor connected before, to connect again at launch. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct KnownBle { + /// The operating system's id for the peripheral (without the `ble:` prefix). + pub id: String, + pub name: String, +} + +/// The sensors to reconnect at launch, kept in the store as `devices`. +#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)] +pub struct Remembered { + #[serde(default)] + pub ble: Vec, + /// The ANT+ stick was on: start it again. ANT+ pairs whichever sensors are near, so there + /// is no list of them to keep. + #[serde(default)] + pub ant: bool, +} + +impl Remembered { + /// Adds a sensor, or renames it if it is already there. + pub fn add_ble(&mut self, id: &str, name: &str) { + match self.ble.iter_mut().find(|k| k.id == id) { + Some(k) => k.name = name.to_string(), + None => self.ble.push(KnownBle { id: id.to_string(), name: name.to_string() }), + } + } + + pub fn forget_ble(&mut self, id: &str) -> bool { + let before = self.ble.len(); + self.ble.retain(|k| k.id != id); + self.ble.len() != before + } +} + +const REMEMBERED: &str = "devices"; + pub struct Devices { app: AppHandle, hub: Mutex, handles: Mutex>, ant_status: Mutex, + looking_for: Mutex>, } impl Devices { pub fn new(app: AppHandle) -> Self { - Self { app, hub: Mutex::default(), handles: Mutex::default(), ant_status: Mutex::new(AntStatus { state: "off", message: String::new() }) } + Self { app, hub: Mutex::default(), handles: Mutex::default(), ant_status: Mutex::new(AntStatus { state: "off", message: String::new() }), looking_for: Mutex::default() } } pub fn snapshot(&self) -> DevicesSnapshot { - DevicesSnapshot { devices: self.hub.lock().unwrap().snapshot(now_ms()), ant: self.ant_status.lock().unwrap().clone() } + DevicesSnapshot { devices: self.hub.lock().unwrap().snapshot(now_ms()), ant: self.ant_status.lock().unwrap().clone(), looking_for: self.looking_for.lock().unwrap().clone() } + } + + /// The sensors to reconnect at launch. + pub fn remembered(&self) -> Remembered { + self.app.state::().store.get(REMEMBERED).unwrap_or_default() + } + + /// Changes the remembered sensors and saves them. + pub fn change_remembered(&self, f: impl FnOnce(&mut Remembered)) { + let store = &self.app.state::().store; + let mut r: Remembered = store.get(REMEMBERED).unwrap_or_default(); + let before = r.clone(); + f(&mut r); + if r != before { + if let Err(e) = store.set(REMEMBERED, &r) { + diag::event("dev", format!("could not save remembered devices: {e}")); + } + } + } + + /// Which remembered sensors are being looked for, shown on the Devices page. + pub fn set_looking_for(&self, pending: Vec) { + let mut current = self.looking_for.lock().unwrap(); + if *current != pending { + *current = pending; + drop(current); + self.changed(); + } } /// Tells the UI the device list or a status changed. @@ -151,3 +220,22 @@ impl Devices { &self.app } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn remembered_sensors_are_kept_once_and_forgotten() { + let mut r = Remembered::default(); + r.add_ble("A1", "Trainer"); + r.add_ble("B2", "HRM"); + r.add_ble("A1", "Tacx Neo"); + assert_eq!(r.ble.iter().map(|k| (k.id.as_str(), k.name.as_str())).collect::>(), [("A1", "Tacx Neo"), ("B2", "HRM")]); + assert!(r.forget_ble("A1") && !r.forget_ble("A1")); + assert_eq!(r.ble.len(), 1); + // Older stores have no list yet. + let old: Remembered = serde_json::from_str("{}").unwrap(); + assert_eq!(old, Remembered::default()); + } +} diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rs index cc78c08..3d4baab 100644 --- a/src-tauri/src/main.rs +++ b/src-tauri/src/main.rs @@ -88,6 +88,19 @@ fn main() { http, rides_lock: Mutex::new(()), }); + // Reconnect the sensors from last time: the ANT+ stick if it was on, and the + // Bluetooth sensors connected before, as they wake up. + let handle = app.handle().clone(); + tauri::async_runtime::spawn(async move { + let state = handle.state::(); + let remembered = state.devices.remembered(); + if remembered.ant { + state.ant.start(state.devices.clone()); + } + if let Err(e) = state.ble.look_for_known(state.devices.clone()).await { + diag::event("ble", format!("could not look for remembered sensors: {e}")); + } + }); Ok(()) }) .invoke_handler(tauri::generate_handler![ @@ -106,6 +119,8 @@ fn main() { commands::reveal_file, commands::open_external, commands::devices_list, + commands::devices_look_for_known, + commands::device_forget, commands::ble_scan_start, commands::ble_scan_stop, commands::ble_connect, diff --git a/web/src/bridge.ts b/web/src/bridge.ts index 2f53d8e..aa6ab66 100644 --- a/web/src/bridge.ts +++ b/web/src/bridge.ts @@ -61,7 +61,11 @@ export const api = { antStop: () => invoke('ant_stop'), demoAdd: () => invoke('demo_add'), demoNudge: (delta: number) => invoke('demo_nudge', { delta }), - remove: (id: string) => invoke('device_remove', { id }) + remove: (id: string) => invoke('device_remove', { id }), + /** Looks again for the Bluetooth sensors connected before that aren't connected now. */ + lookForKnown: () => invoke('devices_look_for_known'), + /** Stops reconnecting a remembered Bluetooth sensor. */ + forget: (id: string) => invoke('device_forget', { id }) }, ride: { start: (request: RideRequest) => invoke('ride_start', { request }), diff --git a/web/src/state.ts b/web/src/state.ts index a30b4b7..1aa83ff 100644 --- a/web/src/state.ts +++ b/web/src/state.ts @@ -36,7 +36,7 @@ export function useSettings(): SettingsStore { } // The device list lives in Rust; this mirrors it and follows its change events. -let devices: DevicesSnapshot = { devices: [], ant: { state: 'off', message: '' } } +let devices: DevicesSnapshot = { devices: [], ant: { state: 'off', message: '' }, lookingFor: [] } const deviceListeners = new Set<() => void>() const setDevices = (next: DevicesSnapshot): void => { devices = next diff --git a/web/src/types.ts b/web/src/types.ts index 119a490..12e47f1 100644 --- a/web/src/types.ts +++ b/web/src/types.ts @@ -371,6 +371,8 @@ export interface DeviceInfo { export interface DevicesSnapshot { devices: DeviceInfo[] ant: { state: 'off' | 'opening' | 'scanning' | 'error'; message: string } + /** Bluetooth sensors connected before and not connected yet, while the app looks for them. */ + lookingFor: { id: string; name: string }[] } export interface WorldLayout { diff --git a/web/src/ui/Devices.tsx b/web/src/ui/Devices.tsx index 464eb09..1426576 100644 --- a/web/src/ui/Devices.tsx +++ b/web/src/ui/Devices.tsx @@ -28,7 +28,7 @@ const ANT_HELP: Record = { } export function Devices(): React.JSX.Element { - const { devices, ant } = useDevices() + const { devices, ant, lookingFor } = useDevices() const [scanning, setScanning] = useState(false) const [connecting, setConnecting] = useState('') const [candidates, setCandidates] = useState([]) @@ -41,6 +41,8 @@ export function Devices(): React.JSX.Element { }, []) useEffect(() => api.devices.onCandidates(setCandidates), []) + // Sensors from last time that haven't woken yet: keep looking while this screen is open. + useEffect(() => void api.devices.lookForKnown().catch(() => undefined), []) // Don't leave the radio scanning if the screen is closed mid-search. useEffect(() => () => void api.devices.scanStop(), []) @@ -103,6 +105,21 @@ export function Devices(): React.JSX.Element { {error &&
{error}
} + {lookingFor.length > 0 && ( +
+ Looking for your sensors from last time. Wake them (spin the cranks, wear the strap) and they connect by themselves. +
+ {lookingFor.map((k) => ( + + {k.name || 'Bluetooth sensor'}{' '} + + + ))} +
+
+ )} {ant.state === 'opening' &&
Opening ANT+ stick…
} {ant.state === 'scanning' && (
diff --git a/web/src/ui/RideSetup.tsx b/web/src/ui/RideSetup.tsx index a5ac7a0..c8c2181 100644 --- a/web/src/ui/RideSetup.tsx +++ b/web/src/ui/RideSetup.tsx @@ -36,6 +36,8 @@ export function RideSetup(props: { route: RouteMeta; room?: string; onCancel: () const sourceNames = [...new Set(segments.map((s) => nameOf(s.connector)))].join(' and ') useEffect(() => { + // Sensors from last time that aren't connected yet: look for them while the ride is set up. + void api.devices.lookForKnown().catch(() => undefined) void api.workouts.list().then(setWorkouts) void api.routes.isLoop(rideId).then(setIsLoop, () => setIsLoop(false)) void api.connectors.list().then(setConnectors)