blew 0.1.0-alpha.7

Cross-platform async BLE library for Rust (Apple, Linux, Android)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
//! Apple (macOS / iOS) implementation of [`PeripheralBackend`].
//!
//! Architecture:
//! - A dedicated GCD serial queue receives all `CBPeripheralManager` delegate callbacks.
//! - GATT service/characteristic mutable objects are retained so we can push
//!   notifications and respond to read/write requests.
//! - RAII [`ReadResponder`] / [`WriteResponder`] carry ATT responses back to the
//!   CB queue via Tokio oneshot channels + background tasks.

#![allow(
    non_snake_case,
    clippy::too_many_arguments,
    clippy::cast_possible_truncation,
    unsafe_op_in_unsafe_fn
)]

use std::collections::HashMap;
use std::future::Future;
use std::sync::{Arc, Mutex};

use dispatch2::{DispatchQueue, DispatchQueueAttr};
use futures_core::Stream;
use objc2::define_class;
use objc2::rc::Retained;
use objc2::runtime::{AnyObject, NSObject, ProtocolObject};
use objc2::{AnyThread, DefinedClass};
use objc2_core_bluetooth::{
    CBATTError, CBATTRequest, CBAdvertisementDataLocalNameKey, CBAdvertisementDataServiceUUIDsKey,
    CBAttributePermissions, CBCentral, CBCharacteristic, CBCharacteristicProperties,
    CBL2CAPChannel, CBL2CAPPSM, CBManagerState, CBMutableCharacteristic, CBMutableService,
    CBPeripheralManager, CBPeripheralManagerConnectionLatency, CBPeripheralManagerDelegate,
    CBService, CBUUID,
};
use objc2_foundation::{NSArray, NSData, NSDictionary, NSError, NSObjectProtocol, NSString};
use tokio::runtime::Handle;
use tokio::sync::{mpsc, oneshot, watch};
use tokio_stream::wrappers::{ReceiverStream, UnboundedReceiverStream};
use uuid::Uuid;

use tracing::{debug, trace, warn};

use crate::error::{BlewError, BlewResult};
use crate::gatt::props::{AttributePermissions, CharacteristicProperties};
use crate::gatt::service::GattService;
use crate::l2cap::{L2capChannel, types::Psm};
use crate::peripheral::backend::{self, PeripheralBackend};
use crate::peripheral::types::{AdvertisingConfig, PeripheralEvent, ReadResponder, WriteResponder};
use crate::types::DeviceId;
use crate::platform::apple::helpers::{
    ObjcSend, cbuuid_to_uuid, central_device_id, retain_send, uuid_to_cbuuid,
};
use crate::platform::apple::l2cap::bridge_l2cap_channel;

fn our_props_to_cb(props: CharacteristicProperties) -> CBCharacteristicProperties {
    let mut out = CBCharacteristicProperties(0);
    if props.contains(CharacteristicProperties::BROADCAST) {
        out |= CBCharacteristicProperties::Broadcast;
    }
    if props.contains(CharacteristicProperties::READ) {
        out |= CBCharacteristicProperties::Read;
    }
    if props.contains(CharacteristicProperties::WRITE_WITHOUT_RESPONSE) {
        out |= CBCharacteristicProperties::WriteWithoutResponse;
    }
    if props.contains(CharacteristicProperties::WRITE) {
        out |= CBCharacteristicProperties::Write;
    }
    if props.contains(CharacteristicProperties::NOTIFY) {
        out |= CBCharacteristicProperties::Notify;
    }
    if props.contains(CharacteristicProperties::INDICATE) {
        out |= CBCharacteristicProperties::Indicate;
    }
    out
}

