1use 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#[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#[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#[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#[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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
134pub enum WriteType {
135 WithResponse = 0,
136 WithoutResponse = 1,
137}
138
139pub fn authorization() -> Authorization {
143 unsafe { Authorization::from(msg_send_t![isize; require_class(c"CBManager"), authorization]) }
144}
145
146pub 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
165pub unsafe fn uuid_string(uuid: Id) -> Option<String> {
170 unsafe { to_string(msg_send![uuid, UUIDString]) }
171}
172
173pub 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
189pub 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
224pub unsafe fn peripheral_open_l2cap(peripheral: Id, psm: u16) {
231 unsafe { msg_send_void![peripheral, openL2CAPChannel: psm] }
232}
233
234#[derive(Debug, Default)]
236pub struct RestoredCentralState {
237 pub peripherals: Vec<Retained>,
239 pub scan_services: Vec<String>,
241 pub scan_allow_duplicates: bool,
243}
244
245pub 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
287pub unsafe fn central_state(central: Id) -> ManagerState {
292 unsafe { ManagerState::from(msg_send_t![isize; central, state]) }
293}
294
295pub unsafe fn central_is_scanning(central: Id) -> bool {
300 unsafe { msg_send_t![bool; central, isScanning] }
301}
302
303pub 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
350pub unsafe fn central_stop_scan(central: Id) {
355 unsafe { msg_send_void![central, stopScan] }
356}
357
358pub unsafe fn central_connect(central: Id, peripheral: Id) {
363 unsafe { msg_send_void![central, connectPeripheral: peripheral, options: NIL] }
364}
365
366pub unsafe fn central_disconnect(central: Id, peripheral: Id) {
371 unsafe { msg_send_void![central, cancelPeripheralConnection: peripheral] }
372}
373
374pub 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
392pub 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
422pub unsafe fn peripheral_name(peripheral: Id) -> Option<String> {
429 unsafe { to_string(msg_send![peripheral, name]) }
430}
431
432pub unsafe fn peripheral_identifier(peripheral: Id) -> Option<String> {
441 unsafe { to_string(msg_send![msg_send![peripheral, identifier], UUIDString]) }
442}
443
444pub unsafe fn peripheral_state(peripheral: Id) -> PeripheralState {
449 unsafe { PeripheralState::from(msg_send_t![isize; peripheral, state]) }
450}
451
452pub unsafe fn peripheral_set_delegate(peripheral: Id, delegate: Id) {
457 unsafe { msg_send_void![peripheral, setDelegate: delegate] }
458}
459
460pub 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
475pub 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
489pub 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
508pub unsafe fn peripheral_discover_descriptors(peripheral: Id, characteristic: Id) {
513 unsafe { msg_send_void![peripheral, discoverDescriptorsForCharacteristic: characteristic] }
514}
515
516pub unsafe fn peripheral_read_characteristic(peripheral: Id, characteristic: Id) {
521 unsafe { msg_send_void![peripheral, readValueForCharacteristic: characteristic] }
522}
523
524pub 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
547pub 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
557pub unsafe fn peripheral_read_descriptor(peripheral: Id, descriptor: Id) {
562 unsafe { msg_send_void![peripheral, readValueForDescriptor: descriptor] }
563}
564
565pub 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
578pub unsafe fn peripheral_read_rssi(peripheral: Id) {
583 unsafe { msg_send_void![peripheral, readRSSI] }
584}
585
586pub 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
594pub unsafe fn peripheral_can_write_without_response(peripheral: Id) -> bool {
599 unsafe { msg_send_t![bool; peripheral, canSendWriteWithoutResponse] }
600}
601
602pub unsafe fn attribute_uuid(attribute: Id) -> Id {
609 unsafe { msg_send![attribute, UUID] }
610}
611
612pub unsafe fn service_is_primary(service: Id) -> bool {
617 unsafe { msg_send_t![bool; service, isPrimary] }
618}
619
620pub 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
634pub 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
658pub 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
672pub unsafe fn characteristic_properties(characteristic: Id) -> Properties {
677 unsafe { Properties(msg_send_t![usize; characteristic, properties] as u32) }
678}
679
680pub unsafe fn characteristic_value(characteristic: Id) -> Option<Vec<u8>> {
685 unsafe { data_bytes(msg_send![characteristic, value]) }
686}
687
688pub unsafe fn characteristic_is_notifying(characteristic: Id) -> bool {
693 unsafe { msg_send_t![bool; characteristic, isNotifying] }
694}
695
696pub unsafe fn characteristic_service(characteristic: Id) -> Id {
701 unsafe { msg_send![characteristic, service] }
702}
703
704pub 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
718pub 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
746pub unsafe fn descriptor_characteristic(descriptor: Id) -> Id {
751 unsafe { msg_send![descriptor, characteristic] }
752}
753
754#[derive(Debug, Clone, Default)]
763pub struct Advertisement {
764 pub local_name: Option<String>,
767 pub tx_power: Option<i16>,
769 pub is_connectable: Option<bool>,
771 pub service_uuids: Vec<String>,
773 pub overflow_service_uuids: Vec<String>,
776 pub solicited_service_uuids: Vec<String>,
778 pub manufacturer_data: Option<Vec<u8>>,
781 pub service_data: Vec<(String, Vec<u8>)>,
783}
784
785pub 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}