btleplug 0.12.0

A Cross-Platform Rust Bluetooth Low Energy (BLE) GATT library.
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
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
// btleplug Source Code File
//
// Copyright 2020 Nonpolynomial Labs LLC. All rights reserved.
//
// Licensed under the BSD 3-Clause license. See LICENSE file in the project root
// for full license information.
//
// Some portions of this file are taken and/or modified from blurmac
// (https://github.com/servo/devices), using a BSD 3-Clause license under the
// following copyright:
//
// Copyright (c) 2017 Akos Kiss.
//
// Licensed under the BSD 3-Clause License
// <LICENSE.md or https://opensource.org/licenses/BSD-3-Clause>.
// This file may not be copied, modified, or distributed except
// according to those terms.

use super::utils::nsstring_to_string;
use super::utils::{core_bluetooth::cbuuid_to_uuid, nsuuid_to_uuid};
use futures::channel::mpsc::Sender;
use futures::sink::SinkExt;
use log::{error, trace};
use objc2::runtime::{AnyObject, ProtocolObject};
use objc2::{ClassType, DeclaredClass, declare_class, msg_send_id, mutability, rc::Retained};
use objc2_core_bluetooth::{
    CBAdvertisementDataLocalNameKey, CBAdvertisementDataManufacturerDataKey,
    CBAdvertisementDataServiceDataKey, CBAdvertisementDataServiceUUIDsKey,
    CBAdvertisementDataTxPowerLevelKey, CBCentralManager, CBCentralManagerDelegate,
    CBCharacteristic, CBDescriptor, CBManagerState, CBPeripheral, CBPeripheralDelegate, CBService,
    CBUUID,
};
use objc2_foundation::{
    NSArray, NSData, NSDictionary, NSError, NSNumber, NSObject, NSObjectProtocol, NSString,
};
use std::convert::TryInto;
use std::{
    collections::HashMap,
    fmt::{self, Debug, Formatter},
    ops::Deref,
};
use uuid::Uuid;

pub enum CentralDelegateEvent {
    DidUpdateState {
        state: CBManagerState,
    },
    DiscoveredPeripheral {
        cbperipheral: Retained<CBPeripheral>,
        advertisement_name: Option<String>,
    },
    DiscoveredServices {
        peripheral_uuid: Uuid,
        services: HashMap<Uuid, Retained<CBService>>,
    },
    ManufacturerData {
        peripheral_uuid: Uuid,
        manufacturer_id: u16,
        data: Vec<u8>,
        rssi: i16,
    },
    ServiceData {
        peripheral_uuid: Uuid,
        service_data: HashMap<Uuid, Vec<u8>>,
        rssi: i16,
    },
    Services {
        peripheral_uuid: Uuid,
        service_uuids: Vec<Uuid>,
        rssi: i16,
    },
    ServicesModified {
        peripheral_uuid: Uuid,
    },
    // DiscoveredIncludedServices(Uuid, HashMap<Uuid, Retained<CBService>>),
    DiscoveredCharacteristics {
        peripheral_uuid: Uuid,
        service_uuid: Uuid,
        /// Characteristic UUID to CBCharacteristic
        characteristics: HashMap<Uuid, Retained<CBCharacteristic>>,
    },
    DiscoveredCharacteristicDescriptors {
        peripheral_uuid: Uuid,
        service_uuid: Uuid,
        characteristic_uuid: Uuid,
        descriptors: HashMap<Uuid, Retained<CBDescriptor>>,
    },
    ConnectedDevice {
        peripheral_uuid: Uuid,
    },
    ConnectionFailed {
        peripheral_uuid: Uuid,
        error_description: Option<String>,
    },
    DisconnectedDevice {
        peripheral_uuid: Uuid,
    },
    CharacteristicSubscribed {
        peripheral_uuid: Uuid,
        service_uuid: Uuid,
        characteristic_uuid: Uuid,
    },
    CharacteristicUnsubscribed {
        peripheral_uuid: Uuid,
        service_uuid: Uuid,
        characteristic_uuid: Uuid,
    },
    CharacteristicNotified {
        peripheral_uuid: Uuid,
        service_uuid: Uuid,
        characteristic_uuid: Uuid,
        data: Vec<u8>,
    },
    CharacteristicWritten {
        peripheral_uuid: Uuid,
        service_uuid: Uuid,
        characteristic_uuid: Uuid,
    },
    DescriptorNotified {
        peripheral_uuid: Uuid,
        service_uuid: Uuid,
        characteristic_uuid: Uuid,
        descriptor_uuid: Uuid,
        data: Vec<u8>,
    },
    DescriptorWritten {
        peripheral_uuid: Uuid,
        service_uuid: Uuid,
        characteristic_uuid: Uuid,
        descriptor_uuid: Uuid,
    },
    TxPowerLevel {
        peripheral_uuid: Uuid,
        tx_power_level: i16,
    },
    DidReadRssi {
        peripheral_uuid: Uuid,
        rssi: i16,
    },
    ReadyToSendWriteWithoutResponse {
        peripheral_uuid: Uuid,
    },
}

