Skip to main content

radiochron_native_ble/
lib.rs

1//! Blocking, Tokio-free native BLE advertisement scanning for `RadioChron`.
2//!
3//! Each supported operating system is implemented directly against its native
4//! Bluetooth surface: `WinRT` on Windows, `BlueZ` over the system D-Bus on
5//! Linux, and `CoreBluetooth` on macOS. The public API is synchronous so
6//! callers do not inherit an async executor.
7
8mod model;
9
10#[cfg(target_os = "linux")]
11mod linux;
12#[cfg(target_os = "macos")]
13mod macos;
14#[cfg(windows)]
15mod windows;
16
17use std::fmt;
18use std::time::Duration;
19
20pub use model::{AdapterReport, ScanReport};
21pub use radiochron::ble::{AddressType, Advertisement, ManufacturerData, ServiceData};
22
23/// Cooperative controls observed while a scan is running.
24pub trait ScanObserver {
25    /// Returns true when the caller no longer needs the scan.
26    fn is_cancelled(&self) -> bool {
27        false
28    }
29
30    /// Reports elapsed and requested scan time.
31    fn progress(&self, _elapsed: Duration, _total: Duration) {}
32}
33
34/// Observer for callers that do not need cancellation or progress.
35#[derive(Debug, Default, Clone, Copy)]
36pub struct NoopObserver;
37
38impl ScanObserver for NoopObserver {}
39
40/// Native BLE backend error.
41#[derive(Debug, Clone, PartialEq, Eq)]
42pub struct Error {
43    message: String,
44}
45
46impl Error {
47    pub(crate) fn new(message: impl Into<String>) -> Self {
48        Self {
49            message: message.into(),
50        }
51    }
52}
53
54impl fmt::Display for Error {
55    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
56        formatter.write_str(&self.message)
57    }
58}
59
60impl std::error::Error for Error {}
61
62/// Scans for BLE advertisements for at most `duration`.
63pub fn scan(duration: Duration) -> Result<ScanReport, Error> {
64    scan_with_observer(duration, &NoopObserver)
65}
66
67/// Scans for BLE advertisements with cooperative cancellation and progress.
68pub fn scan_with_observer(
69    duration: Duration,
70    observer: &dyn ScanObserver,
71) -> Result<ScanReport, Error> {
72    platform_scan(duration, observer)
73}
74
75#[cfg(windows)]
76fn platform_scan(duration: Duration, observer: &dyn ScanObserver) -> Result<ScanReport, Error> {
77    windows::scan(duration, observer)
78}
79
80#[cfg(target_os = "linux")]
81fn platform_scan(duration: Duration, observer: &dyn ScanObserver) -> Result<ScanReport, Error> {
82    linux::scan(duration, observer)
83}
84
85#[cfg(target_os = "macos")]
86fn platform_scan(duration: Duration, observer: &dyn ScanObserver) -> Result<ScanReport, Error> {
87    macos::scan(duration, observer)
88}
89
90#[cfg(not(any(windows, target_os = "linux", target_os = "macos")))]
91fn platform_scan(_duration: Duration, _observer: &dyn ScanObserver) -> Result<ScanReport, Error> {
92    Err(Error::new(
93        "native BLE scanning is supported on Windows, Linux, and macOS",
94    ))
95}