Skip to main content

webbluetooth_apple/
lib.rs

1#![cfg(target_vendor = "apple")]
2//! CoreBluetooth from pure Rust — no Swift source, no Objective-C source, no
3//! generated shim.
4//!
5//! # Why the Objective-C runtime and not the Swift one
6//!
7//! `swiftui-native` reaches SwiftUI by resolving Swift-mangled symbols and
8//! synthesising Swift type metadata, because SwiftUI is a Swift-native
9//! framework — it exports about twenty thousand `$s`-prefixed symbols.
10//! CoreBluetooth exports **none**. Its `.tbd` lists Objective-C classes and its
11//! SDK directory has no `.swiftinterface`; `import CoreBluetooth` in Swift is
12//! the Clang importer synthesising Swift-shaped declarations from Objective-C
13//! headers at compile time, which still lower to `objc_msgSend`.
14//!
15//! So the runtime this crate builds types in is the Objective-C one. The
16//! principle is unchanged: nothing is compiled ahead of time, no source file in
17//! another language is shipped, and the delegate class is produced at run time
18//! by [`objc::ClassBuilder`]. `build.rs` names three libraries and does nothing
19//! else.
20//!
21//! # Layout
22//!
23//! * [`objc`] — message sends, Foundation readers, runtime class synthesis.
24//! * [`dispatch`] — the serial queue delegate callbacks are delivered on.
25//! * [`cb`] — typed accessors for `CBCentralManager` and friends.
26//! * [`delegate`] — the synthesised delegate class and its [`delegate::Event`]s.
27//! * `classic` and `rfcomm` — Bluetooth Classic devices and byte streams over
28//!   IOBluetooth, a separate framework from everything above. macOS only,
29//!   behind `apple-classic` and `rfcomm`.
30//! * [`peripheral`] — the mirror image: `CBPeripheralManager`, its own
31//!   synthesised delegate, and the mutable attribute types a GATT server
32//!   publishes.
33//!
34//! [`Central`] ties them together. For the Web Bluetooth API built on top, see
35//! the `webbluetooth` crate.
36//!
37//! # Authorization
38//!
39//! Bluetooth is TCC-gated on both platforms. A process with no
40//! `NSBluetoothAlwaysUsageDescription` gets [`cb::ManagerState::Unauthorized`]
41//! rather than an error, and no prompt. See the workspace README.
42//!
43//! ## License
44//! MIT — Copyright © 2025 [Eugene Hauptmann](https://github.com/eugenehp)
45
46#[macro_use]
47pub mod macros;
48
49// The adapter: CoreBluetooth expressed as the portable model.
50// Public so `webbluetooth` can reach it, and not an API anyone else
51// should call: the facade is what a caller holds. Hidden from the docs
52// for the same reason, which also keeps the same 38 adapter methods from
53// being documented six times over.
54#[doc(hidden)]
55pub mod backend;
56// The peripheral-role adapter: a GATT server expressed as the portable model.
57#[cfg(peripheral_role)]
58pub mod peripheral_backend;
59
60pub mod cb;
61/// Bluetooth Classic devices through IOBluetooth. **macOS only**, behind
62/// `apple-classic`.
63#[cfg(all(target_os = "macos", feature = "apple-classic"))]
64pub mod classic;
65pub mod delegate;
66pub mod dispatch;
67pub mod l2cap;
68pub mod objc;
69/// The peripheral role. **macOS and iOS only** — see `build.rs`.
70#[cfg(peripheral_role)]
71pub mod peripheral;
72/// RFCOMM over IOBluetooth. **macOS only**, behind `rfcomm`.
73#[cfg(all(target_os = "macos", feature = "rfcomm"))]
74pub mod rfcomm;
75
76use std::sync::Arc;
77
78pub use cb::RestoredCentralState;
79pub use cb::{Advertisement, Authorization, ManagerState, PeripheralState, Properties, WriteType};
80pub use delegate::{Event, EventSink};
81pub use l2cap::{Channel as L2capChannel, Closed as L2capClosed, Psm};
82pub use objc::{AutoreleasePool, Retained};
83pub use objc::{Id, NIL};
84#[cfg(peripheral_role)]
85pub use peripheral::{
86    AttError, InvalidAttribute, PeripheralEvent, PeripheralEventSink, PeripheralHost, Permissions,
87    RestoredPeripheralState,
88};
89
90/// A `CBCentralManager` with a runtime-built delegate on a private queue.
91///
92/// Dropping this releases the manager, which stops any scan and tears down any
93/// connection it owns.
94#[derive(Debug)]
95pub struct Central {
96    manager: Retained,
97    /// Held so the delegate object — and its entry in the sink registry —
98    /// outlives the manager that points at it. `CBCentralManager` holds its
99    /// delegate weakly.
100    _delegate: delegate::Delegate,
101    /// Likewise: the manager does not keep the queue alive.
102    _queue: dispatch::Queue,
103}
104
105impl Central {
106    /// Create a central manager delivering events to `sink`.
107    ///
108    /// `show_power_alert` maps to `CBCentralManagerOptionShowPowerAlertKey`: if
109    /// Bluetooth is off, the system offers to turn it on. Web Bluetooth has no
110    /// equivalent — a browser never raises that dialog — so it defaults off in
111    /// the layer above.
112    pub fn new(sink: Arc<dyn EventSink>, show_power_alert: bool) -> Self {
113        Self::with_restore_identifier(sink, show_power_alert, None)
114    }
115
116    /// As [`Central::new`], opting into state preservation and restoration.
117    ///
118    /// `restore_identifier` must be identical on every launch, or the system
119    /// cannot match the manager it preserved. See
120    /// [`delegate::Event::WillRestoreState`] — and note that only iOS relaunches
121    /// a process to finish Bluetooth work.
122    pub fn with_restore_identifier(
123        sink: Arc<dyn EventSink>,
124        show_power_alert: bool,
125        restore_identifier: Option<&str>,
126    ) -> Self {
127        let queue = dispatch::Queue::serial(c"dev.webbluetooth.central");
128        let delegate = delegate::Delegate::new(sink);
129        // SAFETY: both the queue and the delegate are stored in the returned
130        // value, so they outlive the manager built from them.
131        let manager = unsafe {
132            let options = cb::central_options(show_power_alert, restore_identifier);
133            cb::central_new(
134                delegate.as_ptr(),
135                queue.as_ptr(),
136                options.as_ref().map_or(NIL, |o| o.as_ptr()),
137            )
138            .expect("CBCentralManager allocation failed")
139        };
140        Self {
141            manager,
142            _delegate: delegate,
143            _queue: queue,
144        }
145    }
146
147    #[inline]
148    pub fn as_ptr(&self) -> Id {
149        self.manager.as_ptr()
150    }
151
152    /// The current Bluetooth state.
153    pub fn state(&self) -> ManagerState {
154        unsafe { cb::central_state(self.as_ptr()) }
155    }
156
157    /// Whether a scan is running.
158    pub fn is_scanning(&self) -> bool {
159        unsafe { cb::central_is_scanning(self.as_ptr()) }
160    }
161
162    /// Attach this central's delegate to a peripheral, so its
163    /// `CBPeripheralDelegate` callbacks land in the same sink.
164    ///
165    /// # Safety
166    /// `peripheral` must be a `CBPeripheral` retrieved from this central.
167    pub unsafe fn adopt_peripheral(&self, peripheral: Id) {
168        unsafe { cb::peripheral_set_delegate(peripheral, self._delegate.as_ptr()) }
169    }
170}
171
172// The manager is safe to message from any thread; callbacks are serialised onto
173// the private queue regardless of which thread asked for the work.
174unsafe impl Send for Central {}
175unsafe impl Sync for Central {}
176
177/// Whether CoreBluetooth is present and this process may use it.
178///
179/// Distinct from "a radio exists and is on" — see [`Central::state`].
180pub fn authorization() -> Authorization {
181    cb::authorization()
182}
183
184#[cfg(test)]
185mod tests {
186    use super::*;
187    use std::sync::mpsc;
188
189    struct Collect(mpsc::Sender<ManagerState>);
190    impl EventSink for Collect {
191        fn emit(&self, event: Event) {
192            if let Event::StateChanged(s) = event {
193                let _ = self.0.send(s);
194            }
195        }
196    }
197
198    #[test]
199    // Reaches into the Objective-C runtime, which Miri cannot call.
200    #[cfg_attr(miri, ignore = "calls into the Objective-C runtime")]
201    fn delegate_class_registers_and_receives_state() {
202        let (tx, rx) = mpsc::channel();
203        let central = Central::new(Arc::new(Collect(tx)), false);
204        // `centralManagerDidUpdateState:` is guaranteed to arrive, and is the
205        // proof that a class built at runtime satisfied CoreBluetooth.
206        let state = rx
207            .recv_timeout(std::time::Duration::from_secs(5))
208            .expect("centralManagerDidUpdateState: never arrived");
209        assert_eq!(state, central.state());
210    }
211
212    #[test]
213    // Reaches into the Objective-C runtime, which Miri cannot call.
214    #[cfg_attr(miri, ignore = "calls into the Objective-C runtime")]
215    fn two_centrals_get_independent_sinks() {
216        let (tx1, rx1) = mpsc::channel();
217        let (tx2, rx2) = mpsc::channel();
218        let _a = Central::new(Arc::new(Collect(tx1)), false);
219        let _b = Central::new(Arc::new(Collect(tx2)), false);
220        let t = std::time::Duration::from_secs(5);
221        assert!(rx1.recv_timeout(t).is_ok(), "first central got no state");
222        assert!(rx2.recv_timeout(t).is_ok(), "second central got no state");
223    }
224
225    /// `CBUUID.UUIDString` is **not** a canonical form: it echoes back whichever
226    /// width it was constructed from, uppercased. Web Bluetooth requires the
227    /// lowercase 128-bit form everywhere, so `webbluetooth::BluetoothUuid`
228    /// normalises in both directions rather than trusting this string.
229    #[test]
230    // Reaches into the Objective-C runtime, which Miri cannot call.
231    #[cfg_attr(miri, ignore = "calls into the Objective-C runtime")]
232    fn uuid_string_is_not_canonical() {
233        let short = unsafe { cb::uuid_from_string("180F") }.expect("short CBUUID");
234        assert_eq!(
235            unsafe { cb::uuid_string(short.as_ptr()) }.as_deref(),
236            Some("180F")
237        );
238
239        let long = unsafe { cb::uuid_from_string("0000180f-0000-1000-8000-00805f9b34fb") }
240            .expect("128-bit CBUUID");
241        assert_eq!(
242            unsafe { cb::uuid_string(long.as_ptr()) }.as_deref(),
243            Some("0000180F-0000-1000-8000-00805F9B34FB"),
244            "same UUID, different string — and uppercased"
245        );
246    }
247}