impl Debug for CentralDelegateEvent {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        match self {
            CentralDelegateEvent::DidUpdateState { state } => f
                .debug_struct("CentralDelegateEvent")
                .field("state", state)
                .finish(),
            CentralDelegateEvent::DiscoveredPeripheral {
                cbperipheral,
                advertisement_name,
            } => f
                .debug_struct("CentralDelegateEvent")
                .field("cbperipheral", cbperipheral.deref())
                .field("advertisement_name", advertisement_name)
                .finish(),
            CentralDelegateEvent::DiscoveredServices {
                peripheral_uuid,
                services,
            } => f
                .debug_struct("DiscoveredServices")
                .field("peripheral_uuid", peripheral_uuid)
                .field("services", &services.keys().collect::<Vec<_>>())
                .finish(),
            CentralDelegateEvent::DiscoveredCharacteristics {
                peripheral_uuid,
                service_uuid,
                characteristics,
            } => f
                .debug_struct("DiscoveredCharacteristics")
                .field("peripheral_uuid", peripheral_uuid)
                .field("service_uuid", service_uuid)
                .field(
                    "characteristics",
                    &characteristics.keys().collect::<Vec<_>>(),
                )
                .finish(),
            CentralDelegateEvent::DiscoveredCharacteristicDescriptors {
                peripheral_uuid,
                service_uuid,
                characteristic_uuid,
                descriptors,
            } => f
                .debug_struct("DiscoveredCharacteristicDescriptors")
                .field("peripheral_uuid", peripheral_uuid)
                .field("service_uuid", service_uuid)
                .field("characteristic_uuid", characteristic_uuid)
                .field("descriptors", &descriptors.keys().collect::<Vec<_>>())
                .finish(),
            CentralDelegateEvent::ConnectedDevice { peripheral_uuid } => f
                .debug_struct("ConnectedDevice")
                .field("peripheral_uuid", peripheral_uuid)
                .finish(),
            CentralDelegateEvent::ConnectionFailed {
                peripheral_uuid,
                error_description,
            } => f
                .debug_struct("ConnectionFailed")
                .field("peripheral_uuid", peripheral_uuid)
                .field("error_description", error_description)
                .finish(),
            CentralDelegateEvent::DisconnectedDevice { peripheral_uuid } => f
                .debug_struct("DisconnectedDevice")
                .field("peripheral_uuid", peripheral_uuid)
                .finish(),
            CentralDelegateEvent::CharacteristicSubscribed {
                peripheral_uuid,
                service_uuid,
                characteristic_uuid,
            } => f
                .debug_struct("CharacteristicSubscribed")
                .field("peripheral_uuid", peripheral_uuid)
                .field("service_uuid", service_uuid)
                .field("characteristic_uuid", characteristic_uuid)
                .finish(),
            CentralDelegateEvent::CharacteristicUnsubscribed {
                peripheral_uuid,
                service_uuid,
                characteristic_uuid,
            } => f
                .debug_struct("CharacteristicUnsubscribed")
                .field("peripheral_uuid", peripheral_uuid)
                .field("service_uuid", service_uuid)
                .field("characteristic_uuid", characteristic_uuid)
                .finish(),
            CentralDelegateEvent::CharacteristicNotified {
                peripheral_uuid,
                service_uuid,
                characteristic_uuid,
                data,
            } => f
                .debug_struct("CharacteristicNotified")
                .field("peripheral_uuid", peripheral_uuid)
                .field("service_uuid", service_uuid)
                .field("characteristic_uuid", characteristic_uuid)
                .field("data", data)
                .finish(),
            CentralDelegateEvent::CharacteristicWritten {
                peripheral_uuid,
                service_uuid,
                characteristic_uuid,
            } => f
                .debug_struct("CharacteristicWritten")
                .field("service_uuid", service_uuid)
                .field("peripheral_uuid", peripheral_uuid)
                .field("characteristic_uuid", characteristic_uuid)
                .finish(),
            CentralDelegateEvent::ManufacturerData {
                peripheral_uuid,
                manufacturer_id,
                data,
                rssi,
            } => f
                .debug_struct("ManufacturerData")
                .field("peripheral_uuid", peripheral_uuid)
                .field("manufacturer_id", manufacturer_id)
                .field("data", data)
                .field("rssi", rssi)
                .finish(),
            CentralDelegateEvent::ServiceData {
                peripheral_uuid,
                service_data,
                rssi,
            } => f
                .debug_struct("ServiceData")
                .field("peripheral_uuid", peripheral_uuid)
                .field("service_data", service_data)
                .field("rssi", rssi)
                .finish(),
            CentralDelegateEvent::Services {
                peripheral_uuid,
                service_uuids,
                rssi,
            } => f
                .debug_struct("Services")
                .field("peripheral_uuid", peripheral_uuid)
                .field("service_uuids", service_uuids)
                .field("rssi", rssi)
                .finish(),
            CentralDelegateEvent::ServicesModified { peripheral_uuid } => f
                .debug_struct("ServicesModified")
                .field("peripheral_uuid", peripheral_uuid)
                .finish(),
            CentralDelegateEvent::DescriptorNotified {
                peripheral_uuid,
                service_uuid,
                characteristic_uuid,
                descriptor_uuid,
                data,
            } => f
                .debug_struct("DescriptorNotified")
                .field("peripheral_uuid", peripheral_uuid)
                .field("service_uuid", service_uuid)
                .field("characteristic_uuid", characteristic_uuid)
                .field("descriptor_uuid", descriptor_uuid)
                .field("data", data)
                .finish(),
            CentralDelegateEvent::DescriptorWritten {
                peripheral_uuid,
                service_uuid,
                characteristic_uuid,
                descriptor_uuid,
            } => f
                .debug_struct("DescriptorWritten")
                .field("service_uuid", service_uuid)
                .field("peripheral_uuid", peripheral_uuid)
                .field("characteristic_uuid", characteristic_uuid)
                .field("descriptor_uuid", descriptor_uuid)
                .finish(),
            CentralDelegateEvent::TxPowerLevel {
                peripheral_uuid,
                tx_power_level,
            } => f
                .debug_struct("TxPowerLevel")
                .field("peripheral_uuid", peripheral_uuid)
                .field("tx_power_level", tx_power_level)
                .finish(),
            CentralDelegateEvent::DidReadRssi {
                peripheral_uuid,
                rssi,
            } => f
                .debug_struct("DidReadRssi")
                .field("peripheral_uuid", peripheral_uuid)
                .field("rssi", rssi)
                .finish(),
            CentralDelegateEvent::ReadyToSendWriteWithoutResponse { peripheral_uuid } => f
                .debug_struct("ReadyToSendWriteWithoutResponse")
                .field("peripheral_uuid", peripheral_uuid)
                .finish(),
        }
    }
}

