From 23d4b059a83ab2b0f62d9b7a9640573f80165c25 Mon Sep 17 00:00:00 2001 From: pepperstm Date: Thu, 12 Nov 2026 14:13:09 +0000 Subject: [PATCH 1/2] Stop scanning before connecting a Bluetooth sensor on Linux BlueZ often aborts a connection made while the radio is scanning, with le-connection-abort-by-local or Service discovery timed out (#70). Picking a device to add left the scan running for up to 0.6 s, and the search for remembered sensors connected while scanning. On Linux the scan is now stopped first, and the search for remembered sensors connects one at a time and then scans again. macOS and Windows are unchanged. --- src-tauri/src/commands.rs | 2 +- src-tauri/src/devices/ble.rs | 34 ++++++++++++++++++++++++++++++---- 2 files changed, 31 insertions(+), 5 deletions(-) diff --git a/src-tauri/src/commands.rs b/src-tauri/src/commands.rs index 86d534f..9fc6fd3 100644 --- a/src-tauri/src/commands.rs +++ b/src-tauri/src/commands.rs @@ -190,7 +190,7 @@ pub fn ble_scan_stop(state: State) { #[tauri::command] pub async fn ble_connect(state: State<'_, AppState>, id: String) -> Res<()> { - state.ble.scan_stop(); + state.ble.stop_to_connect().await; state.ble.connect(state.devices.clone(), &id).await } diff --git a/src-tauri/src/devices/ble.rs b/src-tauri/src/devices/ble.rs index 62fa135..80581f5 100644 --- a/src-tauri/src/devices/ble.rs +++ b/src-tauri/src/devices/ble.rs @@ -41,6 +41,10 @@ pub struct Ble { 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); +/// BlueZ often aborts a connection made while the radio is scanning +/// ("le-connection-abort-by-local", "Service discovery timed out"), so on Linux the scan is +/// stopped first. CoreBluetooth and WinRT connect fine while scanning. +const QUIET_TO_CONNECT: bool = cfg!(target_os = "linux"); /// What a device must advertise to be listed: a cycling sensor, or an OpenBikeControl controller. fn sensor_services() -> [Uuid; 6] { @@ -159,12 +163,21 @@ impl Ble { } 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 { + if QUIET_TO_CONNECT { + // One at a time with the radio quiet, then back to looking for the rest. + let _ = adapter.stop_scan().await; + if let Err(e) = open_link(devices.clone(), p, &pid).await { diag::event("ble", format!("remembered sensor id={pid}: {e}")); } - }); + let _ = adapter.start_scan(ScanFilter::default()).await; + } else { + 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; } @@ -182,6 +195,19 @@ impl Ble { self.scanning.store(false, Ordering::SeqCst); } + /// Stops the search for a device to add before connecting to the one picked. On Linux the + /// radio is also stopped there and then, rather than when the search next checks, as BlueZ + /// aborts connections made while it scans. + pub async fn stop_to_connect(&self) { + self.scan_stop(); + if QUIET_TO_CONNECT && !self.looking.load(Ordering::SeqCst) { + if let Some(adapter) = self.adapter.get() { + let _ = adapter.stop_scan().await; + diag::event("ble", "scan stopped to connect"); + } + } + } + /// Connects to a scanned peripheral and keeps it connected until it is removed. pub async fn connect(&self, devices: Arc, peripheral_id: &str) -> Result<(), String> { let adapter = self.adapter().await?; From 4cd8637bfea3c4198461e41d763da4edc476e386 Mon Sep 17 00:00:00 2001 From: pepperstm Date: Thu, 12 Nov 2026 15:43:00 +0000 Subject: [PATCH 2/2] Make every Bluetooth connection keep the radio quiet on Linux One connect path for adding a device and for remembered sensors: it counts the connections under way, stops the scan first on Linux, and starts it again once none are left and a search still wants it. Picking a device to add while remembered sensors were being looked for used to connect with the scan still running. --- src-tauri/src/commands.rs | 2 +- src-tauri/src/devices/ble.rs | 81 +++++++++++++++++++++--------------- 2 files changed, 49 insertions(+), 34 deletions(-) diff --git a/src-tauri/src/commands.rs b/src-tauri/src/commands.rs index 9fc6fd3..86d534f 100644 --- a/src-tauri/src/commands.rs +++ b/src-tauri/src/commands.rs @@ -190,7 +190,7 @@ pub fn ble_scan_stop(state: State) { #[tauri::command] pub async fn ble_connect(state: State<'_, AppState>, id: String) -> Res<()> { - state.ble.stop_to_connect().await; + state.ble.scan_stop(); state.ble.connect(state.devices.clone(), &id).await } diff --git a/src-tauri/src/devices/ble.rs b/src-tauri/src/devices/ble.rs index 80581f5..9ebb56f 100644 --- a/src-tauri/src/devices/ble.rs +++ b/src-tauri/src/devices/ble.rs @@ -1,7 +1,7 @@ //! Bluetooth Low Energy sensors and trainers, using the operating system's //! native stack (CoreBluetooth, WinRT, BlueZ) through btleplug. -use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; use std::sync::Arc; use std::time::Duration; @@ -35,6 +35,38 @@ pub struct Ble { scanning: Arc, /// The app is looking for remembered sensors to connect again. looking: Arc, + /// Connections being made right now. + connecting: Arc, +} + +/// What a connection attempt needs to know about the radio: the adapter, whether a search +/// still wants it scanning, and how many other connections are under way. +#[derive(Clone)] +struct Radio { + adapter: Adapter, + scanning: Arc, + looking: Arc, + connecting: Arc, +} + +impl Radio { + /// Connects to a peripheral (see `open_link`). On Linux the radio is quiet while it does: + /// the scan stops first and starts again once no connection is under way, if a search + /// still wants it. + async fn connect(&self, devices: Arc, peripheral: Peripheral, peripheral_id: &str) -> Result<(), String> { + self.connecting.fetch_add(1, Ordering::SeqCst); + if QUIET_TO_CONNECT { + let _ = self.adapter.stop_scan().await; + diag::event("ble", format!("scan paused to connect id={peripheral_id}")); + } + let result = open_link(devices, peripheral, peripheral_id).await; + let still = self.connecting.fetch_sub(1, Ordering::SeqCst) - 1; + if QUIET_TO_CONNECT && still == 0 && (self.scanning.load(Ordering::SeqCst) || self.looking.load(Ordering::SeqCst)) { + let _ = self.adapter.start_scan(ScanFilter::default()).await; + diag::event("ble", "scan resumed"); + } + result + } } /// How long to look for remembered sensors after launch: long enough to wake them. @@ -56,6 +88,10 @@ fn err(e: impl std::fmt::Display) -> String { } impl Ble { + async fn radio(&self) -> Result { + Ok(Radio { adapter: self.adapter().await?.clone(), scanning: self.scanning.clone(), looking: self.looking.clone(), connecting: self.connecting.clone() }) + } + async fn adapter(&self) -> Result<&Adapter, String> { self.adapter .get_or_try_init(|| async { @@ -133,13 +169,14 @@ impl Ble { if missing(&devices).is_empty() || self.looking.swap(true, Ordering::SeqCst) { return Ok(()); } - let adapter = match self.adapter().await { - Ok(a) => a.clone(), + let radio = match self.radio().await { + Ok(r) => r, Err(e) => { self.looking.store(false, Ordering::SeqCst); return Err(e); } }; + let adapter = radio.adapter.clone(); 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}")); @@ -163,27 +200,18 @@ impl Ble { } tried.insert(pid.clone(), tokio::time::Instant::now()); diag::event("ble", format!("heard remembered sensor id={pid}, connecting")); - if QUIET_TO_CONNECT { - // One at a time with the radio quiet, then back to looking for the rest. - let _ = adapter.stop_scan().await; - if let Err(e) = open_link(devices.clone(), p, &pid).await { + let (radio, devices) = (radio.clone(), devices.clone()); + tauri::async_runtime::spawn(async move { + if let Err(e) = radio.connect(devices, p, &pid).await { diag::event("ble", format!("remembered sensor id={pid}: {e}")); } - let _ = adapter.start_scan(ScanFilter::default()).await; - } else { - 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) { + if !scanning.load(Ordering::SeqCst) && radio.connecting.load(Ordering::SeqCst) == 0 { let _ = adapter.stop_scan().await; } diag::event("ble", "stopped looking for remembered sensors"); @@ -195,24 +223,11 @@ impl Ble { self.scanning.store(false, Ordering::SeqCst); } - /// Stops the search for a device to add before connecting to the one picked. On Linux the - /// radio is also stopped there and then, rather than when the search next checks, as BlueZ - /// aborts connections made while it scans. - pub async fn stop_to_connect(&self) { - self.scan_stop(); - if QUIET_TO_CONNECT && !self.looking.load(Ordering::SeqCst) { - if let Some(adapter) = self.adapter.get() { - let _ = adapter.stop_scan().await; - diag::event("ble", "scan stopped to connect"); - } - } - } - /// Connects to a scanned peripheral and keeps it connected until it is removed. 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.")?; - open_link(devices, peripheral, peripheral_id).await + let radio = self.radio().await?; + let peripheral = radio.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.")?; + radio.connect(devices, peripheral, peripheral_id).await } }