Skip to main content

nimble_rs/
lib.rs

1//! Safe, async, cross-platform Rust API for the esp-nimble BLE host, running
2//! over any [`bt-hci`](https://crates.io/crates/bt-hci) controller.
3//!
4//! Work in progress - see `docs/PLAN.md` in the repository root. The overall
5//! architecture:
6//!
7//! - The NimBLE C host is compiled by `nimble-rs-sys`; its OS layer (NPL) and
8//!   HCI transport are implemented here, in Rust (`npl`, `hci` modules) -
9//!   **thread-free** and **allocation-free**.
10//! - [`Ble::run`] is the single future that drives everything: the host
11//!   event loop, the callout timers and the HCI pump. Host API calls may
12//!   briefly stall the executor while awaiting a command ack from the
13//!   controller (bounded by the HCI command timeout) - the same latency the C
14//!   design imposes, just not hidden behind a context switch.
15#![no_std]
16
17use core::cell::Cell;
18use core::convert::Infallible;
19use core::ffi::{c_int, c_void};
20use core::future::poll_fn;
21use core::pin::pin;
22use core::task::Poll;
23
24use embassy_futures::select::select3;
25
26use nimble_rs_sys as sys;
27
28pub use hci::{AdvCmds, CentralCmds, ConnCmds, Controller, CoreCmds, ScanCmds, SmCmds};
29#[cfg(feature = "std")]
30pub use npl::parker::StdParker;
31#[cfg(all(target_arch = "arm", target_os = "none"))]
32pub use npl::parker::WfeParker;
33pub use npl::parker::{Parker, SpinParker};
34
35#[cfg(feature = "std")]
36extern crate std;
37
38// `fmt` must come first for its macros to be visible
39#[macro_use]
40mod fmt;
41
42mod clog;
43
44pub mod gap;
45pub mod gatt;
46pub mod hci;
47#[cfg(feature = "l2cap")]
48pub mod l2cap;
49pub mod mbuf;
50mod mem;
51mod npl;
52mod port;
53
54/// Support hooks for external test harnesses (the upstream NimBLE test suite
55/// runner). Only present with the `external-ll` feature.
56#[cfg(feature = "external-ll")]
57pub mod test_support {
58    /// Fires every callout whose deadline has passed (the job of the driver's
59    /// `run()` future, which a synchronous test harness does not poll).
60    pub fn fire_due_timers() {
61        crate::npl::timers_fire_due();
62    }
63
64    /// Drains and runs every event on the default queue.
65    pub fn drain_events() {
66        crate::port::drain_events();
67    }
68}
69
70extern "C" {
71    // Declared in `store/ram/ble_store_ram.h` but not surfaced by bindgen
72    fn ble_store_ram_init();
73}
74
75/// A connection handle.
76pub type ConnHandle = u16;
77
78/// The "no connection" handle: *local* GATT reads and writes carry this
79/// instead of a real connection handle.
80pub const CONN_HANDLE_NONE: ConnHandle = sys::BLE_HS_CONN_HANDLE_NONE as ConnHandle;
81
82/// A BLE UUID, either 16-bit (assigned) or 128-bit (vendor-specific).
83#[derive(Clone, Copy)]
84pub enum BleUuid {
85    Uuid16(sys::ble_uuid16_t),
86    Uuid128(sys::ble_uuid128_t),
87}
88
89impl core::fmt::Debug for BleUuid {
90    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
91        match self {
92            Self::Uuid16(uuid) => write!(f, "Uuid16({:#06x})", uuid.value),
93            Self::Uuid128(uuid) => write!(f, "Uuid128({:#034x})", u128::from_le_bytes(uuid.value)),
94        }
95    }
96}
97
98impl BleUuid {
99    pub const fn uuid16(uuid: u16) -> Self {
100        Self::Uuid16(sys::ble_uuid16_t {
101            u: sys::ble_uuid_t {
102                type_: sys::BLE_UUID_TYPE_16 as u8,
103            },
104            value: uuid,
105        })
106    }
107
108    pub const fn uuid128(uuid: u128) -> Self {
109        Self::Uuid128(sys::ble_uuid128_t {
110            u: sys::ble_uuid_t {
111                type_: sys::BLE_UUID_TYPE_128 as u8,
112            },
113            value: uuid.to_le_bytes(),
114        })
115    }
116
117    pub const fn as_ptr(&self) -> *const sys::ble_uuid_t {
118        match self {
119            Self::Uuid16(uuid) => &uuid.u as *const sys::ble_uuid_t,
120            Self::Uuid128(uuid) => &uuid.u as *const sys::ble_uuid_t,
121        }
122    }
123
124    /// # Safety
125    ///
126    /// `uuid` must point to a valid `ble_uuid_t` header and the concrete
127    /// 16-/128-bit body it introduces.
128    pub(crate) unsafe fn from_raw(uuid: *const sys::ble_uuid_t) -> Self {
129        match (*uuid).type_ as u32 {
130            sys::BLE_UUID_TYPE_128 => Self::Uuid128(*uuid.cast::<sys::ble_uuid128_t>()),
131            // Only 16- and 128-bit UUIDs are modelled; anything else reads as 16-bit
132            _ => Self::Uuid16(*uuid.cast::<sys::ble_uuid16_t>()),
133        }
134    }
135}
136
137impl PartialEq for BleUuid {
138    fn eq(&self, other: &Self) -> bool {
139        unsafe { sys::ble_uuid_cmp(self.as_ptr(), other.as_ptr()) == 0 }
140    }
141}
142
143impl Eq for BleUuid {}
144
145/// A BLE device address (type + 6 bytes).
146#[derive(Clone, Copy)]
147#[repr(transparent)]
148pub struct BleAddr(sys::ble_addr_t);
149
150impl BleAddr {
151    pub const fn new(kind: u8, val: [u8; 6]) -> Self {
152        Self(sys::ble_addr_t { type_: kind, val })
153    }
154
155    pub const fn raw(&self) -> &sys::ble_addr_t {
156        &self.0
157    }
158
159    pub const fn kind(&self) -> u8 {
160        self.0.type_
161    }
162
163    pub const fn val(&self) -> [u8; 6] {
164        self.0.val
165    }
166}
167
168impl core::fmt::Debug for BleAddr {
169    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
170        let v = &self.0.val;
171        write!(
172            f,
173            "{:02x}:{:02x}:{:02x}:{:02x}:{:02x}:{:02x}/{}",
174            v[5], v[4], v[3], v[2], v[1], v[0], self.0.type_
175        )
176    }
177}
178
179/// An error code from the NimBLE host (the `BLE_HS_E*` namespace), or 0.
180#[derive(Copy, Clone, Eq, PartialEq)]
181#[cfg_attr(feature = "defmt", derive(defmt::Format))]
182#[repr(transparent)]
183pub struct BleError(c_int);
184
185impl BleError {
186    /// Creates an error from a raw NimBLE host return code.
187    pub const fn new(code: c_int) -> Self {
188        Self(code)
189    }
190
191    /// The raw NimBLE host return code.
192    pub const fn code(&self) -> c_int {
193        self.0
194    }
195
196    /// Converts a raw NimBLE host return code into a result.
197    pub fn check(code: c_int) -> Result<(), Self> {
198        if code == 0 {
199            Ok(())
200        } else {
201            Err(Self(code))
202        }
203    }
204}
205
206impl core::fmt::Debug for BleError {
207    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
208        write!(f, "BleError({})", self.0)
209    }
210}
211
212impl core::fmt::Display for BleError {
213    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
214        write!(f, "BLE host error {}", self.0)
215    }
216}
217
218#[cfg(feature = "std")]
219impl std::error::Error for BleError {}
220
221/// Events of the host stack itself.
222#[derive(Copy, Clone, Debug, Eq, PartialEq)]
223#[cfg_attr(feature = "defmt", derive(defmt::Format))]
224pub enum HostEvent {
225    /// The host and controller are in sync; the stack is usable from now on.
226    Sync,
227    /// The host has reset itself (e.g. after a fatal HCI error); the carried
228    /// value is a `BLE_HS_E*` reason code. A sync will follow.
229    Reset(c_int),
230}
231
232/// A critical-section-guarded slot for a subscribed `&'static` callback.
233pub(crate) struct CallbackSlot<F: ?Sized + 'static>(Cell<Option<&'static F>>);
234
235// Guarded by the global critical section.
236unsafe impl<F: ?Sized> Send for CallbackSlot<F> {}
237unsafe impl<F: ?Sized> Sync for CallbackSlot<F> {}
238
239impl<F: ?Sized> CallbackSlot<F> {
240    const fn new() -> Self {
241        Self(Cell::new(None))
242    }
243
244    fn get(&self) -> Option<&'static F> {
245        critical_section::with(|_| self.0.get())
246    }
247
248    pub(crate) fn set(&self, callback: Option<&'static F>) {
249        critical_section::with(|_| self.0.set(callback));
250    }
251}
252
253static HOST_CALLBACK: CallbackSlot<dyn Fn(HostEvent) + Sync> = CallbackSlot::new();
254static GAP_CALLBACK: CallbackSlot<dyn for<'a> Fn(gap::GapEvent<'a>) -> i32 + Sync> =
255    CallbackSlot::new();
256#[cfg(feature = "peripheral")]
257static GATTS_CALLBACK: CallbackSlot<dyn for<'a> Fn(gatt::server::GattsEvent<'a>) -> u8 + Sync> =
258    CallbackSlot::new();
259
260// Not an atomic: RMW atomics (compare-exchange) do not exist on e.g.
261// thumbv6-m, and a critical section is required infrastructure anyway.
262static TAKEN: critical_section::Mutex<Cell<bool>> = critical_section::Mutex::new(Cell::new(false));
263
264/// Atomically takes or releases the singleton flag; returns the previous value.
265fn taken_swap(new: bool) -> bool {
266    critical_section::with(|cs| TAKEN.borrow(cs).replace(new))
267}
268
269extern "C" fn on_sync() {
270    debug!("NimBLE host sync");
271    if let Some(cb) = HOST_CALLBACK.get() {
272        cb(HostEvent::Sync);
273    }
274}
275
276extern "C" fn on_reset(reason: c_int) {
277    warn!("NimBLE host reset, reason {}", reason);
278    if let Some(cb) = HOST_CALLBACK.get() {
279        cb(HostEvent::Reset(reason));
280    }
281}
282
283/// The connection event callback (wired at `adv_start`). NimBLE multiplexes
284/// role-specific events onto it, so we **demux by role**: the role-agnostic
285/// connection events go to the GAP hook, the server-role events
286/// (`Subscribe`/`NotifyComplete`) to the GATTS hook.
287pub(crate) unsafe extern "C" fn gap_event_cb(
288    event: *mut sys::ble_gap_event,
289    _arg: *mut c_void,
290) -> c_int {
291    let event = &*event;
292
293    match event.type_ as u32 {
294        #[cfg(feature = "peripheral")]
295        sys::BLE_GAP_EVENT_SUBSCRIBE | sys::BLE_GAP_EVENT_NOTIFY_TX => {
296            if let (Some(cb), Some(event)) = (
297                GATTS_CALLBACK.get(),
298                gatt::server::GattsEvent::from_gap(event),
299            ) {
300                cb(event);
301            }
302            0
303        }
304        #[cfg(feature = "central")]
305        sys::BLE_GAP_EVENT_NOTIFY_RX => {
306            if let Some(cb) = gatt::client::GATTC_CALLBACK.get() {
307                cb(gatt::client::GattcEvent::from_notify_rx(event));
308            }
309            0
310        }
311        _ => {
312            if let Some(cb) = GAP_CALLBACK.get() {
313                cb(gap::GapEvent::from(event))
314            } else {
315                0
316            }
317        }
318    }
319}
320
321#[cfg(feature = "peripheral")]
322pub(crate) unsafe extern "C" fn gatts_register_cb(
323    ctxt: *mut sys::ble_gatt_register_ctxt,
324    _arg: *mut c_void,
325) {
326    if let Some(cb) = GATTS_CALLBACK.get() {
327        // The registration events carry no reply; the status return is ignored
328        cb(gatt::server::GattsEvent::Register(
329            gatt::server::BleGattRegister::from(&*ctxt),
330        ));
331    }
332}
333
334/// The single access trampoline shared by *every* characteristic - NimBLE
335/// dispatches reads and writes here, and we route them to the one
336/// [`gatts_subscribe`](Ble::gatts_subscribe) hook, keyed by the
337/// (globally unique) `attr_handle`.
338#[cfg(feature = "peripheral")]
339pub(crate) unsafe extern "C" fn gatts_access_cb(
340    conn_handle: u16,
341    attr_handle: u16,
342    ctxt: *mut sys::ble_gatt_access_ctxt,
343    _arg: *mut c_void,
344) -> c_int {
345    let Some(cb) = GATTS_CALLBACK.get() else {
346        return sys::BLE_ATT_ERR_UNLIKELY as c_int;
347    };
348
349    let mbuf = mbuf::Mbuf::from_raw((*ctxt).om);
350
351    let event = match (*ctxt).op as u32 {
352        sys::BLE_GATT_ACCESS_OP_READ_CHR => gatt::server::GattsEvent::Read {
353            conn_handle,
354            attr_handle,
355            offset: (*ctxt).offset,
356            reply: mbuf,
357        },
358        // Writes are always delivered whole and at offset 0 (NimBLE coalesces
359        // long writes)
360        sys::BLE_GATT_ACCESS_OP_WRITE_CHR => gatt::server::GattsEvent::Write {
361            conn_handle,
362            attr_handle,
363            data: mbuf,
364        },
365        _ => return sys::BLE_ATT_ERR_UNLIKELY as c_int,
366    };
367
368    cb(event) as c_int
369}
370
371/// The BLE host driver: a singleton wrapping the NimBLE host stack.
372///
373/// Construct it with [`Ble::new`] (or, with a GATT service table, via
374/// [`Ble::new_with_services`]), subscribe to the events you need, then
375/// drive the stack by awaiting [`Ble::run`] with a controller. All
376/// callbacks run from inside `run`'s poll.
377///
378/// `S` is the GATT service table (`()` for none); the driver keeps it alive
379/// for as long as the C host may reference it.
380pub struct Ble<'d, S = ()> {
381    // Kept alive (not read back) for as long as the C host may reference it
382    _services: S,
383    // The borrow of an injected [`Parker`], if any (see `new_with_parker`)
384    _parker: core::marker::PhantomData<&'d ()>,
385}
386
387impl<'d> Ble<'d, ()> {
388    /// Initializes the NimBLE host stack (without a GATT service table).
389    /// Errors if another driver instance exists or the stack fails to
390    /// initialize.
391    pub fn new() -> Result<Self, BleError> {
392        Self::init(())?;
393
394        Ok(Self {
395            _services: (),
396            _parker: core::marker::PhantomData,
397        })
398    }
399
400    /// Like [`new`](Self::new), with a custom [`Parker`] for the
401    /// pump-while-pending waits (in place of the default - thread parking
402    /// with the `std` feature, a spin loop otherwise). The parker is
403    /// borrowed for as long as the driver lives.
404    pub fn new_with_parker(parker: &'d dyn Parker) -> Result<Self, BleError> {
405        let this = Self::new()?;
406        npl::parker::set_active(Some(promote!(parker => dyn Parker)));
407
408        Ok(this)
409    }
410}
411
412/// Extends a driver-lifetime (`'d`) borrow - an injected [`Parker`] or a
413/// subscribed callback - to the `'static` the process-wide slots need (the
414/// NPL and callback entry points are reached from C with no lifetime to
415/// carry). Both the reference lifetime and the trait object's own lifetime
416/// bound are erased.
417///
418/// SAFETY: the borrow genuinely ends when the driver does - `Drop` resets
419/// every slot. If the driver is *leaked* (`mem::forget`) the slots keep
420/// their dangling pointers, but nothing can reach them: the singleton stays
421/// taken (no new driver can be constructed), and the C host - the only
422/// consumer - executes exclusively inside driver calls.
423macro_rules! promote {
424    ($r:expr => $ty:ty) => {
425        unsafe { core::mem::transmute::<&$ty, &'static $ty>($r) }
426    };
427}
428
429pub(crate) use promote;
430
431#[cfg(feature = "peripheral")]
432impl<'d, S> Ble<'d, S>
433where
434    S: AsRef<[sys::ble_gatt_svc_def]>,
435{
436    /// Initializes the NimBLE host stack with a GATT service table: either a
437    /// `&'static` one from the [`gatt_services!`](crate::gatt_services) macro,
438    /// or a runtime-built [`BleGattServices`](gatt::server::BleGattServices).
439    ///
440    /// The attribute handles NimBLE assigns are reported through the
441    /// [`Register`](gatt::server::GattsEvent::Register) events during host
442    /// start, so [`gatts_subscribe`](Self::gatts_subscribe) before awaiting
443    /// [`run`](Self::run).
444    pub fn new_with_services(services: S) -> Result<Self, BleError> {
445        Self::init(())?;
446
447        unsafe {
448            let cfg = core::ptr::addr_of_mut!(sys::ble_hs_cfg);
449            (*cfg).gatts_register_cb = Some(gatts_register_cb);
450        }
451
452        let defs = services.as_ref();
453
454        let result = unsafe {
455            BleError::check(sys::ble_gatts_count_cfg(defs.as_ptr()))
456                .and_then(|_| BleError::check(sys::ble_gatts_add_svcs(defs.as_ptr())))
457        };
458
459        if let Err(err) = result {
460            drop(Ble {
461                _services: (),
462                _parker: core::marker::PhantomData,
463            }); // deinit through the common path
464            return Err(err);
465        }
466
467        Ok(Self {
468            _services: services,
469            _parker: core::marker::PhantomData,
470        })
471    }
472
473    /// Like [`new_with_services`](Self::new_with_services), with a custom
474    /// [`Parker`] for the pump-while-pending waits.
475    pub fn new_with_services_and_parker(
476        services: S,
477        parker: &'d dyn Parker,
478    ) -> Result<Self, BleError> {
479        let this = Self::new_with_services(services)?;
480        npl::parker::set_active(Some(promote!(parker => dyn Parker)));
481
482        Ok(this)
483    }
484}
485
486impl<'d, S> Ble<'d, S> {
487    fn init(_: ()) -> Result<(), BleError> {
488        if taken_swap(true) {
489            return Err(BleError::new(sys::BLE_HS_EALREADY as _));
490        }
491
492        if port::init().is_err() {
493            taken_swap(false);
494            return Err(BleError::new(sys::BLE_HS_ENOMEM as _));
495        }
496
497        unsafe {
498            // Pre-`run` single-threaded window: install the host callbacks
499            let cfg = core::ptr::addr_of_mut!(sys::ble_hs_cfg);
500            (*cfg).sync_cb = Some(on_sync);
501            (*cfg).reset_cb = Some(on_reset);
502
503            // The GAP + GATT services exist only when the GATT server is
504            // compiled (`BLE_GATTS`, i.e. the `peripheral` feature)
505            #[cfg(feature = "peripheral")]
506            {
507                sys::ble_svc_gap_init();
508                sys::ble_svc_gatt_init();
509            }
510            ble_store_ram_init();
511        }
512
513        Ok(())
514    }
515
516    /// Subscribes to host events. The callback runs from inside [`Self::run`]'s
517    /// poll and may freely call host APIs.
518    pub fn host_subscribe(&self, callback: &'d (dyn Fn(HostEvent) + Sync)) {
519        HOST_CALLBACK.set(Some(promote!(callback => (dyn Fn(HostEvent) + Sync))));
520    }
521
522    /// Drives the host stack over the given controller. Must be polled for the
523    /// stack to make any progress; never returns under normal operation.
524    ///
525    /// Contract: do not block the task polling `run` with unrelated long
526    /// operations - host API calls made from *other* tasks (or from callbacks)
527    /// rely on `run` being responsive. Calls that send HCI commands stall the
528    /// executor for the command-ack round-trip (µs-ms, bounded by the HCI
529    /// command timeout).
530    pub async fn run<C: Controller>(&self, controller: C) -> Result<Infallible, BleError> {
531        let mut pump = pin!(hci::pump(&controller));
532
533        // SAFETY: `pump` is pinned in this frame and `guard` (dropped before
534        // it) deregisters it.
535        let guard = unsafe {
536            let ptr: *mut (dyn core::future::Future<Output = Infallible> + '_) =
537                pump.as_mut().get_unchecked_mut();
538            hci::register_pump(ptr)
539        };
540
541        let events = pin!(port::run_events());
542        let timers = pin!(port::run_timers());
543        // The pump is driven through the same registration used by blocked NPL
544        // waits, so that polls never race. This arm re-registers the executor's
545        // waker with the transport on every `run` poll, repairing any waker
546        // "stolen" by an intervening pump-while-pending wait.
547        let pump_arm = pin!(poll_fn(|cx| {
548            hci::pump_manual(cx.waker());
549            Poll::<Infallible>::Pending
550        }));
551
552        let never = select3(events, timers, pump_arm).await;
553
554        drop(guard);
555        match never {
556            embassy_futures::select::Either3::First(never) => match never {},
557            embassy_futures::select::Either3::Second(never) => match never {},
558            embassy_futures::select::Either3::Third(never) => match never {},
559        }
560    }
561
562    /// The device's identity address, ensuring one exists (generating a random
563    /// static address if the controller has no public one).
564    pub fn address(&self) -> Result<([u8; 6], u8), BleError> {
565        let mut addr = [0; 6];
566        let mut addr_type = 0;
567
568        unsafe {
569            BleError::check(sys::ble_hs_util_ensure_addr(0))?;
570            BleError::check(sys::ble_hs_id_infer_auto(0, &mut addr_type))?;
571            BleError::check(sys::ble_hs_id_copy_addr(
572                addr_type,
573                addr.as_mut_ptr(),
574                core::ptr::null_mut(),
575            ))?;
576        }
577
578        Ok((addr, addr_type))
579    }
580
581    /// Whether the host is synced with the controller (i.e. operational).
582    pub fn synced(&self) -> bool {
583        unsafe { sys::ble_hs_synced() != 0 }
584    }
585}
586
587impl<'d, S> Drop for Ble<'d, S> {
588    fn drop(&mut self) {
589        unsafe {
590            let cfg = core::ptr::addr_of_mut!(sys::ble_hs_cfg);
591            (*cfg).sync_cb = None;
592            (*cfg).reset_cb = None;
593            #[cfg(feature = "peripheral")]
594            {
595                (*cfg).gatts_register_cb = None;
596            }
597        }
598
599        npl::parker::set_active(None);
600
601        HOST_CALLBACK.set(None);
602        GAP_CALLBACK.set(None);
603        #[cfg(feature = "peripheral")]
604        GATTS_CALLBACK.set(None);
605        #[cfg(feature = "central")]
606        gatt::client::GATTC_CALLBACK.set(None);
607        #[cfg(feature = "l2cap")]
608        l2cap::L2CAP_CALLBACK.set(None);
609
610        // `port::deinit` tears the whole host down (including the GATT service
611        // registry), after which the C side no longer references `self.services`
612        port::deinit();
613
614        taken_swap(false);
615    }
616}