经过一段长期的学习,从开始猥琐发育到最后最后终于来真泰瑞。
倒入头文件
BLE蓝牙使用的是coreBluetooth框架
#import <CoreBluetooth/CoreBluetooth.h>
创建CBCentralManager对象
CBCentralManager *centralManager = [[CBCentralManager alloc] initWithDelegate:self queue:nil];
CBCentralManagerDelegate
coreBluetooth的API大部分都是通过代理回调进行通知实现的,因此在这里首先说一下CBCentralManagerDelegate
1.- (void)centralManagerDidUpdateState:(CBCentralManager *)central;
/*!
* @method centralManagerDidUpdateState:
*
* @param central The central manager whose state has changed.
*
* @discussion Invoked whenever the central manager's state has been updated. Commands should only be issued when the state is
* <code>CBCentralManagerStatePoweredOn</code>. A state below <code>CBCentralManagerStatePoweredOn</code>
* implies that scanning has stopped and any connected peripherals have been disconnected. If the state moves below
* <code>CBCentralManagerStatePoweredOff</code>, all <code>CBPeripheral</code> objects obtained from this central
* manager become invalid and must be retrieved or discovered again.
*
* @see state
*
*/
- (void)centralManagerDidUpdateState:(CBCentralManager *)central;
翻译官方API上的意思是说central manager状态变化时被调用,其实就是在手机蓝牙开关状态变化时(由开到关,由关到开)被调用。
注意:第一次扫描蓝牙的方法一定要放在此代理方法中调用否则扫描蓝牙方法将不起作用。具体见如下代码。
- (void)centralManagerDidUpdateState:(CBCentralManager *)central {
if (central.state == CBCentralManagerStatePoweredOn) { // 当打开蓝牙开关
// 扫描外设 (此方法第一次调用必须在centralManagerDidUpdateState中调用)
[central scanForPeripheralsWithServices:nil options: nil];
} else if (central.state == CBCentralManagerStatePoweredOff) { // 当关闭蓝牙开关
// 根据你的需求做你想做的事
}
}
ok, 那么又有人说了,如果我就是不想在开启蓝牙时自动扫描呢,我想要手动点击扫描呢,怎么办,看下面:
- (void)centralManagerDidUpdateState:(CBCentralManager *)central {
if (central.state == CBCentralManagerStatePoweredOn) { // 当打开蓝牙开关
// 扫描外设 (此方法第一次调用必须在centralManagerDidUpdateState中调用)
[central scanForPeripheralsWithServices:nil options: nil];
// 停止扫描
[central stopScan];
} else if (central.state == CBCentralManagerStatePoweredOff) { // 当关闭蓝牙开关
// 根据你的需求做你想做的事
}
}
2.- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary<NSString *, id> *)advertisementData RSSI:(NSNumber *)RSSI;
当扫描到设备时,会在调用此代理方法。
扫描设备
/**
* @param serviceUUIDs A list of <code>CBUUID</code> objects representing the service(s) to scan for.
* @param options An optional dictionary specifying options for the scan.
*/
[self.centralManager scanForPeripheralsWithServices:nil options:nil];
扫描到设备回调
// 扫描到设备回调代理方法
- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary<NSString *,id> *)advertisementData RSSI:(NSNumber *)RSSI {
/**
* 两个重要参数
* @param peripheral 蓝牙外设对象,非常重要,如何重要慢慢往下看。
讲一下在这里我们利用peripheral做一些事情,比如过滤等等
* @param advertisementData 广播包,同样非常重要,这里牵扯到一个蓝牙回连的问题,会在下面讲解。
*/
}
3.- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral;
链接设备成功回调
// 蓝牙连接成功回调
- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral {
// 注:此回调方法中除了干你想干的事之外,还必须做一件非常重要的事情
/**
* 发现服务
* - (void)discoverServices:(nullable NSArray<CBUUID *> *)serviceUUIDs;
* 什么?你要问我什么是服务?我只能告诉你,你要回去好好学习一下BLE蓝牙的基本原理了:http://blog.csdn.net/xgbing/article/details/42565329
* serviceUUIDs:传什么 传你想要发现的服务数组,你可以问你的硬件同事,当然你也可以传nil来发现所有的服务
*/
[peripheral discoverServices:@[[CBUUID UUIDWithString:PVR_BLE_SERVICE_UUID]]];
peripheral.delegate = self;
}
4,- (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(nullable NSError *)error;
蓝牙中断回调
// 蓝牙链接失败回调代理方法
- (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error {
NSLog(@"%@", error);
// 做一下判断条件 这里你可以继续链接因意外中断的设备(比如拉距中断)
[central connectPeripheral:peripheral options:nil];
}
CBPeripheralDelegate
当你在didConnectPeripheral代理方法中去实现发现服务,并指定代理后,那么下面的回调就跟CBCentralManagerDelegate没关系了,你需要在CBPeripheralDelegate代理中去实现一些事情了。
1.- (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(nullable NSError *)error;
发现服务的回调,当之前调用的discoverServices方法找到服务后,会通过此代理方法回调,下面看代码。
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error
{
// 需要再调用一下discoverCharacteristics 发现特征
// 非常重要 至于你想要发现哪些特征 发现了后用来干什么 根据你的需求来
for (CBService *service in peripheral.services) {
[peripheral discoverCharacteristics:@[[CBUUID UUIDWithString:PVR_BLE_RXCHARACTERISTIC_UUID], [CBUUID UUIDWithString:PVR_BLE_TXCHARACTERISTIC_UUID]] forService:service];
}
}
2.- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(nullable NSError *)error;
发现特征的回调,如果你到了这一步,特征都被你发现了,那你离成功不远了
// 发现特征
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error {
dispatch_async(ble_queue(), ^{
for (CBCharacteristic *characteristic in [service characteristics]) {
// 读取的特征
if ([characteristic.UUID isEqual:[CBUUID UUIDWithString:PVR_BLE_RXCHARACTERISTIC_UUID]]) {
/**
* 用哪两个方法看具体情况和需求
*/
// 监听蓝牙外设特征值
[peripheral setNotifyValue:YES forCharacteristic:characteristic];
// 读取蓝牙外设特征值
[peripheral readValueForCharacteristic:characteristic];
}
// 写入的特征
if ([characteristic.UUID isEqual:[CBUUID UUIDWithString:PVR_BLE_TXCHARACTERISTIC_UUID]]) {
// 一般是在此保存写入的特征 供以后写入数据使用
self.TXCharacteristic = characteristic;
}
}
});
}
3.- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(nullable NSError *)error;
读取特征值,读取蓝牙外设的数据是通过特征值,也就是characteristic.value
// 读取特征值
- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error {
dispatch_async(ble_queue(), ^{
// 解析特征值 在这里你需要将特征值16进制的数据进行解析 下面贴出解析方法供参考
PVRCharacteristicType type = [self changeToCharacteristicTypeWithData:characteristic.value];
// 打印特征值
PVRLog(@"rx:%@", characteristic.value);
}
#pragma mark - 处理接受到的ble数据
- (PVRCharacteristicType)changeToCharacteristicTypeWithData:(NSData *)data
{
// 打问号??的就是根据特征值中的每一个字节 具体的协议外设同事会提供 按照协议解析即可
PVRCharacteristicType type = PVR_BLE_VALUE_ERROR;
// 获取data的bytes数组
Byte *byte = (Byte *)[data bytes];
if (byte[0] == 0x?? && byte[1] == 0x??) { // P-sensor
switch (byte[2]) {
case 0x??:{
type = PVR_BLE_VALUE_PSENSOR_NEAR;
self.isPsensorNear = YES;
PVRLog(@"p_sensor靠近");
break;
}
case 0x??:{
type = PVR_BLE_VALUE_PSENSOR_AWAY;
self.isPsensorNear = NO;
PVRLog(@"p_sensor远离");
break;
}
case 0x??:{
type = PVR_BLE_VALUE_PSENSOR_ERROR;
self.isPsensorNear = NO;
PVRLog(@"p_sensor出错");
break;
}
default:{
type = PVR_BLE_VALUE_ERROR;
self.isPsensorNear = NO;
PVRLog(@"键值发送错误");
break;
}
}
} else if (byte[0] == 0x?? && byte[1] == 0x??) { // Audio jack 耳机
switch (byte[2]) {
case 0x??:{
type = PVR_BLE_VALUE_AUDIO_JACK_NEAR;
PVRLog(@"插入耳机");
break;
}
case 0x??:{
type = PVR_BLE_VALUE_AUDIO_JACK_AWAY;
PVRLog(@"拔出耳机");
break;
}
case 0x??:{
type = PVR_BLE_VALUE_PSENSOR_ERROR;
PVRLog(@"p_sensor出错");
break;
}
default:{
type = PVR_BLE_VALUE_ERROR;
PVRLog(@"键值发送错误");
break;
}
}
} else if (byte[0] == 0x?? && byte[1] == 0x??) { // Audio jack 音量
type = PVR_BLE_VALUE_AUDIO_VOLUME;
self.volume = [[NSString stringWithFormat:@"%d", byte[2]] intValue];
} else if (byte[0] == 0x??) { // 触摸板 back按键
switch (byte[1]) {
case 0x??:{
type = PVR_BLE_VALUE_UPSLIDE;
PVRLog(@"向上滑动");
break;
}
case 0x??:{
type = PVR_BLE_VALUE_DOWNSLIDE;
PVRLog(@"向下滑动");
break;
}
case 0x??:{
type = PVR_BLE_VALUE_RIGHTSLIDE;
PVRLog(@"向右滑动");
break;
}
case 0x??:{
type = PVR_BLE_VALUE_LEFTSLIDE;
PVRLog(@"向左滑动");
break;
}
case 0x??:{
type = PVR_BLE_VALUE_SELECT;
PVRLog(@"点击");
break;
}
case 0x??:{
type = PVR_BLE_VALUE_SHORTBACK;
PVRLog(@"back短按");
break;
}
case 0x??:{
type = PVR_BLE_VALUE_LONGBACK;
PVRLog(@"back长按");
break;
}
default:{
type = PVR_BLE_VALUE_ERROR;
break;
}
}
} else if (byte[0] == 0x?? && byte[1] == 0x??) { // 发送MCU指令后 接受到返回信息
switch (byte[3]) {
case 0x??: {
type = PVR_BLE_VALUE_MCU_OTA;
PVRLog(@"进入OTA");
break;
}
case 0x??: {
type = PVR_BLE_VALUE_MCU_LOWELCTRICITY;
PVRLog(@"电量过低");
break;
}
}
} else if (byte[0] == 0x?? && byte[1] == 0x??) {
switch (byte[2]) {
case 0x??: { // OTA升级失败
type = PVR_BLE_VALUE_OTA_FAIL;
self.isInterruptOTA = NO;
self.errorNum = -1;
self.isOTAUpgrading = NO;
PVRLog(@"OTA升级失败");
[self.currentPeripheral writeValue:[self updateSuccessorFail] forCharacteristic:self.TXCharacteristic type:CBCharacteristicWriteWithoutResponse];
break;
}
case 0x??: { // OTA升级成功
type = PVR_BLE_VALUE_OTA_SUCCESS;
self.isInterruptOTA = NO;
self.errorNum = -1;
self.isOTAUpgrading = NO;
PVRLog(@"OTA升级成功");
[self.currentPeripheral writeValue:[self updateSuccessorFail] forCharacteristic:self.TXCharacteristic type:CBCharacteristicWriteWithoutResponse];
break;
}
case 0x??: { // 版本格式错误
type = PVR_BLE_VALUE_OTA_EDITIONERROR;
self.isInterruptOTA = NO;
self.errorNum = -1;
self.isOTAUpgrading = NO;
PVRLog(@"OTA升级版本格式错误");
[self.currentPeripheral writeValue:[self updateSuccessorFail] forCharacteristic:self.TXCharacteristic type:CBCharacteristicWriteWithoutResponse];
break;
}
case 0x??: { // Lark重启失败
type = PVR_BLE_VALUE_OTA_LARKERROR;
self.isInterruptOTA = NO;
self.errorNum = -1;
self.isOTAUpgrading = NO;
PVRLog(@"Lark重启失败");
break;
}
}
} else if (byte[0] == 0x??) { // 升级OTA错误
// 中断OTA升级
self.isInterruptOTA = YES;
// 获取错误包
byte[1] = byte[1] * 256;
NSString *byte1 = [NSString stringWithFormat:@"%d", byte[1]*256];
NSString *byte2 = [NSString stringWithFormat:@"%d", byte[2]];
int num = [byte1 intValue] + [byte2 intValue];
// 重发
self.errorNum = num;
} else if (byte[0] == 0x??) { // 软件版本查询
type = PVR_BLE_VALUE_BLE_EDITION;
NSString *versionCode = [self stringFromEditonData:data];
PVRLog(@"%@", versionCode);
} else if (byte[0] == 0x??) { // 蓝牙mac地址存储
[self saveMacAddressWithUpdateData:data];
} else if (byte[0] == 0x??) { // 打开手机摄像头
type = PVR_BLE_VALUE_OPEN_CAMERA;
} else {
return PVR_BLE_VALUE_ERROR;
}
return type;
}
👌这一步完成后,蓝牙基本的扫描 收 链接 这些基本功能就告一段落,但是这里面只提讲了“收”,发送数据还没有在此说明,将在之后的一个博客“蓝牙OTA升级”中说明。
补充两点:蓝牙回连,HID的监听
1.蓝牙回连这块,众说纷纭,有说用mac地址做唯一标识的,有说用identifier的。
首先在此说一下identifier,identifier是在CBPeripheral的父类CBPeer中的一个属性,苹果API解析说它是一个持久的 唯一的标识。但在我看来它更像是一个动态的,至少在我的外设中它是会变化(找不到变化规律),我认为它是做不了唯一标识的。
/*!
* @property identifier
*
* @discussion The unique, persistent identifier associated with the peer.
*/
@property(readonly, nonatomic) NSUUID *identifier NS_AVAILABLE(NA, 7_0);
既然identifier走不通了,那就走mac地址吧,但是我找了一些权威资料,苹果官方明确回复了mac地址是不允许被拿到的。所有这里就需要用到advertisementData(前面说过了,这个广播报会在蓝牙被扫描到时拿到)。有了这个广播报就好办了,那么接下来你需要去和你的硬件同事沟通了,让他将蓝牙的mac地址放在advertisementData广播包中,这样以来你就可以在扫描到蓝牙后,拿到它的mac地址了。但是仅仅是能拿到扫描中外设的广播报是远远不够的,因为想要回连,你需要做链接成功后去记录当前链接蓝牙的mac地址。因此你就需要去再和硬件同事去沟通了,让他们去在链接成功后,通过特征值传递给你mac地址。
2.标准键值:只要你听到你的老板或者硬件兄弟跟你说了要发送标准键值数据给你,让你来做某些事情。你直接了当告诉他,我们开发工程师收不到标准键值,因为会被系统截取,至于系统拿它们去做什么事情,也不是我们能控制的。不管安卓能怎么实现,你一定要告诉她就是完成不了,让他改成似有协议。如果老板不信也没事,看下面。
https://forums.developer.apple.com/thread/5865