btleplug 0.10.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
// 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::{
    framework::{cb, ns},
    utils::{
        core_bluetooth::{cbuuid_to_uuid, characteristic_debug, peripheral_debug, service_debug},
        nsdata_to_vec,
        nsstring::nsstring_to_string,
        nsuuid_to_uuid,
    },
};
use cocoa::base::{id, nil};
use futures::channel::mpsc::{self, Receiver, Sender};
use futures::sink::SinkExt;
use libc::c_void;
use log::{error, trace};
use objc::{
    class,
    declare::ClassDecl,
    rc::StrongPtr,
    runtime::{Class, Object, Protocol, Sel},
};
use objc::{msg_send, sel, sel_impl};
use std::convert::TryInto;
use std::{
    collections::HashMap,
    fmt::{self, Debug, Formatter},
    ops::Deref,
    slice,
    sync::Once,
};
use uuid::Uuid;

pub enum CentralDelegateEvent {
    DidUpdateState,
    DiscoveredPeripheral {
        cbperipheral: StrongPtr,
    },
    DiscoveredServices {
        peripheral_uuid: Uuid,
        /// Service UUID to CBService
        services: HashMap<Uuid, StrongPtr>,
    },
    ManufacturerData {
        peripheral_uuid: Uuid,
        manufacturer_id: u16,
        data: Vec<u8>,
    },
    ServiceData {
        peripheral_uuid: Uuid,
        service_data: HashMap<Uuid, Vec<u8>>,
    },
    Services {
        peripheral_uuid: Uuid,
        service_uuids: Vec<Uuid>,
    },
    // DiscoveredIncludedServices(Uuid, HashMap<Uuid, StrongPtr>),
    DiscoveredCharacteristics {
        peripheral_uuid: Uuid,
        service_uuid: Uuid,
        /// Characteristic UUID to CBCharacteristic
        characteristics: HashMap<Uuid, StrongPtr>,
    },
    ConnectedDevice {
        peripheral_uuid: Uuid,
    },
    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,
    },
    // TODO Deal with descriptors at some point, but not a huge worry at the moment.
    // DiscoveredDescriptors(String, )
}

impl Debug for CentralDelegateEvent {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        match self {
            CentralDelegateEvent::DidUpdateState => f.debug_tuple("DidUpdateState").finish(),
            CentralDelegateEvent::DiscoveredPeripheral { cbperipheral } => f
                .debug_struct("CentralDelegateEvent")
                .field("cbperipheral", cbperipheral.deref())
                .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::ConnectedDevice { peripheral_uuid } => f
                .debug_struct("ConnectedDevice")
                .field("peripheral_uuid", peripheral_uuid)
                .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,
            } => f
                .debug_struct("ManufacturerData")
                .field("peripheral_uuid", peripheral_uuid)
                .field("manufacturer_id", manufacturer_id)
                .field("data", data)
                .finish(),
            CentralDelegateEvent::ServiceData {
                peripheral_uuid,
                service_data,
            } => f
                .debug_struct("ServiceData")
                .field("peripheral_uuid", peripheral_uuid)
                .field("service_data", service_data)
                .finish(),
            CentralDelegateEvent::Services {
                peripheral_uuid,
                service_uuids,
            } => f
                .debug_struct("Services")
                .field("peripheral_uuid", peripheral_uuid)
                .field("service_uuids", service_uuids)
                .finish(),
        }
    }
}

pub mod CentralDelegate {
    use super::*;

    pub fn delegate() -> (id, Receiver<CentralDelegateEvent>) {
        let (sender, receiver) = mpsc::channel::<CentralDelegateEvent>(256);
        let sendbox = Box::new(sender);
        let delegate = unsafe {
            let mut delegate: id = msg_send![delegate_class(), alloc];
            delegate = msg_send![
                delegate,
                initWithSender: Box::into_raw(sendbox) as *mut c_void
            ];
            delegate
        };
        (delegate, receiver)
    }

    pub fn delegate_drop_channel(delegate: id) {
        unsafe {
            let _ = Box::from_raw(*(&*delegate).get_ivar::<*mut c_void>(DELEGATE_SENDER_IVAR)
                as *mut Sender<CentralDelegateEvent>);
        }
    }

    const DELEGATE_SENDER_IVAR: &str = "_sender";

