aranet_core/
passive.rs

1//! Passive monitoring via BLE advertisements.
2//!
3//! This module provides functionality to monitor Aranet devices without
4//! establishing a connection, using BLE advertisement data instead.
5//!
6//! # Benefits
7//!
8//! - **Lower power consumption**: No connection overhead
9//! - **More devices**: Can monitor more than the BLE connection limit
10//! - **Simpler**: No connection management needed
11//!
12//! # Requirements
13//!
14//! Smart Home integration must be enabled on each device:
15//! - Go to device Settings > Smart Home > Enable
16//!
17//! # Example
18//!
19//! ```ignore
20//! use aranet_core::passive::{PassiveMonitor, PassiveMonitorOptions};
21//! use tokio_util::sync::CancellationToken;
22//!
23//! let monitor = PassiveMonitor::new(PassiveMonitorOptions::default());
24//! let cancel = CancellationToken::new();
25//!
26//! // Start monitoring in background
27//! let handle = monitor.start(cancel.clone());
28//!
29//! // Receive readings
30//! let mut rx = monitor.subscribe();
31//! while let Ok(reading) = rx.recv().await {
32//!     println!("Device: {} CO2: {:?}", reading.device_name, reading.data.co2);
33//! }
34//! ```
35
36use std::collections::HashMap;
37use std::sync::Arc;
38use std::time::Duration;
39
40use btleplug::api::{Central, Peripheral as _, ScanFilter};
41use tokio::sync::{RwLock, broadcast};
42use tokio::time::sleep;
43use tokio_util::sync::CancellationToken;
44use tracing::{debug, info, warn};
45
46use crate::advertisement::{AdvertisementData, parse_advertisement_with_name};
47use crate::error::Result;
48use crate::scan::get_adapter;
49use crate::util::peripheral_name;
50use crate::uuid::MANUFACTURER_ID;
51
52/// Bitwise-exact comparison of two `Option<f32>` values (handles NaN correctly).
53fn opt_f32_eq(a: Option<f32>, b: Option<f32>) -> bool {
54    match (a, b) {
55        (Some(x), Some(y)) => x.to_bits() == y.to_bits(),
56        (None, None) => true,
57        _ => false,
58    }
59}
60
61/// A reading from passive advertisement monitoring.
62#[derive(Debug, Clone)]
63pub struct PassiveReading {
64    /// Device identifier (MAC address or UUID).
65    pub device_id: String,
66    /// Device name if available.
67    pub device_name: Option<String>,
68    /// RSSI signal strength.
69    pub rssi: Option<i16>,
70    /// Parsed advertisement data.
71    pub data: AdvertisementData,
72    /// When this reading was received.
73    pub received_at: std::time::Instant,
74}
75
76/// Options for passive monitoring.
77#[derive(Debug, Clone)]
78pub struct PassiveMonitorOptions {
79    /// How long to scan between processing cycles.
80    pub scan_duration: Duration,
81    /// Delay between scan cycles.
82    pub scan_interval: Duration,
83    /// Channel capacity for readings.
84    pub channel_capacity: usize,
85    /// Only emit readings when values change (deduplicate).
86    pub deduplicate: bool,
87    /// Maximum age of cached readings before re-emitting (if deduplicate is true).
88    pub max_reading_age: Duration,
89    /// Filter to only these device IDs (empty = all Aranet devices).
90    pub device_filter: Vec<String>,
91}
92
93impl Default for PassiveMonitorOptions {
94    fn default() -> Self {
95        Self {
96            scan_duration: Duration::from_secs(5),
97            scan_interval: Duration::from_secs(1),
98            channel_capacity: 100,
99            deduplicate: true,
100            max_reading_age: Duration::from_secs(60),
101            device_filter: Vec::new(),
102        }
103    }
104}
105
106impl PassiveMonitorOptions {
107    /// Create new options with default settings.
108    pub fn new() -> Self {
109        Self::default()
110    }
111
112    /// Set the scan duration.
113    pub fn scan_duration(mut self, duration: Duration) -> Self {
114        self.scan_duration = duration;
115        self
116    }
117
118    /// Set the interval between scan cycles.
119    pub fn scan_interval(mut self, interval: Duration) -> Self {
120        self.scan_interval = interval;
121        self
122    }
123
124    /// Enable or disable deduplication.
125    pub fn deduplicate(mut self, enable: bool) -> Self {
126        self.deduplicate = enable;
127        self
128    }
129
130    /// Filter to specific device IDs.
131    pub fn filter_devices(mut self, device_ids: Vec<String>) -> Self {
132        self.device_filter = device_ids;
133        self
134    }
135}
136
137/// Cached reading for deduplication.
138struct CachedReading {
139    data: AdvertisementData,
140    received_at: std::time::Instant,
141}
142
143/// Passive monitor for Aranet devices using BLE advertisements.
144///
145/// This allows monitoring multiple devices without establishing connections,
146/// which is useful for scenarios where:
147/// - You need to monitor more devices than the BLE connection limit
148/// - Low power consumption is important
149/// - Real-time data isn't critical (advertisement interval is typically 4+ seconds)
150pub struct PassiveMonitor {
151    options: PassiveMonitorOptions,
152    /// Broadcast sender for readings.
153    sender: broadcast::Sender<PassiveReading>,
154    /// Cache of last readings for deduplication.
155    cache: Arc<RwLock<HashMap<String, CachedReading>>>,
156}
157
158impl PassiveMonitor {
159    /// Create a new passive monitor with the given options.
160    pub fn new(options: PassiveMonitorOptions) -> Self {
161        let (sender, _) = broadcast::channel(options.channel_capacity);
162        Self {
163            options,
164            sender,
165            cache: Arc::new(RwLock::new(HashMap::new())),
166        }
167    }
168
169    /// Subscribe to passive readings.
170    ///
171    /// Returns a receiver that will receive readings as they are detected.
172    pub fn subscribe(&self) -> broadcast::Receiver<PassiveReading> {
173        self.sender.subscribe()
174    }
175
176    /// Get the number of active subscribers.
177    pub fn subscriber_count(&self) -> usize {
178        self.sender.receiver_count()
179    }
180
181    /// Start the passive monitor.
182    ///
183    /// This spawns a background task that continuously scans for BLE
184    /// advertisements and parses Aranet device data.
185    ///
186    /// The task stops as soon as the cancellation token is triggered, even
187    /// while it gets the Bluetooth adapter, scans or waits.
188    pub fn start(self: &Arc<Self>, cancel_token: CancellationToken) -> tokio::task::JoinHandle<()> {
189        let monitor = Arc::clone(self);
190
191        tokio::spawn(async move {
192            info!("Starting passive monitor");
193
194            // Acquire the adapter once and reuse across scan cycles.
195            // On persistent errors we re-acquire it in case the adapter
196            // was reset or the D-Bus connection was lost.
197            let Some(mut adapter) = first_adapter(&cancel_token, get_adapter).await else {
198                info!("Passive monitor cancelled while waiting for adapter");
199                return;
200            };
201            let mut consecutive_errors: u32 = 0;
202
203            loop {
204                // One cycle: a scan, its error handling and the wait before the
205                // next scan. The whole cycle, waits included, ends as soon as the
206                // monitor is cancelled.
207                let cycle = async {
208                    match monitor.scan_cycle_with_adapter(&adapter).await {
209                        Ok(()) => {
210                            consecutive_errors = 0;
211                        }
212                        Err(e) => {
213                            consecutive_errors += 1;
214                            warn!(
215                                "Passive monitor scan error ({consecutive_errors} consecutive): {e}"
216                            );
217                            // After several consecutive failures, try to
218                            // re-acquire the adapter — it may have been
219                            // reset or the D-Bus connection may have died.
220                            if consecutive_errors >= 5 {
221                                warn!(
222                                    "Passive monitor: re-acquiring adapter after {} consecutive errors",
223                                    consecutive_errors
224                                );
225                                match get_adapter().await {
226                                    Ok(a) => {
227                                        adapter = a;
228                                        info!("Passive monitor: adapter re-acquired");
229                                        consecutive_errors = 0;
230                                    }
231                                    Err(e2) => {
232                                        // Adapter re-acquisition failed — back off
233                                        // longer to avoid thrashing when the adapter
234                                        // is permanently unavailable.
235                                        warn!(
236                                            "Passive monitor: failed to re-acquire adapter: {}. Backing off.",
237                                            e2
238                                        );
239                                        let backoff = std::cmp::min(
240                                            monitor
241                                                .options
242                                                .scan_interval
243                                                .saturating_mul(consecutive_errors),
244                                            std::time::Duration::from_secs(300),
245                                        );
246                                        sleep(backoff).await;
247                                    }
248                                }
249                            }
250                        }
251                    }
252                    // Wait before next scan cycle
253                    sleep(monitor.options.scan_interval).await;
254                };
255
256                tokio::select! {
257                    _ = cancel_token.cancelled() => {
258                        info!("Passive monitor cancelled");
259                        break;
260                    }
261                    () = cycle => {}
262                }
263            }
264        })
265    }
266
267    /// Perform a single scan cycle using a pre-existing adapter.
268    async fn scan_cycle_with_adapter(&self, adapter: &btleplug::platform::Adapter) -> Result<()> {
269        // Scan under the process-wide permit. The scan stops even if this cycle
270        // is cancelled part-way through.
271        let permit = crate::scan::scan_lock().acquire().await;
272        crate::scan::run_scan(
273            adapter,
274            permit,
275            ScanFilter::default(),
276            self.options.scan_duration,
277        )
278        .await?;
279
280        // Process discovered peripherals
281        let peripherals = adapter.peripherals().await?;
282
283        for peripheral in peripherals {
284            if let Ok(Some(props)) = peripheral.properties().await {
285                // Check if this is an Aranet device by manufacturer data
286                if let Some(data) = props.manufacturer_data.get(&MANUFACTURER_ID) {
287                    let device_id = crate::util::create_identifier(
288                        &props.address.to_string(),
289                        &peripheral.id(),
290                    );
291
292                    // Check device filter
293                    if !self.options.device_filter.is_empty()
294                        && !self.options.device_filter.contains(&device_id)
295                    {
296                        continue;
297                    }
298
299                    // Try to parse the advertisement
300                    match parse_advertisement_with_name(data, peripheral_name(&props)) {
301                        Ok(adv_data) => {
302                            // Check for deduplication
303                            let should_emit = if self.options.deduplicate {
304                                self.should_emit(&device_id, &adv_data).await
305                            } else {
306                                true
307                            };
308
309                            if should_emit {
310                                let reading = PassiveReading {
311                                    device_id: device_id.clone(),
312                                    device_name: peripheral_name(&props).map(str::to_owned),
313                                    rssi: props.rssi,
314                                    data: adv_data.clone(),
315                                    received_at: std::time::Instant::now(),
316                                };
317
318                                // Update cache
319                                self.cache.write().await.insert(
320                                    device_id,
321                                    CachedReading {
322                                        data: adv_data,
323                                        received_at: std::time::Instant::now(),
324                                    },
325                                );
326
327                                // Send to subscribers (ignore if no receivers)
328                                let _ = self.sender.send(reading);
329                            }
330                        }
331                        Err(e) => {
332                            debug!("Failed to parse advertisement from {}: {}", device_id, e);
333                        }
334                    }
335                }
336            }
337        }
338
339        Ok(())
340    }
341
342    /// Check if a reading should be emitted (for deduplication).
343    async fn should_emit(&self, device_id: &str, data: &AdvertisementData) -> bool {
344        let cache = self.cache.read().await;
345
346        if let Some(cached) = cache.get(device_id) {
347            // Check if reading is too old
348            if cached.received_at.elapsed() > self.options.max_reading_age {
349                return true;
350            }
351
352            // Check if values have changed (use total_cmp for floats to handle NaN correctly)
353            if cached.data.co2 != data.co2
354                || !opt_f32_eq(cached.data.temperature, data.temperature)
355                || cached.data.humidity != data.humidity
356                || !opt_f32_eq(cached.data.pressure, data.pressure)
357                || cached.data.radon != data.radon
358                || !opt_f32_eq(cached.data.radiation_dose_rate, data.radiation_dose_rate)
359                || cached.data.battery != data.battery
360            {
361                return true;
362            }
363
364            // Check if counter changed (new measurement)
365            if cached.data.counter != data.counter {
366                return true;
367            }
368
369            false
370        } else {
371            // Not in cache, emit
372            true
373        }
374    }
375
376    /// Get the last known reading for a device.
377    pub async fn get_last_reading(&self, device_id: &str) -> Option<AdvertisementData> {
378        let cache = self.cache.read().await;
379        cache.get(device_id).map(|c| c.data.clone())
380    }
381
382    /// Get all known device IDs.
383    pub async fn known_devices(&self) -> Vec<String> {
384        let cache = self.cache.read().await;
385        cache.keys().cloned().collect()
386    }
387
388    /// Clear the reading cache.
389    pub async fn clear_cache(&self) {
390        self.cache.write().await.clear();
391    }
392}
393
394impl Default for PassiveMonitor {
395    fn default() -> Self {
396        Self::new(PassiveMonitorOptions::default())
397    }
398}
399
400/// The adapter that a passive monitor starts with, from `get` (`get_adapter` in
401/// the library), which is called again 10 s after each failure. `None` as soon
402/// as `cancel` is triggered, even while `get` is still waiting for an answer,
403/// which on Linux can take up to the 30 s D-Bus timeout when bluetoothd is slow.
404async fn first_adapter<A, F>(cancel: &CancellationToken, mut get: impl FnMut() -> F) -> Option<A>
405where
406    F: Future<Output = Result<A>>,
407{
408    loop {
409        match cancel.run_until_cancelled(get()).await? {
410            Ok(adapter) => return Some(adapter),
411            Err(e) => {
412                warn!("Passive monitor failed to get adapter: {e} — retrying in 10s");
413                cancel
414                    .run_until_cancelled(sleep(Duration::from_secs(10)))
415                    .await?;
416            }
417        }
418    }
419}
420
421#[cfg(test)]
422mod tests {
423    use super::*;
424
425    use crate::error::{DeviceNotFoundReason, Error};
426    use crate::test_support::within;
427
428    #[test]
429    fn test_passive_monitor_options_default() {
430        let opts = PassiveMonitorOptions::default();
431        assert_eq!(opts.scan_duration, Duration::from_secs(5));
432        assert!(opts.deduplicate);
433        assert!(opts.device_filter.is_empty());
434    }
435
436    #[test]
437    fn test_passive_monitor_options_builder() {
438        let opts = PassiveMonitorOptions::new()
439            .scan_duration(Duration::from_secs(10))
440            .deduplicate(false)
441            .filter_devices(vec!["device1".to_string()]);
442
443        assert_eq!(opts.scan_duration, Duration::from_secs(10));
444        assert!(!opts.deduplicate);
445        assert_eq!(opts.device_filter, vec!["device1"]);
446    }
447
448    #[test]
449    fn test_passive_monitor_subscribe() {
450        let monitor = Arc::new(PassiveMonitor::default());
451        let _rx1 = monitor.subscribe();
452        let _rx2 = monitor.subscribe();
453        assert_eq!(monitor.subscriber_count(), 2);
454    }
455
456    /// Helper to create test advertisement data with sensible defaults.
457    fn make_adv_data() -> AdvertisementData {
458        AdvertisementData {
459            device_type: aranet_types::DeviceType::Aranet4,
460            co2: Some(800),
461            temperature: Some(22.5),
462            pressure: Some(1013.2),
463            humidity: Some(45),
464            battery: 85,
465            status: aranet_types::Status::Green,
466            interval: 300,
467            age: 120,
468            radon: None,
469            radiation_dose_rate: None,
470            counter: Some(5),
471            flags: 0x22,
472        }
473    }
474
475    #[tokio::test]
476    async fn test_should_emit_first_reading() {
477        let monitor = PassiveMonitor::default();
478        let data = make_adv_data();
479
480        // First reading for a device should always be emitted.
481        assert!(monitor.should_emit("device-1", &data).await);
482    }
483
484    #[tokio::test]
485    async fn test_should_emit_duplicate_suppressed() {
486        let monitor = PassiveMonitor::default();
487        let data = make_adv_data();
488
489        // Populate the cache.
490        monitor.cache.write().await.insert(
491            "device-1".to_string(),
492            CachedReading {
493                data: data.clone(),
494                received_at: std::time::Instant::now(),
495            },
496        );
497
498        // Identical reading should be suppressed.
499        assert!(!monitor.should_emit("device-1", &data).await);
500    }
501
502    #[tokio::test]
503    async fn test_should_emit_on_value_change() {
504        let monitor = PassiveMonitor::default();
505        let data = make_adv_data();
506
507        monitor.cache.write().await.insert(
508            "device-1".to_string(),
509            CachedReading {
510                data: data.clone(),
511                received_at: std::time::Instant::now(),
512            },
513        );
514
515        // Changed CO2 should trigger emission.
516        let mut changed = data.clone();
517        changed.co2 = Some(900);
518        assert!(monitor.should_emit("device-1", &changed).await);
519
520        // Changed battery should trigger emission.
521        let mut changed = data.clone();
522        changed.battery = 50;
523        assert!(monitor.should_emit("device-1", &changed).await);
524
525        // Changed temperature should trigger emission.
526        let mut changed = data;
527        changed.temperature = Some(23.0);
528        assert!(monitor.should_emit("device-1", &changed).await);
529    }
530
531    #[tokio::test]
532    async fn test_should_emit_on_counter_change() {
533        let monitor = PassiveMonitor::default();
534        let data = make_adv_data();
535
536        monitor.cache.write().await.insert(
537            "device-1".to_string(),
538            CachedReading {
539                data: data.clone(),
540                received_at: std::time::Instant::now(),
541            },
542        );
543
544        // Counter increment means a new measurement was taken.
545        let mut changed = data;
546        changed.counter = Some(6);
547        assert!(monitor.should_emit("device-1", &changed).await);
548    }
549
550    #[tokio::test]
551    async fn test_should_emit_on_stale_cache() {
552        let opts = PassiveMonitorOptions {
553            max_reading_age: Duration::from_millis(10),
554            ..Default::default()
555        };
556        let monitor = PassiveMonitor::new(opts);
557        let data = make_adv_data();
558
559        // Insert a reading that is already "old".
560        monitor.cache.write().await.insert(
561            "device-1".to_string(),
562            CachedReading {
563                data: data.clone(),
564                received_at: std::time::Instant::now() - Duration::from_millis(50),
565            },
566        );
567
568        // Identical data should still be emitted because the cache entry expired.
569        assert!(monitor.should_emit("device-1", &data).await);
570    }
571
572    #[tokio::test]
573    async fn test_should_emit_different_device() {
574        let monitor = PassiveMonitor::default();
575        let data = make_adv_data();
576
577        // Cache a reading for device-1.
578        monitor.cache.write().await.insert(
579            "device-1".to_string(),
580            CachedReading {
581                data: data.clone(),
582                received_at: std::time::Instant::now(),
583            },
584        );
585
586        // device-2 has no cache entry, so it should emit even with identical data.
587        assert!(monitor.should_emit("device-2", &data).await);
588    }
589
590    // ==================== First Adapter Tests ====================
591
592    /// Longest any first-adapter test may take on the paused clock.
593    const TEST_LIMIT: Duration = Duration::from_secs(600);
594
595    /// What `get_adapter` returns when the system has no Bluetooth adapter.
596    fn no_adapter() -> Error {
597        Error::DeviceNotFound(DeviceNotFoundReason::NoAdapter)
598    }
599
600    #[tokio::test(start_paused = true)]
601    async fn a_cancel_stops_the_first_adapter_fetch() {
602        within(TEST_LIMIT, async {
603            // A fetch that never answers, like a D-Bus call to a stalled
604            // bluetoothd, cancelled 1 s in.
605            let cancel = CancellationToken::new();
606            let started = tokio::time::Instant::now();
607            let (adapter, ()) = tokio::join!(
608                within(
609                    Duration::from_secs(10),
610                    first_adapter(&cancel, std::future::pending::<Result<()>>)
611                ),
612                async {
613                    sleep(Duration::from_secs(1)).await;
614                    cancel.cancel();
615                }
616            );
617            assert_eq!(adapter, None);
618            assert_eq!(started.elapsed(), Duration::from_secs(1));
619        })
620        .await;
621    }
622
623    #[tokio::test(start_paused = true)]
624    async fn the_first_adapter_fetch_is_retried_every_10_s_until_cancelled() {
625        within(TEST_LIMIT, async {
626            // Two failures, then an adapter from the third fetch, 20 s in.
627            let calls = std::cell::Cell::new(0);
628            let started = tokio::time::Instant::now();
629            let adapter = first_adapter(&CancellationToken::new(), || {
630                calls.set(calls.get() + 1);
631                let call = calls.get();
632                async move {
633                    if call < 3 {
634                        Err(no_adapter())
635                    } else {
636                        Ok(call)
637                    }
638                }
639            })
640            .await;
641            assert_eq!(adapter, Some(3));
642            assert_eq!(started.elapsed(), Duration::from_secs(20));
643
644            // Fetches that keep failing, cancelled 15 s in, during the wait
645            // before the third.
646            let cancel = CancellationToken::new();
647            let started = tokio::time::Instant::now();
648            let (adapter, ()) = tokio::join!(
649                first_adapter(&cancel, || async { Err::<(), _>(no_adapter()) }),
650                async {
651                    sleep(Duration::from_secs(15)).await;
652                    cancel.cancel();
653                }
654            );
655            assert_eq!(adapter, None);
656            assert_eq!(started.elapsed(), Duration::from_secs(15));
657        })
658        .await;
659    }
660}