iOS蓝牙连接外设一堆代理方法的使用,在此分步骤按顺序梳理了一下,增加了接入的可读性和部分细节说明,详情会后附demo
1.初始化CBCentralManager
并设置代理<CBCentralManagerDelegate,CBPeripheralDelegate>
self.theCentral = [[CBCentralManager alloc] initWithDelegate:self queue:nil options:@{CBCentralManagerOptionShowPowerAlertKey:@(NO)}];
- options 的设置参数Tips :
@{CBCentralManagerOptionShowPowerAlertKey:@(NO)}
这样设置不会有系统的蓝牙配对弹窗
2.上面初始化设置了代理,就有代理方法监听蓝牙状态
- (void)centralManagerDidUpdateState:(CBCentralManager *)central
- 可以在这里获取到
central.state == CBManagerStatePoweredOn
时为蓝牙正常可进行下一步扫描附近蓝牙设备
3.扫描附近的蓝牙设备,当扫描到设备会进入的代理方法中
- 此方法用于搜索附近设备
[central scanForPeripheralsWithServices:nil options:@{CBCentralManagerRestoredStateScanOptionsKey:@(YES)}];
- 搜索到设备后会进入此代理方法中
- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary<NSString *,id> *)advertisementData RSSI:(NSNumber *)RSSI
- 因为此代理方法是搜到一个进一次,可以全局一个数组,往里存这些外设,刷新列表
-
[self.theCentral stopScan];
一直搜索耗电,该停时候,stopScan
方法可停车
4.选中某一个设备即可调用方法链接此外设
[self.theCentral connectPeripheral:peripheral options:nil];
5.链接成功或失败会进入对应的代理方法and断开连接时也有回调方法
- 成功
- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral
- 失败
- (void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error
- 断开连接时
- (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(nullable NSError *)error
6.接下来就进入外设内搞事情了,走外设的代理CBPeripheralDelegate,明确服务与特征
- 注意两个概念
- 服务
CBService
- 特征
CBCharacteristic
- 服务
- 在上面连接外设成功的回调里设置外设代理
- 设置代理
peripheral.delegate = self;
- 设置代理
7.调用下述方法获取此设备服务
[peripheral discoverServices:nil];
8.发现服务后进入此代理方法
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error
- 此处就要依据实际需要的文档说明服务UUID来操作了
for (CBService *service in peripheral.services) {
//遍历设备的服务,依据UUID来找到需要操作的服务
if ([service.UUID isEqual:[CBUUID UUIDWithString:@"xxxx"]]) {
//查找特征
[peripheral discoverCharacteristics:nil forService:service];
break;
}
}
9.调用下述方法获取服务下的特征
[peripheral discoverCharacteristics:nil forService:service];
10.发现特征后进入此代理方法
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(nullable NSError *)error
- 此处就要依据实际需要的文档说明特征UUID来操作了
- 一般会得到的特征会有一个读、一个写,也有可能就一个特征读写都可以
- 读特征可通过
[peripheral setNotifyValue:YES forCharacteristic:characteristic];
设置通知,数据通知会进入:didUpdateValueForCharacteristic
方法 - 写特征可调用
[peripheral writeValue:value forCharacteristic:characteristic type:CBCharacteristicWriteWithResponse];
向外设发送数据,具体咋写,得根据具体硬件文档来写
- 读特征可通过
11.监听到外设来的信息会进入此代理方法
- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
- 得到的数据包,得根据具体实际硬件文档来解析出有用信息
12.一般是先用写特征去给硬件发命令,再通过读特征的监听来获取硬件返回的数据包
小结
此为手机作为中心设备,简单完成连接蓝牙硬件外设并完成交互的步骤,详情可参见我的demo
网友评论