1#![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#[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#[cfg(feature = "external-ll")]
57pub mod test_support {
58 pub fn fire_due_timers() {
61 crate::npl::timers_fire_due();
62 }
63
64 pub fn drain_events() {
66 crate::port::drain_events();
67 }
68}
69
70extern "C" {
71 fn ble_store_ram_init();
73}
74
75pub type ConnHandle = u16;
77
78pub const CONN_HANDLE_NONE: ConnHandle = sys::BLE_HS_CONN_HANDLE_NONE as ConnHandle;
81
82#[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 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 _ => 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#[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#[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 pub const fn new(code: c_int) -> Self {
188 Self(code)
189 }
190
191 pub const fn code(&self) -> c_int {
193 self.0
194 }
195
196 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#[derive(Copy, Clone, Debug, Eq, PartialEq)]
223#[cfg_attr(feature = "defmt", derive(defmt::Format))]
224pub enum HostEvent {
225 Sync,
227 Reset(c_int),
230}
231
232pub(crate) struct CallbackSlot<F: ?Sized + 'static>(Cell<Option<&'static F>>);
234
235unsafe 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
260static TAKEN: critical_section::Mutex<Cell<bool>> = critical_section::Mutex::new(Cell::new(false));
263
264fn 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
283pub(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 cb(gatt::server::GattsEvent::Register(
329 gatt::server::BleGattRegister::from(&*ctxt),
330 ));
331 }
332}
333
334#[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 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
371pub struct Ble<'d, S = ()> {
381 _services: S,
383 _parker: core::marker::PhantomData<&'d ()>,
385}
386
387impl<'d> Ble<'d, ()> {
388 pub fn new() -> Result<Self, BleError> {
392 Self::init(())?;
393
394 Ok(Self {
395 _services: (),
396 _parker: core::marker::PhantomData,
397 })
398 }
399
400 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
412macro_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 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 }); return Err(err);
465 }
466
467 Ok(Self {
468 _services: services,
469 _parker: core::marker::PhantomData,
470 })
471 }
472
473 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 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 #[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 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 pub async fn run<C: Controller>(&self, controller: C) -> Result<Infallible, BleError> {
531 let mut pump = pin!(hci::pump(&controller));
532
533 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 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 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 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();
613
614 taken_swap(false);
615 }
616}