fn our_perms_to_cb(perms: AttributePermissions) -> CBAttributePermissions {
    let mut out = CBAttributePermissions(0);
    if perms.contains(AttributePermissions::READ) {
        out |= CBAttributePermissions::Readable;
    }
    if perms.contains(AttributePermissions::WRITE) {
        out |= CBAttributePermissions::Writeable;
    }
    if perms.contains(AttributePermissions::READ_ENCRYPTED) {
        out |= CBAttributePermissions::ReadEncryptionRequired;
    }
    if perms.contains(AttributePermissions::WRITE_ENCRYPTED) {
        out |= CBAttributePermissions::WriteEncryptionRequired;
    }
    out
}

struct PeripheralInner {
    /// `CBMutableCharacteristic` objects keyed by UUID, for notification sending.
    chars: Mutex<HashMap<Uuid, ObjcSend<CBMutableCharacteristic>>>,
    /// Retained `CBCentral` handles, keyed by (characteristic UUID, device id),
    /// populated by `didSubscribeToCharacteristic` and cleared by
    /// `didUnsubscribeFromCharacteristic`. Used by `notify_characteristic` to
    /// target a single central rather than broadcasting.
    subscribers: Mutex<HashMap<Uuid, HashMap<DeviceId, ObjcSend<CBCentral>>>>,
    /// Pending `start_advertising()` result.
    adv_tx: Mutex<Option<oneshot::Sender<BlewResult<()>>>>,
    /// Pending `add_service()` results.
    add_svc_tx: Mutex<HashMap<Uuid, oneshot::Sender<BlewResult<()>>>>,
    /// Single event subscriber (most recent call to `events()` wins).
    ///
    /// `PeripheralEvent` is `!Clone`, so we cannot fan out to multiple subscribers.
    event_tx: Mutex<Option<mpsc::UnboundedSender<PeripheralEvent>>>,
    /// Powered state watch.
    powered_tx: watch::Sender<bool>,
    /// Result of `publishL2CAPChannelWithEncryption` -- carries the assigned PSM.
    l2cap_publish_tx: Mutex<Option<oneshot::Sender<BlewResult<Psm>>>>,
    /// Sender for incoming L2CAP channels (set by `l2cap_listener`).
    l2cap_channel_tx: Mutex<Option<mpsc::Sender<BlewResult<(DeviceId, L2capChannel)>>>>,
    /// Tokio runtime handle, captured at construction time so GCD callbacks
    /// (which run off the Tokio thread) can spawn tasks onto the runtime.
    runtime: Handle,
}

impl PeripheralInner {
    fn new() -> (Arc<Self>, watch::Receiver<bool>) {
        let (powered_tx, powered_rx) = watch::channel(false);
        let inner = Arc::new(Self {
            chars: Default::default(),
            subscribers: Default::default(),
            adv_tx: Default::default(),
            add_svc_tx: Default::default(),
            event_tx: Mutex::new(None),
            powered_tx,
            l2cap_publish_tx: Mutex::new(None),
            l2cap_channel_tx: Mutex::new(None),
            runtime: Handle::current(),
        });
        (inner, powered_rx)
    }

    fn emit(&self, event: PeripheralEvent) {
        if let Some(tx) = self.event_tx.lock().unwrap().as_ref() {
            let _ = tx.send(event);
        }
    }
}

