Skip to main content

webbluetooth_apple/
delegate.rs

1//! The delegate class, built at runtime.
2//!
3//! CoreBluetooth is entirely delegate-driven: `scanForPeripherals` returns
4//! nothing, `discoverServices` returns nothing, `readValueForCharacteristic`
5//! returns nothing. Every answer arrives as a message to an object conforming
6//! to `CBCentralManagerDelegate` / `CBPeripheralDelegate`.
7//!
8//! Rather than ship an Objective-C or Swift file to be that object, the class
9//! is synthesised on first use with [`crate::objc::ClassBuilder`]: allocate a
10//! pair under `NSObject`, install one `extern "C"` Rust function per delegate
11//! selector, declare both protocols, register. CoreBluetooth cannot tell the
12//! difference — it looks the selectors up through the same runtime that made
13//! them.
14//!
15//! Each delegate *instance* is paired with an [`EventSink`] in a process-wide
16//! registry keyed by the object's address, which is how one shared set of
17//! method implementations serves any number of `CBCentralManager`s.
18
19use crate::cb::{self, Advertisement, ManagerState};
20use crate::objc::Id;
21use crate::objc::{error_message, ClassBuilder, Retained};
22use core::ffi::c_void;
23use std::collections::HashMap;
24use std::sync::{Arc, Mutex, OnceLock};
25
26/// Anything CoreBluetooth tells us, normalised.
27///
28/// `error` is `Some` exactly when the underlying delegate method was handed a
29/// non-nil `NSError`, carrying its `code` and `localizedDescription`.
30#[derive(Debug)]
31pub enum Event {
32    /// The central's Bluetooth state changed. Always delivered once shortly
33    /// after the manager is created — nothing else may be called before it.
34    StateChanged(ManagerState),
35    /// An advertising packet was received.
36    Discovered {
37        peripheral: Retained,
38        advertisement: Box<Advertisement>,
39        rssi: i32,
40    },
41    Connected {
42        peripheral: Retained,
43    },
44    ConnectFailed {
45        peripheral: Retained,
46        error: Option<(i64, String)>,
47    },
48    Disconnected {
49        peripheral: Retained,
50        error: Option<(i64, String)>,
51    },
52    ServicesDiscovered {
53        peripheral: Retained,
54        error: Option<(i64, String)>,
55    },
56    /// `discoverIncludedServices:forService:` finished for one service.
57    IncludedServicesDiscovered {
58        peripheral: Retained,
59        service: Retained,
60        error: Option<(i64, String)>,
61    },
62    /// The peripheral's service set changed; every handle into it is now stale.
63    ServicesModified {
64        peripheral: Retained,
65        invalidated: Vec<Retained>,
66    },
67    CharacteristicsDiscovered {
68        peripheral: Retained,
69        service: Retained,
70        error: Option<(i64, String)>,
71    },
72    DescriptorsDiscovered {
73        peripheral: Retained,
74        characteristic: Retained,
75        error: Option<(i64, String)>,
76    },
77    /// A read completed *or* a notification arrived — CoreBluetooth uses one
78    /// callback for both and does not distinguish them, so the layer above
79    /// correlates against its own outstanding reads.
80    CharacteristicValue {
81        peripheral: Retained,
82        characteristic: Retained,
83        value: Option<Vec<u8>>,
84        error: Option<(i64, String)>,
85    },
86    CharacteristicWritten {
87        peripheral: Retained,
88        characteristic: Retained,
89        error: Option<(i64, String)>,
90    },
91    NotifyStateChanged {
92        peripheral: Retained,
93        characteristic: Retained,
94        notifying: bool,
95        error: Option<(i64, String)>,
96    },
97    DescriptorValue {
98        peripheral: Retained,
99        descriptor: Retained,
100        value: Option<Vec<u8>>,
101        error: Option<(i64, String)>,
102    },
103    DescriptorWritten {
104        peripheral: Retained,
105        descriptor: Retained,
106        error: Option<(i64, String)>,
107    },
108    RssiRead {
109        peripheral: Retained,
110        rssi: i32,
111        error: Option<(i64, String)>,
112    },
113    NameChanged {
114        peripheral: Retained,
115        name: Option<String>,
116    },
117    /// The write-without-response queue drained and can take more.
118    ReadyToWrite {
119        peripheral: Retained,
120    },
121    /// An `openL2CAPChannel:` completed. `channel` is `None` on failure.
122    L2capChannelOpened {
123        peripheral: Retained,
124        channel: Option<Retained>,
125        error: Option<(i64, String)>,
126    },
127    /// The system relaunched this process and is handing back what it preserved.
128    ///
129    /// Delivered **before** the first `StateChanged`, and only when the manager
130    /// was created with a restore identifier.
131    WillRestoreState(Box<crate::cb::RestoredCentralState>),
132}
133
134/// Where a delegate instance sends what it hears.
135///
136/// Called on the central's dispatch queue, one event at a time per delegate,
137/// so an implementation must not block: hand the event off and return.
138pub trait EventSink: Send + Sync {
139    fn emit(&self, event: Event);
140}
141
142// ── Instance registry ───────────────────────────────────────────────────────
143
144static SINKS: OnceLock<Mutex<HashMap<usize, Arc<dyn EventSink>>>> = OnceLock::new();
145
146fn sinks() -> &'static Mutex<HashMap<usize, Arc<dyn EventSink>>> {
147    SINKS.get_or_init(|| Mutex::new(HashMap::new()))
148}
149
150fn emit(delegate: Id, event: Event) {
151    let sink = sinks()
152        .lock()
153        .ok()
154        .and_then(|m| m.get(&(delegate as usize)).cloned());
155    if let Some(sink) = sink {
156        sink.emit(event);
157    }
158}
159
160/// A live delegate object. Deregisters its sink and releases the object on drop.
161#[derive(Debug)]
162pub struct Delegate {
163    object: Retained,
164}
165
166impl Delegate {
167    /// Build a delegate bound to `sink`, synthesising the class if needed.
168    pub fn new(sink: Arc<dyn EventSink>) -> Self {
169        let class = delegate_class();
170        // SAFETY: `class` is a registered class whose `init` is NSObject's.
171        let object = unsafe {
172            let obj: Id = msg_send![class, alloc];
173            let obj: Id = msg_send![obj, init];
174            Retained::adopt(obj).expect("delegate allocation failed")
175        };
176        sinks()
177            .lock()
178            .expect("sink registry poisoned")
179            .insert(object.key(), sink);
180        Self { object }
181    }
182
183    #[inline]
184    pub fn as_ptr(&self) -> Id {
185        self.object.as_ptr()
186    }
187}
188
189impl Drop for Delegate {
190    fn drop(&mut self) {
191        if let Ok(mut m) = sinks().lock() {
192            m.remove(&self.object.key());
193        }
194    }
195}
196
197// ── The class itself ────────────────────────────────────────────────────────
198
199static CLASS: OnceLock<usize> = OnceLock::new();
200
201fn delegate_class() -> Id {
202    *CLASS.get_or_init(|| build_class() as usize) as Id
203}
204
205fn build_class() -> Id {
206    // A second copy of this crate in the same process would collide on the
207    // name, so try suffixes until the runtime accepts one.
208    for attempt in 0..64u32 {
209        let name = if attempt == 0 {
210            c"WBRustCBDelegate".to_owned()
211        } else {
212            std::ffi::CString::new(format!("WBRustCBDelegate{attempt}")).expect("class name")
213        };
214        // SAFETY: NSObject is always registered; every IMP below matches the
215        // `v@:` encoding it is installed with.
216        let built = unsafe { ClassBuilder::new(c"NSObject", &name) };
217        let Some(b) = built else { continue };
218        return unsafe {
219            b.method(
220                c"centralManagerDidUpdateState:",
221                did_update_state as *const c_void,
222                c"v@:@",
223            )
224            .method(
225                c"centralManager:didDiscoverPeripheral:advertisementData:RSSI:",
226                did_discover as *const c_void,
227                c"v@:@@@@",
228            )
229            .method(
230                c"centralManager:didConnectPeripheral:",
231                did_connect as *const c_void,
232                c"v@:@@",
233            )
234            .method(
235                c"centralManager:willRestoreState:",
236                will_restore_state as *const c_void,
237                c"v@:@@",
238            )
239            .method(
240                c"peripheral:didOpenL2CAPChannel:error:",
241                did_open_l2cap as *const c_void,
242                c"v@:@@@",
243            )
244            .method(
245                c"centralManager:didFailToConnectPeripheral:error:",
246                did_fail_connect as *const c_void,
247                c"v@:@@@",
248            )
249            .method(
250                c"centralManager:didDisconnectPeripheral:error:",
251                did_disconnect as *const c_void,
252                c"v@:@@@",
253            )
254            .method(
255                c"peripheral:didDiscoverServices:",
256                did_discover_services as *const c_void,
257                c"v@:@@",
258            )
259            .method(
260                c"peripheral:didModifyServices:",
261                did_modify_services as *const c_void,
262                c"v@:@@",
263            )
264            .method(
265                c"peripheral:didDiscoverIncludedServicesForService:error:",
266                did_discover_included_services as *const c_void,
267                c"v@:@@@",
268            )
269            .method(
270                c"peripheral:didDiscoverCharacteristicsForService:error:",
271                did_discover_characteristics as *const c_void,
272                c"v@:@@@",
273            )
274            .method(
275                c"peripheral:didDiscoverDescriptorsForCharacteristic:error:",
276                did_discover_descriptors as *const c_void,
277                c"v@:@@@",
278            )
279            .method(
280                c"peripheral:didUpdateValueForCharacteristic:error:",
281                did_update_characteristic as *const c_void,
282                c"v@:@@@",
283            )
284            .method(
285                c"peripheral:didWriteValueForCharacteristic:error:",
286                did_write_characteristic as *const c_void,
287                c"v@:@@@",
288            )
289            .method(
290                c"peripheral:didUpdateNotificationStateForCharacteristic:error:",
291                did_update_notification_state as *const c_void,
292                c"v@:@@@",
293            )
294            .method(
295                c"peripheral:didUpdateValueForDescriptor:error:",
296                did_update_descriptor as *const c_void,
297                c"v@:@@@",
298            )
299            .method(
300                c"peripheral:didWriteValueForDescriptor:error:",
301                did_write_descriptor as *const c_void,
302                c"v@:@@@",
303            )
304            .method(
305                c"peripheral:didReadRSSI:error:",
306                did_read_rssi as *const c_void,
307                c"v@:@@@",
308            )
309            .method(
310                c"peripheralDidUpdateName:",
311                did_update_name as *const c_void,
312                c"v@:@",
313            )
314            .method(
315                c"peripheralIsReadyToSendWriteWithoutResponse:",
316                is_ready_to_write as *const c_void,
317                c"v@:@",
318            )
319            .conforms(c"CBCentralManagerDelegate")
320            .conforms(c"CBPeripheralDelegate")
321            .register()
322        };
323    }
324    panic!("could not register a delegate class after 64 attempts");
325}
326
327// ── CBCentralManagerDelegate ────────────────────────────────────────────────
328
329unsafe extern "C" fn did_update_state(this: Id, _cmd: *const c_void, central: Id) {
330    let state = unsafe { cb::central_state(central) };
331    emit(this, Event::StateChanged(state));
332}
333
334unsafe extern "C" fn did_discover(
335    this: Id,
336    _cmd: *const c_void,
337    _central: Id,
338    peripheral: Id,
339    advertisement_data: Id,
340    rssi: Id,
341) {
342    unsafe {
343        let Some(peripheral) = Retained::retain(peripheral) else {
344            return;
345        };
346        let advertisement = Box::new(cb::parse_advertisement(advertisement_data));
347        let rssi = crate::objc::number_i64(rssi).unwrap_or(127) as i32;
348        emit(
349            this,
350            Event::Discovered {
351                peripheral,
352                advertisement,
353                rssi,
354            },
355        );
356    }
357}
358
359unsafe extern "C" fn did_connect(this: Id, _cmd: *const c_void, _central: Id, peripheral: Id) {
360    let Some(peripheral) = (unsafe { Retained::retain(peripheral) }) else {
361        return;
362    };
363    emit(this, Event::Connected { peripheral });
364}
365
366unsafe extern "C" fn did_fail_connect(
367    this: Id,
368    _cmd: *const c_void,
369    _central: Id,
370    peripheral: Id,
371    error: Id,
372) {
373    unsafe {
374        let Some(peripheral) = Retained::retain(peripheral) else {
375            return;
376        };
377        emit(
378            this,
379            Event::ConnectFailed {
380                peripheral,
381                error: error_message(error),
382            },
383        );
384    }
385}
386
387unsafe extern "C" fn did_disconnect(
388    this: Id,
389    _cmd: *const c_void,
390    _central: Id,
391    peripheral: Id,
392    error: Id,
393) {
394    unsafe {
395        let Some(peripheral) = Retained::retain(peripheral) else {
396            return;
397        };
398        emit(
399            this,
400            Event::Disconnected {
401                peripheral,
402                error: error_message(error),
403            },
404        );
405    }
406}
407
408// ── CBPeripheralDelegate ────────────────────────────────────────────────────
409
410unsafe extern "C" fn did_discover_services(
411    this: Id,
412    _cmd: *const c_void,
413    peripheral: Id,
414    error: Id,
415) {
416    unsafe {
417        let Some(peripheral) = Retained::retain(peripheral) else {
418            return;
419        };
420        emit(
421            this,
422            Event::ServicesDiscovered {
423                peripheral,
424                error: error_message(error),
425            },
426        );
427    }
428}
429
430unsafe extern "C" fn did_modify_services(
431    this: Id,
432    _cmd: *const c_void,
433    peripheral: Id,
434    invalidated: Id,
435) {
436    unsafe {
437        let Some(peripheral) = Retained::retain(peripheral) else {
438            return;
439        };
440        let invalidated = crate::objc::array_map(invalidated, |s| Retained::retain(s))
441            .into_iter()
442            .flatten()
443            .collect();
444        emit(
445            this,
446            Event::ServicesModified {
447                peripheral,
448                invalidated,
449            },
450        );
451    }
452}
453
454unsafe extern "C" fn did_discover_included_services(
455    this: Id,
456    _cmd: *const c_void,
457    peripheral: Id,
458    service: Id,
459    error: Id,
460) {
461    unsafe {
462        let (Some(peripheral), Some(service)) =
463            (Retained::retain(peripheral), Retained::retain(service))
464        else {
465            return;
466        };
467        emit(
468            this,
469            Event::IncludedServicesDiscovered {
470                peripheral,
471                service,
472                error: error_message(error),
473            },
474        );
475    }
476}
477
478unsafe extern "C" fn did_discover_characteristics(
479    this: Id,
480    _cmd: *const c_void,
481    peripheral: Id,
482    service: Id,
483    error: Id,
484) {
485    unsafe {
486        let (Some(peripheral), Some(service)) =
487            (Retained::retain(peripheral), Retained::retain(service))
488        else {
489            return;
490        };
491        emit(
492            this,
493            Event::CharacteristicsDiscovered {
494                peripheral,
495                service,
496                error: error_message(error),
497            },
498        );
499    }
500}
501
502unsafe extern "C" fn did_discover_descriptors(
503    this: Id,
504    _cmd: *const c_void,
505    peripheral: Id,
506    characteristic: Id,
507    error: Id,
508) {
509    unsafe {
510        let (Some(peripheral), Some(characteristic)) = (
511            Retained::retain(peripheral),
512            Retained::retain(characteristic),
513        ) else {
514            return;
515        };
516        emit(
517            this,
518            Event::DescriptorsDiscovered {
519                peripheral,
520                characteristic,
521                error: error_message(error),
522            },
523        );
524    }
525}
526
527unsafe extern "C" fn did_update_characteristic(
528    this: Id,
529    _cmd: *const c_void,
530    peripheral: Id,
531    characteristic: Id,
532    error: Id,
533) {
534    unsafe {
535        let (Some(peripheral), Some(characteristic)) = (
536            Retained::retain(peripheral),
537            Retained::retain(characteristic),
538        ) else {
539            return;
540        };
541        let value = cb::characteristic_value(characteristic.as_ptr());
542        emit(
543            this,
544            Event::CharacteristicValue {
545                peripheral,
546                characteristic,
547                value,
548                error: error_message(error),
549            },
550        );
551    }
552}
553
554unsafe extern "C" fn did_write_characteristic(
555    this: Id,
556    _cmd: *const c_void,
557    peripheral: Id,
558    characteristic: Id,
559    error: Id,
560) {
561    unsafe {
562        let (Some(peripheral), Some(characteristic)) = (
563            Retained::retain(peripheral),
564            Retained::retain(characteristic),
565        ) else {
566            return;
567        };
568        emit(
569            this,
570            Event::CharacteristicWritten {
571                peripheral,
572                characteristic,
573                error: error_message(error),
574            },
575        );
576    }
577}
578
579unsafe extern "C" fn did_update_notification_state(
580    this: Id,
581    _cmd: *const c_void,
582    peripheral: Id,
583    characteristic: Id,
584    error: Id,
585) {
586    unsafe {
587        let (Some(peripheral), Some(characteristic)) = (
588            Retained::retain(peripheral),
589            Retained::retain(characteristic),
590        ) else {
591            return;
592        };
593        let notifying = cb::characteristic_is_notifying(characteristic.as_ptr());
594        emit(
595            this,
596            Event::NotifyStateChanged {
597                peripheral,
598                characteristic,
599                notifying,
600                error: error_message(error),
601            },
602        );
603    }
604}
605
606unsafe extern "C" fn did_update_descriptor(
607    this: Id,
608    _cmd: *const c_void,
609    peripheral: Id,
610    descriptor: Id,
611    error: Id,
612) {
613    unsafe {
614        let (Some(peripheral), Some(descriptor)) =
615            (Retained::retain(peripheral), Retained::retain(descriptor))
616        else {
617            return;
618        };
619        let value = cb::descriptor_value(descriptor.as_ptr());
620        emit(
621            this,
622            Event::DescriptorValue {
623                peripheral,
624                descriptor,
625                value,
626                error: error_message(error),
627            },
628        );
629    }
630}
631
632unsafe extern "C" fn did_write_descriptor(
633    this: Id,
634    _cmd: *const c_void,
635    peripheral: Id,
636    descriptor: Id,
637    error: Id,
638) {
639    unsafe {
640        let (Some(peripheral), Some(descriptor)) =
641            (Retained::retain(peripheral), Retained::retain(descriptor))
642        else {
643            return;
644        };
645        emit(
646            this,
647            Event::DescriptorWritten {
648                peripheral,
649                descriptor,
650                error: error_message(error),
651            },
652        );
653    }
654}
655
656unsafe extern "C" fn did_read_rssi(
657    this: Id,
658    _cmd: *const c_void,
659    peripheral: Id,
660    rssi: Id,
661    error: Id,
662) {
663    unsafe {
664        let Some(peripheral) = Retained::retain(peripheral) else {
665            return;
666        };
667        let rssi = crate::objc::number_i64(rssi).unwrap_or(127) as i32;
668        emit(
669            this,
670            Event::RssiRead {
671                peripheral,
672                rssi,
673                error: error_message(error),
674            },
675        );
676    }
677}
678
679unsafe extern "C" fn did_update_name(this: Id, _cmd: *const c_void, peripheral: Id) {
680    unsafe {
681        let name = cb::peripheral_name(peripheral);
682        let Some(peripheral) = Retained::retain(peripheral) else {
683            return;
684        };
685        emit(this, Event::NameChanged { peripheral, name });
686    }
687}
688
689unsafe extern "C" fn will_restore_state(this: Id, _cmd: *const c_void, _central: Id, dict: Id) {
690    let restored = unsafe { cb::parse_restored_central_state(dict) };
691    emit(this, Event::WillRestoreState(Box::new(restored)));
692}
693
694unsafe extern "C" fn did_open_l2cap(
695    this: Id,
696    _cmd: *const c_void,
697    peripheral: Id,
698    channel: Id,
699    error: Id,
700) {
701    unsafe {
702        let Some(peripheral) = Retained::retain(peripheral) else {
703            return;
704        };
705        emit(
706            this,
707            Event::L2capChannelOpened {
708                peripheral,
709                channel: Retained::retain(channel),
710                error: error_message(error),
711            },
712        );
713    }
714}
715
716unsafe extern "C" fn is_ready_to_write(this: Id, _cmd: *const c_void, peripheral: Id) {
717    let Some(peripheral) = (unsafe { Retained::retain(peripheral) }) else {
718        return;
719    };
720    emit(this, Event::ReadyToWrite { peripheral });
721}