iOS BLE开发

经过一段长期的学习,从开始猥琐发育到最后最后终于来真泰瑞。

倒入头文件

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

屏幕快照 2016-11-30 上午10.06.07.png

总结:“没啥说的” “ 没啥说的你说了吗”
guy
guy
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 200,045评论 5 468
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 84,114评论 2 377
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 147,120评论 0 332
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,902评论 1 272
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,828评论 5 360
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,132评论 1 277
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,590评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,258评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,408评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,335评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,385评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,068评论 3 315
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,660评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,747评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,967评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,406评论 2 346
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,970评论 2 341

推荐阅读更多精彩内容