define_class!(
    // SAFETY: NSObject has no subclassing requirements.
    #[unsafe(super(NSObject))]
    #[name = "BlewPeripheralDelegate"]
    #[ivars = Arc<PeripheralInner>]
    struct PeripheralDelegate;

    unsafe impl NSObjectProtocol for PeripheralDelegate {}

    unsafe impl CBPeripheralManagerDelegate for PeripheralDelegate {
        #[unsafe(method(peripheralManagerDidUpdateState:))]
        unsafe fn peripheralManagerDidUpdateState(&self, peripheral: &CBPeripheralManager) {
            let powered = unsafe { peripheral.state() } == CBManagerState::PoweredOn;
            debug!(powered, "peripheral adapter state changed");
            let inner = self.ivars();
            let _ = inner.powered_tx.send(powered);
            inner.emit(PeripheralEvent::AdapterStateChanged { powered });
        }

        #[unsafe(method(peripheralManagerDidStartAdvertising:error:))]
        unsafe fn peripheralManagerDidStartAdvertising_error(
            &self,
            _peripheral: &CBPeripheralManager,
            error: Option<&NSError>,
        ) {
            let inner = self.ivars();
            if let Some(tx) = inner.adv_tx.lock().unwrap().take() {
                let result = error.map_or_else(
                    || {
                        debug!("advertising started");
                        Ok(())
                    },
                    |e| {
                        warn!(error = %e.localizedDescription(), "advertising failed to start");
                        Err(BlewError::Internal(e.localizedDescription().to_string()))
                    },
                );
                let _ = tx.send(result);
            }
        }

        #[unsafe(method(peripheralManager:didAddService:error:))]
        unsafe fn peripheralManager_didAddService_error(
            &self,
            _peripheral: &CBPeripheralManager,
            service: &CBService,
            error: Option<&NSError>,
        ) {
            let inner = self.ivars();
            let svc_uuid_ret = service.UUID();
            let Some(svc_uuid) = cbuuid_to_uuid(&svc_uuid_ret) else {
                return;
            };
            if let Some(tx) = inner.add_svc_tx.lock().unwrap().remove(&svc_uuid) {
                let result = error.map_or_else(
                    || {
                        debug!(service_uuid = %svc_uuid, "GATT service added");
                        Ok(())
                    },
                    |e| {
                        warn!(service_uuid = %svc_uuid, error = %e.localizedDescription(), "failed to add GATT service");
                        Err(BlewError::Internal(e.localizedDescription().to_string()))
                    },
                );
                let _ = tx.send(result);
            }
        }

        #[unsafe(method(peripheralManager:central:didSubscribeToCharacteristic:))]
        unsafe fn peripheralManager_central_didSubscribeToCharacteristic(
            &self,
            _peripheral: &CBPeripheralManager,
            central: &CBCentral,
            characteristic: &CBCharacteristic,
        ) {
            let inner = self.ivars();
            let char_uuid_ret = characteristic.UUID();
            let Some(char_uuid) = cbuuid_to_uuid(&char_uuid_ret) else {
                return;
            };
            let client_id = central_device_id(central);
            trace!(client_id = %client_id, %char_uuid, "client subscribed to characteristic");
            {
                let mut subs = inner.subscribers.lock().unwrap();
                let entry = subs.entry(char_uuid).or_default();
                entry.insert(client_id.clone(), unsafe { retain_send(central) });
            }
            inner.emit(PeripheralEvent::SubscriptionChanged {
                client_id,
                char_uuid,
                subscribed: true,
            });
        }

        #[unsafe(method(peripheralManager:central:didUnsubscribeFromCharacteristic:))]
        unsafe fn peripheralManager_central_didUnsubscribeFromCharacteristic(
            &self,
            _peripheral: &CBPeripheralManager,
            central: &CBCentral,
            characteristic: &CBCharacteristic,
        ) {
            let inner = self.ivars();
            let char_uuid_ret = characteristic.UUID();
            let Some(char_uuid) = cbuuid_to_uuid(&char_uuid_ret) else {
                return;
            };
            let client_id = central_device_id(central);
            trace!(client_id = %client_id, %char_uuid, "client unsubscribed from characteristic");
            {
                let mut subs = inner.subscribers.lock().unwrap();
                if let Some(entry) = subs.get_mut(&char_uuid) {
                    entry.remove(&client_id);
                    if entry.is_empty() {
                        subs.remove(&char_uuid);
                    }
                }
            }
            inner.emit(PeripheralEvent::SubscriptionChanged {
                client_id,
                char_uuid,
                subscribed: false,
            });
        }

        #[unsafe(method(peripheralManager:didReceiveReadRequest:))]
        unsafe fn peripheralManager_didReceiveReadRequest(
            &self,
            peripheral: &CBPeripheralManager,
            request: &CBATTRequest,
        ) {
            let inner = self.ivars();
            let req_char = request.characteristic();
            let req_char_uuid = req_char.UUID();
            let Some(char_uuid) = cbuuid_to_uuid(&req_char_uuid) else {
                peripheral.respondToRequest_withResult(request, CBATTError::AttributeNotFound);
                return;
            };

            let service_uuid = req_char
                .service()
                .and_then(|s| { let u = s.UUID(); cbuuid_to_uuid(&u) })
                .unwrap_or(Uuid::nil());

            let req_central = request.central();
            let client_id = central_device_id(&req_central);
            let offset = request.offset() as u16;

            trace!(client_id = %client_id, %char_uuid, offset, "ATT read request");

            let (tx, rx) = oneshot::channel::<Result<Vec<u8>, ()>>();
            let responder = ReadResponder::new(tx);

            inner.emit(PeripheralEvent::ReadRequest {
                client_id,
                service_uuid,
                char_uuid,
                offset,
                responder,
            });

            // Spawn a task to relay the ATT response back to CoreBluetooth.
            // Must use the captured runtime handle because this callback fires
            // on the GCD queue, outside the Tokio runtime context.
            let request_retained = unsafe { retain_send(request) };
            let manager_retained = unsafe { retain_send(peripheral) };
            inner.runtime.spawn(async move {
                match rx.await {
                    Ok(Ok(data)) => unsafe {
                        let nsdata = NSData::from_vec(data);
                        request_retained.setValue(Some(&nsdata));
                        manager_retained.respondToRequest_withResult(
                            &request_retained,
                            CBATTError::Success,
                        );
                    },
                    _ => unsafe {
                        manager_retained.respondToRequest_withResult(
                            &request_retained,
                            CBATTError::AttributeNotFound,
                        );
                    },
                }
            });
        }

        #[unsafe(method(peripheralManager:didReceiveWriteRequests:))]
        unsafe fn peripheralManager_didReceiveWriteRequests(
            &self,
            peripheral: &CBPeripheralManager,
            requests: &NSArray<CBATTRequest>,
        ) {
            let inner = self.ivars();

            if requests.count() == 0 {
                return;
            }
            let request = requests.objectAtIndex(0);

            let req_char = request.characteristic();
            let req_char_uuid = req_char.UUID();
            let Some(char_uuid) = cbuuid_to_uuid(&req_char_uuid) else {
                peripheral.respondToRequest_withResult(&request, CBATTError::AttributeNotFound);
                return;
            };

            let service_uuid = req_char
                .service()
                .and_then(|s| { let u = s.UUID(); cbuuid_to_uuid(&u) })
                .unwrap_or(Uuid::nil());

            let req_central = request.central();
            let client_id = central_device_id(&req_central);
            let value = request.value().map(|d| d.to_vec()).unwrap_or_default();

            trace!(client_id = %client_id, %char_uuid, len = value.len(), "ATT write request");

            let (tx, rx) = oneshot::channel::<bool>();
            let responder = WriteResponder::new(tx);

            inner.emit(PeripheralEvent::WriteRequest {
                client_id,
                service_uuid,
                char_uuid,
                value,
                responder: Some(responder),
            });

            let request_retained = unsafe { retain_send(&*request) };
            let manager_retained = unsafe { retain_send(peripheral) };
            inner.runtime.spawn(async move {
                let success = rx.await.unwrap_or(false);
                let result = if success {
                    CBATTError::Success
                } else {
                    CBATTError::WriteNotPermitted
                };
                unsafe {
                    manager_retained.respondToRequest_withResult(&request_retained, result);
                };
            });
        }

        /// Fires when `publishL2CAPChannelWithEncryption` completes.
        /// Delivers the OS-assigned PSM (or an error) to the waiting `l2cap_listener` call.
        #[unsafe(method(peripheralManager:didPublishL2CAPChannel:error:))]
        unsafe fn peripheralManager_didPublishL2CAPChannel_error(
            &self,
            _peripheral: &CBPeripheralManager,
            PSM: CBL2CAPPSM,
            error: Option<&NSError>,
        ) {
            let inner = self.ivars();
            if let Some(tx) = inner.l2cap_publish_tx.lock().unwrap().take() {
                let result = if let Some(e) = error {
                    warn!(error = %e.localizedDescription(), "L2CAP channel publish failed");
                    Err(BlewError::Internal(e.localizedDescription().to_string()))
                } else {
                    debug!(psm = PSM, "L2CAP channel published");
                    Ok(Psm(PSM))
                };
                let _ = tx.send(result);
            }
        }

        /// Fires when a central opens an L2CAP channel to us.
        #[unsafe(method(peripheralManager:didOpenL2CAPChannel:error:))]
        unsafe fn peripheralManager_didOpenL2CAPChannel_error(
            &self,
            manager: &CBPeripheralManager,
            channel: Option<&CBL2CAPChannel>,
            error: Option<&NSError>,
        ) {
            let inner = self.ivars();
            let tx = inner.l2cap_channel_tx.lock().unwrap().clone();
            let Some(tx) = tx else { return };

            if let Some(e) = error {
                warn!(error = %e.localizedDescription(), "incoming L2CAP channel failed");
                let _ = tx.blocking_send(Err(BlewError::Internal(
                    e.localizedDescription().to_string(),
                )));
                return;
            }
            let Some(ch) = channel else { return };
            debug!("incoming L2CAP channel accepted");

            // Request low-latency connection parameters for higher throughput.
            // On the peripheral side the channel peer is always CBCentral.
            let device_id = if let Some(peer) = ch.peer() {
                let central: Retained<CBCentral> = Retained::cast_unchecked(peer);
                manager.setDesiredConnectionLatency_forCentral(
                    CBPeripheralManagerConnectionLatency::Low,
                    &central,
                );
                central_device_id(&central)
            } else {
                DeviceId::from("unknown")
            };

            let l2cap = bridge_l2cap_channel(ch, &inner.runtime);
            let _ = tx.blocking_send(Ok((device_id, l2cap)));
        }
    }
);

