forked from pauldemarco/flutter_blue
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFlutterBluePlugin.m
753 lines (694 loc) · 33.9 KB
/
FlutterBluePlugin.m
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
// Copyright 2017, Paul DeMarco.
// All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
#import "FlutterBluePlugin.h"
#import "Flutterblue.pbobjc.h"
@interface CBUUID (CBUUIDAdditionsFlutterBlue)
- (NSString *)fullUUIDString;
@end
@implementation CBUUID (CBUUIDAdditionsFlutterBlue)
- (NSString *)fullUUIDString {
if(self.UUIDString.length == 4) {
return [[NSString stringWithFormat:@"0000%@-0000-1000-8000-00805F9B34FB", self.UUIDString] lowercaseString];
}
return [self.UUIDString lowercaseString];
}
@end
typedef NS_ENUM(NSUInteger, LogLevel) {
emergency = 0,
alert = 1,
critical = 2,
error = 3,
warning = 4,
notice = 5,
info = 6,
debug = 7
};
@interface FlutterBluePlugin ()
@property(nonatomic, retain) NSObject<FlutterPluginRegistrar> *registrar;
@property(nonatomic, retain) FlutterMethodChannel *channel;
@property(nonatomic, retain) FlutterBlueStreamHandler *stateStreamHandler;
@property(nonatomic, retain) FlutterBlueStreamHandler *scanResultStreamHandler;
@property(nonatomic, retain) FlutterBlueStreamHandler *servicesDiscoveredStreamHandler;
@property(nonatomic, retain) FlutterBlueStreamHandler *characteristicReadStreamHandler;
@property(nonatomic, retain) FlutterBlueStreamHandler *descriptorReadStreamHandler;
@property(nonatomic, retain) CBCentralManager *centralManager;
@property(nonatomic) NSMutableDictionary *scannedPeripherals;
@property(nonatomic) NSMutableArray *servicesThatNeedDiscovered;
@property(nonatomic) NSMutableArray *characteristicsThatNeedDiscovered;
@property(nonatomic) LogLevel logLevel;
@end
@implementation FlutterBluePlugin
+ (void)registerWithRegistrar:(NSObject<FlutterPluginRegistrar>*)registrar {
FlutterMethodChannel* channel = [FlutterMethodChannel
methodChannelWithName:NAMESPACE @"/methods"
binaryMessenger:[registrar messenger]];
FlutterEventChannel* stateChannel = [FlutterEventChannel eventChannelWithName:NAMESPACE @"/state" binaryMessenger:[registrar messenger]];
FlutterEventChannel* scanResultChannel = [FlutterEventChannel eventChannelWithName:NAMESPACE @"/scanResult" binaryMessenger:[registrar messenger]];
FlutterEventChannel* servicesDiscoveredChannel = [FlutterEventChannel eventChannelWithName:NAMESPACE @"/servicesDiscovered" binaryMessenger:[registrar messenger]];
FlutterEventChannel* characteristicReadChannel = [FlutterEventChannel eventChannelWithName:NAMESPACE @"/characteristicRead" binaryMessenger:[registrar messenger]];
FlutterEventChannel* descriptorReadChannel = [FlutterEventChannel eventChannelWithName:NAMESPACE @"/descriptorRead" binaryMessenger:[registrar messenger]];
FlutterBluePlugin* instance = [[FlutterBluePlugin alloc] init];
instance.channel = channel;
instance.centralManager = [[CBCentralManager alloc] initWithDelegate:instance queue:nil];
instance.scannedPeripherals = [NSMutableDictionary new];
instance.servicesThatNeedDiscovered = [NSMutableArray new];
instance.characteristicsThatNeedDiscovered = [NSMutableArray new];
instance.logLevel = emergency;
// STATE
FlutterBlueStreamHandler* stateStreamHandler = [[FlutterBlueStreamHandler alloc] init];
[stateChannel setStreamHandler:stateStreamHandler];
instance.stateStreamHandler = stateStreamHandler;
// SCAN RESULTS
FlutterBlueStreamHandler* scanResultStreamHandler = [[FlutterBlueStreamHandler alloc] init];
[scanResultChannel setStreamHandler:scanResultStreamHandler];
instance.scanResultStreamHandler = scanResultStreamHandler;
// SERVICES DISCOVERED
FlutterBlueStreamHandler* servicesDiscoveredStreamHandler = [[FlutterBlueStreamHandler alloc] init];
[servicesDiscoveredChannel setStreamHandler:servicesDiscoveredStreamHandler];
instance.servicesDiscoveredStreamHandler = servicesDiscoveredStreamHandler;
// CHARACTERISTIC READ
FlutterBlueStreamHandler* characteristicReadStreamHandler = [[FlutterBlueStreamHandler alloc] init];
[characteristicReadChannel setStreamHandler:characteristicReadStreamHandler];
instance.characteristicReadStreamHandler = characteristicReadStreamHandler;
// DESCRIPTOR READ
FlutterBlueStreamHandler* descriptorReadStreamHandler = [[FlutterBlueStreamHandler alloc] init];
[descriptorReadChannel setStreamHandler:descriptorReadStreamHandler];
instance.descriptorReadStreamHandler = descriptorReadStreamHandler;
[registrar addMethodCallDelegate:instance channel:channel];
}
- (void)handleMethodCall:(FlutterMethodCall*)call result:(FlutterResult)result {
if ([@"setLogLevel" isEqualToString:call.method]) {
NSNumber *logLevelIndex = [call arguments];
_logLevel = (LogLevel)[logLevelIndex integerValue];
result(nil);
} else if ([@"state" isEqualToString:call.method]) {
FlutterStandardTypedData *data = [self toFlutterData:[self toBluetoothStateProto:self->_centralManager.state]];
result(data);
} else if([@"isAvailable" isEqualToString:call.method]) {
if(self.centralManager.state != CBManagerStateUnsupported && self.centralManager.state != CBManagerStateUnknown) {
result(@(YES));
} else {
result(@(NO));
}
} else if([@"isOn" isEqualToString:call.method]) {
if(self.centralManager.state == CBManagerStatePoweredOn) {
result(@(YES));
} else {
result(@(NO));
}
} else if([@"startScan" isEqualToString:call.method]) {
// Clear any existing scan results
[self.scannedPeripherals removeAllObjects];
// TODO: Request Permission?
FlutterStandardTypedData *data = [call arguments];
ProtosScanSettings *request = [[ProtosScanSettings alloc] initWithData:[data data] error:nil];
// UUID Service filter
NSArray *uuids = [NSArray array];
for (int i = 0; i < [request serviceUuidsArray_Count]; i++) {
NSString *u = [request.serviceUuidsArray objectAtIndex:i];
uuids = [uuids arrayByAddingObject:[CBUUID UUIDWithString:u]];
}
// TODO: iOS Scan Options (#35)
[self->_centralManager scanForPeripheralsWithServices:uuids options:nil];
result(nil);
} else if([@"stopScan" isEqualToString:call.method]) {
[self->_centralManager stopScan];
result(nil);
} else if([@"connect" isEqualToString:call.method]) {
FlutterStandardTypedData *data = [call arguments];
ProtosConnectRequest *request = [[ProtosConnectRequest alloc] initWithData:[data data] error:nil];
NSString *remoteId = [request remoteId];
@try {
CBPeripheral *peripheral = [_scannedPeripherals objectForKey:remoteId];
if(peripheral == nil) {
@throw [FlutterError errorWithCode:@"connect"
message:@"Peripheral not found"
details:nil];
}
// TODO: Implement Connect options (#36)
[_centralManager connectPeripheral:peripheral options:nil];
result(nil);
} @catch(FlutterError *e) {
result(e);
}
} else if([@"disconnect" isEqualToString:call.method]) {
NSString *remoteId = [call arguments];
@try {
CBPeripheral *peripheral = [self findPeripheral:remoteId];
[_centralManager cancelPeripheralConnection:peripheral];
result(nil);
} @catch(FlutterError *e) {
result(e);
}
} else if([@"deviceState" isEqualToString:call.method]) {
NSString *remoteId = [call arguments];
@try {
CBPeripheral *peripheral = [self findPeripheral:remoteId];
result([self toFlutterData:[self toDeviceStateProto:peripheral state:peripheral.state]]);
} @catch(FlutterError *e) {
result(e);
}
} else if([@"discoverServices" isEqualToString:call.method]) {
NSString *remoteId = [call arguments];
@try {
CBPeripheral *peripheral = [self findPeripheral:remoteId];
// Clear helper arrays
[_servicesThatNeedDiscovered removeAllObjects];
[_characteristicsThatNeedDiscovered removeAllObjects ];
[peripheral discoverServices:nil];
result(nil);
} @catch(FlutterError *e) {
result(e);
}
} else if([@"services" isEqualToString:call.method]) {
NSString *remoteId = [call arguments];
@try {
CBPeripheral *peripheral = [self findPeripheral:remoteId];
result([self toFlutterData:[self toServicesResultProto:peripheral]]);
} @catch(FlutterError *e) {
result(e);
}
} else if([@"readCharacteristic" isEqualToString:call.method]) {
FlutterStandardTypedData *data = [call arguments];
ProtosReadCharacteristicRequest *request = [[ProtosReadCharacteristicRequest alloc] initWithData:[data data] error:nil];
NSString *remoteId = [request remoteId];
@try {
// Find peripheral
CBPeripheral *peripheral = [self findPeripheral:remoteId];
// Find characteristic
CBCharacteristic *characteristic = [self locateCharacteristic:[request characteristicUuid] peripheral:peripheral serviceId:[request serviceUuid] secondaryServiceId:[request secondaryServiceUuid]];
// Trigger a read
[peripheral readValueForCharacteristic:characteristic];
result(nil);
} @catch(FlutterError *e) {
result(e);
}
} else if([@"readDescriptor" isEqualToString:call.method]) {
FlutterStandardTypedData *data = [call arguments];
ProtosReadDescriptorRequest *request = [[ProtosReadDescriptorRequest alloc] initWithData:[data data] error:nil];
NSString *remoteId = [request remoteId];
@try {
// Find peripheral
CBPeripheral *peripheral = [self findPeripheral:remoteId];
// Find characteristic
CBCharacteristic *characteristic = [self locateCharacteristic:[request characteristicUuid] peripheral:peripheral serviceId:[request serviceUuid] secondaryServiceId:[request secondaryServiceUuid]];
// Find descriptor
CBDescriptor *descriptor = [self locateDescriptor:[request descriptorUuid] characteristic:characteristic];
[peripheral readValueForDescriptor:descriptor];
result(nil);
} @catch(FlutterError *e) {
result(e);
}
} else if([@"writeCharacteristic" isEqualToString:call.method]) {
FlutterStandardTypedData *data = [call arguments];
ProtosWriteCharacteristicRequest *request = [[ProtosWriteCharacteristicRequest alloc] initWithData:[data data] error:nil];
NSString *remoteId = [request remoteId];
@try {
// Find peripheral
CBPeripheral *peripheral = [self findPeripheral:remoteId];
// Find characteristic
CBCharacteristic *characteristic = [self locateCharacteristic:[request characteristicUuid] peripheral:peripheral serviceId:[request serviceUuid] secondaryServiceId:[request secondaryServiceUuid]];
// Get correct write type
CBCharacteristicWriteType type = ([request writeType] == ProtosWriteCharacteristicRequest_WriteType_WithoutResponse) ? CBCharacteristicWriteWithoutResponse : CBCharacteristicWriteWithResponse;
// Write to characteristic
[peripheral writeValue:[request value] forCharacteristic:characteristic type:type];
result(nil);
} @catch(FlutterError *e) {
result(e);
}
} else if([@"writeDescriptor" isEqualToString:call.method]) {
FlutterStandardTypedData *data = [call arguments];
ProtosWriteDescriptorRequest *request = [[ProtosWriteDescriptorRequest alloc] initWithData:[data data] error:nil];
NSString *remoteId = [request remoteId];
@try {
// Find peripheral
CBPeripheral *peripheral = [self findPeripheral:remoteId];
// Find characteristic
CBCharacteristic *characteristic = [self locateCharacteristic:[request characteristicUuid] peripheral:peripheral serviceId:[request serviceUuid] secondaryServiceId:[request secondaryServiceUuid]];
// Find descriptor
CBDescriptor *descriptor = [self locateDescriptor:[request descriptorUuid] characteristic:characteristic];
// Write descriptor
[peripheral writeValue:[request value] forDescriptor:descriptor];
result(nil);
} @catch(FlutterError *e) {
result(e);
}
} else if([@"setNotification" isEqualToString:call.method]) {
FlutterStandardTypedData *data = [call arguments];
ProtosSetNotificationRequest *request = [[ProtosSetNotificationRequest alloc] initWithData:[data data] error:nil];
NSString *remoteId = [request remoteId];
@try {
// Find peripheral
CBPeripheral *peripheral = [self findPeripheral:remoteId];
// Find characteristic
CBCharacteristic *characteristic = [self locateCharacteristic:[request characteristicUuid] peripheral:peripheral serviceId:[request serviceUuid] secondaryServiceId:[request secondaryServiceUuid]];
// Set notification value
[peripheral setNotifyValue:[request enable] forCharacteristic:characteristic];
result(nil);
} @catch(FlutterError *e) {
result(e);
}
} else {
result(FlutterMethodNotImplemented);
}
}
- (CBPeripheral*)findPeripheral:(NSString*)remoteId {
NSArray<CBPeripheral*> *peripherals = [_centralManager retrievePeripheralsWithIdentifiers:@[[[NSUUID alloc] initWithUUIDString:remoteId]]];
CBPeripheral *peripheral;
for(CBPeripheral *p in peripherals) {
if([[p.identifier UUIDString] isEqualToString:remoteId]) {
peripheral = p;
break;
}
}
if(peripheral == nil) {
@throw [FlutterError errorWithCode:@"findPeripheral"
message:@"Peripheral not found"
details:nil];
}
return peripheral;
}
- (CBCharacteristic*)locateCharacteristic:(NSString*)characteristicId peripheral:(CBPeripheral*)peripheral serviceId:(NSString*)serviceId secondaryServiceId:(NSString*)secondaryServiceId {
CBService *primaryService = [self getServiceFromArray:serviceId array:[peripheral services]];
if(primaryService == nil || [primaryService isPrimary] == false) {
@throw [FlutterError errorWithCode:@"locateCharacteristic"
message:@"service could not be located on the device"
details:nil];
}
CBService *secondaryService;
if(secondaryServiceId.length) {
secondaryService = [self getServiceFromArray:secondaryServiceId array:[primaryService includedServices]];
@throw [FlutterError errorWithCode:@"locateCharacteristic"
message:@"secondary service could not be located on the device"
details:secondaryServiceId];
}
CBService *service = (secondaryService != nil) ? secondaryService : primaryService;
CBCharacteristic *characteristic = [self getCharacteristicFromArray:characteristicId array:[service characteristics]];
if(characteristic == nil) {
@throw [FlutterError errorWithCode:@"locateCharacteristic"
message:@"characteristic could not be located on the device"
details:nil];
}
return characteristic;
}
- (CBDescriptor*)locateDescriptor:(NSString*)descriptorId characteristic:(CBCharacteristic*)characteristic {
CBDescriptor *descriptor = [self getDescriptorFromArray:descriptorId array:[characteristic descriptors]];
if(descriptor == nil) {
@throw [FlutterError errorWithCode:@"locateDescriptor"
message:@"descriptor could not be located on the device"
details:nil];
}
return descriptor;
}
// Reverse search to find primary service
- (CBService*)findPrimaryService:(CBService*)secondaryService peripheral:(CBPeripheral*)peripheral {
for(CBService *s in [peripheral services]) {
for(CBService *ss in [s includedServices]) {
if([[ss.UUID UUIDString] isEqualToString:[secondaryService.UUID UUIDString]]) {
return s;
}
}
}
return nil;
}
- (CBDescriptor*)findCCCDescriptor:(CBCharacteristic*)characteristic {
for(CBDescriptor *d in characteristic.descriptors) {
if([d.UUID.UUIDString isEqualToString:@"2902"]) {
return d;
}
}
return nil;
}
- (CBService*)getServiceFromArray:(NSString*)uuidString array:(NSArray<CBService*>*)array {
for(CBService *s in array) {
if([[s UUID] isEqual:[CBUUID UUIDWithString:uuidString]]) {
return s;
}
}
return nil;
}
- (CBCharacteristic*)getCharacteristicFromArray:(NSString*)uuidString array:(NSArray<CBCharacteristic*>*)array {
for(CBCharacteristic *c in array) {
if([[c UUID] isEqual:[CBUUID UUIDWithString:uuidString]]) {
return c;
}
}
return nil;
}
- (CBDescriptor*)getDescriptorFromArray:(NSString*)uuidString array:(NSArray<CBDescriptor*>*)array {
for(CBDescriptor *d in array) {
if([[d UUID] isEqual:[CBUUID UUIDWithString:uuidString]]) {
return d;
}
}
return nil;
}
//
// CBCentralManagerDelegate methods
//
- (void)centralManagerDidUpdateState:(nonnull CBCentralManager *)central {
if(_stateStreamHandler.sink != nil) {
FlutterStandardTypedData *data = [self toFlutterData:[self toBluetoothStateProto:self->_centralManager.state]];
self.stateStreamHandler.sink(data);
}
}
- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary<NSString *,id> *)advertisementData RSSI:(NSNumber *)RSSI {
[self.scannedPeripherals setObject:peripheral
forKey:[[peripheral identifier] UUIDString]];
if(_scanResultStreamHandler.sink != nil) {
FlutterStandardTypedData *data = [self toFlutterData:[self toScanResultProto:peripheral advertisementData:advertisementData RSSI:RSSI]];
_scanResultStreamHandler.sink(data);
}
}
- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral {
NSLog(@"didConnectPeripheral");
// Register self as delegate for peripheral
peripheral.delegate = self;
// Send connection state
[_channel invokeMethod:@"DeviceState" arguments:[self toFlutterData:[self toDeviceStateProto:peripheral state:peripheral.state]]];
}
- (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error {
NSLog(@"didDisconnectPeripheral");
// Unregister self as delegate for peripheral, not working #42
peripheral.delegate = nil;
// Send connection state
[_channel invokeMethod:@"DeviceState" arguments:[self toFlutterData:[self toDeviceStateProto:peripheral state:peripheral.state]]];
}
- (void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error {
// TODO:?
}
//
// CBPeripheralDelegate methods
//
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error {
NSLog(@"didDiscoverServices");
// Loop through and discover characteristics and secondary services
[_servicesThatNeedDiscovered addObjectsFromArray:peripheral.services];
for(CBService *s in [peripheral services]) {
NSLog(@"Found service: %@", [s.UUID UUIDString]);
[peripheral discoverCharacteristics:nil forService:s];
// [peripheral discoverIncludedServices:nil forService:s]; // Secondary services in the future (#8)
}
}
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error {
NSLog(@"didDiscoverCharacteristicsForService");
// Loop through and discover descriptors for characteristics
[_servicesThatNeedDiscovered removeObject:service];
[_characteristicsThatNeedDiscovered addObjectsFromArray:service.characteristics];
for(CBCharacteristic *c in [service characteristics]) {
[peripheral discoverDescriptorsForCharacteristic:c];
}
}
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverDescriptorsForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error {
NSLog(@"didDiscoverDescriptorsForCharacteristic");
[_characteristicsThatNeedDiscovered removeObject:characteristic];
if(_servicesThatNeedDiscovered.count > 0 || _characteristicsThatNeedDiscovered.count > 0) {
// Still discovering
return;
}
// Send updated tree
if(_servicesDiscoveredStreamHandler.sink != nil) {
ProtosDiscoverServicesResult *result = [self toServicesResultProto:peripheral];
_servicesDiscoveredStreamHandler.sink([self toFlutterData:result]);
}
}
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverIncludedServicesForService:(CBService *)service error:(NSError *)error {
NSLog(@"didDiscoverIncludedServicesForService");
// Loop through and discover characteristics for secondary services
for(CBService *ss in [service includedServices]) {
[peripheral discoverCharacteristics:nil forService:ss];
}
}
- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error {
NSLog(@"didUpdateValueForCharacteristic %@", [peripheral.identifier UUIDString]);
if(_characteristicReadStreamHandler.sink != nil) {
ProtosReadCharacteristicResponse *result = [[ProtosReadCharacteristicResponse alloc] init];
[result setRemoteId:[peripheral.identifier UUIDString]];
[result setCharacteristic:[self toCharacteristicProto:characteristic]];
_characteristicReadStreamHandler.sink([self toFlutterData:result]);
}
// on iOS, this method also handle notification values
ProtosOnNotificationResponse *result = [[ProtosOnNotificationResponse alloc] init];
[result setRemoteId:[peripheral.identifier UUIDString]];
[result setCharacteristic:[self toCharacteristicProto:characteristic]];
[_channel invokeMethod:@"OnValueChanged" arguments:[self toFlutterData:result]];
}
- (void)peripheral:(CBPeripheral *)peripheral didWriteValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error {
NSLog(@"didWriteValueForCharacteristic");
ProtosWriteCharacteristicRequest *request = [[ProtosWriteCharacteristicRequest alloc] init];
[request setRemoteId:[peripheral.identifier UUIDString]];
[request setCharacteristicUuid:[characteristic.UUID fullUUIDString]];
[request setServiceUuid:[characteristic.service.UUID fullUUIDString]];
ProtosWriteCharacteristicResponse *result = [[ProtosWriteCharacteristicResponse alloc] init];
[result setRequest:request];
[result setSuccess:(error == nil)];
[_channel invokeMethod:@"WriteCharacteristicResponse" arguments:[self toFlutterData:result]];
}
- (void)peripheral:(CBPeripheral *)peripheral didUpdateNotificationStateForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error {
NSLog(@"didUpdateNotificationStateForCharacteristic");
// Read CCC descriptor of characteristic
CBDescriptor *cccd = [self findCCCDescriptor:characteristic];
if(cccd == nil || error != nil) {
// Send error
ProtosSetNotificationResponse *response = [[ProtosSetNotificationResponse alloc] init];
[response setRemoteId:[peripheral.identifier UUIDString]];
[response setCharacteristic:[self toCharacteristicProto:characteristic]];
[response setSuccess:false];
[_channel invokeMethod:@"SetNotificationResponse" arguments:[self toFlutterData:response]];
return;
}
// Request a read
[peripheral readValueForDescriptor:cccd];
}
- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForDescriptor:(CBDescriptor *)descriptor error:(NSError *)error {
if(_descriptorReadStreamHandler.sink != nil) {
ProtosReadDescriptorRequest *q = [[ProtosReadDescriptorRequest alloc] init];
[q setRemoteId:[peripheral.identifier UUIDString]];
[q setCharacteristicUuid:[descriptor.characteristic.UUID fullUUIDString]];
[q setDescriptorUuid:[descriptor.UUID fullUUIDString]];
if([descriptor.characteristic.service isPrimary]) {
[q setServiceUuid:[descriptor.characteristic.service.UUID fullUUIDString]];
} else {
[q setSecondaryServiceUuid:[descriptor.characteristic.service.UUID fullUUIDString]];
CBService *primaryService = [self findPrimaryService:[descriptor.characteristic service] peripheral:[descriptor.characteristic.service peripheral]];
[q setServiceUuid:[primaryService.UUID fullUUIDString]];
}
ProtosReadDescriptorResponse *result = [[ProtosReadDescriptorResponse alloc] init];
[result setRequest:q];
int value = [descriptor.value intValue];
[result setValue:[NSData dataWithBytes:&value length:sizeof(value)]];
_descriptorReadStreamHandler.sink([self toFlutterData:result]);
}
// If descriptor is CCCD, send a SetNotificationResponse in case anything is awaiting
if([descriptor.UUID.UUIDString isEqualToString:@"2902"]){
ProtosSetNotificationResponse *response = [[ProtosSetNotificationResponse alloc] init];
[response setRemoteId:[peripheral.identifier UUIDString]];
[response setCharacteristic:[self toCharacteristicProto:descriptor.characteristic]];
[response setSuccess:true];
[_channel invokeMethod:@"SetNotificationResponse" arguments:[self toFlutterData:response]];
}
}
- (void)peripheral:(CBPeripheral *)peripheral didWriteValueForDescriptor:(CBDescriptor *)descriptor error:(NSError *)error {
ProtosWriteDescriptorRequest *request = [[ProtosWriteDescriptorRequest alloc] init];
[request setRemoteId:[peripheral.identifier UUIDString]];
[request setCharacteristicUuid:[descriptor.characteristic.UUID fullUUIDString]];
[request setDescriptorUuid:[descriptor.UUID fullUUIDString]];
if([descriptor.characteristic.service isPrimary]) {
[request setServiceUuid:[descriptor.characteristic.service.UUID fullUUIDString]];
} else {
[request setSecondaryServiceUuid:[descriptor.characteristic.service.UUID fullUUIDString]];
CBService *primaryService = [self findPrimaryService:[descriptor.characteristic service] peripheral:[descriptor.characteristic.service peripheral]];
[request setServiceUuid:[primaryService.UUID fullUUIDString]];
}
ProtosWriteDescriptorResponse *result = [[ProtosWriteDescriptorResponse alloc] init];
[result setRequest:request];
[result setSuccess:(error == nil)];
[_channel invokeMethod:@"WriteDescriptorResponse" arguments:[self toFlutterData:result]];
}
//
// Proto Helper methods
//
- (FlutterStandardTypedData*)toFlutterData:(GPBMessage*)proto {
FlutterStandardTypedData *data = [FlutterStandardTypedData typedDataWithBytes:[[proto data] copy]];
return data;
}
- (ProtosBluetoothState*)toBluetoothStateProto:(CBManagerState)state {
ProtosBluetoothState *result = [[ProtosBluetoothState alloc] init];
switch(state) {
case CBManagerStateResetting:
[result setState:ProtosBluetoothState_State_TurningOn];
break;
case CBManagerStateUnsupported:
[result setState:ProtosBluetoothState_State_Unavailable];
break;
case CBManagerStateUnauthorized:
[result setState:ProtosBluetoothState_State_Unauthorized];
break;
case CBManagerStatePoweredOff:
[result setState:ProtosBluetoothState_State_Off];
break;
case CBManagerStatePoweredOn:
[result setState:ProtosBluetoothState_State_On];
break;
default:
[result setState:ProtosBluetoothState_State_Unknown];
break;
}
return result;
}
- (ProtosScanResult*)toScanResultProto:(CBPeripheral *)peripheral advertisementData:(NSDictionary<NSString *,id> *)advertisementData RSSI:(NSNumber *)RSSI {
ProtosScanResult *result = [[ProtosScanResult alloc] init];
[result setDevice:[self toDeviceProto:peripheral]];
[result setRssi:[RSSI intValue]];
ProtosAdvertisementData *ads = [[ProtosAdvertisementData alloc] init];
[ads setConnectable:[advertisementData[CBAdvertisementDataIsConnectable] boolValue]];
[ads setLocalName:advertisementData[CBAdvertisementDataLocalNameKey]];
// Tx Power Level
NSNumber *txPower = advertisementData[CBAdvertisementDataTxPowerLevelKey];
if(txPower != nil) {
ProtosInt32Value *txPowerWrapper = [[ProtosInt32Value alloc] init];
[txPowerWrapper setValue:[txPower intValue]];
[ads setTxPowerLevel:txPowerWrapper];
}
// Manufacturer Specific Data
NSData *manufData = advertisementData[CBAdvertisementDataManufacturerDataKey];
if(manufData.length > 2) {
unsigned short manufacturerId;
[manufData getBytes:&manufacturerId length:2];
[[ads manufacturerData] setObject:[manufData subdataWithRange:NSMakeRange(2, manufData.length - 2)] forKey:manufacturerId];
}
// Service Data
NSDictionary *serviceData = advertisementData[CBAdvertisementDataServiceDataKey];
for (CBUUID *uuid in serviceData) {
[[ads serviceData] setObject:serviceData[uuid] forKey:uuid.UUIDString];
}
// Service Uuids
NSArray *serviceUuids = advertisementData[CBAdvertisementDataServiceUUIDsKey];
for (CBUUID *uuid in serviceUuids) {
[[ads serviceUuidsArray] addObject:uuid.UUIDString];
}
[result setAdvertisementData:ads];
return result;
}
- (ProtosBluetoothDevice*)toDeviceProto:(CBPeripheral *)peripheral {
ProtosBluetoothDevice *result = [[ProtosBluetoothDevice alloc] init];
[result setName:[peripheral name]];
[result setRemoteId:[[peripheral identifier] UUIDString]];
[result setType:ProtosBluetoothDevice_Type_Le]; // TODO: Does iOS differentiate?
return result;
}
- (ProtosDeviceStateResponse*)toDeviceStateProto:(CBPeripheral *)peripheral state:(CBPeripheralState)state {
ProtosDeviceStateResponse *result = [[ProtosDeviceStateResponse alloc] init];
switch(state) {
case CBPeripheralStateDisconnected:
[result setState:ProtosDeviceStateResponse_BluetoothDeviceState_Disconnected];
break;
case CBPeripheralStateConnecting:
[result setState:ProtosDeviceStateResponse_BluetoothDeviceState_Connecting];
break;
case CBPeripheralStateConnected:
[result setState:ProtosDeviceStateResponse_BluetoothDeviceState_Connected];
break;
case CBPeripheralStateDisconnecting:
[result setState:ProtosDeviceStateResponse_BluetoothDeviceState_Disconnecting];
break;
}
[result setRemoteId:[[peripheral identifier] UUIDString]];
return result;
}
- (ProtosDiscoverServicesResult*)toServicesResultProto:(CBPeripheral *)peripheral {
ProtosDiscoverServicesResult *result = [[ProtosDiscoverServicesResult alloc] init];
[result setRemoteId:[peripheral.identifier UUIDString]];
NSMutableArray *servicesProtos = [NSMutableArray new];
for(CBService *s in [peripheral services]) {
[servicesProtos addObject:[self toServiceProto:peripheral service:s]];
}
[result setServicesArray:servicesProtos];
return result;
}
- (ProtosBluetoothService*)toServiceProto:(CBPeripheral *)peripheral service:(CBService *)service {
ProtosBluetoothService *result = [[ProtosBluetoothService alloc] init];
NSLog(@"peripheral uuid:%@", [peripheral.identifier UUIDString]);
NSLog(@"service uuid:%@", [service.UUID fullUUIDString]);
[result setRemoteId:[peripheral.identifier UUIDString]];
[result setUuid:[service.UUID fullUUIDString]];
[result setIsPrimary:[service isPrimary]];
// Characteristic Array
NSMutableArray *characteristicProtos = [NSMutableArray new];
for(CBCharacteristic *c in [service characteristics]) {
[characteristicProtos addObject:[self toCharacteristicProto:c]];
}
[result setCharacteristicsArray:characteristicProtos];
// Included Services Array
NSMutableArray *includedServicesProtos = [NSMutableArray new];
for(CBService *s in [service includedServices]) {
[includedServicesProtos addObject:[self toServiceProto:peripheral service:s]];
}
[result setIncludedServicesArray:includedServicesProtos];
return result;
}
- (ProtosBluetoothCharacteristic*)toCharacteristicProto:(CBCharacteristic *)characteristic {
ProtosBluetoothCharacteristic *result = [[ProtosBluetoothCharacteristic alloc] init];
[result setUuid:[characteristic.UUID fullUUIDString]];
[result setProperties:[self toCharacteristicPropsProto:characteristic.properties]];
[result setValue:[characteristic value]];
NSLog(@"uuid: %@ value: %@", [characteristic.UUID fullUUIDString], [characteristic value]);
NSMutableArray *descriptorProtos = [NSMutableArray new];
for(CBDescriptor *d in [characteristic descriptors]) {
[descriptorProtos addObject:[self toDescriptorProto:d]];
}
[result setDescriptorsArray:descriptorProtos];
if([characteristic.service isPrimary]) {
[result setServiceUuid:[characteristic.service.UUID fullUUIDString]];
} else {
// Reverse search to find service and secondary service UUID
[result setSecondaryServiceUuid:[characteristic.service.UUID fullUUIDString]];
CBService *primaryService = [self findPrimaryService:[characteristic service] peripheral:[characteristic.service peripheral]];
[result setServiceUuid:[primaryService.UUID fullUUIDString]];
}
return result;
}
- (ProtosBluetoothDescriptor*)toDescriptorProto:(CBDescriptor *)descriptor {
ProtosBluetoothDescriptor *result = [[ProtosBluetoothDescriptor alloc] init];
[result setUuid:[descriptor.UUID fullUUIDString]];
[result setCharacteristicUuid:[descriptor.characteristic.UUID fullUUIDString]];
[result setServiceUuid:[descriptor.characteristic.service.UUID fullUUIDString]];
int value = [descriptor.value intValue];
[result setValue:[NSData dataWithBytes:&value length:sizeof(value)]];
return result;
}
- (ProtosCharacteristicProperties*)toCharacteristicPropsProto:(CBCharacteristicProperties)props {
ProtosCharacteristicProperties *result = [[ProtosCharacteristicProperties alloc] init];
[result setBroadcast:(props & CBCharacteristicPropertyBroadcast) != 0];
[result setRead:(props & CBCharacteristicPropertyRead) != 0];
[result setWriteWithoutResponse:(props & CBCharacteristicPropertyWriteWithoutResponse) != 0];
[result setWrite:(props & CBCharacteristicPropertyWrite) != 0];
[result setNotify:(props & CBCharacteristicPropertyNotify) != 0];
[result setIndicate:(props & CBCharacteristicPropertyIndicate) != 0];
[result setAuthenticatedSignedWrites:(props & CBCharacteristicPropertyAuthenticatedSignedWrites) != 0];
[result setExtendedProperties:(props & CBCharacteristicPropertyExtendedProperties) != 0];
[result setNotifyEncryptionRequired:(props & CBCharacteristicPropertyNotifyEncryptionRequired) != 0];
[result setIndicateEncryptionRequired:(props & CBCharacteristicPropertyIndicateEncryptionRequired) != 0];
return result;
}
- (void)log:(LogLevel)level format:(NSString *)format, ... {
if(level <= _logLevel) {
va_list args;
va_start(args, format);
// NSString* formattedMessage = [[NSString alloc] initWithFormat:format arguments:args];
NSLog(format, args);
va_end(args);
}
}
@end
@implementation FlutterBlueStreamHandler
- (FlutterError*)onListenWithArguments:(id)arguments eventSink:(FlutterEventSink)eventSink {
self.sink = eventSink;
return nil;
}
- (FlutterError*)onCancelWithArguments:(id)arguments {
self.sink = nil;
return nil;
}
@end