1use crate::chooser::Candidate;
24use crate::filter::{Advertisement, RequestDeviceOptions};
25use crate::registry::Grant;
26use crate::uuid::BluetoothUuid;
27use std::collections::HashSet;
28use std::sync::atomic::{AtomicU64, Ordering};
29use std::sync::Mutex;
30
31#[cfg_attr(target_arch = "wasm32", allow(dead_code))]
36const ADVERTISEMENT_BACKLOG: usize = 256;
43
44pub enum Want {
50 Request(RequestDeviceOptions),
53 Scan {
55 options: RequestDeviceOptions,
57 keep_repeated: bool,
59 },
60 Device {
64 id: String,
66 grant: Grant,
68 },
69}
70
71impl Want {
72 fn options(&self) -> Option<&RequestDeviceOptions> {
73 match self {
74 Self::Request(options) => Some(options),
75 Self::Scan { options, .. } => Some(options),
76 Self::Device { .. } => None,
77 }
78 }
79
80 fn grant(&self) -> Option<Grant> {
95 match self {
96 Self::Request(_) => None,
97 Self::Scan { options, .. } => Some(options.grant()),
98 Self::Device { grant, .. } => Some(grant.clone()),
99 }
100 }
101
102 fn wants_duplicates(&self) -> bool {
103 match self {
104 Self::Request(_) | Self::Device { .. } => true,
105 Self::Scan { keep_repeated, .. } => *keep_repeated,
106 }
107 }
108
109 fn accepts(&self, id: &str, name: Option<&str>, advertisement: &Advertisement) -> bool {
111 match self {
112 Self::Device { id: wanted, .. } => wanted == id,
113 Self::Request(options) | Self::Scan { options, .. } => {
114 options.matches(name, advertisement)
115 }
116 }
117 }
118}
119
120struct Watcher {
121 id: u64,
122 want: Want,
123 grant: Option<Grant>,
125 tx: crate::backlog::Sender<Candidate>,
126 delivered: HashSet<String>,
128}
129
130pub struct ScanHub {
132 watchers: Mutex<Vec<Watcher>>,
133 next_id: AtomicU64,
134}
135
136impl Default for ScanHub {
137 fn default() -> Self {
138 Self::new()
139 }
140}
141
142impl ScanHub {
143 pub fn new() -> Self {
145 Self {
146 watchers: Mutex::new(Vec::new()),
147 next_id: AtomicU64::new(1),
148 }
149 }
150
151 pub fn add(&self, want: Want) -> (u64, crate::backlog::Receiver<Candidate>, bool) {
156 let (tx, rx) =
163 crate::backlog::bounded(ADVERTISEMENT_BACKLOG, crate::backlog::Overflow::KeepNewest);
164 let id = self.next_id.fetch_add(1, Ordering::Relaxed);
165 let mut watchers = self.watchers.lock().unwrap();
166 let before = Self::radio_filter(&watchers);
167 watchers.push(Watcher {
168 id,
169 grant: want.grant(),
170 want,
171 tx,
172 delivered: HashSet::new(),
173 });
174 let after = Self::radio_filter(&watchers);
175 (id, rx, before != after || watchers.len() == 1)
176 }
177
178 pub fn remove(&self, id: u64) -> bool {
180 let mut watchers = self.watchers.lock().unwrap();
181 watchers.retain(|w| w.id != id);
182 watchers.is_empty()
183 }
184
185 #[allow(dead_code)]
194 pub fn close_all(&self) {
195 self.watchers.lock().unwrap().clear();
196 }
197
198 pub fn is_watching_device(&self, id: &str) -> bool {
201 self.watchers
202 .lock()
203 .unwrap()
204 .iter()
205 .any(|w| matches!(&w.want, Want::Device { id: watched, .. } if watched == id))
206 }
207
208 #[cfg_attr(target_arch = "wasm32", allow(dead_code))]
209 pub fn is_watching(&self) -> bool {
211 !self.watchers.lock().unwrap().is_empty()
212 }
213
214 pub fn contains(&self, id: u64) -> bool {
217 self.watchers.lock().unwrap().iter().any(|w| w.id == id)
218 }
219
220 #[allow(dead_code)]
230 pub fn scan_services(&self) -> Vec<BluetoothUuid> {
231 Self::radio_filter(&self.watchers.lock().unwrap())
232 }
233
234 fn radio_filter(watchers: &[Watcher]) -> Vec<BluetoothUuid> {
235 let mut union: Vec<BluetoothUuid> = Vec::new();
236 for watcher in watchers {
237 let Some(options) = watcher.want.options() else {
238 return Vec::new();
240 };
241 let services = options.scan_services();
242 if services.is_empty() {
243 return Vec::new();
244 }
245 for uuid in services {
246 if !union.contains(&uuid) {
247 union.push(uuid);
248 }
249 }
250 }
251 union.sort_by(|a, b| a.as_str().cmp(b.as_str()));
252 union
253 }
254
255 #[allow(dead_code)]
259 pub fn wants_duplicates(&self) -> bool {
260 self.watchers
261 .lock()
262 .unwrap()
263 .iter()
264 .any(|w| w.want.wants_duplicates())
265 }
266
267 pub fn publish(&self, id: &str, name: Option<&str>, advertisement: &Advertisement) {
273 let mut watchers = self.watchers.lock().unwrap();
274 for watcher in watchers.iter_mut() {
275 if !watcher.want.accepts(id, name, advertisement) {
276 continue;
277 }
278 if !watcher.want.wants_duplicates() && !watcher.delivered.insert(id.to_owned()) {
279 continue;
280 }
281 let mut advertisement = advertisement.clone();
289 advertisement.restrict_to(watcher.grant.as_ref());
290
291 let _ = watcher.tx.send(Candidate {
292 id: id.to_owned(),
293 name: name.map(str::to_owned),
294 advertisement,
295 });
296 }
297 }
298}
299
300#[cfg_attr(target_arch = "wasm32", allow(dead_code))]
315pub async fn choose(
316 hub: &ScanHub,
317 options: RequestDeviceOptions,
318 chooser: &dyn crate::chooser::DeviceChooser,
319 set_scanning: impl Fn(bool) -> crate::error::Result<()>,
320 on_joined: impl Fn(),
321) -> crate::error::Result<String> {
322 options.validate()?;
323 let (watcher, from_scan, restart) = hub.add(Want::Request(options));
324
325 if restart {
326 if let Err(e) = set_scanning(true) {
327 hub.remove(watcher);
328 return Err(e);
329 }
330 } else {
331 on_joined();
332 }
333
334 let chosen = chooser
335 .choose(crate::chooser::Candidates { inner: from_scan })
336 .await;
337
338 if hub.remove(watcher) {
339 let _ = set_scanning(false);
340 }
341
342 chosen.ok_or_else(|| crate::error::Error::NotFound("no device was chosen".into()))
343}
344
345#[cfg(test)]
346mod tests {
347 use super::*;
348 use crate::filter::DeviceFilter;
349 use crate::uuid::services;
350
351 fn next(rx: &mut crate::backlog::Receiver<Candidate>) -> Option<Candidate> {
353 rx.try_recv()
354 }
355
356 fn advertisement(uuids: &[u16]) -> Advertisement {
357 Advertisement {
358 #[cfg(feature = "classic")]
359 class_of_device: None,
360 service_uuids: uuids.iter().map(|u| BluetoothUuid::from_u16(*u)).collect(),
361 ..Default::default()
362 }
363 }
364
365 fn requesting(service: u16) -> Want {
366 Want::Request(
367 RequestDeviceOptions::new().filter(
368 DeviceFilter::new()
369 .service(BluetoothUuid::from_u16(service))
370 .unwrap(),
371 ),
372 )
373 }
374
375 #[test]
376 fn the_first_watcher_starts_the_radio_and_the_last_stops_it() {
377 let hub = ScanHub::new();
378 let (first, _a, start) = hub.add(requesting(0x180F));
379 assert!(start, "the first watcher has to start the scan");
380 let (second, _b, _) = hub.add(requesting(0x180F));
381
382 assert!(!hub.remove(first), "another watcher still wants the scan");
383 assert!(hub.remove(second), "the last one stops it");
384 assert!(!hub.is_watching());
385 }
386
387 #[test]
391 fn a_finished_request_does_not_stop_somebody_elses_scan() {
392 let hub = ScanHub::new();
393 let (scan, mut stream, _) = hub.add(Want::Scan {
394 options: RequestDeviceOptions::new().accept_all_devices(),
395 keep_repeated: true,
396 });
397 let (request, _r, _) = hub.add(requesting(0x180F));
398
399 assert!(!hub.remove(request));
400 hub.publish("aa", Some("Sensor"), &advertisement(&[0x180F]));
401 assert!(next(&mut stream).is_some(), "the scan still runs");
402 assert!(hub.contains(scan));
403 }
404
405 #[test]
406 fn one_unfiltered_watcher_widens_the_radio_scan_for_everyone() {
407 let hub = ScanHub::new();
408 let (_a, _s, _) = hub.add(requesting(0x180F));
409 assert_eq!(
410 hub.scan_services(),
411 vec![BluetoothUuid::from_u16(0x180F)],
412 "a single service filter narrows the scan"
413 );
414
415 let (_b, _t, restart) = hub.add(Want::Device {
418 id: "aa".into(),
419 grant: Grant::default(),
420 });
421 assert!(restart, "widening the filter has to restart the radio");
422 assert!(hub.scan_services().is_empty());
423 }
424
425 #[test]
426 fn filters_are_combined_not_intersected() {
427 let hub = ScanHub::new();
428 hub.add(requesting(0x180F));
429 hub.add(requesting(0x180D));
430 assert_eq!(
431 hub.scan_services(),
432 vec![
433 BluetoothUuid::from_u16(0x180D),
434 BluetoothUuid::from_u16(0x180F)
435 ],
436 "the radio must be at least as wide as the widest watcher"
437 );
438 }
439
440 #[test]
441 fn a_watcher_only_sees_what_its_own_filter_accepts() {
442 let hub = ScanHub::new();
443 let (_a, mut battery, _) = hub.add(requesting(0x180F));
444 let (_b, mut heart, _) = hub.add(requesting(0x180D));
445
446 hub.publish("aa", None, &advertisement(&[0x180F]));
447 assert!(next(&mut battery).is_some());
448 assert!(next(&mut heart).is_none(), "not this watcher's device");
449 }
450
451 #[test]
452 fn a_device_knows_whether_it_is_being_watched() {
453 let hub = ScanHub::new();
454 assert!(!hub.is_watching_device("mine"));
455
456 let (id, _stream, _) = hub.add(Want::Device {
457 id: "mine".into(),
458 grant: Grant::default(),
459 });
460 assert!(hub.is_watching_device("mine"));
461 assert!(!hub.is_watching_device("theirs"));
463
464 hub.remove(id);
465 assert!(!hub.is_watching_device("mine"), "the watch ended");
466 }
467
468 #[test]
469 fn watching_a_device_ignores_every_other_device() {
470 let hub = ScanHub::new();
471 let (_id, mut stream, _) = hub.add(Want::Device {
472 id: "mine".into(),
473 grant: Grant::default(),
474 });
475
476 hub.publish("theirs", Some("Someone Else"), &advertisement(&[]));
477 assert!(next(&mut stream).is_none());
478
479 hub.publish("mine", Some("Mine"), &advertisement(&[]));
480 let event = next(&mut stream).expect("the watched device");
481 assert_eq!(event.id, "mine");
482 }
483
484 #[test]
485 fn a_scan_without_keep_repeated_reports_each_device_once() {
486 let hub = ScanHub::new();
487 let (_id, mut stream, _) = hub.add(Want::Scan {
488 options: RequestDeviceOptions::new().accept_all_devices(),
489 keep_repeated: false,
490 });
491 assert!(!hub.wants_duplicates());
492
493 hub.publish("aa", None, &advertisement(&[]));
494 hub.publish("aa", None, &advertisement(&[]));
495 assert!(next(&mut stream).is_some());
496 assert!(next(&mut stream).is_none(), "the repeat is suppressed");
497
498 hub.publish("bb", None, &advertisement(&[]));
500 assert!(next(&mut stream).is_some());
501 }
502
503 #[test]
504 fn a_chooser_gets_duplicates_so_its_rssi_stays_live() {
505 let hub = ScanHub::new();
506 let (_id, mut stream, _) = hub.add(requesting(0x180F));
507 assert!(hub.wants_duplicates());
508 hub.publish("aa", None, &advertisement(&[0x180F]));
509 hub.publish("aa", None, &advertisement(&[0x180F]));
510 assert!(next(&mut stream).is_some());
511 assert!(next(&mut stream).is_some(), "repeats are wanted");
512 }
513
514 #[test]
517 fn closing_the_hub_ends_every_stream() {
518 let hub = ScanHub::new();
519 let (id, mut stream, _) = hub.add(requesting(0x180F));
520 hub.close_all();
521
522 assert!(!hub.is_watching());
523 assert!(!hub.contains(id));
524 assert!(stream.try_recv().is_none());
526 }
527
528 #[test]
536 fn manufacturer_data_is_filtered_to_what_was_granted() {
537 const APPLE: u16 = 0x004C;
538 const OTHER: u16 = 0x00E0;
539
540 let hub = ScanHub::new();
541 let (_id, mut stream, _) = hub.add(Want::Scan {
542 options: RequestDeviceOptions::new()
543 .accept_all_devices()
544 .optional_manufacturer_data([APPLE]),
545 keep_repeated: true,
546 });
547
548 let mut advertisement = advertisement(&[]);
549 advertisement.manufacturer_data.insert(APPLE, vec![1, 2, 3]);
550 advertisement.manufacturer_data.insert(OTHER, vec![9, 9]);
551 hub.publish("aa", None, &advertisement);
552
553 let seen = next(&mut stream).expect("the device matches");
554 assert_eq!(
555 seen.advertisement.manufacturer_data.get(&APPLE),
556 Some(&vec![1, 2, 3]),
557 "what was asked for comes through"
558 );
559 assert!(
560 !seen.advertisement.manufacturer_data.contains_key(&OTHER),
561 "a company that was not asked for must not be reported"
562 );
563 }
564
565 #[test]
568 fn services_and_service_data_are_filtered_to_the_grant() {
569 const GRANTED: u16 = 0x180D; const PRIVATE: u16 = 0x180F; let (granted, private) = (
573 BluetoothUuid::from_u16(GRANTED),
574 BluetoothUuid::from_u16(PRIVATE),
575 );
576
577 let hub = ScanHub::new();
578 let (_id, mut stream, _) = hub.add(Want::Scan {
579 options: RequestDeviceOptions::new()
580 .filter(DeviceFilter::new().service(granted).unwrap()),
581 keep_repeated: true,
582 });
583
584 let mut advertisement = advertisement(&[GRANTED, PRIVATE]);
585 advertisement.service_data.insert(granted, vec![0x50]);
586 advertisement.service_data.insert(private, vec![0x63]);
587 advertisement.solicited_service_uuids.push(private);
588 hub.publish("aa", None, &advertisement);
589
590 let seen = next(&mut stream).expect("the device matches on the granted service");
591 assert_eq!(
592 seen.advertisement.service_uuids,
593 vec![granted],
594 "an ungranted service must not be reported"
595 );
596 assert!(
597 seen.advertisement.solicited_service_uuids.is_empty(),
598 "nor solicited under one"
599 );
600 assert_eq!(seen.advertisement.service_data.len(), 1);
601 assert!(seen.advertisement.service_data.contains_key(&granted));
602 }
603
604 #[test]
608 fn the_chooser_sees_the_advertisement_whole() {
609 const APPLE: u16 = 0x004C;
610 let battery = BluetoothUuid::from_u16(0x180F);
611
612 let hub = ScanHub::new();
613 let (_id, mut stream, _) = hub.add(Want::Request(
614 RequestDeviceOptions::new().accept_all_devices(),
615 ));
616
617 let mut advertisement = advertisement(&[0x180F]);
618 advertisement.service_data.insert(battery, vec![0x63]);
619 advertisement.manufacturer_data.insert(APPLE, vec![0x09]);
620 advertisement
621 .manufacturer_data
622 .insert(0x00E0, vec![0x02, 0x15]);
623 hub.publish("aa", None, &advertisement);
624
625 let seen = next(&mut stream).expect("accept_all_devices matches");
626 assert_eq!(seen.advertisement.service_uuids, vec![battery]);
627 assert_eq!(seen.advertisement.service_data.len(), 1);
628 assert_eq!(
629 seen.advertisement.manufacturer_data.len(),
630 2,
631 "the picker needs to show what is actually being broadcast"
632 );
633 }
634
635 #[test]
638 fn the_chooser_does_not_escape_the_manufacturer_blocklist() {
639 let hub = ScanHub::new();
640 let (_id, mut stream, _) = hub.add(Want::Request(
641 RequestDeviceOptions::new().accept_all_devices(),
642 ));
643
644 let mut advertisement = advertisement(&[]);
645 advertisement
646 .manufacturer_data
647 .insert(0x004C, vec![0x02, 0x15, 0xAB]);
648 hub.publish("aa", None, &advertisement);
649
650 let seen = next(&mut stream).expect("accept_all_devices matches");
651 assert!(seen.advertisement.manufacturer_data.is_empty());
652 }
653
654 #[test]
658 fn a_device_still_matches_on_what_the_grant_hides() {
659 const SECRET: u16 = 0x180F;
660 let hub = ScanHub::new();
661 let (_id, mut stream, _) = hub.add(Want::Scan {
663 options: RequestDeviceOptions::new().accept_all_devices(),
664 keep_repeated: true,
665 });
666
667 hub.publish("aa", None, &advertisement(&[SECRET]));
668 let seen = next(&mut stream).expect("the device is still reported");
669 assert!(
670 seen.advertisement.service_uuids.is_empty(),
671 "but without the service it was found by"
672 );
673 }
674
675 #[test]
678 fn a_grant_does_not_override_the_manufacturer_blocklist() {
679 const APPLE: u16 = 0x004C;
680
681 let hub = ScanHub::new();
682 let (_id, mut stream, _) = hub.add(Want::Scan {
683 options: RequestDeviceOptions::new()
684 .accept_all_devices()
685 .optional_manufacturer_data([APPLE]),
686 keep_repeated: true,
687 });
688
689 let mut advertisement = advertisement(&[]);
690 advertisement
691 .manufacturer_data
692 .insert(APPLE, vec![0x02, 0x15, 0xAB]); hub.publish("aa", None, &advertisement);
694
695 let seen = next(&mut stream).expect("the device still matches");
696 assert!(
697 seen.advertisement.manufacturer_data.is_empty(),
698 "asking for Apple's data must not yield a proximity beacon"
699 );
700 }
701
702 #[test]
704 fn manufacturer_data_is_withheld_when_none_was_asked_for() {
705 let hub = ScanHub::new();
706 let (_id, mut stream, _) = hub.add(Want::Scan {
707 options: RequestDeviceOptions::new().accept_all_devices(),
708 keep_repeated: true,
709 });
710
711 let mut advertisement = advertisement(&[]);
712 advertisement.manufacturer_data.insert(0x004C, vec![1]);
713 hub.publish("aa", None, &advertisement);
714
715 let seen = next(&mut stream).expect("the device matches");
716 assert!(seen.advertisement.manufacturer_data.is_empty());
717 }
718
719 #[test]
722 fn each_watcher_sees_only_its_own_grant() {
723 const APPLE: u16 = 0x004C;
724 const OTHER: u16 = 0x00E0;
725
726 let hub = ScanHub::new();
727 let (_a, mut permissive, _) = hub.add(Want::Scan {
728 options: RequestDeviceOptions::new()
729 .accept_all_devices()
730 .optional_manufacturer_data([APPLE, OTHER]),
731 keep_repeated: true,
732 });
733 let (_b, mut narrow, _) = hub.add(Want::Scan {
734 options: RequestDeviceOptions::new()
735 .accept_all_devices()
736 .optional_manufacturer_data([OTHER]),
737 keep_repeated: true,
738 });
739
740 let mut advertisement = advertisement(&[]);
741 advertisement.manufacturer_data.insert(APPLE, vec![1]);
742 advertisement.manufacturer_data.insert(OTHER, vec![2]);
743 hub.publish("aa", None, &advertisement);
744
745 assert_eq!(
746 next(&mut permissive)
747 .unwrap()
748 .advertisement
749 .manufacturer_data
750 .len(),
751 2
752 );
753 let narrow = next(&mut narrow).unwrap().advertisement.manufacturer_data;
754 assert_eq!(narrow.len(), 1);
755 assert!(narrow.contains_key(&OTHER));
756 }
757
758 #[test]
759 fn the_allowlist_still_decides_what_a_scan_may_see() {
760 let hub = ScanHub::new();
763 let (_id, mut stream, _) = hub.add(Want::Scan {
764 options: RequestDeviceOptions::new()
765 .filter(DeviceFilter::new().name("Sensor"))
766 .optional_service(services::BATTERY_SERVICE)
767 .unwrap(),
768 keep_repeated: true,
769 });
770 hub.publish("aa", Some("Sensor"), &advertisement(&[]));
771 assert!(next(&mut stream).is_some());
772 hub.publish("bb", Some("Other"), &advertisement(&[]));
773 assert!(next(&mut stream).is_none());
774 }
775}