impl PeripheralDelegate {
    fn new(inner: Arc<PeripheralInner>) -> Retained<Self> {
        let this = Self::alloc().set_ivars(inner);
        unsafe { objc2::msg_send![super(this), init] }
    }
}

struct PeripheralHandle {
    manager: ObjcSend<CBPeripheralManager>,
    /// Held here so the CB manager's weak-ref delegate stays alive.
    _delegate: ObjcSend<PeripheralDelegate>,
    inner: Arc<PeripheralInner>,
}

unsafe impl Send for PeripheralHandle {}
unsafe impl Sync for PeripheralHandle {}

pub struct ApplePeripheral(Arc<PeripheralHandle>);

impl backend::private::Sealed for ApplePeripheral {}

impl PeripheralBackend for ApplePeripheral {
    type EventStream = UnboundedReceiverStream<PeripheralEvent>;

    async fn new() -> BlewResult<Self>
    where
        Self: Sized,
    {
        let (inner, mut powered_rx) = PeripheralInner::new();
        let delegate = PeripheralDelegate::new(Arc::clone(&inner));

        let queue = DispatchQueue::new("blew.peripheral", DispatchQueueAttr::SERIAL);

        let manager = ObjcSend(unsafe {
            CBPeripheralManager::initWithDelegate_queue(
                CBPeripheralManager::alloc(),
                Some(ProtocolObject::from_ref(&*delegate)),
                Some(&queue),
            )
        });
        let delegate = ObjcSend(delegate);

        let timeout = tokio::time::sleep(std::time::Duration::from_secs(15));
        tokio::pin!(timeout);
        loop {
            tokio::select! {
                _ = powered_rx.changed() => {
                    let state = unsafe { manager.state() };
                    if state == CBManagerState::PoweredOn {
                        break;
                    }
                    if state == CBManagerState::Unsupported
                        || state == CBManagerState::Unauthorized
                    {
                        return Err(BlewError::AdapterNotFound);
                    }
                    // Unknown / Resetting / PoweredOff -> keep waiting
                }
                () = &mut timeout => {
                    if unsafe { manager.state() } == CBManagerState::PoweredOn {
                        break;
                    }
                    return Err(BlewError::NotPowered);
                }
            }
        }

        let handle = Arc::new(PeripheralHandle {
            manager,
            _delegate: delegate,
            inner,
        });
        Ok(ApplePeripheral(handle))
    }