    fn delegate_class() -> &'static Class {
        trace!("delegate_class");
        static REGISTER_DELEGATE_CLASS: Once = Once::new();
        REGISTER_DELEGATE_CLASS.call_once(|| {
            let mut decl = ClassDecl::new("BtlePlugCentralManagerDelegate", class!(NSObject)).unwrap();
            decl.add_protocol(Protocol::get("CBCentralManagerDelegate").unwrap());

            decl.add_ivar::<*mut c_void>(DELEGATE_SENDER_IVAR); /* crossbeam_channel::Sender<DelegateMessage>* */
            unsafe {
                // Initialization
                decl.add_method(sel!(initWithSender:),
                                delegate_init as extern fn(&mut Object, Sel, *mut c_void) -> id);

                // CentralManager Events
                decl.add_method(sel!(centralManagerDidUpdateState:),
                                delegate_centralmanagerdidupdatestate as extern fn(&mut Object, Sel, id));
                // decl.add_method(sel!(centralManager:willRestoreState:),
                //                 delegate_centralmanager_willrestorestate as extern fn(&mut Object, Sel, id, id));
                decl.add_method(sel!(centralManager:didConnectPeripheral:),
                                delegate_centralmanager_didconnectperipheral as extern fn(&mut Object, Sel, id, id));
                decl.add_method(sel!(centralManager:didDisconnectPeripheral:error:),
                                delegate_centralmanager_diddisconnectperipheral_error as extern fn(&mut Object, Sel, id, id, id));
                // decl.add_method(sel!(centralManager:didFailToConnectPeripheral:error:),
                //                 delegate_centralmanager_didfailtoconnectperipheral_error as extern fn(&mut Object, Sel, id, id, id));
                decl.add_method(sel!(centralManager:didDiscoverPeripheral:advertisementData:RSSI:),
                                delegate_centralmanager_diddiscoverperipheral_advertisementdata_rssi as extern fn(&mut Object, Sel, id, id, id, id));

                // Peripheral events
                decl.add_method(sel!(peripheral:didDiscoverServices:),
                                delegate_peripheral_diddiscoverservices as extern fn(&mut Object, Sel, id, id));
                decl.add_method(sel!(peripheral:didDiscoverIncludedServicesForService:error:),
                                delegate_peripheral_diddiscoverincludedservicesforservice_error as extern fn(&mut Object, Sel, id, id, id));
                decl.add_method(sel!(peripheral:didDiscoverCharacteristicsForService:error:),
                                delegate_peripheral_diddiscovercharacteristicsforservice_error as extern fn(&mut Object, Sel, id, id, id));
                // TODO Finish implementing this.
                // decl.add_method(sel!(peripheral:didDiscoverDescriptorsForCharacteristic:error:),
                //                 delegate_peripheral_diddiscoverdescriptorsforcharacteristic_error as extern fn(&mut Object, Sel, id, id, id));
                decl.add_method(sel!(peripheral:didUpdateValueForCharacteristic:error:),
                                delegate_peripheral_didupdatevalueforcharacteristic_error as extern fn(&mut Object, Sel, id, id, id));
                decl.add_method(sel!(peripheral:didUpdateNotificationStateForCharacteristic:error:),
                                delegate_peripheral_didupdatenotificationstateforcharacteristic_error as extern fn(&mut Object, Sel, id, id, id));
                decl.add_method(sel!(peripheral:didWriteValueForCharacteristic:error:),
                                delegate_peripheral_didwritevalueforcharacteristic_error as extern fn(&mut Object, Sel, id, id, id));
                decl.add_method(sel!(peripheral:didReadRSSI:error:),
                                delegate_peripheral_didreadrssi_error as extern fn(&mut Object, Sel, id, id, id));
            }

            decl.register();
        });

