Skip to main content

webbluetooth_apple/
cb.rs

1//! Typed accessors for the CoreBluetooth classes.
2//!
3//! Thin, borrow-based wrappers: every function takes a borrowed `Id` and does
4//! one message send. Ownership lives a layer up, in [`crate::objc::Retained`].
5
6use crate::objc::{
7    self, array_map, data_bytes, dict_get, global_nsstring, nsarray, nsdata, nsstring, number_bool,
8    number_i64, require_class, to_string, Retained,
9};
10use crate::objc::{Id, NIL};
11
12// ── Enums ───────────────────────────────────────────────────────────────────
13
14/// `CBManagerState`.
15#[derive(Debug, Clone, Copy, PartialEq, Eq)]
16pub enum ManagerState {
17    Unknown = 0,
18    Resetting = 1,
19    Unsupported = 2,
20    Unauthorized = 3,
21    PoweredOff = 4,
22    PoweredOn = 5,
23}
24
25impl From<isize> for ManagerState {
26    fn from(v: isize) -> Self {
27        match v {
28            1 => Self::Resetting,
29            2 => Self::Unsupported,
30            3 => Self::Unauthorized,
31            4 => Self::PoweredOff,
32            5 => Self::PoweredOn,
33            _ => Self::Unknown,
34        }
35    }
36}
37
38/// `CBManagerAuthorization` — the process-wide Bluetooth TCC verdict.
39#[derive(Debug, Clone, Copy, PartialEq, Eq)]
40pub enum Authorization {
41    NotDetermined = 0,
42    Restricted = 1,
43    Denied = 2,
44    Allowed = 3,
45}
46
47impl From<isize> for Authorization {
48    fn from(v: isize) -> Self {
49        match v {
50            1 => Self::Restricted,
51            2 => Self::Denied,
52            3 => Self::Allowed,
53            _ => Self::NotDetermined,
54        }
55    }
56}
57
58/// `CBPeripheralState`.
59#[derive(Debug, Clone, Copy, PartialEq, Eq)]
60pub enum PeripheralState {
61    Disconnected = 0,
62    Connecting = 1,
63    Connected = 2,
64    Disconnecting = 3,
65}
66
67impl From<isize> for PeripheralState {
68    fn from(v: isize) -> Self {
69        match v {
70            1 => Self::Connecting,
71            2 => Self::Connected,
72            3 => Self::Disconnecting,
73            _ => Self::Disconnected,
74        }
75    }
76}
77
78/// `CBCharacteristicProperties`, a bitmask.
79#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
80pub struct Properties(pub u32);
81
82impl Properties {
83    pub const BROADCAST: u32 = 0x01;
84    pub const READ: u32 = 0x02;
85    pub const WRITE_WITHOUT_RESPONSE: u32 = 0x04;
86    pub const WRITE: u32 = 0x08;
87    pub const NOTIFY: u32 = 0x10;
88    pub const INDICATE: u32 = 0x20;
89    pub const AUTHENTICATED_SIGNED_WRITES: u32 = 0x40;
90    pub const EXTENDED_PROPERTIES: u32 = 0x80;
91    pub const NOTIFY_ENCRYPTION_REQUIRED: u32 = 0x100;
92    pub const INDICATE_ENCRYPTION_REQUIRED: u32 = 0x200;
93
94    #[inline]
95    pub fn has(self, bit: u32) -> bool {
96        self.0 & bit != 0
97    }
98    #[inline]
99    pub fn broadcast(self) -> bool {
100        self.has(Self::BROADCAST)
101    }
102    #[inline]
103    pub fn read(self) -> bool {
104        self.has(Self::READ)
105    }
106    #[inline]
107    pub fn write_without_response(self) -> bool {
108        self.has(Self::WRITE_WITHOUT_RESPONSE)
109    }
110    #[inline]
111    pub fn write(self) -> bool {
112        self.has(Self::WRITE)
113    }
114    #[inline]
115    pub fn notify(self) -> bool {
116        self.has(Self::NOTIFY)
117    }
118    #[inline]
119    pub fn indicate(self) -> bool {
120        self.has(Self::INDICATE)
121    }
122    #[inline]
123    pub fn authenticated_signed_writes(self) -> bool {
124        self.has(Self::AUTHENTICATED_SIGNED_WRITES)
125    }
126    #[inline]
127    pub fn reliable_write(self) -> bool {
128        self.has(Self::EXTENDED_PROPERTIES)
129    }
130}
131
132/// `CBCharacteristicWriteType`.
133#[derive(Debug, Clone, Copy, PartialEq, Eq)]
134pub enum WriteType {
135    WithResponse = 0,
136    WithoutResponse = 1,
137}
138
139// ── CBManager ───────────────────────────────────────────────────────────────
140
141/// `[CBManager authorization]` — the process-wide Bluetooth TCC verdict.
142pub fn authorization() -> Authorization {
143    unsafe { Authorization::from(msg_send_t![isize; require_class(c"CBManager"), authorization]) }
144}
145
146// ── CBUUID ──────────────────────────────────────────────────────────────────
147
148/// `[CBUUID UUIDWithString:]`.
149///
150/// Accepts the 16-bit (`"180F"`), 32-bit, and 128-bit dashed forms.
151///
152/// # Safety
153/// **`UUIDWithString:` raises an Objective-C exception on a malformed string**,
154/// and an Objective-C exception unwinding through a Rust frame aborts the
155/// process. The caller must have validated the string first — which is what
156/// `webbluetooth::BluetoothUuid` exists to do.
157pub unsafe fn uuid_from_string(s: &str) -> Option<Retained> {
158    unsafe {
159        let ns = Retained::adopt(nsstring(s))?;
160        let u: Id = msg_send![require_class(c"CBUUID"), UUIDWithString: ns.as_ptr()];
161        Retained::retain(u)
162    }
163}
164
165/// `[cbuuid UUIDString]` — short form for 16/32-bit UUIDs, dashed for 128-bit.
166///
167/// # Safety
168/// `uuid` must be a `CBUUID`.
169pub unsafe fn uuid_string(uuid: Id) -> Option<String> {
170    unsafe { to_string(msg_send![uuid, UUIDString]) }
171}
172
173// ── CBCentralManager ────────────────────────────────────────────────────────
174
175/// `[[CBCentralManager alloc] initWithDelegate:queue:options:]`.
176///
177/// `options` may be nil. Returned at `+1`.
178///
179/// # Safety
180/// `delegate` and `queue` must outlive the manager.
181pub unsafe fn central_new(delegate: Id, queue: Id, options: Id) -> Option<Retained> {
182    unsafe {
183        let m: Id = msg_send![require_class(c"CBCentralManager"), alloc];
184        let m: Id = msg_send![m, initWithDelegate: delegate, queue: queue, options: options];
185        Retained::adopt(m)
186    }
187}
188
189/// `CBCentralManagerOptionShowPowerAlertKey: @(show)` as an `NSDictionary`, `+1`.
190///
191/// # Safety
192/// Caller owns the result.
193pub unsafe fn central_options(
194    show_power_alert: bool,
195    restore_identifier: Option<&str>,
196) -> Option<Retained> {
197    unsafe {
198        let mut keys: Vec<Id> = Vec::new();
199        let mut values: Vec<Id> = Vec::new();
200        let mut owned: Vec<Retained> = Vec::new();
201
202        if show_power_alert {
203            let key = global_nsstring(c"CBCentralManagerOptionShowPowerAlertKey");
204            if !key.is_null() {
205                keys.push(key);
206                values.push(msg_send![require_class(c"NSNumber"), numberWithBool: true]);
207            }
208        }
209        if let Some(id) = restore_identifier {
210            let key = global_nsstring(c"CBCentralManagerOptionRestoreIdentifierKey");
211            if let (false, Some(value)) = (key.is_null(), Retained::adopt(nsstring(id))) {
212                keys.push(key);
213                values.push(value.as_ptr());
214                owned.push(value);
215            }
216        }
217        if keys.is_empty() {
218            return None;
219        }
220        objc::nsdictionary(&keys, &values)
221    }
222}
223
224/// `openL2CAPChannel:` — ask the peer to open an L2CAP channel on `psm`.
225///
226/// The answer arrives as `peripheral:didOpenL2CAPChannel:error:`.
227///
228/// # Safety
229/// `peripheral` must be a connected `CBPeripheral`.
230pub unsafe fn peripheral_open_l2cap(peripheral: Id, psm: u16) {
231    unsafe { msg_send_void![peripheral, openL2CAPChannel: psm] }
232}
233
234/// What the system preserved for a `CBCentralManager` across a relaunch.
235#[derive(Debug, Default)]
236pub struct RestoredCentralState {
237    /// Peripherals that were connected or connecting.
238    pub peripherals: Vec<Retained>,
239    /// The services the interrupted scan was filtering on, as CBUUID strings.
240    pub scan_services: Vec<String>,
241    /// Whether that scan had `CBCentralManagerScanOptionAllowDuplicatesKey`.
242    pub scan_allow_duplicates: bool,
243}
244
245/// Parse the dictionary handed to `centralManager:willRestoreState:`.
246///
247/// # Safety
248/// `dict` must be null or the `NSDictionary` CoreBluetooth supplied.
249pub unsafe fn parse_restored_central_state(dict: Id) -> RestoredCentralState {
250    unsafe {
251        let peripherals = {
252            let arr = dict_get(
253                dict,
254                global_nsstring(c"CBCentralManagerRestoredStatePeripheralsKey"),
255            );
256            array_map(arr, |p| Retained::retain(p))
257                .into_iter()
258                .flatten()
259                .collect()
260        };
261        let scan_services = {
262            let arr = dict_get(
263                dict,
264                global_nsstring(c"CBCentralManagerRestoredStateScanServicesKey"),
265            );
266            array_map(arr, |u| uuid_string(u))
267                .into_iter()
268                .flatten()
269                .collect()
270        };
271        let scan_allow_duplicates = {
272            let opts = dict_get(
273                dict,
274                global_nsstring(c"CBCentralManagerRestoredStateScanOptionsKey"),
275            );
276            let key = global_nsstring(c"CBCentralManagerScanOptionAllowDuplicatesKey");
277            number_bool(dict_get(opts, key)).unwrap_or(false)
278        };
279        RestoredCentralState {
280            peripherals,
281            scan_services,
282            scan_allow_duplicates,
283        }
284    }
285}
286
287/// `[central state]`.
288///
289/// # Safety
290/// `central` must be a `CBCentralManager`.
291pub unsafe fn central_state(central: Id) -> ManagerState {
292    unsafe { ManagerState::from(msg_send_t![isize; central, state]) }
293}
294
295/// `[central isScanning]`.
296///
297/// # Safety
298/// `central` must be a `CBCentralManager`.
299pub unsafe fn central_is_scanning(central: Id) -> bool {
300    unsafe { msg_send_t![bool; central, isScanning] }
301}
302
303/// `scanForPeripheralsWithServices:options:`. An empty slice scans for all.
304///
305/// `allow_duplicates` maps to `CBCentralManagerScanOptionAllowDuplicatesKey`,
306/// which the Web Bluetooth scanning path wants so that RSSI keeps updating
307/// while a chooser is deciding.
308///
309/// # Safety
310/// `central` must be a `CBCentralManager` and every element of `services` a
311/// `CBUUID`.
312pub unsafe fn central_scan(central: Id, services: &[Id], allow_duplicates: bool) {
313    unsafe {
314        let arr = if services.is_empty() {
315            None
316        } else {
317            Retained::adopt(nsarray(services))
318        };
319        let opts = if allow_duplicates {
320            let key = global_nsstring(c"CBCentralManagerScanOptionAllowDuplicatesKey");
321            if key.is_null() {
322                None
323            } else {
324                let val: Id = msg_send![require_class(c"NSNumber"), numberWithBool: true];
325                let keys = Retained::adopt(nsarray(&[key]));
326                let vals = Retained::adopt(nsarray(&[val]));
327                match (keys, vals) {
328                    (Some(k), Some(v)) => {
329                        let d: Id = msg_send![
330                            require_class(c"NSDictionary"),
331                            dictionaryWithObjects: v.as_ptr(),
332                            forKeys: k.as_ptr()
333                        ];
334                        Retained::retain(d)
335                    }
336                    _ => None,
337                }
338            }
339        } else {
340            None
341        };
342        msg_send_void![
343            central,
344            scanForPeripheralsWithServices: arr.as_ref().map_or(NIL, |a| a.as_ptr()),
345            options: opts.as_ref().map_or(NIL, |o| o.as_ptr())
346        ];
347    }
348}
349
350/// `[central stopScan]`.
351///
352/// # Safety
353/// `central` must be a `CBCentralManager`.
354pub unsafe fn central_stop_scan(central: Id) {
355    unsafe { msg_send_void![central, stopScan] }
356}
357
358/// `connectPeripheral:options:`.
359///
360/// # Safety
361/// `central` must be a `CBCentralManager` and `peripheral` a `CBPeripheral`.
362pub unsafe fn central_connect(central: Id, peripheral: Id) {
363    unsafe { msg_send_void![central, connectPeripheral: peripheral, options: NIL] }
364}
365
366/// `cancelPeripheralConnection:`.
367///
368/// # Safety
369/// `central` must be a `CBCentralManager` and `peripheral` a `CBPeripheral`.
370pub unsafe fn central_disconnect(central: Id, peripheral: Id) {
371    unsafe { msg_send_void![central, cancelPeripheralConnection: peripheral] }
372}
373
374/// `retrieveConnectedPeripheralsWithServices:` — peripherals *another* process
375/// on this machine already has connected.
376///
377/// # Safety
378/// `central` must be a `CBCentralManager`, `services` all `CBUUID`.
379pub unsafe fn central_retrieve_connected(central: Id, services: &[Id]) -> Vec<Retained> {
380    unsafe {
381        let Some(arr) = Retained::adopt(nsarray(services)) else {
382            return Vec::new();
383        };
384        let res: Id = msg_send![central, retrieveConnectedPeripheralsWithServices: arr.as_ptr()];
385        array_map(res, |p| Retained::retain(p))
386            .into_iter()
387            .flatten()
388            .collect()
389    }
390}
391
392/// `retrievePeripheralsWithIdentifiers:` — re-find a peripheral across process
393/// restarts from its `NSUUID` identifier string.
394///
395/// # Safety
396/// `central` must be a `CBCentralManager`.
397pub unsafe fn central_retrieve_by_identifier(central: Id, identifiers: &[&str]) -> Vec<Retained> {
398    unsafe {
399        let mut nsuuids = Vec::with_capacity(identifiers.len());
400        for id in identifiers {
401            let Some(s) = Retained::adopt(nsstring(id)) else {
402                continue;
403            };
404            let u: Id = msg_send![require_class(c"NSUUID"), alloc];
405            let u: Id = msg_send![u, initWithUUIDString: s.as_ptr()];
406            if let Some(r) = Retained::adopt(u) {
407                nsuuids.push(r);
408            }
409        }
410        let ptrs: Vec<Id> = nsuuids.iter().map(|u| u.as_ptr()).collect();
411        let Some(arr) = Retained::adopt(nsarray(&ptrs)) else {
412            return Vec::new();
413        };
414        let res: Id = msg_send![central, retrievePeripheralsWithIdentifiers: arr.as_ptr()];
415        array_map(res, |p| Retained::retain(p))
416            .into_iter()
417            .flatten()
418            .collect()
419    }
420}
421
422// ── CBPeripheral ────────────────────────────────────────────────────────────
423
424/// `[peripheral name]`.
425///
426/// # Safety
427/// `peripheral` must be a `CBPeripheral`.
428pub unsafe fn peripheral_name(peripheral: Id) -> Option<String> {
429    unsafe { to_string(msg_send![peripheral, name]) }
430}
431
432/// `[[peripheral identifier] UUIDString]` — stable per machine, per peripheral.
433///
434/// This is what Web Bluetooth's `BluetoothDevice.id` maps to. Note that Apple
435/// rotates it per-host, so it is not the BD_ADDR and is not comparable across
436/// machines.
437///
438/// # Safety
439/// `peripheral` must be a `CBPeripheral`.
440pub unsafe fn peripheral_identifier(peripheral: Id) -> Option<String> {
441    unsafe { to_string(msg_send![msg_send![peripheral, identifier], UUIDString]) }
442}
443
444/// `[peripheral state]`.
445///
446/// # Safety
447/// `peripheral` must be a `CBPeripheral`.
448pub unsafe fn peripheral_state(peripheral: Id) -> PeripheralState {
449    unsafe { PeripheralState::from(msg_send_t![isize; peripheral, state]) }
450}
451
452/// `[peripheral setDelegate:]`.
453///
454/// # Safety
455/// `delegate` must outlive the peripheral's use.
456pub unsafe fn peripheral_set_delegate(peripheral: Id, delegate: Id) {
457    unsafe { msg_send_void![peripheral, setDelegate: delegate] }
458}
459
460/// `discoverServices:`. An empty slice discovers everything.
461///
462/// # Safety
463/// `peripheral` must be a connected `CBPeripheral`.
464pub unsafe fn peripheral_discover_services(peripheral: Id, services: &[Id]) {
465    unsafe {
466        let arr = if services.is_empty() {
467            None
468        } else {
469            Retained::adopt(nsarray(services))
470        };
471        msg_send_void![peripheral, discoverServices: arr.as_ref().map_or(NIL, |a| a.as_ptr())];
472    }
473}
474
475/// `[peripheral services]`, retained.
476///
477/// # Safety
478/// `peripheral` must be a `CBPeripheral`.
479pub unsafe fn peripheral_services(peripheral: Id) -> Vec<Retained> {
480    unsafe {
481        let arr: Id = msg_send![peripheral, services];
482        array_map(arr, |s| Retained::retain(s))
483            .into_iter()
484            .flatten()
485            .collect()
486    }
487}
488
489/// `discoverCharacteristics:forService:`.
490///
491/// # Safety
492/// `peripheral` must own `service`.
493pub unsafe fn peripheral_discover_characteristics(peripheral: Id, uuids: &[Id], service: Id) {
494    unsafe {
495        let arr = if uuids.is_empty() {
496            None
497        } else {
498            Retained::adopt(nsarray(uuids))
499        };
500        msg_send_void![
501            peripheral,
502            discoverCharacteristics: arr.as_ref().map_or(NIL, |a| a.as_ptr()),
503            forService: service
504        ];
505    }
506}
507
508/// `discoverDescriptorsForCharacteristic:`.
509///
510/// # Safety
511/// `peripheral` must own `characteristic`.
512pub unsafe fn peripheral_discover_descriptors(peripheral: Id, characteristic: Id) {
513    unsafe { msg_send_void![peripheral, discoverDescriptorsForCharacteristic: characteristic] }
514}
515
516/// `readValueForCharacteristic:`.
517///
518/// # Safety
519/// `peripheral` must own `characteristic`.
520pub unsafe fn peripheral_read_characteristic(peripheral: Id, characteristic: Id) {
521    unsafe { msg_send_void![peripheral, readValueForCharacteristic: characteristic] }
522}
523
524/// `writeValue:forCharacteristic:type:`.
525///
526/// # Safety
527/// `peripheral` must own `characteristic`.
528pub unsafe fn peripheral_write_characteristic(
529    peripheral: Id,
530    characteristic: Id,
531    value: &[u8],
532    write_type: WriteType,
533) {
534    unsafe {
535        let Some(data) = Retained::adopt(nsdata(value)) else {
536            return;
537        };
538        msg_send_void![
539            peripheral,
540            writeValue: data.as_ptr(),
541            forCharacteristic: characteristic,
542            type: write_type as isize
543        ];
544    }
545}
546
547/// `setNotifyValue:forCharacteristic:`.
548///
549/// # Safety
550/// `peripheral` must own `characteristic`.
551pub unsafe fn peripheral_set_notify(peripheral: Id, characteristic: Id, enabled: bool) {
552    unsafe {
553        msg_send_void![peripheral, setNotifyValue: enabled, forCharacteristic: characteristic]
554    }
555}
556
557/// `readValueForDescriptor:`.
558///
559/// # Safety
560/// `peripheral` must own `descriptor`.
561pub unsafe fn peripheral_read_descriptor(peripheral: Id, descriptor: Id) {
562    unsafe { msg_send_void![peripheral, readValueForDescriptor: descriptor] }
563}
564
565/// `writeValue:forDescriptor:`.
566///
567/// # Safety
568/// `peripheral` must own `descriptor`.
569pub unsafe fn peripheral_write_descriptor(peripheral: Id, descriptor: Id, value: &[u8]) {
570    unsafe {
571        let Some(data) = Retained::adopt(nsdata(value)) else {
572            return;
573        };
574        msg_send_void![peripheral, writeValue: data.as_ptr(), forDescriptor: descriptor];
575    }
576}
577
578/// `readRSSI`.
579///
580/// # Safety
581/// `peripheral` must be a connected `CBPeripheral`.
582pub unsafe fn peripheral_read_rssi(peripheral: Id) {
583    unsafe { msg_send_void![peripheral, readRSSI] }
584}
585
586/// `maximumWriteValueLengthForType:` — the ATT MTU payload budget.
587///
588/// # Safety
589/// `peripheral` must be a connected `CBPeripheral`.
590pub unsafe fn peripheral_max_write_len(peripheral: Id, write_type: WriteType) -> usize {
591    unsafe { msg_send_t![usize; peripheral, maximumWriteValueLengthForType: write_type as isize] }
592}
593
594/// `canSendWriteWithoutResponse`.
595///
596/// # Safety
597/// `peripheral` must be a `CBPeripheral`.
598pub unsafe fn peripheral_can_write_without_response(peripheral: Id) -> bool {
599    unsafe { msg_send_t![bool; peripheral, canSendWriteWithoutResponse] }
600}
601
602// ── CBService / CBCharacteristic / CBDescriptor ─────────────────────────────
603
604/// `[attribute UUID]`, borrowed.
605///
606/// # Safety
607/// `attribute` must be a `CBAttribute` subclass.
608pub unsafe fn attribute_uuid(attribute: Id) -> Id {
609    unsafe { msg_send![attribute, UUID] }
610}
611
612/// `[service isPrimary]`.
613///
614/// # Safety
615/// `service` must be a `CBService`.
616pub unsafe fn service_is_primary(service: Id) -> bool {
617    unsafe { msg_send_t![bool; service, isPrimary] }
618}
619
620/// `[service characteristics]`, retained.
621///
622/// # Safety
623/// `service` must be a `CBService`.
624pub unsafe fn service_characteristics(service: Id) -> Vec<Retained> {
625    unsafe {
626        let arr: Id = msg_send![service, characteristics];
627        array_map(arr, |c| Retained::retain(c))
628            .into_iter()
629            .flatten()
630            .collect()
631    }
632}
633
634/// `[peripheral discoverIncludedServices:forService:]`.
635///
636/// Answered by `peripheral:didDiscoverIncludedServicesForService:error:`, after
637/// which `service_included` returns the results. An empty `services` filter
638/// means "every included service".
639///
640/// # Safety
641/// `peripheral` must be a `CBPeripheral`, `service` one of its `CBService`s,
642/// and every entry of `services` a `CBUUID`.
643pub unsafe fn peripheral_discover_included_services(peripheral: Id, services: &[Id], service: Id) {
644    unsafe {
645        let filter = if services.is_empty() {
646            NIL
647        } else {
648            nsarray(services)
649        };
650        msg_send_void![
651            peripheral,
652            discoverIncludedServices: filter,
653            forService: service
654        ];
655    }
656}
657
658/// `[service includedServices]`, retained.
659///
660/// # Safety
661/// `service` must be a `CBService`.
662pub unsafe fn service_included(service: Id) -> Vec<Retained> {
663    unsafe {
664        let arr: Id = msg_send![service, includedServices];
665        array_map(arr, |s| Retained::retain(s))
666            .into_iter()
667            .flatten()
668            .collect()
669    }
670}
671
672/// `[characteristic properties]`.
673///
674/// # Safety
675/// `characteristic` must be a `CBCharacteristic`.
676pub unsafe fn characteristic_properties(characteristic: Id) -> Properties {
677    unsafe { Properties(msg_send_t![usize; characteristic, properties] as u32) }
678}
679
680/// `[characteristic value]` — the last value read or notified.
681///
682/// # Safety
683/// `characteristic` must be a `CBCharacteristic`.
684pub unsafe fn characteristic_value(characteristic: Id) -> Option<Vec<u8>> {
685    unsafe { data_bytes(msg_send![characteristic, value]) }
686}
687
688/// `[characteristic isNotifying]`.
689///
690/// # Safety
691/// `characteristic` must be a `CBCharacteristic`.
692pub unsafe fn characteristic_is_notifying(characteristic: Id) -> bool {
693    unsafe { msg_send_t![bool; characteristic, isNotifying] }
694}
695
696/// `[characteristic service]`, borrowed. Nil once the service is released.
697///
698/// # Safety
699/// `characteristic` must be a `CBCharacteristic`.
700pub unsafe fn characteristic_service(characteristic: Id) -> Id {
701    unsafe { msg_send![characteristic, service] }
702}
703
704/// `[characteristic descriptors]`, retained.
705///
706/// # Safety
707/// `characteristic` must be a `CBCharacteristic`.
708pub unsafe fn characteristic_descriptors(characteristic: Id) -> Vec<Retained> {
709    unsafe {
710        let arr: Id = msg_send![characteristic, descriptors];
711        array_map(arr, |d| Retained::retain(d))
712            .into_iter()
713            .flatten()
714            .collect()
715    }
716}
717
718/// `[descriptor value]`.
719///
720/// CoreBluetooth types a descriptor's value per descriptor UUID — `NSNumber`
721/// for the client configuration bits, `NSString` for a user description — so
722/// this normalises to bytes the way the ATT layer would have carried them.
723///
724/// # Safety
725/// `descriptor` must be a `CBDescriptor`.
726pub unsafe fn descriptor_value(descriptor: Id) -> Option<Vec<u8>> {
727    unsafe {
728        let v: Id = msg_send![descriptor, value];
729        if v.is_null() {
730            return None;
731        }
732        if msg_send_t![bool; v, isKindOfClass: require_class(c"NSData")] {
733            return data_bytes(v);
734        }
735        if msg_send_t![bool; v, isKindOfClass: require_class(c"NSNumber")] {
736            let n = number_i64(v).unwrap_or(0);
737            return Some((n as u16).to_le_bytes().to_vec());
738        }
739        if msg_send_t![bool; v, isKindOfClass: require_class(c"NSString")] {
740            return to_string(v).map(String::into_bytes);
741        }
742        None
743    }
744}
745
746/// `[descriptor characteristic]`, borrowed.
747///
748/// # Safety
749/// `descriptor` must be a `CBDescriptor`.
750pub unsafe fn descriptor_characteristic(descriptor: Id) -> Id {
751    unsafe { msg_send![descriptor, characteristic] }
752}
753
754// ── Advertisement data ──────────────────────────────────────────────────────
755
756/// One advertising packet, as CoreBluetooth surfaces it.
757///
758/// CoreBluetooth does not expose raw AD structures — it hands over a parsed
759/// `NSDictionary` — so this is what a scan can honestly report. Notably absent
760/// versus the Web Bluetooth spec: there is no way to see the peripheral's
761/// Bluetooth address, and `appearance` is not advertised through this API.
762#[derive(Debug, Clone, Default)]
763pub struct Advertisement {
764    /// `CBAdvertisementDataLocalNameKey` — the advertised name, which may differ
765    /// from `CBPeripheral.name` (that one is the cached GAP name).
766    pub local_name: Option<String>,
767    /// `CBAdvertisementDataTxPowerLevelKey`, in dBm.
768    pub tx_power: Option<i16>,
769    /// `CBAdvertisementDataIsConnectable`.
770    pub is_connectable: Option<bool>,
771    /// `CBAdvertisementDataServiceUUIDsKey`, as CBUUID strings.
772    pub service_uuids: Vec<String>,
773    /// `CBAdvertisementDataOverflowServiceUUIDsKey` — services that did not fit
774    /// in the primary advertisement, visible only to an iOS/macOS scanner.
775    pub overflow_service_uuids: Vec<String>,
776    /// `CBAdvertisementDataSolicitedServiceUUIDsKey`.
777    pub solicited_service_uuids: Vec<String>,
778    /// `CBAdvertisementDataManufacturerDataKey`, including the leading
779    /// little-endian company identifier.
780    pub manufacturer_data: Option<Vec<u8>>,
781    /// `CBAdvertisementDataServiceDataKey`, keyed by CBUUID string.
782    pub service_data: Vec<(String, Vec<u8>)>,
783}
784
785/// Parse the `advertisementData` dictionary from `didDiscoverPeripheral`.
786///
787/// # Safety
788/// `dict` must be null or the `NSDictionary` CoreBluetooth supplied.
789pub unsafe fn parse_advertisement(dict: Id) -> Advertisement {
790    unsafe {
791        let uuids_at = |sym: &core::ffi::CStr| -> Vec<String> {
792            let arr = dict_get(dict, global_nsstring(sym));
793            array_map(arr, |u| uuid_string(u))
794                .into_iter()
795                .flatten()
796                .collect()
797        };
798
799        let service_data = {
800            let sd = dict_get(dict, global_nsstring(c"CBAdvertisementDataServiceDataKey"));
801            let keys = objc::dict_keys(sd);
802            array_map(keys, |k| {
803                let uuid = uuid_string(k)?;
804                let bytes = data_bytes(dict_get(sd, k))?;
805                Some((uuid, bytes))
806            })
807            .into_iter()
808            .flatten()
809            .collect()
810        };
811
812        Advertisement {
813            local_name: to_string(dict_get(
814                dict,
815                global_nsstring(c"CBAdvertisementDataLocalNameKey"),
816            )),
817            tx_power: number_i64(dict_get(
818                dict,
819                global_nsstring(c"CBAdvertisementDataTxPowerLevelKey"),
820            ))
821            .map(|v| v as i16),
822            is_connectable: number_bool(dict_get(
823                dict,
824                global_nsstring(c"CBAdvertisementDataIsConnectable"),
825            )),
826            service_uuids: uuids_at(c"CBAdvertisementDataServiceUUIDsKey"),
827            overflow_service_uuids: uuids_at(c"CBAdvertisementDataOverflowServiceUUIDsKey"),
828            solicited_service_uuids: uuids_at(c"CBAdvertisementDataSolicitedServiceUUIDsKey"),
829            manufacturer_data: data_bytes(dict_get(
830                dict,
831                global_nsstring(c"CBAdvertisementDataManufacturerDataKey"),
832            )),
833            service_data,
834        }
835    }
836}