    fn is_powered(&self) -> impl Future<Output = BlewResult<bool>> + Send {
        let handle = Arc::clone(&self.0);
        async move {
            let state = unsafe { handle.manager.state() };
            Ok(state == CBManagerState::PoweredOn)
        }
    }

    fn add_service(&self, service: &GattService) -> impl Future<Output = BlewResult<()>> + Send {
        let handle = Arc::clone(&self.0);
        let service = service.clone();
        async move {
            debug!(service_uuid = %service.uuid, characteristics = service.characteristics.len(), "adding GATT service");
            let rx = {
                let svc_uuid = uuid_to_cbuuid(service.uuid);
                let cb_service = unsafe {
                    CBMutableService::initWithType_primary(
                        CBMutableService::alloc(),
                        &svc_uuid,
                        service.primary,
                    )
                };

                let mut cb_chars: Vec<Retained<CBMutableCharacteristic>> = vec![];
                let mut char_map: HashMap<Uuid, ObjcSend<CBMutableCharacteristic>> = HashMap::new();

                for ch in &service.characteristics {
                    let c_uuid = uuid_to_cbuuid(ch.uuid);
                    let props = our_props_to_cb(ch.properties);
                    let perms = our_perms_to_cb(ch.permissions);

                    let value = if ch.value.is_empty() {
                        None
                    } else {
                        Some(NSData::from_vec(ch.value.clone()))
                    };

                    let cb_char = unsafe {
                        CBMutableCharacteristic::initWithType_properties_value_permissions(
                            CBMutableCharacteristic::alloc(),
                            &c_uuid,
                            props,
                            value.as_deref(),
                            perms,
                        )
                    };
                    let retained_char = unsafe { retain_send(&*cb_char) };
                    char_map.insert(ch.uuid, retained_char);
                    cb_chars.push(cb_char);
                }

                let retained_refs: Vec<&CBCharacteristic> = cb_chars
                    .iter()
                    .map(|c| c.as_ref() as &CBCharacteristic)
                    .collect();
                let char_array = NSArray::from_slice(&retained_refs);
                unsafe { cb_service.setCharacteristics(Some(&char_array)) };

                {
                    let mut lock = handle.inner.chars.lock().unwrap();
                    lock.extend(char_map);
                }
                let (tx, rx) = oneshot::channel();
                {
                    let mut lock = handle.inner.add_svc_tx.lock().unwrap();
                    lock.insert(service.uuid, tx);
                }

                unsafe { handle.manager.addService(&cb_service) };
                rx
                // All ObjC objects drop here, before .await
            };

            rx.await.unwrap_or(Err(BlewError::Internal(
                "add_service channel dropped".into(),
            )))
        }
    }