declare_class!(
    #[derive(Debug)]
    pub struct CentralDelegate;

    unsafe impl ClassType for CentralDelegate {
        type Super = NSObject;
        type Mutability = mutability::InteriorMutable;
        const NAME: &'static str = "BtlePlugCentralManagerDelegate";
    }

    impl DeclaredClass for CentralDelegate {
        type Ivars = Sender<CentralDelegateEvent>;
    }

    unsafe impl NSObjectProtocol for CentralDelegate {}

    unsafe impl CBCentralManagerDelegate for CentralDelegate {
        #[method(centralManagerDidUpdateState:)]
        fn delegate_centralmanagerdidupdatestate(&self, central: &CBCentralManager) {
            trace!("delegate_centralmanagerdidupdatestate");
            let state = unsafe { central.state() };
            self.send_event(CentralDelegateEvent::DidUpdateState { state });
        }

        // #[method(centralManager:willRestoreState:)]
        // fn delegate_centralmanager_willrestorestate(&self, _central: &CBCentralManager, _dict: &NSDictionary<NSString, AnyObject>) {
        //     trace!("delegate_centralmanager_willrestorestate");
        // }

        #[method(centralManager:didConnectPeripheral:)]
        fn delegate_centralmanager_didconnectperipheral(
            &self,
            _central: &CBCentralManager,
            peripheral: &CBPeripheral,
        ) {
            trace!(
                "delegate_centralmanager_didconnectperipheral {}",
                peripheral_debug(peripheral)
            );
            unsafe { peripheral.setDelegate(Some(ProtocolObject::from_ref(self))) };
            let id = unsafe { peripheral.identifier() };
            let peripheral_uuid = nsuuid_to_uuid(&id);
            self.send_event(CentralDelegateEvent::ConnectedDevice { peripheral_uuid });
        }

        #[method(centralManager:didDisconnectPeripheral:error:)]
        fn delegate_centralmanager_diddisconnectperipheral_error(
            &self,
            _central: &CBCentralManager,
            peripheral: &CBPeripheral,
            error: Option<&NSError>,
        ) {
            trace!(
                "delegate_centralmanager_diddisconnectperipheral_error {} (error={:?})",
                peripheral_debug(peripheral),
                error
            );
            let id = unsafe { peripheral.identifier() };
            let peripheral_uuid = nsuuid_to_uuid(&id);
            self.send_event(CentralDelegateEvent::DisconnectedDevice { peripheral_uuid });
        }

        #[method(centralManager:didFailToConnectPeripheral:error:)]
        fn delegate_centralmanager_didfailtoconnectperipheral_error(
            &self,
            _central: &CBCentralManager,
            peripheral: &CBPeripheral,
            error: Option<&NSError>,
        ) {
            trace!("delegate_centralmanager_didfailtoconnectperipheral_error");
            let id = unsafe { peripheral.identifier() };
            let peripheral_uuid = nsuuid_to_uuid(&id);
            let error_description = error.map(|error| error.localizedDescription().to_string());
            self.send_event(CentralDelegateEvent::ConnectionFailed {
                peripheral_uuid,
                error_description,
            });
        }

        #[method(centralManager:didDiscoverPeripheral:advertisementData:RSSI:)]
        fn delegate_centralmanager_diddiscoverperipheral_advertisementdata_rssi(
            &self,
            _central: &CBCentralManager,
            peripheral: &CBPeripheral,
            adv_data: &NSDictionary<NSString, AnyObject>,
            rssi: &NSNumber,
        ) {
            trace!(
                "delegate_centralmanager_diddiscoverperipheral_advertisementdata_rssi {}",
                peripheral_debug(peripheral)
            );

            let advertisement_name = adv_data
                .get(unsafe { CBAdvertisementDataLocalNameKey })
                .map(|name| name as *const AnyObject as *const NSString)
                .and_then(|name| unsafe { nsstring_to_string(name) });

            self.send_event(CentralDelegateEvent::DiscoveredPeripheral {
                cbperipheral: peripheral.retain(),
                advertisement_name,
            });

            let rssi_value = rssi.as_i16();

            let id = unsafe { peripheral.identifier() };
            let peripheral_uuid = nsuuid_to_uuid(&id);

            let manufacturer_data = adv_data.get(unsafe { CBAdvertisementDataManufacturerDataKey });
            if let Some(manufacturer_data) = manufacturer_data {
                // SAFETY: manufacturer_data is `NSData`
                let manufacturer_data: *const AnyObject = manufacturer_data;
                let manufacturer_data: *const NSData = manufacturer_data.cast();
                let manufacturer_data = unsafe { &*manufacturer_data };

                if manufacturer_data.len() >= 2 {
                    let (manufacturer_id, manufacturer_data) =
                        manufacturer_data.bytes().split_at(2);

                    self.send_event(CentralDelegateEvent::ManufacturerData {
                        peripheral_uuid,
                        manufacturer_id: u16::from_le_bytes(manufacturer_id.try_into().unwrap()),
                        data: Vec::from(manufacturer_data),
                        rssi: rssi_value,
                    });
                }
            }

            let service_data = adv_data.get(unsafe { CBAdvertisementDataServiceDataKey });
            if let Some(service_data) = service_data {
                // SAFETY: service_data is `NSDictionary<CBUUID, NSData>`
                let service_data: *const AnyObject = service_data;
                let service_data: *const NSDictionary<CBUUID, NSData> = service_data.cast();
                let service_data = unsafe { &*service_data };

                let mut result = HashMap::new();
                for uuid in service_data.keys() {
                    let data = &service_data[uuid];
                    result.insert(cbuuid_to_uuid(uuid), data.bytes().to_vec());
                }

                self.send_event(CentralDelegateEvent::ServiceData {
                    peripheral_uuid,
                    service_data: result,
                    rssi: rssi_value,
                });
            }

            let services = adv_data.get(unsafe { CBAdvertisementDataServiceUUIDsKey });
            if let Some(services) = services {
                // SAFETY: services is `NSArray<CBUUID>`
                let services: *const AnyObject = services;
                let services: *const NSArray<CBUUID> = services.cast();
                let services = unsafe { &*services };

                let mut service_uuids = Vec::new();
                for uuid in services {
                    service_uuids.push(cbuuid_to_uuid(uuid));
                }

                self.send_event(CentralDelegateEvent::Services {
                    peripheral_uuid,
                    service_uuids,
                    rssi: rssi_value,
                });
            }

            let tx_power_level = adv_data
                .get(unsafe { CBAdvertisementDataTxPowerLevelKey })
                .map(|val| {
                    let val: *const AnyObject = val;
                    let val: *const NSNumber = val.cast();
                    unsafe { &*val }.as_i16()
                });

            if let Some(tx_power_level) = tx_power_level {
                self.send_event(CentralDelegateEvent::TxPowerLevel {
                    peripheral_uuid,
                    tx_power_level,
                });
            }
        }
    }

    unsafe impl CBPeripheralDelegate for CentralDelegate {
        #[method(peripheral:didDiscoverServices:)]
        fn delegate_peripheral_diddiscoverservices(
            &self,
            peripheral: &CBPeripheral,
            error: Option<&NSError>,
        ) {
            trace!(
                "delegate_peripheral_diddiscoverservices {} {}",
                peripheral_debug(peripheral),
                localized_description(error)
            );
            if error.is_none() {
                let services = unsafe { peripheral.services() }.unwrap_or_default();
                let mut service_map = HashMap::new();
                for s in services {
                    // go ahead and ask for characteristics and other services
                    unsafe {
                        peripheral.discoverCharacteristics_forService(None, &s);
                        peripheral.discoverIncludedServices_forService(None, &s);
                    }

                    // Create the map entry we'll need to export.
                    let raw_uuid = unsafe { s.UUID() };
                    let uuid = cbuuid_to_uuid(&raw_uuid);
                    service_map.insert(uuid, s);
                }
                let id = unsafe { peripheral.identifier() };
                let peripheral_uuid = nsuuid_to_uuid(&id);
                self.send_event(CentralDelegateEvent::DiscoveredServices {
                    peripheral_uuid,
                    services: service_map,
                });
            }
        }

        #[method(peripheral:didDiscoverIncludedServicesForService:error:)]
        fn delegate_peripheral_diddiscoverincludedservicesforservice_error(
            &self,
            peripheral: &CBPeripheral,
            service: &CBService,
            error: Option<&NSError>,
        ) {
            trace!(
                "delegate_peripheral_diddiscoverincludedservicesforservice_error {} {} {}",
                peripheral_debug(peripheral),
                service_debug(service),
                localized_description(error)
            );
            if error.is_none() {
                let includes = unsafe { service.includedServices() }.unwrap_or_default();
                for s in includes {
                    unsafe { peripheral.discoverCharacteristics_forService(None, &s) };
                }
            }
        }

        #[method(peripheral:didDiscoverCharacteristicsForService:error:)]
        fn delegate_peripheral_diddiscovercharacteristicsforservice_error(
            &self,
            peripheral: &CBPeripheral,
            service: &CBService,
            error: Option<&NSError>,
        ) {
            trace!(
                "delegate_peripheral_diddiscovercharacteristicsforservice_error {} {} {}",
                peripheral_debug(peripheral),
                service_debug(service),
                localized_description(error)
            );
            if error.is_none() {
                let mut characteristics = HashMap::new();
                let chars = unsafe { service.characteristics() }.unwrap_or_default();
                for c in chars {
                    unsafe { peripheral.discoverDescriptorsForCharacteristic(&c) };
                    // Create the map entry we'll need to export.
                    let raw_uuid = unsafe { c.UUID() };
                    let uuid = cbuuid_to_uuid(&raw_uuid);
                    characteristics.insert(uuid, c);
                }
                let id = unsafe { peripheral.identifier() };
                let peripheral_uuid = nsuuid_to_uuid(&id);
                let raw_service_uuid = unsafe { service.UUID() };
                let service_uuid = cbuuid_to_uuid(&raw_service_uuid);
                self.send_event(CentralDelegateEvent::DiscoveredCharacteristics {
                    peripheral_uuid,
                    service_uuid,
                    characteristics,
                });
            }
        }

        #[method(peripheral:didDiscoverDescriptorsForCharacteristic:error:)]
        fn delegate_peripheral_diddiscoverdescriptorsforcharacteristic_error(
            &self,
            peripheral: &CBPeripheral,
            characteristic: &CBCharacteristic,
            error: Option<&NSError>,
        ) {
            trace!(
                "delegate_peripheral_diddiscoverdescriptorsforcharacteristic_error {} {} {}",
                peripheral_debug(peripheral),
                characteristic_debug(characteristic),
                localized_description(error)
            );
            if error.is_none() {
                let mut descriptors = HashMap::new();
                let descs = unsafe { characteristic.descriptors() }.unwrap_or_default();
                for d in descs {
                    // Create the map entry we'll need to export.
                    let raw_uuid = unsafe { d.UUID() };
                    let uuid = cbuuid_to_uuid(&raw_uuid);
                    descriptors.insert(uuid, d);
                }
                let id = unsafe { peripheral.identifier() };
                let peripheral_uuid = nsuuid_to_uuid(&id);
                let service = unsafe { characteristic.service() }.unwrap();
                let raw_service_uuid = unsafe { service.UUID() };
                let service_uuid = cbuuid_to_uuid(&raw_service_uuid);
                let raw_char_uuid = unsafe { characteristic.UUID() };
                let characteristic_uuid = cbuuid_to_uuid(&raw_char_uuid);
                self.send_event(CentralDelegateEvent::DiscoveredCharacteristicDescriptors {
                    peripheral_uuid,
                    service_uuid,
                    characteristic_uuid,
                    descriptors,
                });
            }
        }

        #[method(peripheral:didUpdateValueForCharacteristic:error:)]
        fn delegate_peripheral_didupdatevalueforcharacteristic_error(
            &self,
            peripheral: &CBPeripheral,
            characteristic: &CBCharacteristic,
            error: Option<&NSError>,
        ) {
            trace!(
                "delegate_peripheral_didupdatevalueforcharacteristic_error {} {} {}",
                peripheral_debug(peripheral),
                characteristic_debug(characteristic),
                localized_description(error)
            );
            if error.is_none() {
                let service = unsafe { characteristic.service() }.unwrap();
                let id = unsafe { peripheral.identifier() };
                let peripheral_uuid = nsuuid_to_uuid(&id);
                let raw_service_uuid = unsafe { service.UUID() };
                let service_uuid = cbuuid_to_uuid(&raw_service_uuid);
                let raw_char_uuid = unsafe { characteristic.UUID() };
                let characteristic_uuid = cbuuid_to_uuid(&raw_char_uuid);
                self.send_event(CentralDelegateEvent::CharacteristicNotified {
                    peripheral_uuid,
                    service_uuid,
                    characteristic_uuid,
                    data: get_characteristic_value(characteristic),
                });
                // Notify BluetoothGATTCharacteristic::read_value that read was successful.
            }
        }

        #[method(peripheral:didWriteValueForCharacteristic:error:)]
        fn delegate_peripheral_didwritevalueforcharacteristic_error(
            &self,
            peripheral: &CBPeripheral,
            characteristic: &CBCharacteristic,
            error: Option<&NSError>,
        ) {
            trace!(
                "delegate_peripheral_didwritevalueforcharacteristic_error {} {} {}",
                peripheral_debug(peripheral),
                characteristic_debug(characteristic),
                localized_description(error)
            );
            if error.is_none() {
                let service = unsafe { characteristic.service() }.unwrap();
                let id = unsafe { peripheral.identifier() };
                let peripheral_uuid = nsuuid_to_uuid(&id);
                let raw_service_uuid = unsafe { service.UUID() };
                let service_uuid = cbuuid_to_uuid(&raw_service_uuid);
                let raw_char_uuid = unsafe { characteristic.UUID() };
                let characteristic_uuid = cbuuid_to_uuid(&raw_char_uuid);
                self.send_event(CentralDelegateEvent::CharacteristicWritten {
                    peripheral_uuid,
                    service_uuid,
                    characteristic_uuid,
                });
            }
        }

        #[method(peripheral:didUpdateNotificationStateForCharacteristic:error:)]
        fn delegate_peripheral_didupdatenotificationstateforcharacteristic_error(
            &self,
            peripheral: &CBPeripheral,
            characteristic: &CBCharacteristic,
            _error: Option<&NSError>,
        ) {
            trace!("delegate_peripheral_didupdatenotificationstateforcharacteristic_error");
            // TODO check for error here
            let id = unsafe { peripheral.identifier() };
            let peripheral_uuid = nsuuid_to_uuid(&id);
            let service = unsafe { characteristic.service() }.unwrap();
            let raw_service_uuid = unsafe { service.UUID() };
            let service_uuid = cbuuid_to_uuid(&raw_service_uuid);
            let raw_char_uuid = unsafe { characteristic.UUID() };
            let characteristic_uuid = cbuuid_to_uuid(&raw_char_uuid);
            if unsafe { characteristic.isNotifying() } {
                self.send_event(CentralDelegateEvent::CharacteristicSubscribed {
                    peripheral_uuid,
                    service_uuid,
                    characteristic_uuid,
                });
            } else {
                self.send_event(CentralDelegateEvent::CharacteristicUnsubscribed {
                    peripheral_uuid,
                    service_uuid,
                    characteristic_uuid,
                });
            }
        }

        #[method(peripheral:didReadRSSI:error:)]
        fn delegate_peripheral_didreadrssi_error(
            &self,
            peripheral: &CBPeripheral,
            rssi: &NSNumber,
            error: Option<&NSError>,
        ) {
            trace!(
                "delegate_peripheral_didreadrssi_error {}",
                peripheral_debug(peripheral)
            );
            if error.is_none() {
                let id = unsafe { peripheral.identifier() };
                let peripheral_uuid = nsuuid_to_uuid(&id);
                let rssi_value = rssi.as_i16();
                self.send_event(CentralDelegateEvent::DidReadRssi {
                    peripheral_uuid,
                    rssi: rssi_value,
                });
            }
        }

        #[method(peripheral:didUpdateValueForDescriptor:error:)]
        fn delegate_peripheral_didupdatevaluefordescriptor_error(
            &self,
            peripheral: &CBPeripheral,
            descriptor: &CBDescriptor,
            error: Option<&NSError>,
        ) {
            trace!(
                "delegate_peripheral_didupdatevaluefordescriptor_error {} {} {}",
                peripheral_debug(peripheral),
                descriptor_debug(descriptor),
                localized_description(error)
            );
            if error.is_none() {
                let characteristic = unsafe { descriptor.characteristic() }.unwrap();
                let service = unsafe { characteristic.service() }.unwrap();
                let id = unsafe { peripheral.identifier() };
                let peripheral_uuid = nsuuid_to_uuid(&id);
                let raw_service_uuid = unsafe { service.UUID() };
                let service_uuid = cbuuid_to_uuid(&raw_service_uuid);
                let raw_char_uuid = unsafe { characteristic.UUID() };
                let characteristic_uuid = cbuuid_to_uuid(&raw_char_uuid);
                let raw_desc_uuid = unsafe { descriptor.UUID() };
                let descriptor_uuid = cbuuid_to_uuid(&raw_desc_uuid);
                self.send_event(CentralDelegateEvent::DescriptorNotified {
                    peripheral_uuid,
                    service_uuid,
                    characteristic_uuid,
                    descriptor_uuid,
                    data: get_descriptor_value(&descriptor),
                });
                // Notify BluetoothGATTCharacteristic::read_value that read was successful.
            }
        }

        #[method(peripheral:didWriteValueForDescriptor:error:)]
        fn delegate_peripheral_didwritevaluefordescriptor_error(
            &self,
            peripheral: &CBPeripheral,
            descriptor: &CBDescriptor,
            error: Option<&NSError>,
        ) {
            trace!(
                "delegate_peripheral_didwritevaluefordescriptor_error {} {} {}",
                peripheral_debug(peripheral),
                descriptor_debug(descriptor),
                localized_description(error)
            );
            if error.is_none() {
                let characteristic = unsafe { descriptor.characteristic() }.unwrap();
                let service = unsafe { characteristic.service() }.unwrap();
                let id = unsafe { peripheral.identifier() };
                let peripheral_uuid = nsuuid_to_uuid(&id);
                let raw_service_uuid = unsafe { service.UUID() };
                let service_uuid = cbuuid_to_uuid(&raw_service_uuid);
                let raw_char_uuid = unsafe { characteristic.UUID() };
                let characteristic_uuid = cbuuid_to_uuid(&raw_char_uuid);
                let raw_desc_uuid = unsafe { descriptor.UUID() };
                let descriptor_uuid = cbuuid_to_uuid(&raw_desc_uuid);
                self.send_event(CentralDelegateEvent::DescriptorWritten {
                    peripheral_uuid,
                    service_uuid,
                    characteristic_uuid,
                    descriptor_uuid,
                });
            }
        }

        #[method(peripheral:didModifyServices:)]
        fn delegate_peripheral_didmodifyservices(
            &self,
            peripheral: &CBPeripheral,
            _invalidated_services: &NSArray<CBService>,
        ) {
            trace!(
                "delegate_peripheral_didmodifyservices {}",
                peripheral_debug(peripheral),
            );
            // This is a corebluetooth-only event that makes peripheral services unusable until discovery has been performed again.
            // https://developer.apple.com/documentation/corebluetooth/cbperipheraldelegate/peripheral(_:didmodifyservices:)?language=objc
            // Trigger the removal of internal corebluetooth peripheral discovered services. It is also expected that
            // discover_services() will be performed again on the peripheral at the API level as soon as is practical.
            // NOTE: the list of modified services does not appear to be particularly useful; a full service rediscovery is needed.
            let id = unsafe { peripheral.identifier() };
            let peripheral_uuid = nsuuid_to_uuid(&id);
            self.send_event(CentralDelegateEvent::ServicesModified {
                peripheral_uuid,
            });
        }

        #[method(peripheralIsReadyToSendWriteWithoutResponse:)]
        fn delegate_peripheral_is_ready_to_send_write_without_response(
            &self,
            peripheral: &CBPeripheral,
        ) {
            trace!(
                "delegate_peripheral_is_ready_to_send_write_without_response {}",
                peripheral_debug(peripheral)
            );
            let id = unsafe { peripheral.identifier() };
            let peripheral_uuid = nsuuid_to_uuid(&id);
            self.send_event(CentralDelegateEvent::ReadyToSendWriteWithoutResponse {
                peripheral_uuid,
            });
        }
    }
);

