Reputation: 9606
I have written some CoreBluetooth code, I can discover the devices but I seem to be unable to discover the characteristics for peripherals that I discover. Does anyone have a good sample code that I can use to verify my code?
This is what I wrote:
#import "ViewController.h"
@property(nonatomic, strong) CBCentralManager* centralmanager;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.centralmanager = [[CBCentralManager alloc] initWithDelegate:self queue:nil];
}
- (void)centralManagerDidUpdateState:(CBCentralManager *)central
{
CBCentralManagerState currentState = central.state;
NSLog(@"state %i", currentState);
switch (central.state)
{
case CBCentralManagerStatePoweredOn:
{
NSDictionary *options = @{
CBCentralManagerScanOptionAllowDuplicatesKey: @YES
};
[self.centralmanager scanForPeripheralsWithServices:nil options:options];
NSLog(@"I just started scanning for peripherals");
break;
}
}
}
- (void)centralManager:(CBCentralManager *)central
didConnectPeripheral:(CBPeripheral *)peripheral{
NSLog(@"connected!");
}
- (void) centralManager:(CBCentralManager *)central
didDiscoverPeripheral:(CBPeripheral *)peripheral
advertisementData:(NSDictionary *)advertisementData
RSSI:(NSNumber *)RSSI
{
[self.centralmanager connectPeripheral:peripheral options:nil];
if ([[advertisementData description] containsString:@“keyword”]) {
NSLog(@"peripheral count %lu", (unsigned long)[peripheral.services count]);
[peripheral.services count];
for (int i=0; [peripheral.services count]; i++) {
for (CBService *s in peripheral.services) {
[peripheral discoverCharacteristics:nil forService:s];
}
}
}
}
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error{
NSLog(@"did discover characteristic for service");
}
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSArray *)serviceUuids{
NSLog(@"discovered a peripheral's services: %@", serviceUuids);
}
Upvotes: 0
Views: 3018
Reputation: 330
Have a look here: Sample Code
Basically the process is:
Subsequently you don't have to search for and discover devices, as previously discovered devices can be retrieved from cache and connected to directly.
Edit: --------------------
Read example:
[aPeripheral readValueForCharacteristic:aChar];
Notify example:
[aPeripheral setNotifyValue:YES forCharacteristic:aChar];
Both of these calls will result in the - (void) peripheral:(CBPeripheral *)aPeripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
- function to get called when the BLE device returns a value. When using notify, this callback get called automatically every time the device updates its value for that characteristic.
Upvotes: 5