    fn start_advertising(
        &self,
        config: &AdvertisingConfig,
    ) -> impl Future<Output = BlewResult<()>> + Send {
        let handle = Arc::clone(&self.0);
        let config = config.clone();
        async move {
            if unsafe { handle.manager.isAdvertising() } {
                return Err(BlewError::AlreadyAdvertising);
            }
            debug!(local_name = %config.local_name, "starting advertising");

            let rx = {
                let local_name = NSString::from_str(&config.local_name);

                let service_uuids: Vec<Retained<CBUUID>> = config
                    .service_uuids
                    .iter()
                    .map(|u| uuid_to_cbuuid(*u))
                    .collect();
                let uuid_array = NSArray::from_retained_slice(&service_uuids);

                let key_name = unsafe { CBAdvertisementDataLocalNameKey };
                let key_uuids = unsafe { CBAdvertisementDataServiceUUIDsKey };

                let ln_any: &AnyObject = &local_name;
                let ua_any: &AnyObject = &uuid_array;

                let adv_data = NSDictionary::from_slices(&[key_name, key_uuids], &[ln_any, ua_any]);

                let (tx, rx) = oneshot::channel();
                *handle.inner.adv_tx.lock().unwrap() = Some(tx);
                unsafe { handle.manager.startAdvertising(Some(&adv_data)) };
                rx
            };

            rx.await.unwrap_or(Err(BlewError::Internal(
                "start_advertising channel dropped".into(),
            )))
        }
    }