        class!(BtlePlugCentralManagerDelegate)
    }

    fn localized_description(error: id) -> String {
        if error == nil {
            "".to_string()
        } else {
            let nsstring = unsafe { msg_send![error, localizedDescription] };
            nsstring_to_string(nsstring).unwrap_or_else(|| "".to_string())
        }
    }

    ////////////////////////////////////////////////////////////////
    //
    // Utility functions
    //
    ////////////////////////////////////////////////////////////////

    fn delegate_get_sender_clone(delegate: &mut Object) -> Sender<CentralDelegateEvent> {
        unsafe {
            (*(*(&*delegate).get_ivar::<*mut c_void>(DELEGATE_SENDER_IVAR)
                as *mut Sender<CentralDelegateEvent>))
                .clone()
        }
    }

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

    extern "C" fn delegate_init(delegate: &mut Object, _cmd: Sel, sender: *mut c_void) -> id {
        trace!("delegate_init");
        // TODO Should these maybe be Option<T>, so we can denote when we've
        // dropped? Not quite sure how delegate lifetime works here.
        unsafe {
            trace!("Storing off ivars!");
            delegate.set_ivar(DELEGATE_SENDER_IVAR, sender);
        }
        delegate
    }

    fn get_characteristic_value(characteristic: id) -> Vec<u8> {
        trace!("Getting data!");
        let value = cb::characteristic_value(characteristic);
        let v = nsdata_to_vec(value);
        trace!("BluetoothGATTCharacteristic::get_value -> {:?}", v);
        v
    }

    ////////////////////////////////////////////////////////////////
    //
    // CentralManager Handlers
    //
    ////////////////////////////////////////////////////////////////

    extern "C" fn delegate_centralmanagerdidupdatestate(
        delegate: &mut Object,
        _cmd: Sel,
        _central: id,
    ) {
        trace!("delegate_centralmanagerdidupdatestate");
        send_delegate_event(delegate, CentralDelegateEvent::DidUpdateState);
    }

    // extern fn delegate_centralmanager_willrestorestate(_delegate: &mut Object, _cmd: Sel, _central: id, _dict: id) {
    //     trace!("delegate_centralmanager_willrestorestate");
    // }

    extern "C" fn delegate_centralmanager_didconnectperipheral(
        delegate: &mut Object,
        _cmd: Sel,
        _central: id,
        peripheral: id,
    ) {
        trace!(
            "delegate_centralmanager_didconnectperipheral {}",
            peripheral_debug(peripheral)
        );
        cb::peripheral_setdelegate(peripheral, delegate);
        cb::peripheral_discoverservices(peripheral);
        let peripheral_uuid = nsuuid_to_uuid(cb::peer_identifier(peripheral));
        send_delegate_event(
            delegate,
            CentralDelegateEvent::ConnectedDevice { peripheral_uuid },
        );
    }

    extern "C" fn delegate_centralmanager_diddisconnectperipheral_error(
        delegate: &mut Object,
        _cmd: Sel,
        _central: id,
        peripheral: id,
        _error: id,
    ) {
        trace!(
            "delegate_centralmanager_diddisconnectperipheral_error {}",
            peripheral_debug(peripheral)
        );
        let peripheral_uuid = nsuuid_to_uuid(cb::peer_identifier(peripheral));
        send_delegate_event(
            delegate,
            CentralDelegateEvent::DisconnectedDevice { peripheral_uuid },
        );
    }

    // extern fn delegate_centralmanager_didfailtoconnectperipheral_error(_delegate: &mut Object, _cmd: Sel, _central: id, _peripheral: id, _error: id) {
    //     trace!("delegate_centralmanager_didfailtoconnectperipheral_error");
    // }

    extern "C" fn delegate_centralmanager_diddiscoverperipheral_advertisementdata_rssi(
        delegate: &mut Object,
        _cmd: Sel,
        _central: id,
        peripheral: id,
        adv_data: id,
        _rssi: id,
    ) {
        trace!(
            "delegate_centralmanager_diddiscoverperipheral_advertisementdata_rssi {}",
            peripheral_debug(peripheral)
        );

        let held_peripheral = unsafe { StrongPtr::retain(peripheral) };
        send_delegate_event(
            delegate,
            CentralDelegateEvent::DiscoveredPeripheral {
                cbperipheral: held_peripheral,
            },
        );

        let peripheral_uuid = nsuuid_to_uuid(cb::peer_identifier(peripheral));

        let manufacturer_data = ns::dictionary_objectforkey(adv_data, unsafe {
            cb::ADVERTISEMENT_DATA_MANUFACTURER_DATA_KEY
        });
        if manufacturer_data != nil {
            // manufacturer_data: NSData
            let length = ns::data_length(manufacturer_data);
            if length >= 2 {
                let bytes = ns::data_bytes(manufacturer_data);
                let v = unsafe { slice::from_raw_parts(bytes, length as usize) };
                let (manufacturer_id, manufacturer_data) = v.split_at(2);

                send_delegate_event(
                    delegate,
                    CentralDelegateEvent::ManufacturerData {
                        peripheral_uuid,
                        manufacturer_id: u16::from_le_bytes(manufacturer_id.try_into().unwrap()),
                        data: Vec::from(manufacturer_data),
                    },
                );
            }
        }
        let service_data = ns::dictionary_objectforkey(adv_data, unsafe {
            cb::ADVERTISEMENT_DATA_SERVICE_DATA_KEY
        });
        if service_data != nil {
            // service_data: [CBUUID, NSData]
            let uuids = ns::dictionary_allkeys(service_data);
            let mut result = HashMap::new();
            for i in 0..ns::array_count(uuids) {
                let uuid = ns::array_objectatindex(uuids, i);
                let data = ns::dictionary_objectforkey(service_data, uuid);
                let data = nsdata_to_vec(data);
                result.insert(cbuuid_to_uuid(uuid), data);
            }

            send_delegate_event(
                delegate,
                CentralDelegateEvent::ServiceData {
                    peripheral_uuid,
                    service_data: result,
                },
            );
        }

        let services = ns::dictionary_objectforkey(adv_data, unsafe {
            cb::ADVERTISEMENT_DATA_SERVICE_UUIDS_KEY
        });
        if services != nil {
            // services: [CBUUID]
            let mut service_uuids = Vec::new();
            for i in 0..ns::array_count(services) {
                let uuid = ns::array_objectatindex(services, i);
                service_uuids.push(cbuuid_to_uuid(uuid));
            }

            send_delegate_event(
                delegate,
                CentralDelegateEvent::Services {
                    peripheral_uuid,
                    service_uuids,
                },
            );
        }
    }

    ////////////////////////////////////////////////////////////////
    //
    // Peripheral Handlers
    //
    ////////////////////////////////////////////////////////////////

    extern "C" fn delegate_peripheral_diddiscoverservices(
        delegate: &mut Object,
        _cmd: Sel,
        peripheral: id,
        error: id,
    ) {
        trace!(
            "delegate_peripheral_diddiscoverservices {} {}",
            peripheral_debug(peripheral),
            localized_description(error)
        );
        if error == nil {
            let services = cb::peripheral_services(peripheral);
            let mut service_map = HashMap::new();
            for i in 0..ns::array_count(services) {
                // get the service out of the services array
                let s = ns::array_objectatindex(services, i);

                // go ahead and ask for characteristics and other services
                cb::peripheral_discovercharacteristicsforservice(peripheral, s);
                cb::peripheral_discoverincludedservicesforservice(peripheral, s);

                // Create the map entry we'll need to export.
                let uuid = cbuuid_to_uuid(cb::attribute_uuid(s));
                let held_service;
                unsafe {
                    held_service = StrongPtr::retain(s);
                }
                service_map.insert(uuid, held_service);
            }
            let peripheral_uuid = nsuuid_to_uuid(cb::peer_identifier(peripheral));
            send_delegate_event(
                delegate,
                CentralDelegateEvent::DiscoveredServices {
                    peripheral_uuid,
                    services: service_map,
                },
            );
        }
    }

    extern "C" fn delegate_peripheral_diddiscoverincludedservicesforservice_error(
        _delegate: &mut Object,
        _cmd: Sel,
        peripheral: id,
        service: id,
        error: id,
    ) {
        trace!(
            "delegate_peripheral_diddiscoverincludedservicesforservice_error {} {} {}",
            peripheral_debug(peripheral),
            service_debug(service),
            localized_description(error)
        );
        if error == nil {
            let includes = cb::service_includedservices(service);
            for i in 0..ns::array_count(includes) {
                let s = ns::array_objectatindex(includes, i);
                cb::peripheral_discovercharacteristicsforservice(peripheral, s);
            }
        }
    }

    extern "C" fn delegate_peripheral_diddiscovercharacteristicsforservice_error(
        delegate: &mut Object,
        _cmd: Sel,
        peripheral: id,
        service: id,
        error: id,
    ) {
        trace!(
            "delegate_peripheral_diddiscovercharacteristicsforservice_error {} {} {}",
            peripheral_debug(peripheral),
            service_debug(service),
            localized_description(error)
        );
        if error == nil {
            let mut characteristics = HashMap::new();
            let chars = cb::service_characteristics(service);
            for i in 0..ns::array_count(chars) {
                let c = ns::array_objectatindex(chars, i);
                // TODO Actually implement characteristic descriptor enumeration
                // cb::peripheral_discoverdescriptorsforcharacteristic(peripheral, c);
                // Create the map entry we'll need to export.
                let uuid = cbuuid_to_uuid(cb::attribute_uuid(c));
                let held_char = unsafe { StrongPtr::retain(c) };
                characteristics.insert(uuid, held_char);
            }
            let peripheral_uuid = nsuuid_to_uuid(cb::peer_identifier(peripheral));
            let service_uuid = cbuuid_to_uuid(cb::attribute_uuid(service));
            send_delegate_event(
                delegate,
                CentralDelegateEvent::DiscoveredCharacteristics {
                    peripheral_uuid,
                    service_uuid,
                    characteristics,
                },
            );
        }
    }

    extern "C" fn delegate_peripheral_didupdatevalueforcharacteristic_error(
        delegate: &mut Object,
        _cmd: Sel,
        peripheral: id,
        characteristic: id,
        error: id,
    ) {
        trace!(
            "delegate_peripheral_didupdatevalueforcharacteristic_error {} {} {}",
            peripheral_debug(peripheral),
            characteristic_debug(characteristic),
            localized_description(error)
        );
        if error == nil {
            let service = cb::characteristic_service(characteristic);
            send_delegate_event(
                delegate,
                CentralDelegateEvent::CharacteristicNotified {
                    peripheral_uuid: nsuuid_to_uuid(cb::peer_identifier(peripheral)),
                    service_uuid: cbuuid_to_uuid(cb::attribute_uuid(service)),
                    characteristic_uuid: cbuuid_to_uuid(cb::attribute_uuid(characteristic)),
                    data: get_characteristic_value(characteristic),
                },
            );
            // Notify BluetoothGATTCharacteristic::read_value that read was successful.
        }
    }

    extern "C" fn delegate_peripheral_didwritevalueforcharacteristic_error(
        delegate: &mut Object,
        _cmd: Sel,
        peripheral: id,
        characteristic: id,
        error: id,
    ) {
        trace!(
            "delegate_peripheral_didwritevalueforcharacteristic_error {} {} {}",
            peripheral_debug(peripheral),
            characteristic_debug(characteristic),
            localized_description(error)
        );
        if error == nil {
            let service = cb::characteristic_service(characteristic);
            send_delegate_event(
                delegate,
                CentralDelegateEvent::CharacteristicWritten {
                    peripheral_uuid: nsuuid_to_uuid(cb::peer_identifier(peripheral)),
                    service_uuid: cbuuid_to_uuid(cb::attribute_uuid(service)),
                    characteristic_uuid: cbuuid_to_uuid(cb::attribute_uuid(characteristic)),
                },
            );
        }
    }

    extern "C" fn delegate_peripheral_didupdatenotificationstateforcharacteristic_error(
        delegate: &mut Object,
        _cmd: Sel,
        peripheral: id,
        characteristic: id,
        _error: id,
    ) {
        trace!("delegate_peripheral_didupdatenotificationstateforcharacteristic_error");
        // TODO check for error here
        let peripheral_uuid = nsuuid_to_uuid(cb::peer_identifier(peripheral));
        let service = cb::characteristic_service(characteristic);
        let service_uuid = cbuuid_to_uuid(cb::attribute_uuid(service));
        let characteristic_uuid = cbuuid_to_uuid(cb::attribute_uuid(characteristic));
        if cb::characteristic_isnotifying(characteristic) == objc::runtime::YES {
            send_delegate_event(
                delegate,
                CentralDelegateEvent::CharacteristicSubscribed {
                    peripheral_uuid,
                    service_uuid,
                    characteristic_uuid,
                },
            );
        } else {
            send_delegate_event(
                delegate,
                CentralDelegateEvent::CharacteristicUnsubscribed {
                    peripheral_uuid,
                    service_uuid,
                    characteristic_uuid,
                },
            );
        }
    }

    // extern fn delegate_peripheral_diddiscoverdescriptorsforcharacteristic_error(_delegate: &mut Object, _cmd: Sel, _peripheral: id, _characteristic: id, _error: id) {
    //     info!("delegate_peripheral_diddiscoverdescriptorsforcharacteristic_error");
    // }

    // extern fn delegate_peripheral_didupdatevaluefordescriptor(_delegate: &mut Object, _cmd: Sel, _peripheral: id, _descriptor: id, _error: id) {
    //     trace!("delegate_peripheral_didupdatevaluefordescriptor");
    // }

    // extern fn delegate_peripheral_didwritevaluefordescriptor_error(_delegate: &mut Object, _cmd: Sel, _peripheral: id, _descriptor: id, _error: id) {
    //     trace!("delegate_peripheral_didwritevaluefordescriptor_error");
    // }

    extern "C" fn delegate_peripheral_didreadrssi_error(
        _delegate: &mut Object,
        _cmd: Sel,
        peripheral: id,
        _rssi: id,
        error: id,
    ) {
        trace!(
            "delegate_peripheral_didreadrssi_error {}",
            peripheral_debug(peripheral)
        );
        if error == nil {}
    }
}