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
3 changes: 1 addition & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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

Expand Down
24 changes: 24 additions & 0 deletions src-tauri/src/commands.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<AppState>, 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<AppState>) {
state.devices.change_remembered(|r| r.ant = true);
state.ant.start(state.devices.clone());
}

#[tauri::command]
pub fn ant_stop(state: State<AppState>) {
state.devices.change_remembered(|r| r.ant = false);
state.ant.stop();
}

Expand All @@ -214,9 +232,15 @@ pub fn demo_nudge(state: State<AppState>, 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<AppState>, id: String) {
state.devices.remove(&id);
if let Some(peripheral) = id.strip_prefix("ble:") {
state.devices.change_remembered(|r| {
r.forget_ble(peripheral);
});
}
}

// ── Ride ───────────────────────────────────────────────────────────────────
Expand Down
151 changes: 113 additions & 38 deletions src-tauri/src/devices/ble.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,9 +31,17 @@ pub struct Candidate {
#[derive(Default)]
pub struct Ble {
adapter: OnceCell<Adapter>,
/// The rider is searching for a device to add.
scanning: Arc<AtomicBool>,
/// The app is looking for remembered sensors to connect again.
looking: Arc<AtomicBool>,
}

/// 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)]
Expand Down Expand Up @@ -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<Candidate> = Vec::new();
Expand Down Expand Up @@ -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<Devices>) -> Result<(), String> {
let missing = |devices: &Devices| devices.remembered().ble.into_iter().filter(|k| !devices.contains(&format!("ble:{}", k.id))).collect::<Vec<_>>();
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<String, tokio::time::Instant> = 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);
}
Expand All @@ -119,44 +186,52 @@ impl Ble {
pub async fn connect(&self, devices: Arc<Devices>, 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::<TrainerCommand>();
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<Devices>, 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::<TrainerCommand>();
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.
Expand Down
94 changes: 91 additions & 3 deletions src-tauri/src/devices/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
Expand All @@ -28,25 +28,94 @@ pub struct AntStatus {
}

#[derive(Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct DevicesSnapshot {
pub devices: Vec<DeviceInfo>,
pub ant: AntStatus,
/// Remembered Bluetooth sensors not connected yet, while the app looks for them.
pub looking_for: Vec<KnownBle>,
}

/// 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<KnownBle>,
/// 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<Hub>,
handles: Mutex<HashMap<String, Handle>>,
ant_status: Mutex<AntStatus>,
looking_for: Mutex<Vec<KnownBle>>,
}

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::<crate::AppState>().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::<crate::AppState>().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<KnownBle>) {
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.
Expand Down Expand Up @@ -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::<Vec<_>>(), [("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());
}
}
Loading
Loading