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 service_uuids: uuids.iter().map(|u| BluetoothUuid::from_u16(*u)).collect(),
359 ..Default::default()
360 }
361 }
362
363 fn requesting(service: u16) -> Want {
364 Want::Request(
365 RequestDeviceOptions::new().filter(
366 DeviceFilter::new()
367 .service(BluetoothUuid::from_u16(service))
368 .unwrap(),
369 ),
370 )
371 }
372
373 #[test]
374 fn the_first_watcher_starts_the_radio_and_the_last_stops_it() {
375 let hub = ScanHub::new();
376 let (first, _a, start) = hub.add(requesting(0x180F));
377 assert!(start, "the first watcher has to start the scan");
378 let (second, _b, _) = hub.add(requesting(0x180F));
379
380 assert!(!hub.remove(first), "another watcher still wants the scan");
381 assert!(hub.remove(second), "the last one stops it");
382 assert!(!hub.is_watching());
383 }
384
385 #[test]
389 fn a_finished_request_does_not_stop_somebody_elses_scan() {
390 let hub = ScanHub::new();
391 let (scan, mut stream, _) = hub.add(Want::Scan {
392 options: RequestDeviceOptions::new().accept_all_devices(),
393 keep_repeated: true,
394 });
395 let (request, _r, _) = hub.add(requesting(0x180F));
396
397 assert!(!hub.remove(request));
398 hub.publish("aa", Some("Sensor"), &advertisement(&[0x180F]));
399 assert!(next(&mut stream).is_some(), "the scan still runs");
400 assert!(hub.contains(scan));
401 }
402
403 #[test]
404 fn one_unfiltered_watcher_widens_the_radio_scan_for_everyone() {
405 let hub = ScanHub::new();
406 let (_a, _s, _) = hub.add(requesting(0x180F));
407 assert_eq!(
408 hub.scan_services(),
409 vec![BluetoothUuid::from_u16(0x180F)],
410 "a single service filter narrows the scan"
411 );
412
413 let (_b, _t, restart) = hub.add(Want::Device {
416 id: "aa".into(),
417 grant: Grant::default(),
418 });
419 assert!(restart, "widening the filter has to restart the radio");
420 assert!(hub.scan_services().is_empty());
421 }
422
423 #[test]
424 fn filters_are_combined_not_intersected() {
425 let hub = ScanHub::new();
426 hub.add(requesting(0x180F));
427 hub.add(requesting(0x180D));
428 assert_eq!(
429 hub.scan_services(),
430 vec![
431 BluetoothUuid::from_u16(0x180D),
432 BluetoothUuid::from_u16(0x180F)
433 ],
434 "the radio must be at least as wide as the widest watcher"
435 );
436 }
437
438 #[test]
439 fn a_watcher_only_sees_what_its_own_filter_accepts() {
440 let hub = ScanHub::new();
441 let (_a, mut battery, _) = hub.add(requesting(0x180F));
442 let (_b, mut heart, _) = hub.add(requesting(0x180D));
443
444 hub.publish("aa", None, &advertisement(&[0x180F]));
445 assert!(next(&mut battery).is_some());
446 assert!(next(&mut heart).is_none(), "not this watcher's device");
447 }
448
449 #[test]
450 fn a_device_knows_whether_it_is_being_watched() {
451 let hub = ScanHub::new();
452 assert!(!hub.is_watching_device("mine"));
453
454 let (id, _stream, _) = hub.add(Want::Device {
455 id: "mine".into(),
456 grant: Grant::default(),
457 });
458 assert!(hub.is_watching_device("mine"));
459 assert!(!hub.is_watching_device("theirs"));
461
462 hub.remove(id);
463 assert!(!hub.is_watching_device("mine"), "the watch ended");
464 }
465
466 #[test]
467 fn watching_a_device_ignores_every_other_device() {
468 let hub = ScanHub::new();
469 let (_id, mut stream, _) = hub.add(Want::Device {
470 id: "mine".into(),
471 grant: Grant::default(),
472 });
473
474 hub.publish("theirs", Some("Someone Else"), &advertisement(&[]));
475 assert!(next(&mut stream).is_none());
476
477 hub.publish("mine", Some("Mine"), &advertisement(&[]));
478 let event = next(&mut stream).expect("the watched device");
479 assert_eq!(event.id, "mine");
480 }
481
482 #[test]
483 fn a_scan_without_keep_repeated_reports_each_device_once() {
484 let hub = ScanHub::new();
485 let (_id, mut stream, _) = hub.add(Want::Scan {
486 options: RequestDeviceOptions::new().accept_all_devices(),
487 keep_repeated: false,
488 });
489 assert!(!hub.wants_duplicates());
490
491 hub.publish("aa", None, &advertisement(&[]));
492 hub.publish("aa", None, &advertisement(&[]));
493 assert!(next(&mut stream).is_some());
494 assert!(next(&mut stream).is_none(), "the repeat is suppressed");
495
496 hub.publish("bb", None, &advertisement(&[]));
498 assert!(next(&mut stream).is_some());
499 }
500
501 #[test]
502 fn a_chooser_gets_duplicates_so_its_rssi_stays_live() {
503 let hub = ScanHub::new();
504 let (_id, mut stream, _) = hub.add(requesting(0x180F));
505 assert!(hub.wants_duplicates());
506 hub.publish("aa", None, &advertisement(&[0x180F]));
507 hub.publish("aa", None, &advertisement(&[0x180F]));
508 assert!(next(&mut stream).is_some());
509 assert!(next(&mut stream).is_some(), "repeats are wanted");
510 }
511
512 #[test]
515 fn closing_the_hub_ends_every_stream() {
516 let hub = ScanHub::new();
517 let (id, mut stream, _) = hub.add(requesting(0x180F));
518 hub.close_all();
519
520 assert!(!hub.is_watching());
521 assert!(!hub.contains(id));
522 assert!(stream.try_recv().is_none());
524 }
525
526 #[test]
534 fn manufacturer_data_is_filtered_to_what_was_granted() {
535 const APPLE: u16 = 0x004C;
536 const OTHER: u16 = 0x00E0;
537
538 let hub = ScanHub::new();
539 let (_id, mut stream, _) = hub.add(Want::Scan {
540 options: RequestDeviceOptions::new()
541 .accept_all_devices()
542 .optional_manufacturer_data([APPLE]),
543 keep_repeated: true,
544 });
545
546 let mut advertisement = advertisement(&[]);
547 advertisement.manufacturer_data.insert(APPLE, vec![1, 2, 3]);
548 advertisement.manufacturer_data.insert(OTHER, vec![9, 9]);
549 hub.publish("aa", None, &advertisement);
550
551 let seen = next(&mut stream).expect("the device matches");
552 assert_eq!(
553 seen.advertisement.manufacturer_data.get(&APPLE),
554 Some(&vec![1, 2, 3]),
555 "what was asked for comes through"
556 );
557 assert!(
558 !seen.advertisement.manufacturer_data.contains_key(&OTHER),
559 "a company that was not asked for must not be reported"
560 );
561 }
562
563 #[test]
566 fn services_and_service_data_are_filtered_to_the_grant() {
567 const GRANTED: u16 = 0x180D; const PRIVATE: u16 = 0x180F; let (granted, private) = (
571 BluetoothUuid::from_u16(GRANTED),
572 BluetoothUuid::from_u16(PRIVATE),
573 );
574
575 let hub = ScanHub::new();
576 let (_id, mut stream, _) = hub.add(Want::Scan {
577 options: RequestDeviceOptions::new()
578 .filter(DeviceFilter::new().service(granted).unwrap()),
579 keep_repeated: true,
580 });
581
582 let mut advertisement = advertisement(&[GRANTED, PRIVATE]);
583 advertisement.service_data.insert(granted, vec![0x50]);
584 advertisement.service_data.insert(private, vec![0x63]);
585 advertisement.solicited_service_uuids.push(private);
586 hub.publish("aa", None, &advertisement);
587
588 let seen = next(&mut stream).expect("the device matches on the granted service");
589 assert_eq!(
590 seen.advertisement.service_uuids,
591 vec![granted],
592 "an ungranted service must not be reported"
593 );
594 assert!(
595 seen.advertisement.solicited_service_uuids.is_empty(),
596 "nor solicited under one"
597 );
598 assert_eq!(seen.advertisement.service_data.len(), 1);
599 assert!(seen.advertisement.service_data.contains_key(&granted));
600 }
601
602 #[test]
606 fn the_chooser_sees_the_advertisement_whole() {
607 const APPLE: u16 = 0x004C;
608 let battery = BluetoothUuid::from_u16(0x180F);
609
610 let hub = ScanHub::new();
611 let (_id, mut stream, _) = hub.add(Want::Request(
612 RequestDeviceOptions::new().accept_all_devices(),
613 ));
614
615 let mut advertisement = advertisement(&[0x180F]);
616 advertisement.service_data.insert(battery, vec![0x63]);
617 advertisement.manufacturer_data.insert(APPLE, vec![0x09]);
618 advertisement
619 .manufacturer_data
620 .insert(0x00E0, vec![0x02, 0x15]);
621 hub.publish("aa", None, &advertisement);
622
623 let seen = next(&mut stream).expect("accept_all_devices matches");
624 assert_eq!(seen.advertisement.service_uuids, vec![battery]);
625 assert_eq!(seen.advertisement.service_data.len(), 1);
626 assert_eq!(
627 seen.advertisement.manufacturer_data.len(),
628 2,
629 "the picker needs to show what is actually being broadcast"
630 );
631 }
632
633 #[test]
636 fn the_chooser_does_not_escape_the_manufacturer_blocklist() {
637 let hub = ScanHub::new();
638 let (_id, mut stream, _) = hub.add(Want::Request(
639 RequestDeviceOptions::new().accept_all_devices(),
640 ));
641
642 let mut advertisement = advertisement(&[]);
643 advertisement
644 .manufacturer_data
645 .insert(0x004C, vec![0x02, 0x15, 0xAB]);
646 hub.publish("aa", None, &advertisement);
647
648 let seen = next(&mut stream).expect("accept_all_devices matches");
649 assert!(seen.advertisement.manufacturer_data.is_empty());
650 }
651
652 #[test]
656 fn a_device_still_matches_on_what_the_grant_hides() {
657 const SECRET: u16 = 0x180F;
658 let hub = ScanHub::new();
659 let (_id, mut stream, _) = hub.add(Want::Scan {
661 options: RequestDeviceOptions::new().accept_all_devices(),
662 keep_repeated: true,
663 });
664
665 hub.publish("aa", None, &advertisement(&[SECRET]));
666 let seen = next(&mut stream).expect("the device is still reported");
667 assert!(
668 seen.advertisement.service_uuids.is_empty(),
669 "but without the service it was found by"
670 );
671 }
672
673 #[test]
676 fn a_grant_does_not_override_the_manufacturer_blocklist() {
677 const APPLE: u16 = 0x004C;
678
679 let hub = ScanHub::new();
680 let (_id, mut stream, _) = hub.add(Want::Scan {
681 options: RequestDeviceOptions::new()
682 .accept_all_devices()
683 .optional_manufacturer_data([APPLE]),
684 keep_repeated: true,
685 });
686
687 let mut advertisement = advertisement(&[]);
688 advertisement
689 .manufacturer_data
690 .insert(APPLE, vec![0x02, 0x15, 0xAB]); hub.publish("aa", None, &advertisement);
692
693 let seen = next(&mut stream).expect("the device still matches");
694 assert!(
695 seen.advertisement.manufacturer_data.is_empty(),
696 "asking for Apple's data must not yield a proximity beacon"
697 );
698 }
699
700 #[test]
702 fn manufacturer_data_is_withheld_when_none_was_asked_for() {
703 let hub = ScanHub::new();
704 let (_id, mut stream, _) = hub.add(Want::Scan {
705 options: RequestDeviceOptions::new().accept_all_devices(),
706 keep_repeated: true,
707 });
708
709 let mut advertisement = advertisement(&[]);
710 advertisement.manufacturer_data.insert(0x004C, vec![1]);
711 hub.publish("aa", None, &advertisement);
712
713 let seen = next(&mut stream).expect("the device matches");
714 assert!(seen.advertisement.manufacturer_data.is_empty());
715 }
716
717 #[test]
720 fn each_watcher_sees_only_its_own_grant() {
721 const APPLE: u16 = 0x004C;
722 const OTHER: u16 = 0x00E0;
723
724 let hub = ScanHub::new();
725 let (_a, mut permissive, _) = hub.add(Want::Scan {
726 options: RequestDeviceOptions::new()
727 .accept_all_devices()
728 .optional_manufacturer_data([APPLE, OTHER]),
729 keep_repeated: true,
730 });
731 let (_b, mut narrow, _) = hub.add(Want::Scan {
732 options: RequestDeviceOptions::new()
733 .accept_all_devices()
734 .optional_manufacturer_data([OTHER]),
735 keep_repeated: true,
736 });
737
738 let mut advertisement = advertisement(&[]);
739 advertisement.manufacturer_data.insert(APPLE, vec![1]);
740 advertisement.manufacturer_data.insert(OTHER, vec![2]);
741 hub.publish("aa", None, &advertisement);
742
743 assert_eq!(
744 next(&mut permissive)
745 .unwrap()
746 .advertisement
747 .manufacturer_data
748 .len(),
749 2
750 );
751 let narrow = next(&mut narrow).unwrap().advertisement.manufacturer_data;
752 assert_eq!(narrow.len(), 1);
753 assert!(narrow.contains_key(&OTHER));
754 }
755
756 #[test]
757 fn the_allowlist_still_decides_what_a_scan_may_see() {
758 let hub = ScanHub::new();
761 let (_id, mut stream, _) = hub.add(Want::Scan {
762 options: RequestDeviceOptions::new()
763 .filter(DeviceFilter::new().name("Sensor"))
764 .optional_service(services::BATTERY_SERVICE)
765 .unwrap(),
766 keep_repeated: true,
767 });
768 hub.publish("aa", Some("Sensor"), &advertisement(&[]));
769 assert!(next(&mut stream).is_some());
770 hub.publish("bb", Some("Other"), &advertisement(&[]));
771 assert!(next(&mut stream).is_none());
772 }
773}