impl CentralDelegate {
    pub fn new(sender: Sender<CentralDelegateEvent>) -> Retained<Self> {
        let this = CentralDelegate::alloc().set_ivars(sender);
        unsafe { msg_send_id![super(this), init] }
    }

    fn send_event(&self, event: CentralDelegateEvent) {
        let mut sender = self.ivars().clone();
        futures::executor::block_on(async {
            if let Err(e) = sender.send(event).await {
                error!("Error sending delegate event: {}", e);
            }
        });
    }
}

fn localized_description(error: Option<&NSError>) -> String {
    if let Some(error) = error {
        error.localizedDescription().to_string()
    } else {
        "".to_string()
    }
}

fn get_characteristic_value(characteristic: &CBCharacteristic) -> Vec<u8> {
    trace!("Getting data!");
    let v = unsafe { characteristic.value() }.map(|value| value.bytes().into());
    trace!("BluetoothGATTCharacteristic::get_value -> {:?}", v);
    v.unwrap_or_default()
}

fn get_descriptor_value(descriptor: &CBDescriptor) -> Vec<u8> {
    trace!("Getting data!");
    let v = unsafe { descriptor.value() }.map(|value| unsafe {
        let mut clazz = value.class();
        // Find the root class until we reach NSObject
        while let Some(superclass) = clazz.superclass() {
            if superclass == NSObject::class() {
                break;
            }
            clazz = superclass;
        }

        match clazz.name() {
            "NSString" => {
                let d: Retained<NSString> = Retained::cast(value);
                d.to_string().into_bytes()
            }
            "NSData" => {
                let d: Retained<NSData> = Retained::cast(value);
                d.bytes().into()
            }
            "NSNumber" => {
                let d: Retained<NSNumber> = Retained::cast(value);
                d.stringValue().to_string().into_bytes()
            }
            _ => {
                error!("Unknown descriptor value class: {:?}", clazz);
                Vec::new()
            }
        }
    });
    trace!("BluetoothGATTDescriptor::get_value -> {:?}", v);
    v.unwrap_or_default()
}

fn peripheral_debug(peripheral: &CBPeripheral) -> String {
    let uuid = unsafe { peripheral.identifier() }.UUIDString();
    match unsafe { peripheral.name() } {
        Some(name) => {
            format!("CBPeripheral({}, {})", name, uuid)
        }
        _ => {
            format!("CBPeripheral({})", uuid)
        }
    }
}

fn service_debug(service: &CBService) -> String {
    let uuid = unsafe { service.UUID().UUIDString() };
    format!("CBService({})", uuid)
}

fn characteristic_debug(characteristic: &CBCharacteristic) -> String {
    let uuid = unsafe { characteristic.UUID().UUIDString() };
    format!("CBCharacteristic({})", uuid)
}

fn descriptor_debug(descriptor: &CBDescriptor) -> String {
    let uuid = unsafe { descriptor.UUID().UUIDString() };
    format!("CBDescriptor({})", uuid)
}