aranet_core/
scan.rs

1//! Device discovery and scanning.
2//!
3//! This module provides functionality to scan for Aranet devices
4//! using Bluetooth Low Energy.
5//!
6//! Scans in one process run one at a time: each scan window takes a
7//! process-wide permit and releases it only after the scan has stopped. A
8//! window runs on aranet-core's background runtime and stops as soon as its
9//! caller is dropped.
10
11use std::ops::ControlFlow;
12use std::sync::{Arc, LazyLock};
13use std::time::Duration;
14
15use btleplug::api::{Central, Manager as _, Peripheral as _, ScanFilter};
16use btleplug::platform::{Adapter, Manager, Peripheral, PeripheralId};
17use tokio::runtime::Handle;
18use tokio::sync::RwLock;
19use tokio::time::sleep;
20use tokio_util::sync::CancellationToken;
21use tracing::{debug, info, warn};
22
23/// Cached BLE manager — avoids creating a new D-Bus connection on every call.
24///
25/// Using `RwLock<Option<Manager>>` instead of `OnceCell` so the manager can
26/// be re-created if the underlying D-Bus connection dies (e.g., dbus-daemon
27/// restart, adapter reset).
28static MANAGER: RwLock<Option<Manager>> = RwLock::const_new(None);
29
30/// Get or create the shared BLE manager.
31async fn shared_manager() -> Result<Manager> {
32    // Fast path: read lock to return existing manager.
33    {
34        let guard = MANAGER.read().await;
35        if let Some(m) = guard.as_ref() {
36            return Ok(m.clone());
37        }
38    }
39    // Slow path: create a new manager under write lock.
40    let mut guard = MANAGER.write().await;
41    // Double-check after acquiring write lock.
42    if let Some(m) = guard.as_ref() {
43        return Ok(m.clone());
44    }
45    // bluez-async spawns the D-Bus connection's only I/O task on the runtime
46    // that creates the manager. On the caller's runtime that task would die when
47    // the runtime shuts down, and every later call on the cached manager would
48    // wait out the 30 s D-Bus timeout and fail.
49    let m = crate::runtime::run(Manager::new()).await??;
50    *guard = Some(m.clone());
51    Ok(m)
52}
53
54/// Reset the cached manager, forcing the next call to create a fresh one.
55///
56/// Call this when the D-Bus connection appears to be dead (e.g., adapter
57/// enumeration fails with a connection error).
58async fn reset_manager() {
59    let mut guard = MANAGER.write().await;
60    if guard.take().is_some() {
61        warn!("BLE manager reset — next operation will create a new D-Bus connection");
62    }
63}
64
65use crate::error::{Error, Result};
66use crate::util::{create_identifier, peripheral_name};
67use crate::uuid::{MANUFACTURER_ID, SAF_TEHNIKA_SERVICE_NEW, SAF_TEHNIKA_SERVICE_OLD};
68use aranet_types::DeviceType;
69
70/// Progress update for device finding operations.
71#[derive(Debug, Clone)]
72pub enum FindProgress {
73    /// Found the device among the devices the adapter already knows, without
74    /// scanning for it: before the first scan, or after waiting for another
75    /// search's scan.
76    CacheHit,
77    /// Starting scan attempt.
78    ScanAttempt {
79        /// Current attempt number (1-based).
80        attempt: u32,
81        /// Total number of attempts.
82        total: u32,
83        /// Duration of this scan attempt.
84        duration_secs: u64,
85    },
86    /// Device found on specific attempt.
87    Found { attempt: u32 },
88    /// Attempt failed, will retry.
89    RetryNeeded { attempt: u32 },
90}
91
92/// Callback type for progress updates during device finding.
93pub type ProgressCallback = Box<dyn Fn(FindProgress) + Send + Sync>;
94
95/// Information about a discovered Aranet device.
96#[derive(Debug, Clone)]
97pub struct DiscoveredDevice {
98    /// The device name (e.g., "Aranet4 12345").
99    pub name: Option<String>,
100    /// The peripheral ID for connecting.
101    pub id: PeripheralId,
102    /// The BLE address as a string (may be zeros on macOS, use `id` instead).
103    pub address: String,
104    /// A connection identifier (peripheral ID on macOS, address on other platforms).
105    pub identifier: String,
106    /// RSSI signal strength.
107    pub rssi: Option<i16>,
108    /// Device type if detected from advertisement.
109    pub device_type: Option<DeviceType>,
110    /// Whether the device is connectable.
111    pub is_aranet: bool,
112    /// Raw manufacturer data from advertisement (if available).
113    pub manufacturer_data: Option<Vec<u8>>,
114}
115
116/// Options for scanning.
117#[derive(Debug, Clone)]
118pub struct ScanOptions {
119    /// How long to scan for devices.
120    pub duration: Duration,
121    /// Only return devices that appear to be Aranet devices.
122    pub filter_aranet_only: bool,
123    /// Use targeted BLE scan filter for Aranet service UUIDs.
124    /// This reduces noise from non-Aranet devices but may not work on all platforms.
125    pub use_service_filter: bool,
126}
127
128impl Default for ScanOptions {
129    fn default() -> Self {
130        Self {
131            duration: Duration::from_secs(5),
132            filter_aranet_only: true,
133            // Default to false for maximum compatibility - service filtering
134            // may not work on all platforms/adapters
135            use_service_filter: false,
136        }
137    }
138}
139
140impl ScanOptions {
141    /// Create new scan options with defaults.
142    pub fn new() -> Self {
143        Self::default()
144    }
145
146    /// Set the scan duration.
147    pub fn duration(mut self, duration: Duration) -> Self {
148        self.duration = duration;
149        self
150    }
151
152    /// Set scan duration in seconds.
153    pub fn duration_secs(mut self, secs: u64) -> Self {
154        self.duration = Duration::from_secs(secs);
155        self
156    }
157
158    /// Set whether to filter for Aranet devices only.
159    pub fn filter_aranet_only(mut self, filter: bool) -> Self {
160        self.filter_aranet_only = filter;
161        self
162    }
163
164    /// Scan for all BLE devices, not just Aranet.
165    pub fn all_devices(self) -> Self {
166        self.filter_aranet_only(false)
167    }
168
169    /// Enable or disable BLE service UUID filtering.
170    ///
171    /// When enabled, the BLE scan will filter for Aranet service UUIDs at the
172    /// adapter level, reducing noise from non-Aranet devices. This may not
173    /// work on all platforms or with all BLE adapters.
174    ///
175    /// Default: `false` (for maximum compatibility)
176    pub fn use_service_filter(mut self, enable: bool) -> Self {
177        self.use_service_filter = enable;
178        self
179    }
180
181    /// Create optimized scan options for finding Aranet devices quickly.
182    ///
183    /// Uses service UUID filtering if available and a shorter scan duration.
184    pub fn optimized() -> Self {
185        Self {
186            duration: Duration::from_secs(3),
187            filter_aranet_only: true,
188            use_service_filter: true,
189        }
190    }
191}
192
193/// Adapter reused by [`get_adapter`] on macOS.
194///
195/// On CoreBluetooth every `Manager::adapters()` call starts a new
196/// `CBCentralManager` on its own OS thread that never exits, so creating an
197/// adapter per connection leaks a thread per poll. Other platforms create
198/// adapters cheaply and stay uncached, so a dead D-Bus connection can still
199/// be recovered by `reset_manager`.
200///
201/// The adapter is created on aranet-core's background runtime (`crate::runtime`),
202/// because btleplug runs its event loop (device discovery, and each peripheral's
203/// notification task) on the runtime that creates it. Created on a caller's
204/// runtime, it would stop seeing devices, with no error, once that runtime shut
205/// down, which happens after every `#[tokio::test]` and in any program that
206/// builds a runtime per call.
207static ADAPTER: RwLock<Option<Adapter>> = RwLock::const_new(None);
208
209/// Get the first available Bluetooth adapter.
210///
211/// The adapter, and the Bluetooth manager behind it, are created on aranet-core's
212/// background runtime (thread `aranet-ble`), so they keep working after the caller's
213/// tokio runtime shuts down. On macOS the adapter is also created once, shared by
214/// every caller in the process, and replaced if its CoreBluetooth thread stops.
215pub async fn get_adapter() -> Result<Adapter> {
216    if cfg!(target_os = "macos") {
217        cached_adapter().await
218    } else {
219        crate::runtime::run(create_adapter()).await?
220    }
221}
222
223async fn cached_adapter() -> Result<Adapter> {
224    let cached = ADAPTER.read().await.clone();
225    if let Some(adapter) = cached
226        && adapter_thread_is_running(&adapter).await
227    {
228        return Ok(adapter);
229    }
230    let mut guard = ADAPTER.write().await;
231    if let Some(adapter) = guard.as_ref() {
232        if adapter_thread_is_running(adapter).await {
233            return Ok(adapter.clone());
234        }
235        warn!("CoreBluetooth adapter thread has stopped; creating a new adapter");
236    }
237    let adapter = crate::runtime::run(create_adapter()).await??;
238    *guard = Some(adapter.clone());
239    Ok(adapter)
240}
241
242/// Whether the cached adapter's CoreBluetooth thread still takes requests.
243///
244/// btleplug's CoreBluetooth thread runs a loop that never returns (btleplug
245/// 0.13.5 `src/corebluetooth/internal.rs:2030-2038`), so it stops only if it
246/// panics. btleplug 0.11.8 panicked on a discovery callback that came late,
247/// for a service it no longer knew or with no connect waiting; 0.13.5
248/// ignores those (`:397-400`, `:534-538`). This check stays as a guard
249/// against any other panic: every later request on an adapter whose thread
250/// has stopped fails with "Channel closed"
251/// (`src/corebluetooth/peripheral.rs:678-682`), so the adapter has to be
252/// replaced. A reply that is merely slow keeps the adapter: only a closed
253/// channel proves the thread is gone.
254async fn adapter_thread_is_running(adapter: &Adapter) -> bool {
255    let adapter = adapter.clone();
256    // Run on aranet-core's runtime so the timeout works even if the caller's
257    // runtime has no time driver.
258    let state = crate::runtime::run(async move {
259        tokio::time::timeout(Duration::from_secs(2), adapter.adapter_state()).await
260    })
261    .await;
262    match state {
263        Ok(Ok(Err(e))) => {
264            debug!("Cached Bluetooth adapter is unusable: {e}");
265            false
266        }
267        _ => true,
268    }
269}
270
271async fn create_adapter() -> Result<Adapter> {
272    use crate::error::DeviceNotFoundReason;
273
274    let manager = shared_manager().await?;
275    let adapters = match manager.adapters().await {
276        Ok(a) => a,
277        Err(e) => {
278            // The D-Bus connection may have died — reset the cached manager
279            // so the next call creates a fresh connection.
280            reset_manager().await;
281            return Err(e.into());
282        }
283    };
284
285    adapters
286        .into_iter()
287        .next()
288        .ok_or(Error::DeviceNotFound(DeviceNotFoundReason::NoAdapter))
289}
290
291/// Starts and stops a Bluetooth scan: btleplug's [`Adapter`] in production, a
292/// fake in the tests.
293pub(crate) trait ScanControl: Clone + Send + Sync + 'static {
294    /// Start scanning. BlueZ fails with `org.bluez.Error.InProgress` if this
295    /// process is already scanning.
296    fn start(&self, filter: ScanFilter) -> impl Future<Output = Result<()>> + Send;
297
298    /// Stop scanning.
299    fn stop(&self) -> impl Future<Output = Result<()>> + Send;
300}
301
302impl ScanControl for Adapter {
303    async fn start(&self, filter: ScanFilter) -> Result<()> {
304        Central::start_scan(self, filter).await?;
305        Ok(())
306    }
307
308    async fn stop(&self) -> Result<()> {
309        Central::stop_scan(self).await?;
310        Ok(())
311    }
312}
313
314/// Lets one scan window run at a time. Whoever holds its [`ScanPermit`] may scan.
315///
316/// A scan is process-wide: BlueZ gives each D-Bus client (this whole process)
317/// one discovery session, and on macOS the adapter from `get_adapter` is one
318/// `CBCentralManager` shared by the whole process, so one caller's stop ends
319/// every caller's scan. tokio's mutex hands the permit out in the order it was
320/// asked for.
321#[derive(Clone, Default)]
322pub(crate) struct ScanLock(Arc<tokio::sync::Mutex<()>>);
323
324impl ScanLock {
325    /// Wait for the permit.
326    pub(crate) async fn acquire(&self) -> ScanPermit {
327        ScanPermit {
328            _guard: Arc::clone(&self.0).lock_owned().await,
329        }
330    }
331}
332
333/// Permission to scan, from [`ScanLock::acquire`]. The next caller can scan once
334/// it is dropped, so it must be held until the scan has stopped.
335///
336/// While holding a permit, never wait for another lock or another scan: only
337/// start, stop, sleep and read the adapter's known peripherals. Callers may hold
338/// their own locks while they wait for the permit, because its holder never
339/// waits for them.
340pub(crate) struct ScanPermit {
341    _guard: tokio::sync::OwnedMutexGuard<()>,
342}
343
344static SCAN_LOCK: LazyLock<ScanLock> = LazyLock::new(ScanLock::default);
345
346/// The [`ScanLock`] that every scan in this process takes. See [`ScanPermit`]
347/// for what its holder may wait for.
348pub(crate) fn scan_lock() -> &'static ScanLock {
349    &SCAN_LOCK
350}
351
352/// One scan window: start, wait `duration`, stop.
353///
354/// The window runs as a task on `runtime`, so it finishes even if this future is
355/// dropped (a timeout, an aborted task, or a caller whose runtime shuts down).
356/// Dropping the future ends the wait early, but the scan is still stopped, and
357/// `permit` is released only once `stop` has returned, so the next window can't
358/// start while this one is still stopping.
359async fn scan_window<S: ScanControl>(
360    runtime: &Handle,
361    scanner: &S,
362    permit: ScanPermit,
363    filter: ScanFilter,
364    duration: Duration,
365) -> Result<()> {
366    let scanner = scanner.clone();
367    let cancel = CancellationToken::new();
368    // Dropping the caller's future drops this guard, which ends the window early.
369    let _end_early_on_drop = cancel.clone().drop_guard();
370    let window = runtime.spawn(async move {
371        let _permit = permit; // released only after stop has returned
372        if cancel.is_cancelled() {
373            return Ok(());
374        }
375        scanner.start(filter).await?; // a failed start has nothing to stop
376        let _ = cancel.run_until_cancelled(sleep(duration)).await;
377        let stopped = scanner.stop().await;
378        if let Err(e) = &stopped {
379            // Nobody may be awaiting this task any more.
380            warn!("Failed to stop the Bluetooth scan: {e}");
381        }
382        stopped
383    });
384    window.await.map_err(std::io::Error::from)?
385}
386
387/// Scan with `scanner` (the adapter, in production) for `duration`, holding
388/// `permit` (from [`scan_lock`]) until the scan has stopped. The window runs on
389/// aranet-core's runtime.
390pub(crate) async fn run_scan<S: ScanControl>(
391    scanner: &S,
392    permit: ScanPermit,
393    filter: ScanFilter,
394    duration: Duration,
395) -> Result<()> {
396    scan_window(
397        &crate::runtime::handle()?,
398        scanner,
399        permit,
400        filter,
401        duration,
402    )
403    .await
404}
405
406/// Scan for Aranet devices in range.
407///
408/// Returns a list of discovered devices, or an error if the scan failed.
409/// An empty list indicates no devices were found (not an error).
410///
411/// # Errors
412///
413/// Returns an error if:
414/// - No Bluetooth adapter is available
415/// - Bluetooth is not enabled
416/// - The scan could not be started or stopped
417pub async fn scan_for_devices() -> Result<Vec<DiscoveredDevice>> {
418    scan_with_options(ScanOptions::default()).await
419}
420
421/// Scan for devices with custom options.
422pub async fn scan_with_options(options: ScanOptions) -> Result<Vec<DiscoveredDevice>> {
423    let adapter = get_adapter().await?;
424    scan_with_adapter(&adapter, options).await
425}
426
427/// Scan for devices with retry logic for flaky Bluetooth environments.
428///
429/// This function will retry the scan up to `max_retries` times if:
430/// - The scan fails due to a Bluetooth error
431/// - No devices are found (when `retry_on_empty` is true)
432///
433/// A delay is applied between retries, starting at 500ms and doubling each attempt.
434///
435/// # Arguments
436///
437/// * `options` - Scan options
438/// * `max_retries` - Maximum number of retry attempts
439/// * `retry_on_empty` - Whether to retry if no devices are found
440///
441/// # Example
442///
443/// ```ignore
444/// use aranet_core::scan::{ScanOptions, scan_with_retry};
445///
446/// // Retry up to 3 times, including when no devices found
447/// let devices = scan_with_retry(ScanOptions::default(), 3, true).await?;
448/// ```
449pub async fn scan_with_retry(
450    options: ScanOptions,
451    max_retries: u32,
452    retry_on_empty: bool,
453) -> Result<Vec<DiscoveredDevice>> {
454    let mut attempt = 0;
455    let mut delay = Duration::from_millis(500);
456
457    loop {
458        match scan_with_options(options.clone()).await {
459            Ok(devices) if devices.is_empty() && retry_on_empty && attempt < max_retries => {
460                attempt += 1;
461                warn!(
462                    "No devices found, retrying ({}/{})...",
463                    attempt, max_retries
464                );
465                sleep(delay).await;
466                delay = delay.saturating_mul(2).min(Duration::from_secs(5));
467            }
468            Ok(devices) => return Ok(devices),
469            Err(e) if attempt < max_retries => {
470                attempt += 1;
471                warn!(
472                    "Scan failed ({}), retrying ({}/{})...",
473                    e, attempt, max_retries
474                );
475                sleep(delay).await;
476                delay = delay.saturating_mul(2).min(Duration::from_secs(5));
477            }
478            Err(e) => return Err(e),
479        }
480    }
481}
482
483/// Scan for devices using a specific adapter.
484pub async fn scan_with_adapter(
485    adapter: &Adapter,
486    options: ScanOptions,
487) -> Result<Vec<DiscoveredDevice>> {
488    info!(
489        "Starting BLE scan for {} seconds (service_filter={})...",
490        options.duration.as_secs(),
491        options.use_service_filter
492    );
493
494    // Create scan filter - optionally filter for Aranet service UUIDs
495    let scan_filter = if options.use_service_filter {
496        aranet_service_filter()
497    } else {
498        ScanFilter::default()
499    };
500
501    let permit = scan_lock().acquire().await;
502    run_scan(adapter, permit, scan_filter, options.duration).await?;
503
504    // Get discovered peripherals
505    let peripherals = adapter.peripherals().await?;
506    let mut discovered = Vec::new();
507
508    for peripheral in peripherals {
509        match process_peripheral(&peripheral, options.filter_aranet_only).await {
510            Ok(Some(device)) => {
511                info!("Found Aranet device: {:?}", device.name);
512                discovered.push(device);
513            }
514            Ok(None) => {
515                // Not an Aranet device or filtered out
516            }
517            Err(e) => {
518                debug!("Error processing peripheral: {}", e);
519            }
520        }
521    }
522
523    info!("Scan complete. Found {} device(s)", discovered.len());
524    Ok(discovered)
525}
526
527/// Process a peripheral and determine if it's an Aranet device.
528async fn process_peripheral(
529    peripheral: &Peripheral,
530    filter_aranet_only: bool,
531) -> Result<Option<DiscoveredDevice>> {
532    let properties = peripheral.properties().await?;
533    let properties = match properties {
534        Some(p) => p,
535        None => return Ok(None),
536    };
537
538    let id = peripheral.id();
539    let address = properties.address.to_string();
540    let name = peripheral_name(&properties).map(str::to_owned);
541    let rssi = properties.rssi;
542
543    // Check if this is an Aranet device
544    let is_aranet = is_aranet_device(&properties);
545
546    if filter_aranet_only && !is_aranet {
547        return Ok(None);
548    }
549
550    // Try to determine device type from name
551    let device_type = name.as_ref().and_then(|n| DeviceType::from_name(n));
552
553    // Get manufacturer data if available
554    let manufacturer_data = properties.manufacturer_data.get(&MANUFACTURER_ID).cloned();
555
556    // Create identifier: use peripheral ID string on macOS (where address is 00:00:00:00:00:00)
557    // On other platforms, use the address
558    let identifier = create_identifier(&address, &id);
559
560    Ok(Some(DiscoveredDevice {
561        name,
562        id,
563        address,
564        identifier,
565        rssi,
566        device_type,
567        is_aranet,
568        manufacturer_data,
569    }))
570}
571
572/// Check if a peripheral is an Aranet device based on its properties.
573fn is_aranet_device(properties: &btleplug::api::PeripheralProperties) -> bool {
574    // Check manufacturer data for Aranet manufacturer ID
575    if properties.manufacturer_data.contains_key(&MANUFACTURER_ID) {
576        return true;
577    }
578
579    // Check service UUIDs for Aranet services
580    for service_uuid in properties.service_data.keys() {
581        if *service_uuid == SAF_TEHNIKA_SERVICE_NEW || *service_uuid == SAF_TEHNIKA_SERVICE_OLD {
582            return true;
583        }
584    }
585
586    // Check advertised services
587    for service_uuid in &properties.services {
588        if *service_uuid == SAF_TEHNIKA_SERVICE_NEW || *service_uuid == SAF_TEHNIKA_SERVICE_OLD {
589            return true;
590        }
591    }
592
593    // Check device name for Aranet
594    if let Some(name) = peripheral_name(properties) {
595        let name_lower = name.to_lowercase();
596        if name_lower.contains("aranet") {
597            return true;
598        }
599    }
600
601    false
602}
603
604/// A scan filter that asks the Bluetooth stack only for devices that advertise
605/// an Aranet service.
606fn aranet_service_filter() -> ScanFilter {
607    ScanFilter {
608        services: vec![SAF_TEHNIKA_SERVICE_NEW, SAF_TEHNIKA_SERVICE_OLD],
609    }
610}
611
612/// Whether every scan window of a device search asks the Bluetooth stack only for
613/// devices that advertise an Aranet service (see `search_filter`). Only on macOS:
614/// btleplug's CoreBluetooth backend keeps every device a scan reports (its
615/// `CBPeripheral`, an entry in the adapter's list and a task of its own) until
616/// the device disconnects after a connection, Bluetooth is switched off or
617/// `clear_peripherals()` is called (btleplug 0.13.5
618/// `src/corebluetooth/internal.rs:1010-1013`; removed at `:1175`, `:1153` and
619/// `:1924`). aranet never calls `clear_peripherals()` and shares one adapter for
620/// the life of the process, so a device that is only scanned stays until
621/// Bluetooth is switched off or the process ends. With the filter, a device
622/// search adds only Aranet sensors to that list.
623///
624/// The filter was added on btleplug 0.11.8, which also leaked a little memory
625/// for every advertisement it received, and the figures here were measured on
626/// it. Unfiltered searches near many Bluetooth devices made a long-running
627/// program grow by 1-2 MB an hour. Leaving only a search's last window
628/// unfiltered wasn't enough: in a 12 h macOS soak, the 8.5% of the service's
629/// polls whose search reached that window added about 106 kB each (about 80% of
630/// the growth, against about 2 kB for a search that ended earlier), and a
631/// sensor out of range ran it on every poll, about 6 MB an hour.
632///
633/// btleplug 0.13.5 drains an autorelease pool for every message on its
634/// CoreBluetooth thread (`src/corebluetooth/internal.rs:1990-2014`,
635/// `:2034-2036`), which by its source ends the growth per advertisement
636/// (<https://github.com/deviceplug/btleplug/issues/494>). That has not been
637/// measured, and the list of kept devices is as it was, so the filter stays
638/// unchanged until a memory measurement on 0.13.5 says otherwise.
639///
640/// The cost: a macOS search doesn't find a sensor that advertises neither Aranet
641/// service UUID. All four current Aranet sensor types advertise 0xFCE0; older
642/// firmware is untested. `aranet scan`, `scan_with_options` and the passive
643/// monitor still see every device. Linux and Windows searches ask for every
644/// device.
645const FILTER_SEARCH_WINDOWS: bool = cfg!(target_os = "macos");
646
647/// The scan filter of every window of a device search: with `aranet_only`, it
648/// asks only for devices that advertise an Aranet service; without it, for every
649/// device.
650fn search_filter(aranet_only: bool) -> ScanFilter {
651    if aranet_only {
652        aranet_service_filter()
653    } else {
654        ScanFilter::default()
655    }
656}
657
658/// What a device search does after its scan window `attempt` (counted from 1) of
659/// `max_attempts` found no device that `query` names, where `similar` are the
660/// names that contain the query (from `Search::Missing`): `Continue` to scan
661/// again, or `Break` with the error the search fails with.
662///
663/// Similar names end the search at once with `NoExactMatch`, so a query that is
664/// part of a name, the commonest mistake, fails after the first window that
665/// leaves such names known instead of after the last window. Scanning on could
666/// still find a device that the query names only if no window has heard that
667/// device yet and its whole name is part of the name of one that has been
668/// heard. Without similar names the search scans again until its last window,
669/// then fails with `NotFound`.
670fn after_missed_scan(
671    query: &str,
672    similar: Vec<String>,
673    attempt: u32,
674    max_attempts: u32,
675) -> ControlFlow<Error> {
676    use crate::error::DeviceNotFoundReason;
677
678    if !similar.is_empty() {
679        return ControlFlow::Break(Error::DeviceNotFound(DeviceNotFoundReason::NoExactMatch {
680            identifier: query.to_string(),
681            similar,
682        }));
683    }
684    if attempt < max_attempts {
685        return ControlFlow::Continue(());
686    }
687    ControlFlow::Break(Error::device_not_found(query))
688}
689
690/// Find a device by its address, identifier or full name.
691///
692/// `identifier` is trimmed and case is ignored, but otherwise it must match one
693/// of these exactly:
694/// - the device's [`DiscoveredDevice::identifier`]: the MAC address on Linux
695///   and Windows, the CoreBluetooth UUID on macOS;
696/// - btleplug's device ID as [`DiscoveredDevice::id`] displays it
697///   (`hci0/dev_AA_BB_CC_DD_EE_FF` on Linux);
698/// - the MAC address, with or without colons;
699/// - the device's whole name, as [`peripheral_name`] gives it and
700///   [`DiscoveredDevice::name`] holds it.
701///
702/// An address or identifier match wins over a name match.
703///
704/// The device is searched for as [`find_device_with_options`] describes, with the
705/// default [`ScanOptions`].
706///
707/// # Errors
708///
709/// - [`Error::InvalidConfig`] if `identifier` is empty or blank, before
710///   Bluetooth is used.
711/// - [`Error::DeviceNotFound`] with
712///   [`DeviceNotFoundReason::NoAdapter`](crate::error::DeviceNotFoundReason::NoAdapter)
713///   if there is no Bluetooth adapter.
714/// - [`Error::DeviceNotFound`] with
715///   [`DeviceNotFoundReason::Ambiguous`](crate::error::DeviceNotFoundReason::Ambiguous)
716///   at once if several nearby devices match;
717///   [`DeviceNotFoundReason::NoExactMatch`](crate::error::DeviceNotFoundReason::NoExactMatch)
718///   if none matches but some Aranet device names contain `identifier`, after
719///   the first scan that ends that way rather than after the last; and
720///   [`DeviceNotFoundReason::NotFound`](crate::error::DeviceNotFoundReason::NotFound)
721///   otherwise, after the last scan.
722/// - [`Error::Bluetooth`] if the adapter fails.
723pub async fn find_device(identifier: &str) -> Result<(Adapter, Peripheral)> {
724    find_device_with_options(identifier, ScanOptions::default()).await
725}
726
727/// Find a specific device by name or address with custom options.
728///
729/// `identifier` must match exactly, as [`find_device`] describes.
730///
731/// This function uses a retry strategy to improve reliability:
732/// 1. First checks if the device is already known (cached from previous scans)
733/// 2. Performs up to 3 scan attempts with increasing durations
734///
735/// This helps with BLE reliability issues where devices may not appear
736/// on every scan due to advertisement timing.
737///
738/// Only `options.duration` is used: the search ignores the filter flags of
739/// `options`. On macOS every scan attempt asks the Bluetooth stack only for
740/// devices that advertise an Aranet service, as every current Aranet sensor does.
741/// On other platforms every attempt asks for every device.
742pub async fn find_device_with_options(
743    identifier: &str,
744    options: ScanOptions,
745) -> Result<(Adapter, Peripheral)> {
746    find_device_with_progress(identifier, options, None).await
747}
748
749/// Find a specific device using a pre-existing adapter.
750///
751/// `identifier` must match exactly, as [`find_device`] describes, and the device
752/// is searched for as [`find_device_with_options`] describes.
753///
754/// This avoids creating a new btleplug `Manager` (and D-Bus connection) on
755/// every call.  The caller is responsible for keeping the `Adapter` alive.
756pub async fn find_device_with_adapter(
757    adapter: &Adapter,
758    identifier: &str,
759    options: ScanOptions,
760) -> Result<Peripheral> {
761    find_device_with_adapter_progress(adapter, identifier, options, None).await
762}
763
764/// Find a specific device using a pre-existing adapter, with progress callback.
765///
766/// `identifier` must match exactly, as [`find_device`] describes, and the device
767/// is searched for as [`find_device_with_options`] describes.
768pub async fn find_device_with_adapter_progress(
769    adapter: &Adapter,
770    identifier: &str,
771    options: ScanOptions,
772    progress: Option<ProgressCallback>,
773) -> Result<Peripheral> {
774    let query = parse_query(identifier)?;
775
776    info!("Looking for device: {}", identifier);
777
778    if let Search::Found(peripheral) = search_known_peripherals(adapter, query).await? {
779        info!("Found device in cache (no scan needed)");
780        if let Some(ref cb) = progress {
781            cb(FindProgress::CacheHit);
782        }
783        return Ok(peripheral);
784    }
785
786    let max_attempts: u32 = 3;
787    let base_duration = options.duration.as_millis() as u64 / 2;
788    let base_duration = Duration::from_millis(base_duration.max(2000));
789
790    // Ends after `max_attempts` windows at the latest: `after_missed_scan`
791    // stops the search after the last one.
792    let mut attempt = 0;
793    loop {
794        attempt += 1;
795        let scan_duration = base_duration * attempt;
796        let duration_secs = scan_duration.as_secs();
797
798        let permit = scan_lock().acquire().await;
799        // Another search may have scanned while this one waited for the permit.
800        if let Search::Found(peripheral) = search_known_peripherals(adapter, query).await? {
801            info!("Found device while waiting to scan");
802            if let Some(ref cb) = progress {
803                cb(FindProgress::CacheHit);
804            }
805            return Ok(peripheral);
806        }
807
808        info!(
809            "Scan attempt {}/{} ({}s)...",
810            attempt, max_attempts, duration_secs
811        );
812        let filter = search_filter(FILTER_SEARCH_WINDOWS);
813        debug!(
814            "Scan attempt {}/{} ({}s, {})",
815            attempt,
816            max_attempts,
817            duration_secs,
818            if filter.services.is_empty() {
819                "all devices"
820            } else {
821                "Aranet sensors only"
822            }
823        );
824
825        if let Some(ref cb) = progress {
826            cb(FindProgress::ScanAttempt {
827                attempt,
828                total: max_attempts,
829                duration_secs,
830            });
831        }
832
833        run_scan(adapter, permit, filter, scan_duration).await?;
834
835        let similar = match search_known_peripherals(adapter, query).await? {
836            Search::Found(peripheral) => {
837                info!("Found device on attempt {}", attempt);
838                if let Some(ref cb) = progress {
839                    cb(FindProgress::Found { attempt });
840                }
841                return Ok(peripheral);
842            }
843            Search::Missing { similar } => similar,
844        };
845
846        match after_missed_scan(query, similar, attempt, max_attempts) {
847            ControlFlow::Break(error) => {
848                warn!(
849                    "Device not found after {} of {} attempts: {}",
850                    attempt, max_attempts, identifier
851                );
852                return Err(error);
853            }
854            ControlFlow::Continue(()) => {
855                warn!("Device not found, retrying...");
856                if let Some(ref cb) = progress {
857                    cb(FindProgress::RetryNeeded { attempt });
858                }
859            }
860        }
861    }
862}
863
864/// Find a specific device with progress callback for UI feedback.
865///
866/// `identifier` must match exactly, as [`find_device`] describes, and the device
867/// is searched for as [`find_device_with_options`] describes.
868///
869/// The progress callback is called with updates about the search progress,
870/// including cache hits, scan attempts, and retry information.
871pub async fn find_device_with_progress(
872    identifier: &str,
873    options: ScanOptions,
874    progress: Option<ProgressCallback>,
875) -> Result<(Adapter, Peripheral)> {
876    // Reject an empty identifier before Bluetooth is touched.
877    parse_query(identifier)?;
878    let adapter = get_adapter().await?;
879    let peripheral =
880        find_device_with_adapter_progress(&adapter, identifier, options, progress).await?;
881    Ok((adapter, peripheral))
882}
883
884/// The address CoreBluetooth reports for every peripheral. It identifies
885/// nothing, so a query never matches it.
886const UNKNOWN_ADDRESS: &str = "00:00:00:00:00:00";
887
888/// What a device lookup knows about one peripheral the adapter has seen.
889#[derive(Debug, Clone, PartialEq, Eq)]
890struct KnownPeripheral {
891    /// What `aranet scan` prints (`create_identifier`): the MAC address on
892    /// Linux and Windows, the CoreBluetooth UUID on macOS.
893    identifier: String,
894    /// btleplug's device ID in the form the TUI and GUI store
895    /// (`peripheral.id().to_string()`): `hci0/dev_AA_BB_CC_DD_EE_FF` on Linux,
896    /// the UUID on macOS, the MAC address on Windows.
897    peripheral_id: String,
898    /// The Bluetooth address; `00:00:00:00:00:00` on macOS.
899    address: String,
900    /// The device's name as `peripheral_name` gives it: the advertised name,
901    /// or on macOS CoreBluetooth's own name for a peripheral that advertised
902    /// none.
903    name: Option<String>,
904}
905
906/// The peripherals a query picks, as indices into the slice given to `lookup`.
907#[derive(Debug, PartialEq, Eq)]
908enum Lookup {
909    /// Exactly one peripheral matches.
910    Found(usize),
911    /// Several peripherals match, in ascending order.
912    Ambiguous(Vec<usize>),
913    /// Nothing matches. `similar` are the peripherals whose name contains both
914    /// the query and `aranet`, ordered by name and then identifier.
915    NotFound { similar: Vec<usize> },
916}
917
918/// Trims `identifier`. An identifier that is empty after trimming is
919/// `Error::InvalidConfig("device identifier is empty")`.
920fn parse_query(identifier: &str) -> Result<&str> {
921    let query = identifier.trim();
922    if query.is_empty() {
923        return Err(Error::invalid_config("device identifier is empty"));
924    }
925    Ok(query)
926}
927
928/// Pick the peripheral that `query` names, ignoring case. `query` comes from
929/// `parse_query`, so it is trimmed and not empty.
930///
931/// The rules, in order. A later rule is used only when the earlier ones match
932/// nothing, so a device's own address beats a device named like it:
933/// 1. an identifier: the one `aranet scan` prints, btleplug's device ID (the
934///    `hci0/dev_…` form on Linux), or the Bluetooth address with or without
935///    colons, never `00:00:00:00:00:00`;
936/// 2. the whole name, ignoring the spaces around it. Part of a name never
937///    matches, and that includes a name with a bracketed part: btleplug
938///    0.11.8 named some macOS peripherals
939///    `"<system name> [<advertised name>]"`, and 0.13.5 never builds that
940///    form (`src/corebluetooth/internal.rs:1003-1008`,
941///    `src/corebluetooth/peripheral.rs:221-235`).
942///
943/// One match is `Found` and several are `Ambiguous`. With no match, `NotFound`
944/// lists the peripherals whose name contains both `query` and `aranet`, so a
945/// short query never lists every phone and headset nearby. The answer depends
946/// only on which peripherals are known, never on their order.
947fn lookup(query: &str, known: &[KnownPeripheral]) -> Lookup {
948    let query = query.to_lowercase();
949    let bare_query = query.replace(':', "");
950
951    let by_identifier = matching(known, |peripheral| {
952        peripheral.identifier.to_lowercase() == query
953            || peripheral.peripheral_id.to_lowercase() == query
954            || (peripheral.address != UNKNOWN_ADDRESS
955                && peripheral.address.to_lowercase().replace(':', "") == bare_query)
956    });
957    if let Some(found) = decide(by_identifier) {
958        return found;
959    }
960
961    let by_name = matching(known, |peripheral| {
962        peripheral
963            .name
964            .as_deref()
965            .is_some_and(|name| name_matches(name, &query))
966    });
967    if let Some(found) = decide(by_name) {
968        return found;
969    }
970
971    let mut similar = matching(known, |peripheral| {
972        peripheral.name.as_deref().is_some_and(|name| {
973            let name = name.to_lowercase();
974            name.contains("aranet") && name.contains(&query)
975        })
976    });
977    similar.sort_by_key(|&index| (&known[index].name, &known[index].identifier));
978    Lookup::NotFound { similar }
979}
980
981/// Indices of the peripherals that satisfy `predicate`, in ascending order.
982fn matching(known: &[KnownPeripheral], predicate: impl Fn(&KnownPeripheral) -> bool) -> Vec<usize> {
983    known
984        .iter()
985        .enumerate()
986        .filter_map(|(index, peripheral)| predicate(peripheral).then_some(index))
987        .collect()
988}
989
990/// `Found` for one index, `Ambiguous` for several, `None` for none.
991fn decide(indices: Vec<usize>) -> Option<Lookup> {
992    match indices.len() {
993        0 => None,
994        1 => Some(Lookup::Found(indices[0])),
995        _ => Some(Lookup::Ambiguous(indices)),
996    }
997}
998
999/// Whether `name` is `query` (lower case): the whole name, ignoring case and
1000/// the spaces around it.
1001fn name_matches(name: &str, query: &str) -> bool {
1002    name.trim().to_lowercase() == query
1003}
1004
1005/// What a search of the known peripherals found.
1006#[derive(Debug, PartialEq, Eq)]
1007enum Search<T> {
1008    /// The one peripheral the query names.
1009    Found(T),
1010    /// Nothing matches; `similar` are the names that contain the query,
1011    /// trimmed, sorted and without duplicates.
1012    Missing { similar: Vec<String> },
1013}
1014
1015/// `lookup`'s answer for `query`, with `Found` holding an index into `known`.
1016///
1017/// An ambiguous query is an error,
1018/// `Error::DeviceNotFound(DeviceNotFoundReason::Ambiguous { .. })`, whose
1019/// candidates are `"<name or 'unnamed'> (<identifier>)"`, sorted: scanning
1020/// again can't make it less ambiguous, so the find loop returns it at once.
1021fn resolve(query: &str, known: &[KnownPeripheral]) -> Result<Search<usize>> {
1022    use crate::error::DeviceNotFoundReason;
1023
1024    match lookup(query, known) {
1025        Lookup::Found(index) => Ok(Search::Found(index)),
1026        Lookup::Ambiguous(indices) => {
1027            let mut candidates: Vec<String> = indices
1028                .iter()
1029                .map(|&index| {
1030                    let device = &known[index];
1031                    let name = device.name.as_deref().unwrap_or("unnamed");
1032                    format!("{name} ({})", device.identifier)
1033                })
1034                .collect();
1035            candidates.sort();
1036            Err(Error::DeviceNotFound(DeviceNotFoundReason::Ambiguous {
1037                identifier: query.to_string(),
1038                candidates,
1039            }))
1040        }
1041        Lookup::NotFound { similar } => {
1042            let mut names: Vec<String> = similar
1043                .iter()
1044                .filter_map(|&index| known[index].name.as_deref())
1045                .map(|name| name.trim().to_string())
1046                .collect();
1047            names.sort();
1048            names.dedup();
1049            Ok(Search::Missing { similar: names })
1050        }
1051    }
1052}
1053
1054/// Look `query` up among the peripherals that `adapter` already knows, as
1055/// `resolve` decides.
1056async fn search_known_peripherals(adapter: &Adapter, query: &str) -> Result<Search<Peripheral>> {
1057    let mut peripherals = Vec::new();
1058    let mut known = Vec::new();
1059    for peripheral in adapter.peripherals().await? {
1060        if let Ok(Some(props)) = peripheral.properties().await {
1061            let id = peripheral.id();
1062            let address = props.address.to_string();
1063            known.push(KnownPeripheral {
1064                identifier: create_identifier(&address, &id),
1065                peripheral_id: id.to_string(),
1066                address,
1067                name: peripheral_name(&props).map(str::to_owned),
1068            });
1069            peripherals.push(peripheral);
1070        }
1071    }
1072
1073    match resolve(query, &known)? {
1074        Search::Found(index) => {
1075            let device = &known[index];
1076            debug!("Matched {:?} ({})", device.name, device.identifier);
1077            Ok(Search::Found(peripherals.swap_remove(index)))
1078        }
1079        Search::Missing { similar } => Ok(Search::Missing { similar }),
1080    }
1081}
1082
1083#[cfg(test)]
1084mod tests {
1085    use super::*;
1086
1087    use std::sync::atomic::{AtomicBool, Ordering};
1088
1089    use futures::FutureExt;
1090
1091    use crate::error::DeviceNotFoundReason;
1092    use crate::test_support::within;
1093
1094    // ==================== ScanOptions Tests ====================
1095
1096    #[test]
1097    fn test_scan_options_default() {
1098        let options = ScanOptions::default();
1099        assert_eq!(options.duration, Duration::from_secs(5));
1100        assert!(options.filter_aranet_only);
1101    }
1102
1103    #[test]
1104    fn test_scan_options_new() {
1105        let options = ScanOptions::new();
1106        assert_eq!(options.duration, Duration::from_secs(5));
1107        assert!(options.filter_aranet_only);
1108    }
1109
1110    #[test]
1111    fn test_scan_options_duration() {
1112        let options = ScanOptions::new().duration(Duration::from_secs(10));
1113        assert_eq!(options.duration, Duration::from_secs(10));
1114    }
1115
1116    #[test]
1117    fn test_scan_options_duration_secs() {
1118        let options = ScanOptions::new().duration_secs(15);
1119        assert_eq!(options.duration, Duration::from_secs(15));
1120    }
1121
1122    #[test]
1123    fn test_scan_options_filter_aranet_only() {
1124        let options = ScanOptions::new().filter_aranet_only(false);
1125        assert!(!options.filter_aranet_only);
1126
1127        let options = ScanOptions::new().filter_aranet_only(true);
1128        assert!(options.filter_aranet_only);
1129    }
1130
1131    #[test]
1132    fn test_scan_options_all_devices() {
1133        let options = ScanOptions::new().all_devices();
1134        assert!(!options.filter_aranet_only);
1135    }
1136
1137    #[test]
1138    fn test_scan_options_chaining() {
1139        let options = ScanOptions::new()
1140            .duration_secs(20)
1141            .filter_aranet_only(false);
1142
1143        assert_eq!(options.duration, Duration::from_secs(20));
1144        assert!(!options.filter_aranet_only);
1145    }
1146
1147    #[test]
1148    fn test_scan_options_clone() {
1149        let options1 = ScanOptions::new().duration_secs(8);
1150        let options2 = options1.clone();
1151
1152        assert_eq!(options1.duration, options2.duration);
1153        assert_eq!(options1.filter_aranet_only, options2.filter_aranet_only);
1154    }
1155
1156    #[test]
1157    fn test_scan_options_debug() {
1158        let options = ScanOptions::new();
1159        let debug = format!("{:?}", options);
1160        assert!(debug.contains("ScanOptions"));
1161        assert!(debug.contains("duration"));
1162        assert!(debug.contains("filter_aranet_only"));
1163    }
1164
1165    // ==================== FindProgress Tests ====================
1166
1167    #[test]
1168    fn test_find_progress_cache_hit() {
1169        let progress = FindProgress::CacheHit;
1170        let debug = format!("{:?}", progress);
1171        assert!(debug.contains("CacheHit"));
1172    }
1173
1174    #[test]
1175    fn test_find_progress_scan_attempt() {
1176        let progress = FindProgress::ScanAttempt {
1177            attempt: 2,
1178            total: 3,
1179            duration_secs: 5,
1180        };
1181
1182        if let FindProgress::ScanAttempt {
1183            attempt,
1184            total,
1185            duration_secs,
1186        } = progress
1187        {
1188            assert_eq!(attempt, 2);
1189            assert_eq!(total, 3);
1190            assert_eq!(duration_secs, 5);
1191        } else {
1192            panic!("Expected ScanAttempt variant");
1193        }
1194    }
1195
1196    #[test]
1197    fn test_find_progress_found() {
1198        let progress = FindProgress::Found { attempt: 1 };
1199        assert!(matches!(progress, FindProgress::Found { attempt: 1 }));
1200    }
1201
1202    #[test]
1203    fn test_find_progress_retry_needed() {
1204        let progress = FindProgress::RetryNeeded { attempt: 2 };
1205        assert!(matches!(progress, FindProgress::RetryNeeded { attempt: 2 }));
1206    }
1207
1208    #[test]
1209    fn test_find_progress_clone() {
1210        let progress1 = FindProgress::ScanAttempt {
1211            attempt: 1,
1212            total: 3,
1213            duration_secs: 4,
1214        };
1215        let progress2 = progress1.clone();
1216
1217        assert!(matches!(
1218            (&progress1, &progress2),
1219            (
1220                FindProgress::ScanAttempt {
1221                    attempt: 1,
1222                    total: 3,
1223                    duration_secs: 4,
1224                },
1225                FindProgress::ScanAttempt {
1226                    attempt: 1,
1227                    total: 3,
1228                    duration_secs: 4,
1229                },
1230            )
1231        ));
1232    }
1233
1234    // ==================== Bluetooth Manager Tests ====================
1235
1236    /// bluez-async spawns the D-Bus connection's only I/O task on the runtime
1237    /// that creates the manager, and `shared_manager` caches the manager for the
1238    /// whole process, so that task has to outlive the runtime that created it.
1239    /// Needs a system bus but not BlueZ: an error reply (no `org.bluez` on the
1240    /// bus) still proves the connection works; only a missing reply fails.
1241    ///
1242    /// To run it on a Linux host:
1243    /// `cargo test --locked -p aranet-core --lib manager_still_answers -- --ignored`.
1244    /// In a Debian container, start a throwaway system bus first:
1245    /// `apt-get install dbus; mkdir -p /run/dbus; dbus-daemon --system --fork`.
1246    #[cfg(target_os = "linux")]
1247    #[test]
1248    #[ignore = "needs a system D-Bus (BlueZ not required)"]
1249    fn manager_still_answers_after_its_first_runtime_shuts_down() {
1250        let runtime = || {
1251            tokio::runtime::Builder::new_current_thread()
1252                .enable_all()
1253                .build()
1254                .unwrap()
1255        };
1256
1257        let first = runtime();
1258        let manager = first.block_on(shared_manager()).expect("manager");
1259        drop(first);
1260
1261        let second = runtime();
1262        let answered = second.block_on(async {
1263            tokio::time::timeout(Duration::from_secs(5), manager.adapters()).await
1264        });
1265        assert!(
1266            answered.is_ok(),
1267            "the manager's D-Bus connection died with the runtime that created it"
1268        );
1269    }
1270
1271    // ==================== Scan Window Tests ====================
1272
1273    /// Longest any scan-window test may take on the paused clock.
1274    const TEST_LIMIT: Duration = Duration::from_secs(600);
1275
1276    fn secs(n: u64) -> Duration {
1277        Duration::from_secs(n)
1278    }
1279
1280    /// A scanner that behaves like BlueZ: one discovery session per D-Bus
1281    /// client, so a second `start` before `stop` fails with InProgress. It logs
1282    /// when each start and stop happened, measured from its creation.
1283    #[derive(Clone)]
1284    struct FakeScanner {
1285        started_at: tokio::time::Instant,
1286        log: Arc<std::sync::Mutex<Vec<(Duration, &'static str)>>>,
1287        scanning: Arc<AtomicBool>,
1288        fail_start: bool,
1289        /// How long `stop` takes to end the session: StopDiscovery is a D-Bus
1290        /// round trip on BlueZ.
1291        stop_latency: Duration,
1292        on_stop: Option<std::sync::mpsc::Sender<()>>,
1293    }
1294
1295    impl FakeScanner {
1296        fn new() -> Self {
1297            Self {
1298                started_at: tokio::time::Instant::now(),
1299                log: Arc::default(),
1300                scanning: Arc::default(),
1301                fail_start: false,
1302                stop_latency: Duration::ZERO,
1303                on_stop: None,
1304            }
1305        }
1306
1307        fn record(&self, event: &'static str) {
1308            self.log
1309                .lock()
1310                .unwrap()
1311                .push((self.started_at.elapsed(), event));
1312        }
1313
1314        fn log(&self) -> Vec<(Duration, &'static str)> {
1315            self.log.lock().unwrap().clone()
1316        }
1317
1318        fn is_scanning(&self) -> bool {
1319            self.scanning.load(Ordering::SeqCst)
1320        }
1321    }
1322
1323    impl ScanControl for FakeScanner {
1324        async fn start(&self, _filter: ScanFilter) -> Result<()> {
1325            if self.fail_start {
1326                return Err(Error::InvalidData("start failed".into()));
1327            }
1328            if self.scanning.swap(true, Ordering::SeqCst) {
1329                return Err(Error::InvalidData("org.bluez.Error.InProgress".into()));
1330            }
1331            self.record("start");
1332            Ok(())
1333        }
1334
1335        async fn stop(&self) -> Result<()> {
1336            self.record("stop");
1337            sleep(self.stop_latency).await;
1338            self.scanning.store(false, Ordering::SeqCst);
1339            if let Some(on_stop) = &self.on_stop {
1340                let _ = on_stop.send(());
1341            }
1342            Ok(())
1343        }
1344    }
1345
1346    #[tokio::test(start_paused = true)]
1347    async fn scan_window_stops_the_scan_when_the_window_ends() {
1348        within(TEST_LIMIT, async {
1349            let rt = tokio::runtime::Handle::current();
1350            let lock = ScanLock::default();
1351            let scanner = FakeScanner::new();
1352
1353            let permit = lock.acquire().await;
1354            scan_window(&rt, &scanner, permit, ScanFilter::default(), secs(5))
1355                .await
1356                .unwrap();
1357
1358            assert_eq!(scanner.log(), [(secs(0), "start"), (secs(5), "stop")]);
1359            assert!(!scanner.is_scanning());
1360        })
1361        .await;
1362    }
1363
1364    #[tokio::test(start_paused = true)]
1365    async fn dropping_the_caller_stops_the_scan_immediately() {
1366        within(TEST_LIMIT, async {
1367            let rt = tokio::runtime::Handle::current();
1368            let lock = ScanLock::default();
1369            let scanner = FakeScanner::new();
1370
1371            let permit = lock.acquire().await;
1372            let window = scan_window(&rt, &scanner, permit, ScanFilter::default(), secs(5));
1373            assert!(tokio::time::timeout(secs(1), window).await.is_err());
1374            tokio::time::sleep(Duration::from_millis(10)).await;
1375
1376            assert_eq!(scanner.log(), [(secs(0), "start"), (secs(1), "stop")]);
1377            assert!(!scanner.is_scanning());
1378        })
1379        .await;
1380    }
1381
1382    #[tokio::test(start_paused = true)]
1383    async fn aborting_the_task_stops_the_scan() {
1384        within(TEST_LIMIT, async {
1385            let rt = tokio::runtime::Handle::current();
1386            let lock = ScanLock::default();
1387            let scanner = FakeScanner::new();
1388
1389            // A service reload or stop aborts its tasks like this (`abort_all`).
1390            let task = tokio::spawn({
1391                let scanner = scanner.clone();
1392                let lock = lock.clone();
1393                async move {
1394                    let permit = lock.acquire().await;
1395                    scan_window(&rt, &scanner, permit, ScanFilter::default(), secs(5)).await
1396                }
1397            });
1398            tokio::time::sleep(secs(1)).await;
1399            task.abort();
1400            assert!(task.await.unwrap_err().is_cancelled());
1401            tokio::time::sleep(Duration::from_millis(10)).await;
1402
1403            assert_eq!(scanner.log(), [(secs(0), "start"), (secs(1), "stop")]);
1404            assert!(!scanner.is_scanning());
1405        })
1406        .await;
1407    }
1408
1409    #[tokio::test(start_paused = true)]
1410    async fn failed_start_releases_the_permit_without_stopping() {
1411        within(TEST_LIMIT, async {
1412            let rt = tokio::runtime::Handle::current();
1413            let lock = ScanLock::default();
1414            let scanner = FakeScanner {
1415                fail_start: true,
1416                ..FakeScanner::new()
1417            };
1418
1419            let permit = lock.acquire().await;
1420            let result = scan_window(&rt, &scanner, permit, ScanFilter::default(), secs(5)).await;
1421
1422            assert!(matches!(result, Err(Error::InvalidData(ref m)) if m == "start failed"));
1423            assert!(
1424                scanner.log().is_empty(),
1425                "a scan that never started must not be stopped"
1426            );
1427            within(secs(1), lock.acquire()).await;
1428        })
1429        .await;
1430    }
1431
1432    #[test]
1433    fn scan_stops_after_the_callers_runtime_shuts_down() {
1434        let (tx, rx) = std::sync::mpsc::channel();
1435        let caller = tokio::runtime::Builder::new_current_thread()
1436            .enable_all()
1437            .build()
1438            .unwrap();
1439
1440        caller.block_on(async {
1441            let lock = ScanLock::default();
1442            let scanner = FakeScanner {
1443                on_stop: Some(tx),
1444                ..FakeScanner::new()
1445            };
1446            let permit = lock.acquire().await;
1447            // Through `run_scan`, which picks the runtime the window runs on.
1448            let window = run_scan(&scanner, permit, ScanFilter::default(), secs(10));
1449            let started = async {
1450                while !scanner.is_scanning() {
1451                    tokio::time::sleep(Duration::from_millis(1)).await;
1452                }
1453            };
1454            // Give up on the window once its scan is running, however late the
1455            // aranet-ble thread gets to it.
1456            tokio::select! {
1457                result = window => panic!("the 10 s window ended early: {result:?}"),
1458                started = tokio::time::timeout(secs(5), started) => {
1459                    started.expect("the scan never started");
1460                }
1461            }
1462        });
1463        drop(caller);
1464
1465        rx.recv_timeout(secs(5))
1466            .expect("scan never stopped after the caller's runtime shut down");
1467    }
1468
1469    #[tokio::test(start_paused = true)]
1470    async fn concurrent_scans_run_one_after_another() {
1471        within(TEST_LIMIT, async {
1472            let rt = tokio::runtime::Handle::current();
1473            let lock = ScanLock::default();
1474            let scanner = FakeScanner {
1475                stop_latency: Duration::from_millis(100),
1476                ..FakeScanner::new()
1477            };
1478            let scan = || async {
1479                let permit = lock.acquire().await;
1480                scan_window(&rt, &scanner, permit, ScanFilter::default(), secs(2)).await
1481            };
1482
1483            let (first, second) = tokio::join!(scan(), scan());
1484
1485            first.expect("first scan");
1486            second.expect("second scan should wait for the first instead of failing");
1487            assert_eq!(
1488                scanner.log(),
1489                [
1490                    (secs(0), "start"),
1491                    (secs(2), "stop"),
1492                    (Duration::from_millis(2100), "start"),
1493                    (Duration::from_millis(4100), "stop"),
1494                ]
1495            );
1496        })
1497        .await;
1498    }
1499
1500    #[tokio::test(start_paused = true)]
1501    async fn next_scan_waits_until_a_cancelled_scan_has_stopped() {
1502        within(TEST_LIMIT, async {
1503            let rt = tokio::runtime::Handle::current();
1504            let lock = ScanLock::default();
1505            let scanner = FakeScanner::new();
1506
1507            let first = tokio::time::timeout(secs(1), async {
1508                let permit = lock.acquire().await;
1509                scan_window(&rt, &scanner, permit, ScanFilter::default(), secs(5)).await
1510            });
1511            let second = async {
1512                tokio::task::yield_now().await;
1513                let permit = lock.acquire().await;
1514                scan_window(&rt, &scanner, permit, ScanFilter::default(), secs(2)).await
1515            };
1516            let (first, second) = tokio::join!(first, second);
1517
1518            assert!(first.is_err(), "the first scan should have been cancelled");
1519            second.expect("the second scan should start after the first has stopped");
1520            assert_eq!(
1521                scanner.log(),
1522                [
1523                    (secs(0), "start"),
1524                    (secs(1), "stop"),
1525                    (secs(1), "start"),
1526                    (secs(3), "stop"),
1527                ]
1528            );
1529        })
1530        .await;
1531    }
1532
1533    #[tokio::test(start_paused = true)]
1534    async fn cancelling_while_waiting_for_the_permit_never_starts_a_scan() {
1535        within(TEST_LIMIT, async {
1536            let rt = tokio::runtime::Handle::current();
1537            let lock = ScanLock::default();
1538            let scanner = FakeScanner::new();
1539
1540            let permit = lock.acquire().await;
1541            let first = tokio::spawn({
1542                let (rt, scanner) = (rt.clone(), scanner.clone());
1543                async move {
1544                    scan_window(&rt, &scanner, permit, ScanFilter::default(), secs(5)).await
1545                }
1546            });
1547            let second = tokio::time::timeout(secs(1), async {
1548                let permit = lock.acquire().await;
1549                scan_window(&rt, &scanner, permit, ScanFilter::default(), secs(1)).await
1550            });
1551            assert!(
1552                second.await.is_err(),
1553                "the second scan should still be waiting for the permit"
1554            );
1555            tokio::time::sleep(secs(6)).await;
1556            first.await.unwrap().unwrap();
1557            assert_eq!(scanner.log(), [(secs(0), "start"), (secs(5), "stop")]);
1558
1559            // A caller dropped after taking the permit, before its window task
1560            // first ran: `now_or_never` polls the window once, then drops it.
1561            let permit = lock.acquire().await;
1562            let window = scan_window(&rt, &scanner, permit, ScanFilter::default(), secs(1));
1563            assert!(window.now_or_never().is_none());
1564            tokio::time::sleep(Duration::from_millis(10)).await;
1565            assert_eq!(scanner.log(), [(secs(0), "start"), (secs(5), "stop")]);
1566            within(secs(1), lock.acquire()).await;
1567        })
1568        .await;
1569    }
1570
1571    // ==================== Search Filter Tests ====================
1572
1573    /// The filters that the windows of a search with `windows` scan windows use,
1574    /// in order: the search asks `search_filter` once per window.
1575    fn search_filters(windows: u32, aranet_only: bool) -> Vec<ScanFilter> {
1576        (1..=windows).map(|_| search_filter(aranet_only)).collect()
1577    }
1578
1579    #[test]
1580    fn search_filter_asks_only_for_aranet_sensors_in_every_window() {
1581        let aranet = ScanFilter {
1582            services: vec![SAF_TEHNIKA_SERVICE_NEW, SAF_TEHNIKA_SERVICE_OLD],
1583        };
1584        for windows in 1..=3 {
1585            assert_eq!(
1586                search_filters(windows, true),
1587                vec![aranet.clone(); windows as usize],
1588                "{windows}-window search"
1589            );
1590        }
1591    }
1592
1593    #[test]
1594    fn search_filter_asks_for_every_device_when_not_filtering() {
1595        for windows in 1..=3 {
1596            assert_eq!(
1597                search_filters(windows, false),
1598                vec![ScanFilter::default(); windows as usize],
1599                "{windows}-window search"
1600            );
1601        }
1602    }
1603
1604    // ==================== Missed Scan Tests ====================
1605
1606    #[test]
1607    fn a_search_fails_after_the_first_scan_that_finds_only_similar_names() {
1608        // A partial name such as `-d Aranet4` fails as soon as a scan window
1609        // ends with names that contain it, not after the last window.
1610        for attempt in 1..=3 {
1611            let similar = vec!["Aranet4 12345".to_string(), "Aranet4 1ABCD".to_string()];
1612            match after_missed_scan("Aranet4", similar, attempt, 3) {
1613                ControlFlow::Break(Error::DeviceNotFound(DeviceNotFoundReason::NoExactMatch {
1614                    identifier,
1615                    similar,
1616                })) => {
1617                    assert_eq!(identifier, "Aranet4", "attempt {attempt}");
1618                    assert_eq!(
1619                        similar,
1620                        ["Aranet4 12345", "Aranet4 1ABCD"],
1621                        "attempt {attempt}"
1622                    );
1623                }
1624                other => panic!("attempt {attempt} of 3: {other:?}"),
1625            }
1626        }
1627    }
1628
1629    #[test]
1630    fn a_search_without_similar_names_scans_until_its_last_attempt() {
1631        for attempt in 1..3 {
1632            let decision = after_missed_scan("Aranet4 12345", Vec::new(), attempt, 3);
1633            assert!(
1634                matches!(decision, ControlFlow::Continue(())),
1635                "attempt {attempt} of 3: {decision:?}"
1636            );
1637        }
1638        match after_missed_scan("Aranet4 12345", Vec::new(), 3, 3) {
1639            ControlFlow::Break(Error::DeviceNotFound(DeviceNotFoundReason::NotFound {
1640                identifier,
1641            })) => assert_eq!(identifier, "Aranet4 12345"),
1642            other => panic!("attempt 3 of 3: {other:?}"),
1643        }
1644    }
1645
1646    // ==================== Aranet Detection Tests ====================
1647
1648    /// Properties that carry nothing but the two names btleplug reports.
1649    fn named(local_name: &str, advertisement_name: &str) -> btleplug::api::PeripheralProperties {
1650        btleplug::api::PeripheralProperties {
1651            local_name: Some(local_name.to_string()),
1652            advertisement_name: Some(advertisement_name.to_string()),
1653            ..Default::default()
1654        }
1655    }
1656
1657    #[test]
1658    fn is_aranet_device_recognises_a_sensor_by_its_name_alone() {
1659        // No manufacturer data and no service: the name is all there is. Both
1660        // fields hold it, as btleplug 0.13.5 reports a named sensor on BlueZ
1661        // while no alias is set, on CoreBluetooth once a name has been
1662        // advertised, and on WinRT before a connect, so the answer is the same
1663        // on every host.
1664        assert!(is_aranet_device(&named("Aranet4 12345", "Aranet4 12345")));
1665        assert!(is_aranet_device(&named("ARANET2 2751B", "ARANET2 2751B")));
1666        assert!(!is_aranet_device(&named("Standing desk", "Standing desk")));
1667        let unnamed = btleplug::api::PeripheralProperties::default();
1668        assert!(!is_aranet_device(&unnamed));
1669    }
1670
1671    #[test]
1672    fn is_aranet_device_takes_the_name_from_peripheral_name() {
1673        // As BlueZ reports a sensor that the user has renamed: the first name
1674        // is the alias, the second the sensor's own.
1675        assert!(is_aranet_device(&named("Kitchen", "Aranet4 12345")));
1676        // A device that the user has named after a sensor is not one.
1677        assert!(!is_aranet_device(&named("Aranet shelf", "Standing desk")));
1678    }
1679
1680    // ==================== Device Lookup Tests ====================
1681
1682    /// CoreBluetooth UUIDs as `aranet scan` prints them on macOS. The first two
1683    /// are those of a real Aranet2 and AranetRn+; the other two are made up.
1684    const UUID_1: &str = "1f8893bf-9f7e-02b4-ef4a-7718f4f5d4be";
1685    const UUID_2: &str = "387c18c7-299f-cc32-d01c-6cf29a8d3ca5";
1686    const UUID_3: &str = "5b0e4c1d-7a3f-4e2b-9c6d-8f1a2b3c4d5e";
1687    const UUID_4: &str = "c4a7e2d9-3b1f-4c8e-a6d5-2f9b8e7c1a04";
1688
1689    fn known(
1690        identifier: &str,
1691        peripheral_id: &str,
1692        address: &str,
1693        name: Option<&str>,
1694    ) -> KnownPeripheral {
1695        KnownPeripheral {
1696            identifier: identifier.to_string(),
1697            peripheral_id: peripheral_id.to_string(),
1698            address: address.to_string(),
1699            name: name.map(str::to_string),
1700        }
1701    }
1702
1703    /// A peripheral as CoreBluetooth reports it: a UUID and no address.
1704    fn on_macos(uuid: &str, name: &str) -> KnownPeripheral {
1705        known(uuid, uuid, UNKNOWN_ADDRESS, Some(name))
1706    }
1707
1708    /// A peripheral as BlueZ reports it: its address, and the device ID
1709    /// `hci0/dev_AA_BB_…` that btleplug's `PeripheralId` displays.
1710    fn on_linux(address: &str, name: &str) -> KnownPeripheral {
1711        let device_id = format!("hci0/dev_{}", address.replace(':', "_"));
1712        known(address, &device_id, address, Some(name))
1713    }
1714
1715    /// `lookup`'s answer as its kind and the identifiers it picked, so answers
1716    /// for the same peripherals in different orders can be compared.
1717    fn outcome(query: &str, known: &[KnownPeripheral]) -> (&'static str, Vec<String>) {
1718        let (kind, indices) = match lookup(query, known) {
1719            Lookup::Found(index) => ("found", vec![index]),
1720            Lookup::Ambiguous(indices) => ("ambiguous", indices),
1721            Lookup::NotFound { similar } => ("not found", similar),
1722        };
1723        let mut identifiers: Vec<String> = indices
1724            .iter()
1725            .map(|&index| known[index].identifier.clone())
1726            .collect();
1727        if kind == "ambiguous" {
1728            // In slice order, which depends on the shuffle.
1729            identifiers.sort();
1730        }
1731        (kind, identifiers)
1732    }
1733
1734    /// The candidates of the `Ambiguous` error that `resolve` returns.
1735    fn candidates(query: &str, known: &[KnownPeripheral]) -> Vec<String> {
1736        match resolve(query, known) {
1737            Err(Error::DeviceNotFound(crate::error::DeviceNotFoundReason::Ambiguous {
1738                identifier,
1739                candidates,
1740            })) => {
1741                assert_eq!(identifier, query);
1742                candidates
1743            }
1744            other => panic!("{query:?} is not ambiguous: {other:?}"),
1745        }
1746    }
1747
1748    #[test]
1749    fn lookup_does_not_match_part_of_a_name() {
1750        let devices = [
1751            on_macos(UUID_1, "Aranet4 12345"),
1752            on_macos(UUID_2, "Aranet4 1ABCD"),
1753        ];
1754        assert_eq!(
1755            lookup("Aranet4 1", &devices),
1756            Lookup::NotFound {
1757                similar: vec![0, 1]
1758            }
1759        );
1760    }
1761
1762    #[test]
1763    fn lookup_does_not_match_part_of_a_uuid() {
1764        let devices = [on_macos(UUID_1, "Aranet2 2751B")];
1765        for query in ["4", "1f8893bf"] {
1766            assert_eq!(
1767                lookup(query, &devices),
1768                Lookup::NotFound { similar: vec![] },
1769                "{query:?}"
1770            );
1771        }
1772    }
1773
1774    #[test]
1775    fn lookup_ignores_linux_object_path_fragments() {
1776        let devices = [on_linux("AA:BB:CC:DD:EE:FF", "Aranet4 12345")];
1777        for query in ["hci0", "dev"] {
1778            assert_eq!(
1779                lookup(query, &devices),
1780                Lookup::NotFound { similar: vec![] },
1781                "{query:?}"
1782            );
1783        }
1784    }
1785
1786    #[test]
1787    fn lookup_matches_the_bluez_device_id_display_form() {
1788        // The TUI and GUI keep `DiscoveredDevice::id.to_string()` as a device's
1789        // ID, store it in the database and connect with it later.
1790        let devices = [
1791            on_linux("11:22:33:44:55:66", "Aranet2 2751B"),
1792            on_linux("AA:BB:CC:DD:EE:FF", "Aranet4 12345"),
1793        ];
1794        for query in ["hci0/dev_AA_BB_CC_DD_EE_FF", "hci0/dev_aa_bb_cc_dd_ee_ff"] {
1795            assert_eq!(lookup(query, &devices), Lookup::Found(1), "{query:?}");
1796        }
1797    }
1798
1799    #[test]
1800    fn lookup_matches_the_full_name_ignoring_case_and_whitespace() {
1801        let devices = [
1802            on_macos(UUID_2, "AranetRn+ 306B8"),
1803            on_macos(UUID_1, "Aranet2 2751B"),
1804        ];
1805        let query = parse_query(" aranet2 2751b ").unwrap();
1806        assert_eq!(lookup(query, &devices), Lookup::Found(1));
1807    }
1808
1809    #[test]
1810    fn lookup_matches_a_uuid_in_any_case() {
1811        let devices = [
1812            on_macos(UUID_2, "AranetRn+ 306B8"),
1813            on_macos(UUID_1, "Aranet2 2751B"),
1814        ];
1815        assert_eq!(
1816            lookup("1F8893BF-9F7E-02B4-EF4A-7718F4F5D4BE", &devices),
1817            Lookup::Found(1)
1818        );
1819    }
1820
1821    #[test]
1822    fn lookup_matches_an_address_with_or_without_colons() {
1823        let devices = [
1824            on_linux("11:22:33:44:55:66", "Aranet2 2751B"),
1825            on_linux("AA:BB:CC:DD:EE:FF", "Aranet4 12345"),
1826        ];
1827        for query in ["aa:bb:cc:dd:ee:ff", "AABBCCDDEEFF"] {
1828            assert_eq!(lookup(query, &devices), Lookup::Found(1), "{query:?}");
1829        }
1830    }
1831
1832    #[test]
1833    fn lookup_never_matches_the_all_zero_address() {
1834        let devices = [on_macos(UUID_1, "Aranet2 2751B")];
1835        for query in ["00:00:00:00:00:00", "000000000000"] {
1836            assert_eq!(
1837                lookup(query, &devices),
1838                Lookup::NotFound { similar: vec![] },
1839                "{query:?}"
1840            );
1841        }
1842    }
1843
1844    /// Only the whole name matches, also when the name has a bracketed part.
1845    /// btleplug 0.11.8 named some macOS peripherals
1846    /// `"<system name> [<advertised name>]"`, and while aranet used it, each
1847    /// half of such a name matched too. btleplug 0.13.5 never builds that form.
1848    #[test]
1849    fn lookup_matches_a_name_with_a_bracketed_part_only_as_a_whole() {
1850        let devices = [
1851            on_macos(UUID_2, "AranetRn+ 306B8"),
1852            on_macos(UUID_1, "Kitchen [Aranet4 1A2B3]"),
1853        ];
1854        assert_eq!(
1855            lookup("kitchen [aranet4 1a2b3]", &devices),
1856            Lookup::Found(1)
1857        );
1858        for half in ["Kitchen", "Aranet4 1A2B3"] {
1859            assert_eq!(
1860                lookup(half, &devices),
1861                Lookup::NotFound { similar: vec![1] },
1862                "{half:?}"
1863            );
1864        }
1865    }
1866
1867    #[test]
1868    fn lookup_ignores_spaces_around_a_device_name() {
1869        let devices = [on_macos(UUID_1, " Aranet2 2751B ")];
1870        assert_eq!(lookup("aranet2 2751b", &devices), Lookup::Found(0));
1871    }
1872
1873    #[test]
1874    fn lookup_prefers_an_identifier_match_over_a_name_match() {
1875        let devices = [
1876            on_macos(UUID_1, "AA:BB:CC:DD:EE:FF"),
1877            on_linux("AA:BB:CC:DD:EE:FF", "Aranet4 12345"),
1878        ];
1879        assert_eq!(lookup("aa:bb:cc:dd:ee:ff", &devices), Lookup::Found(1));
1880    }
1881
1882    #[test]
1883    fn lookup_reports_duplicate_names_as_ambiguous() {
1884        let devices = [
1885            on_macos(UUID_1, "Aranet4 12345"),
1886            on_macos(UUID_2, "Aranet4 12345"),
1887        ];
1888        assert_eq!(
1889            lookup("Aranet4 12345", &devices),
1890            Lookup::Ambiguous(vec![0, 1])
1891        );
1892    }
1893
1894    #[test]
1895    fn lookup_suggests_only_aranet_names() {
1896        // "Standing desk" contains the query too, but it isn't an Aranet.
1897        let devices = [
1898            on_macos(UUID_1, "Aranet4 12345"),
1899            on_macos(UUID_2, "Standing desk"),
1900            on_macos(UUID_3, "Aranet2 2751B"),
1901        ];
1902        assert_eq!(
1903            lookup("an", &devices),
1904            Lookup::NotFound {
1905                similar: vec![2, 0]
1906            }
1907        );
1908    }
1909
1910    /// Every order of the indices `0..n`.
1911    fn orders(n: usize) -> Vec<Vec<usize>> {
1912        if n == 0 {
1913            return vec![Vec::new()];
1914        }
1915        let mut all = Vec::new();
1916        for shorter in orders(n - 1) {
1917            for at in 0..n {
1918                let mut order = shorter.clone();
1919                order.insert(at, n - 1);
1920                all.push(order);
1921            }
1922        }
1923        all
1924    }
1925
1926    #[test]
1927    fn lookup_result_is_independent_of_order() {
1928        let devices = [
1929            on_macos(UUID_1, "Aranet4 12345"),
1930            on_macos(UUID_2, "Aranet4 1ABCD"),
1931            on_macos(UUID_3, "Aranet2 2751B"),
1932            // A second sensor with the first one's name.
1933            on_macos(UUID_4, "Aranet4 12345"),
1934        ];
1935        let cases = [
1936            ("Aranet4 1", "not found", vec![UUID_1, UUID_4, UUID_2]),
1937            ("aranet2 2751b", "found", vec![UUID_3]),
1938            ("Aranet4", "not found", vec![UUID_1, UUID_4, UUID_2]),
1939            ("Aranet4 12345", "ambiguous", vec![UUID_1, UUID_4]),
1940        ];
1941        for (query, kind, identifiers) in cases {
1942            let outcomes: Vec<(&str, Vec<String>)> = orders(devices.len())
1943                .iter()
1944                .map(|order| {
1945                    let shuffled: Vec<KnownPeripheral> =
1946                        order.iter().map(|&index| devices[index].clone()).collect();
1947                    outcome(query, &shuffled)
1948                })
1949                .collect();
1950            assert!(
1951                outcomes.iter().all(|answer| *answer == outcomes[0]),
1952                "the answer for {query:?} depends on the order: {outcomes:?}"
1953            );
1954            assert_eq!(outcomes[0].0, kind, "{query:?}");
1955            assert_eq!(outcomes[0].1, identifiers, "{query:?}");
1956        }
1957    }
1958
1959    #[test]
1960    fn resolve_lists_candidates_and_similar_names_sorted() {
1961        // Two sensors share a name; the one listed second sorts first.
1962        let same_name = [
1963            on_macos(UUID_2, "Aranet4 12345"),
1964            on_macos(UUID_1, "Aranet4 12345"),
1965        ];
1966        assert_eq!(
1967            candidates("Aranet4 12345", &same_name),
1968            [
1969                format!("Aranet4 12345 ({UUID_1})"),
1970                format!("Aranet4 12345 ({UUID_2})"),
1971            ]
1972        );
1973
1974        // Two entries with one address, the first without a name.
1975        let one_address = [
1976            known(
1977                "AA:BB:CC:DD:EE:FF",
1978                "hci1/dev_AA_BB_CC_DD_EE_FF",
1979                "AA:BB:CC:DD:EE:FF",
1980                None,
1981            ),
1982            on_linux("AA:BB:CC:DD:EE:FF", "Aranet4 12345"),
1983        ];
1984        assert_eq!(
1985            candidates("aa:bb:cc:dd:ee:ff", &one_address),
1986            [
1987                "Aranet4 12345 (AA:BB:CC:DD:EE:FF)",
1988                "unnamed (AA:BB:CC:DD:EE:FF)",
1989            ]
1990        );
1991
1992        // Similar names come back trimmed, sorted and without duplicates.
1993        let similar = [
1994            on_macos(UUID_1, "Aranet4 1ABCD "),
1995            on_macos(UUID_2, "Aranet4 12345"),
1996            on_macos(UUID_3, "Aranet4 1ABCD"),
1997        ];
1998        assert_eq!(
1999            resolve("aranet4 1", &similar).unwrap(),
2000            Search::Missing {
2001                similar: vec!["Aranet4 12345".to_string(), "Aranet4 1ABCD".to_string()]
2002            }
2003        );
2004    }
2005
2006    #[test]
2007    fn parse_query_rejects_empty_and_blank_identifiers() {
2008        for identifier in ["", "   ", "\t\n"] {
2009            assert!(
2010                matches!(parse_query(identifier), Err(Error::InvalidConfig(_))),
2011                "{identifier:?}"
2012            );
2013        }
2014        assert_eq!(parse_query(" x ").unwrap(), "x");
2015    }
2016
2017    #[tokio::test]
2018    async fn find_device_rejects_an_empty_identifier_without_bluetooth() {
2019        // The real clock, unlike the other async tests here. Both calls must
2020        // return before they touch Bluetooth. If one reached the Bluetooth
2021        // stack, a paused clock would jump to the limit while the call waited
2022        // on the `aranet-ble` thread, and the failure would show a timeout
2023        // instead of the stack's own error. A correct call never waits, so the
2024        // 5 s limit matters only then.
2025        let found = within(Duration::from_secs(5), find_device("")).await;
2026        assert!(
2027            matches!(found, Err(Error::InvalidConfig(_))),
2028            "{:?}",
2029            found.err()
2030        );
2031
2032        let connected = within(Duration::from_secs(5), crate::device::Device::connect("  ")).await;
2033        assert!(
2034            matches!(connected, Err(Error::InvalidConfig(_))),
2035            "{:?}",
2036            connected.err()
2037        );
2038    }
2039
2040    // ==================== DiscoveredDevice Tests ====================
2041    // Note: this module has no test that builds a DiscoveredDevice. Its `id` is
2042    // btleplug's PeripheralId, which wraps a different type on each platform
2043    // (btleplug 0.13.5):
2044    // - macOS: PeripheralId wraps a UUID (`src/corebluetooth/peripheral.rs:46`)
2045    // - Linux: PeripheralId wraps bluez_async::DeviceId
2046    //   (`src/bluez/peripheral.rs:49`). btleplug doesn't re-export bluez-async
2047    //   and aranet-core doesn't depend on it directly, so this crate can't name
2048    //   that type to make one
2049    // - Windows: PeripheralId wraps a BDAddr (`src/winrtble/peripheral.rs:57`)
2050    //
2051    // The DiscoveredDevice struct derives Clone and Debug, so these traits are
2052    // guaranteed to work correctly by the compiler.
2053}