1use 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
52fn 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#[derive(Debug, Clone)]
63pub struct PassiveReading {
64 pub device_id: String,
66 pub device_name: Option<String>,
68 pub rssi: Option<i16>,
70 pub data: AdvertisementData,
72 pub received_at: std::time::Instant,
74}
75
76#[derive(Debug, Clone)]
78pub struct PassiveMonitorOptions {
79 pub scan_duration: Duration,
81 pub scan_interval: Duration,
83 pub channel_capacity: usize,
85 pub deduplicate: bool,
87 pub max_reading_age: Duration,
89 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 pub fn new() -> Self {
109 Self::default()
110 }
111
112 pub fn scan_duration(mut self, duration: Duration) -> Self {
114 self.scan_duration = duration;
115 self
116 }
117
118 pub fn scan_interval(mut self, interval: Duration) -> Self {
120 self.scan_interval = interval;
121 self
122 }
123
124 pub fn deduplicate(mut self, enable: bool) -> Self {
126 self.deduplicate = enable;
127 self
128 }
129
130 pub fn filter_devices(mut self, device_ids: Vec<String>) -> Self {
132 self.device_filter = device_ids;
133 self
134 }
135}
136
137struct CachedReading {
139 data: AdvertisementData,
140 received_at: std::time::Instant,
141}
142
143pub struct PassiveMonitor {
151 options: PassiveMonitorOptions,
152 sender: broadcast::Sender<PassiveReading>,
154 cache: Arc<RwLock<HashMap<String, CachedReading>>>,
156}
157
158impl PassiveMonitor {
159 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 pub fn subscribe(&self) -> broadcast::Receiver<PassiveReading> {
173 self.sender.subscribe()
174 }
175
176 pub fn subscriber_count(&self) -> usize {
178 self.sender.receiver_count()
179 }
180
181 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 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 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 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 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 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 async fn scan_cycle_with_adapter(&self, adapter: &btleplug::platform::Adapter) -> Result<()> {
269 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 let peripherals = adapter.peripherals().await?;
282
283 for peripheral in peripherals {
284 if let Ok(Some(props)) = peripheral.properties().await {
285 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 if !self.options.device_filter.is_empty()
294 && !self.options.device_filter.contains(&device_id)
295 {
296 continue;
297 }
298
299 match parse_advertisement_with_name(data, peripheral_name(&props)) {
301 Ok(adv_data) => {
302 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 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 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 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 if cached.received_at.elapsed() > self.options.max_reading_age {
349 return true;
350 }
351
352 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 if cached.data.counter != data.counter {
366 return true;
367 }
368
369 false
370 } else {
371 true
373 }
374 }
375
376 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 pub async fn known_devices(&self) -> Vec<String> {
384 let cache = self.cache.read().await;
385 cache.keys().cloned().collect()
386 }
387
388 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
400async 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 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 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 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 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 let mut changed = data.clone();
517 changed.co2 = Some(900);
518 assert!(monitor.should_emit("device-1", &changed).await);
519
520 let mut changed = data.clone();
522 changed.battery = 50;
523 assert!(monitor.should_emit("device-1", &changed).await);
524
525 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 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 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 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 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 assert!(monitor.should_emit("device-2", &data).await);
588 }
589
590 const TEST_LIMIT: Duration = Duration::from_secs(600);
594
595 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 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 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 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}