参考SDK:Core Bluetooth Programming Guide
1,框架总览
2,中心和外设
中心:需要数据方
外设:提供数据方
3,中心,外设,外设数据的表示
3.1 中心侧对象
3.2 外设侧对象
4,中心侧任务
4.1 建立中心管理者对象
myCentralManager =
[[CBCentralManager alloc] initWithDelegate:self queue:nil options:nil];
并且实现centralManagerDidUpdateState:代理方法,确保当前BLE设备可以支持并可以作为中心。
4.2 发现外设
[myCentralManager scanForPeripheralsWithServices:nil options:nil];
发现外设后,下面的代理方法会被调用
- (void)centralManager:(CBCentralManager *)central
didDiscoverPeripheral:(CBPeripheral *)peripheral
advertisementData:(NSDictionary *)advertisementData
RSSI:(NSNumber *)RSSI {
NSLog(@"Discovered %@", peripheral.name);
self.discoveredPeripheral = peripheral;
...
停掉扫描
[myCentralManager stopScan];
4.3 连接到外设
[myCentralManager connectPeripheral:peripheral options:nil];
连接成功后,下面的代理被调用
- (void)centralManager:(CBCentralManager *)central
didConnectPeripheral:(CBPeripheral *)peripheral {
NSLog(@"Peripheral connected");
peripheral.delegate = self;
...
4.4 搜索已连接外设的服务
[peripheral discoverServices:nil];
这样会搜索该外设上的所有可用服务,会耗费电量。可以通过制定服务的UUID来节省电量。
搜索成功后的回调:
- (void)peripheral:(CBPeripheral *)peripheral
didDiscoverServices:(NSError *)error {
for (CBService *service in peripheral.services) {
NSLog(@"Discovered service %@", service);
...
}
...
4.5 搜索服务的特性
[peripheral discoverCharacteristics:nil forService:interestingService];
回调:
- (void)peripheral:(CBPeripheral *)peripheral
didDiscoverCharacteristicsForService:(CBService *)service
error:(NSError *)error {
for (CBCharacteristic *characteristic in service.characteristics) {
NSLog(@"Discovered characteristic %@", characteristic);
...
}
...
4.6 读取特征的值
NSLog(@”Reading value for characteristic %@”, interestingCharacteristic);
[peripheral readValueForCharacteristic:interestingCharacteristic];
回调
- (void)peripheral:(CBPeripheral *)peripheral
didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic
error:(NSError *)error {
NSData *data = characteristic.value;
// parse the data as needed
...
4.7 订阅特征值
[peripheral setNotifyValue:YES forCharacteristic:interestingCharacteristic];
回调
- (void)peripheral:(CBPeripheral *)peripheral
didUpdateNotificationStateForCharacteristic:(CBCharacteristic *)characteristic
error:(NSError *)error {
if (error) {
NSLog(@"Error changing notification state: %@",
[error localizedDescription]);
}
...
4.8 写特征值
NSLog(@”Writing value for characteristic %@”, interestingCharacteristic);
[peripheral writeValue:dataToWrite forCharacteristic:interestingCharacteristic
type:CBCharacteristicWriteWithResponse];
回调
- (void)peripheral:(CBPeripheral *)peripheral
didWriteValueForCharacteristic:(CBCharacteristic *)characteristic
error:(NSError *)error {
if (error) {
NSLog(@"Error writing characteristic value: %@",
[error localizedDescription]);
}
...
5,外设侧任务
暂时省略
6,Core Bluetooth后台处理
App进入后台状态后立刻进入挂起状态,便无法接受蓝牙事件。
6.1 增加后台模式
bluetooth-centeral
bluetooth-peripheral
6.2 做负责任的后台App,尽可能少的在后台工作。
7,其他注意
iOS10之后,要在info.plist中增加NSBluetoothPeripheralUsageDescription.