    fn stop_advertising(&self) -> impl Future<Output = BlewResult<()>> + Send {
        let handle = Arc::clone(&self.0);
        async move {
            debug!("stopping advertising");
            unsafe { handle.manager.stopAdvertising() };
            Ok(())
        }
    }

    fn notify_characteristic(
        &self,
        device_id: &DeviceId,
        char_uuid: Uuid,
        value: Vec<u8>,
    ) -> impl Future<Output = BlewResult<()>> + Send {
        let handle = Arc::clone(&self.0);
        let device_id = device_id.clone();
        async move {
            trace!(device = %device_id, %char_uuid, len = value.len(), "notifying characteristic");
            let cb_char = {
                let lock = handle.inner.chars.lock().unwrap();
                lock.get(&char_uuid).map(|c| unsafe { retain_send(&**c) })
            };

            let Some(cb_char) = cb_char else {
                return Err(BlewError::LocalCharacteristicNotFound { char_uuid });
            };

            let cb_central = {
                let lock = handle.inner.subscribers.lock().unwrap();
                lock.get(&char_uuid)
                    .and_then(|m| m.get(&device_id))
                    .map(|c| unsafe { retain_send(&**c) })
            };

            let Some(cb_central) = cb_central else {
                // Subscriber disappeared between our caller's decision and
                // now — treat as no-op rather than an error.
                return Ok(());
            };

            let data = NSData::from_vec(value);
            let centrals = NSArray::from_slice(&[cb_central.0.as_ref()]);
            unsafe {
                handle
                    .manager
                    .updateValue_forCharacteristic_onSubscribedCentrals(
                        &data,
                        &cb_char.0,
                        Some(&centrals),
                    );
            }
            Ok(())
        }
    }

    fn l2cap_listener(
        &self,
    ) -> impl Future<
        Output = BlewResult<(
            Psm,
            impl Stream<Item = BlewResult<(DeviceId, L2capChannel)>> + Send + 'static,
        )>,
    > + Send {
        let handle = Arc::clone(&self.0);
        async move {
            debug!("publishing L2CAP CoC channel");
            let (ch_tx, ch_rx) = mpsc::channel::<BlewResult<(DeviceId, L2capChannel)>>(16);
            let (pub_tx, pub_rx) = oneshot::channel::<BlewResult<Psm>>();
            {
                *handle.inner.l2cap_channel_tx.lock().unwrap() = Some(ch_tx);
                *handle.inner.l2cap_publish_tx.lock().unwrap() = Some(pub_tx);
                unsafe { handle.manager.publishL2CAPChannelWithEncryption(false) };
            }
            let psm = pub_rx.await.unwrap_or(Err(BlewError::Internal(
                "l2cap_publish channel dropped".into(),
            )))?;
            debug!(psm = psm.0, "L2CAP listener ready");
            Ok((psm, ReceiverStream::new(ch_rx)))
        }
    }

    fn events(&self) -> Self::EventStream {
        let (tx, rx) = mpsc::unbounded_channel();
        *self.0.inner.event_tx.lock().unwrap() = Some(tx);
        UnboundedReceiverStream::new(rx)
    }
}