use crate::chooser::Candidate;
use crate::filter::{Advertisement, RequestDeviceOptions};
use crate::registry::Grant;
use crate::uuid::BluetoothUuid;
use std::collections::HashSet;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Mutex;
#[cfg_attr(target_arch = "wasm32", allow(dead_code))]
const ADVERTISEMENT_BACKLOG: usize = 256;
pub enum Want {
Request(RequestDeviceOptions),
Scan {
options: RequestDeviceOptions,
keep_repeated: bool,
},
Device {
id: String,
grant: Grant,
},
}
impl Want {
fn options(&self) -> Option<&RequestDeviceOptions> {
match self {
Self::Request(options) => Some(options),
Self::Scan { options, .. } => Some(options),
Self::Device { .. } => None,
}
}
fn grant(&self) -> Option<Grant> {
match self {
Self::Request(_) => None,
Self::Scan { options, .. } => Some(options.grant()),
Self::Device { grant, .. } => Some(grant.clone()),
}
}
fn wants_duplicates(&self) -> bool {
match self {
Self::Request(_) | Self::Device { .. } => true,
Self::Scan { keep_repeated, .. } => *keep_repeated,
}
}
fn accepts(&self, id: &str, name: Option<&str>, advertisement: &Advertisement) -> bool {
match self {
Self::Device { id: wanted, .. } => wanted == id,
Self::Request(options) | Self::Scan { options, .. } => {
options.matches(name, advertisement)
}
}
}
}
struct Watcher {
id: u64,
want: Want,
grant: Option<Grant>,
tx: crate::backlog::Sender<Candidate>,
delivered: HashSet<String>,
}
pub struct ScanHub {
watchers: Mutex<Vec<Watcher>>,
next_id: AtomicU64,
}
impl Default for ScanHub {
fn default() -> Self {
Self::new()
}
}
impl ScanHub {
pub fn new() -> Self {
Self {
watchers: Mutex::new(Vec::new()),
next_id: AtomicU64::new(1),
}
}
pub fn add(&self, want: Want) -> (u64, crate::backlog::Receiver<Candidate>, bool) {
let (tx, rx) =
crate::backlog::bounded(ADVERTISEMENT_BACKLOG, crate::backlog::Overflow::KeepNewest);
let id = self.next_id.fetch_add(1, Ordering::Relaxed);
let mut watchers = self.watchers.lock().unwrap();
let before = Self::radio_filter(&watchers);
watchers.push(Watcher {
id,
grant: want.grant(),
want,
tx,
delivered: HashSet::new(),
});
let after = Self::radio_filter(&watchers);
(id, rx, before != after || watchers.len() == 1)
}
pub fn remove(&self, id: u64) -> bool {
let mut watchers = self.watchers.lock().unwrap();
watchers.retain(|w| w.id != id);
watchers.is_empty()
}
#[allow(dead_code)]
pub fn close_all(&self) {
self.watchers.lock().unwrap().clear();
}
pub fn is_watching_device(&self, id: &str) -> bool {
self.watchers
.lock()
.unwrap()
.iter()
.any(|w| matches!(&w.want, Want::Device { id: watched, .. } if watched == id))
}
#[cfg_attr(target_arch = "wasm32", allow(dead_code))]
pub fn is_watching(&self) -> bool {
!self.watchers.lock().unwrap().is_empty()
}
pub fn contains(&self, id: u64) -> bool {
self.watchers.lock().unwrap().iter().any(|w| w.id == id)
}
#[allow(dead_code)]
pub fn scan_services(&self) -> Vec<BluetoothUuid> {
Self::radio_filter(&self.watchers.lock().unwrap())
}
fn radio_filter(watchers: &[Watcher]) -> Vec<BluetoothUuid> {
let mut union: Vec<BluetoothUuid> = Vec::new();
for watcher in watchers {
let Some(options) = watcher.want.options() else {
return Vec::new();
};
let services = options.scan_services();
if services.is_empty() {
return Vec::new();
}
for uuid in services {
if !union.contains(&uuid) {
union.push(uuid);
}
}
}
union.sort_by(|a, b| a.as_str().cmp(b.as_str()));
union
}
#[allow(dead_code)]
pub fn wants_duplicates(&self) -> bool {
self.watchers
.lock()
.unwrap()
.iter()
.any(|w| w.want.wants_duplicates())
}
pub fn publish(&self, id: &str, name: Option<&str>, advertisement: &Advertisement) {
let mut watchers = self.watchers.lock().unwrap();
for watcher in watchers.iter_mut() {
if !watcher.want.accepts(id, name, advertisement) {
continue;
}
if !watcher.want.wants_duplicates() && !watcher.delivered.insert(id.to_owned()) {
continue;
}
let mut advertisement = advertisement.clone();
advertisement.restrict_to(watcher.grant.as_ref());
let _ = watcher.tx.send(Candidate {
id: id.to_owned(),
name: name.map(str::to_owned),
advertisement,
});
}
}
}
#[cfg_attr(target_arch = "wasm32", allow(dead_code))]
pub async fn choose(
hub: &ScanHub,
options: RequestDeviceOptions,
chooser: &dyn crate::chooser::DeviceChooser,
set_scanning: impl Fn(bool) -> crate::error::Result<()>,
on_joined: impl Fn(),
) -> crate::error::Result<String> {
options.validate()?;
let (watcher, from_scan, restart) = hub.add(Want::Request(options));
if restart {
if let Err(e) = set_scanning(true) {
hub.remove(watcher);
return Err(e);
}
} else {
on_joined();
}
let chosen = chooser
.choose(crate::chooser::Candidates { inner: from_scan })
.await;
if hub.remove(watcher) {
let _ = set_scanning(false);
}
chosen.ok_or_else(|| crate::error::Error::NotFound("no device was chosen".into()))
}
#[cfg(test)]
mod tests {
use super::*;
use crate::filter::DeviceFilter;
use crate::uuid::services;
fn next(rx: &mut crate::backlog::Receiver<Candidate>) -> Option<Candidate> {
rx.try_recv()
}
fn advertisement(uuids: &[u16]) -> Advertisement {
Advertisement {
#[cfg(feature = "classic")]
class_of_device: None,
service_uuids: uuids.iter().map(|u| BluetoothUuid::from_u16(*u)).collect(),
..Default::default()
}
}
fn requesting(service: u16) -> Want {
Want::Request(
RequestDeviceOptions::new().filter(
DeviceFilter::new()
.service(BluetoothUuid::from_u16(service))
.unwrap(),
),
)
}
#[test]
fn the_first_watcher_starts_the_radio_and_the_last_stops_it() {
let hub = ScanHub::new();
let (first, _a, start) = hub.add(requesting(0x180F));
assert!(start, "the first watcher has to start the scan");
let (second, _b, _) = hub.add(requesting(0x180F));
assert!(!hub.remove(first), "another watcher still wants the scan");
assert!(hub.remove(second), "the last one stops it");
assert!(!hub.is_watching());
}
#[test]
fn a_finished_request_does_not_stop_somebody_elses_scan() {
let hub = ScanHub::new();
let (scan, mut stream, _) = hub.add(Want::Scan {
options: RequestDeviceOptions::new().accept_all_devices(),
keep_repeated: true,
});
let (request, _r, _) = hub.add(requesting(0x180F));
assert!(!hub.remove(request));
hub.publish("aa", Some("Sensor"), &advertisement(&[0x180F]));
assert!(next(&mut stream).is_some(), "the scan still runs");
assert!(hub.contains(scan));
}
#[test]
fn one_unfiltered_watcher_widens_the_radio_scan_for_everyone() {
let hub = ScanHub::new();
let (_a, _s, _) = hub.add(requesting(0x180F));
assert_eq!(
hub.scan_services(),
vec![BluetoothUuid::from_u16(0x180F)],
"a single service filter narrows the scan"
);
let (_b, _t, restart) = hub.add(Want::Device {
id: "aa".into(),
grant: Grant::default(),
});
assert!(restart, "widening the filter has to restart the radio");
assert!(hub.scan_services().is_empty());
}
#[test]
fn filters_are_combined_not_intersected() {
let hub = ScanHub::new();
hub.add(requesting(0x180F));
hub.add(requesting(0x180D));
assert_eq!(
hub.scan_services(),
vec![
BluetoothUuid::from_u16(0x180D),
BluetoothUuid::from_u16(0x180F)
],
"the radio must be at least as wide as the widest watcher"
);
}
#[test]
fn a_watcher_only_sees_what_its_own_filter_accepts() {
let hub = ScanHub::new();
let (_a, mut battery, _) = hub.add(requesting(0x180F));
let (_b, mut heart, _) = hub.add(requesting(0x180D));
hub.publish("aa", None, &advertisement(&[0x180F]));
assert!(next(&mut battery).is_some());
assert!(next(&mut heart).is_none(), "not this watcher's device");
}
#[test]
fn a_device_knows_whether_it_is_being_watched() {
let hub = ScanHub::new();
assert!(!hub.is_watching_device("mine"));
let (id, _stream, _) = hub.add(Want::Device {
id: "mine".into(),
grant: Grant::default(),
});
assert!(hub.is_watching_device("mine"));
assert!(!hub.is_watching_device("theirs"));
hub.remove(id);
assert!(!hub.is_watching_device("mine"), "the watch ended");
}
#[test]
fn watching_a_device_ignores_every_other_device() {
let hub = ScanHub::new();
let (_id, mut stream, _) = hub.add(Want::Device {
id: "mine".into(),
grant: Grant::default(),
});
hub.publish("theirs", Some("Someone Else"), &advertisement(&[]));
assert!(next(&mut stream).is_none());
hub.publish("mine", Some("Mine"), &advertisement(&[]));
let event = next(&mut stream).expect("the watched device");
assert_eq!(event.id, "mine");
}
#[test]
fn a_scan_without_keep_repeated_reports_each_device_once() {
let hub = ScanHub::new();
let (_id, mut stream, _) = hub.add(Want::Scan {
options: RequestDeviceOptions::new().accept_all_devices(),
keep_repeated: false,
});
assert!(!hub.wants_duplicates());
hub.publish("aa", None, &advertisement(&[]));
hub.publish("aa", None, &advertisement(&[]));
assert!(next(&mut stream).is_some());
assert!(next(&mut stream).is_none(), "the repeat is suppressed");
hub.publish("bb", None, &advertisement(&[]));
assert!(next(&mut stream).is_some());
}
#[test]
fn a_chooser_gets_duplicates_so_its_rssi_stays_live() {
let hub = ScanHub::new();
let (_id, mut stream, _) = hub.add(requesting(0x180F));
assert!(hub.wants_duplicates());
hub.publish("aa", None, &advertisement(&[0x180F]));
hub.publish("aa", None, &advertisement(&[0x180F]));
assert!(next(&mut stream).is_some());
assert!(next(&mut stream).is_some(), "repeats are wanted");
}
#[test]
fn closing_the_hub_ends_every_stream() {
let hub = ScanHub::new();
let (id, mut stream, _) = hub.add(requesting(0x180F));
hub.close_all();
assert!(!hub.is_watching());
assert!(!hub.contains(id));
assert!(stream.try_recv().is_none());
}
#[test]
fn manufacturer_data_is_filtered_to_what_was_granted() {
const APPLE: u16 = 0x004C;
const OTHER: u16 = 0x00E0;
let hub = ScanHub::new();
let (_id, mut stream, _) = hub.add(Want::Scan {
options: RequestDeviceOptions::new()
.accept_all_devices()
.optional_manufacturer_data([APPLE]),
keep_repeated: true,
});
let mut advertisement = advertisement(&[]);
advertisement.manufacturer_data.insert(APPLE, vec![1, 2, 3]);
advertisement.manufacturer_data.insert(OTHER, vec![9, 9]);
hub.publish("aa", None, &advertisement);
let seen = next(&mut stream).expect("the device matches");
assert_eq!(
seen.advertisement.manufacturer_data.get(&APPLE),
Some(&vec![1, 2, 3]),
"what was asked for comes through"
);
assert!(
!seen.advertisement.manufacturer_data.contains_key(&OTHER),
"a company that was not asked for must not be reported"
);
}
#[test]
fn services_and_service_data_are_filtered_to_the_grant() {
const GRANTED: u16 = 0x180D; const PRIVATE: u16 = 0x180F;
let (granted, private) = (
BluetoothUuid::from_u16(GRANTED),
BluetoothUuid::from_u16(PRIVATE),
);
let hub = ScanHub::new();
let (_id, mut stream, _) = hub.add(Want::Scan {
options: RequestDeviceOptions::new()
.filter(DeviceFilter::new().service(granted).unwrap()),
keep_repeated: true,
});
let mut advertisement = advertisement(&[GRANTED, PRIVATE]);
advertisement.service_data.insert(granted, vec![0x50]);
advertisement.service_data.insert(private, vec![0x63]);
advertisement.solicited_service_uuids.push(private);
hub.publish("aa", None, &advertisement);
let seen = next(&mut stream).expect("the device matches on the granted service");
assert_eq!(
seen.advertisement.service_uuids,
vec![granted],
"an ungranted service must not be reported"
);
assert!(
seen.advertisement.solicited_service_uuids.is_empty(),
"nor solicited under one"
);
assert_eq!(seen.advertisement.service_data.len(), 1);
assert!(seen.advertisement.service_data.contains_key(&granted));
}
#[test]
fn the_chooser_sees_the_advertisement_whole() {
const APPLE: u16 = 0x004C;
let battery = BluetoothUuid::from_u16(0x180F);
let hub = ScanHub::new();
let (_id, mut stream, _) = hub.add(Want::Request(
RequestDeviceOptions::new().accept_all_devices(),
));
let mut advertisement = advertisement(&[0x180F]);
advertisement.service_data.insert(battery, vec![0x63]);
advertisement.manufacturer_data.insert(APPLE, vec![0x09]);
advertisement
.manufacturer_data
.insert(0x00E0, vec![0x02, 0x15]);
hub.publish("aa", None, &advertisement);
let seen = next(&mut stream).expect("accept_all_devices matches");
assert_eq!(seen.advertisement.service_uuids, vec![battery]);
assert_eq!(seen.advertisement.service_data.len(), 1);
assert_eq!(
seen.advertisement.manufacturer_data.len(),
2,
"the picker needs to show what is actually being broadcast"
);
}
#[test]
fn the_chooser_does_not_escape_the_manufacturer_blocklist() {
let hub = ScanHub::new();
let (_id, mut stream, _) = hub.add(Want::Request(
RequestDeviceOptions::new().accept_all_devices(),
));
let mut advertisement = advertisement(&[]);
advertisement
.manufacturer_data
.insert(0x004C, vec![0x02, 0x15, 0xAB]);
hub.publish("aa", None, &advertisement);
let seen = next(&mut stream).expect("accept_all_devices matches");
assert!(seen.advertisement.manufacturer_data.is_empty());
}
#[test]
fn a_device_still_matches_on_what_the_grant_hides() {
const SECRET: u16 = 0x180F;
let hub = ScanHub::new();
let (_id, mut stream, _) = hub.add(Want::Scan {
options: RequestDeviceOptions::new().accept_all_devices(),
keep_repeated: true,
});
hub.publish("aa", None, &advertisement(&[SECRET]));
let seen = next(&mut stream).expect("the device is still reported");
assert!(
seen.advertisement.service_uuids.is_empty(),
"but without the service it was found by"
);
}
#[test]
fn a_grant_does_not_override_the_manufacturer_blocklist() {
const APPLE: u16 = 0x004C;
let hub = ScanHub::new();
let (_id, mut stream, _) = hub.add(Want::Scan {
options: RequestDeviceOptions::new()
.accept_all_devices()
.optional_manufacturer_data([APPLE]),
keep_repeated: true,
});
let mut advertisement = advertisement(&[]);
advertisement
.manufacturer_data
.insert(APPLE, vec![0x02, 0x15, 0xAB]); hub.publish("aa", None, &advertisement);
let seen = next(&mut stream).expect("the device still matches");
assert!(
seen.advertisement.manufacturer_data.is_empty(),
"asking for Apple's data must not yield a proximity beacon"
);
}
#[test]
fn manufacturer_data_is_withheld_when_none_was_asked_for() {
let hub = ScanHub::new();
let (_id, mut stream, _) = hub.add(Want::Scan {
options: RequestDeviceOptions::new().accept_all_devices(),
keep_repeated: true,
});
let mut advertisement = advertisement(&[]);
advertisement.manufacturer_data.insert(0x004C, vec![1]);
hub.publish("aa", None, &advertisement);
let seen = next(&mut stream).expect("the device matches");
assert!(seen.advertisement.manufacturer_data.is_empty());
}
#[test]
fn each_watcher_sees_only_its_own_grant() {
const APPLE: u16 = 0x004C;
const OTHER: u16 = 0x00E0;
let hub = ScanHub::new();
let (_a, mut permissive, _) = hub.add(Want::Scan {
options: RequestDeviceOptions::new()
.accept_all_devices()
.optional_manufacturer_data([APPLE, OTHER]),
keep_repeated: true,
});
let (_b, mut narrow, _) = hub.add(Want::Scan {
options: RequestDeviceOptions::new()
.accept_all_devices()
.optional_manufacturer_data([OTHER]),
keep_repeated: true,
});
let mut advertisement = advertisement(&[]);
advertisement.manufacturer_data.insert(APPLE, vec![1]);
advertisement.manufacturer_data.insert(OTHER, vec![2]);
hub.publish("aa", None, &advertisement);
assert_eq!(
next(&mut permissive)
.unwrap()
.advertisement
.manufacturer_data
.len(),
2
);
let narrow = next(&mut narrow).unwrap().advertisement.manufacturer_data;
assert_eq!(narrow.len(), 1);
assert!(narrow.contains_key(&OTHER));
}
#[test]
fn the_allowlist_still_decides_what_a_scan_may_see() {
let hub = ScanHub::new();
let (_id, mut stream, _) = hub.add(Want::Scan {
options: RequestDeviceOptions::new()
.filter(DeviceFilter::new().name("Sensor"))
.optional_service(services::BATTERY_SERVICE)
.unwrap(),
keep_repeated: true,
});
hub.publish("aa", Some("Sensor"), &advertisement(&[]));
assert!(next(&mut stream).is_some());
hub.publish("bb", Some("Other"), &advertisement(&[]));
assert!(next(&mut stream).is_none());
}
}