iOS蓝牙开发,踩过的坑

       近五年做的项目都是和蓝牙有关,网上关于蓝牙开发的文章也比比皆是。此文只是记录我司在实际工作中遇到的一些特定的应用场景和解决小技巧,并对网络上通用的开发技术流程的梳理总结。记录以备回顾,也分享欢迎交流。

一、特定的使用场景

1、蓝牙外设设备升级等,大数据传输,耗时操作

        数据发送时选择CBCharacteristicWriteWithResponse,会影响总交互时间, 使用CBCharacteristicWriteWithoutResponse又回出现丢包的现象。
[self.peripheral writeValue:data forCharacteristic:self.characteristic type:CBCharacteristicWriteWithResponse];
[self.peripheral writeValue:data forCharacteristic:self.characteristic type:CBCharacteristicWriteWithResponse];
       如果交互的总时间我们不能接受,可以选用CBCharacteristicWriteWithoutResponse模式每包20字节循环发,但注意每发12包延迟100毫秒(经验值,12包240字节小于250),即可加快大数据传输速率。此方法也分享给使用我司外设硬件的客户(多为政企,银行),截止目前iOS13,屡试不爽。

2、需要蓝牙传输在后台进行

       我们蓝牙开发为了能使app在后台运行时依旧保持与外设的连接,就需要在工程目录下的 info.plist 文件中, iOS9及其以前的做法:新建一行 Required background modes , 加入下面两项。
App shares data using CoreBluetooth
App communicates using CoreBluetooth
       高版本的XCode直接在项目的Capablities中,在Background Modes下添加Uses Bluetooth LE accessories即可

3、连接断开后,在后台再次扫描周围设备再完成重连。

       后台扫描设备跟前台扫描周围设备有一点不同:
       也许是考虑到功耗的原因,在后台只能搜索特定的设备,所以必须要传Service UUID。不传的 话一台设备都搜不到。而这时就需要外设在广播包中有Service UUID,需要广播包中含有。

4、首次使用APP时候扫描设备,并显示出每台设备的mac地址,点击设备进行绑定。后续直接链接绑定的设备。

       此场景Andriod可以做到,iOS不可以,是由于iOS端扫描到的设备对象获取不到mac地址,需要连接上设备获取服务和 特征值后才能得到mac地址。解决方法可以让硬件工程师在广播的时候添加mac地址,如果不然,只能逐个连接断开尝试,获取匹配的mac值。
最后我们硬件工程师在广播包中添加了设备序列号。根据序列号区分蓝牙设备。毕竟序列号区别于mac地址,用户看起来更直观。

另:推荐LightBlue App,基于CoreBluetooth。是BLE开发的调试利器,该App上能获取的数据,你就能用代码实现,软硬件工程师蓝牙开发必备。

二、CoreBluetooth框架使用

       目前蓝牙智能硬件主流都是低功耗的蓝牙4.0技术,由于耗电低,也称作为BLE(Bluetooth Low Energy)),对应iOS的系统库是<CoreBluetooth/CoreBluetooth.h>。另外一种是基于Wi-Fi的连接方式,很少见。我们的设备都是BLE设备,以下介绍为CoreBluetooth框架。

核心概念:

  • CBCentralManager: 外部设备管理者
  • CBPeripheral: 连接的外部设备
  • CBService: 设备携带的服务
  • CBCharacteristic: 服务中包含的特征值

使用流程:

创建一个CBCentralManager实例
扫描外围设备
连接扫描到的设备
获得连接设备的服务
获得服务的特征值
从外围设备读取数据
向外围设备写入(发送)数据

三、代码实现:

1. 初始化

#import <CoreBluetooth/CoreBluetooth.h>
self.centralManager = [[CBCentralManager alloc] initWithDelegate:self
    queue:nil];

2. 搜索扫描外围设备

/**
* 初始化成功自动调用
* 必须实现的代理,用来返回创建的centralManager的状态。
* CBCentralManagerStatePoweredOn状态才可以扫描到外设:
*/
- (void)centralManagerDidUpdateState:(CBCentralManager *)central{
    switch (central.state) {
        case CBCentralManagerStateUnknown:
            NSLog(@">>>CBCentralManagerStateUnknown");
            break;
        case CBCentralManagerStateResetting:
            NSLog(@">>>CBCentralManagerStateResetting");
            break;
        case CBCentralManagerStateUnsupported:
            NSLog(@">>>CBCentralManagerStateUnsupported");
            break;
        case CBCentralManagerStateUnauthorized:
            NSLog(@">>>CBCentralManagerStateUnauthorized");
            break;
        case CBCentralManagerStatePoweredOff:
            NSLog(@">>>CBCentralManagerStatePoweredOff");
            break;
        case CBCentralManagerStatePoweredOn:
            {
                NSLog(@">>>CBCentralManagerStatePoweredOn");
                /**开始扫描周围的外设。
                * 第一个参数是用来扫描有指定服务的外设。
                * 传nil表示扫描所有外设。成功扫描到外设后调用didDiscoverPeripheral
                 * */
                [self.centralManager scanForPeripheralsWithServices:nil options:nil];
            }
            break;
        default:
            break;
        }
    }

#pragma mark 发现外设

- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary<NSString *,id> *)advertisementData RSSI:(NSNumber *)RSSI{
    NSLog(@"Find device:%@", [peripheral name]);
    if (![_deviceDic objectForKey:[peripheral name]]) {
         NSLog(@"Find device:%@", [peripheral name]);
        if (peripheral!=nil) {
            if ([peripheral name]!=nil) {
                if ([[peripheral name] hasPrefix:@"过滤"]) {
                    //连接外设
                    [self.centralManager connectPeripheral:peripheral options:nil];
                 }
             }
         }
     }
}

3.连接外围设备

- (void)connectDeviceWithPeripheral:(CBPeripheral *)peripheral
{
    [self.centralManager connectPeripheral:peripheral options:nil];
}

#pragma mark 连接成功回调

- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral{

    [central stopScan];
    peripheral.delegate = self;
    self.peripheral = peripheral;
    /**
     *外设的服务、特征、描述等方法是CBPeripheralDelegate的内容,
     *所以要先设置代理peripheral.delegate = self
     *参数表示你要的服务的UUID,nil表示扫描所有服务。
     *成功发现服务,回调didDiscoverServices
     */
     [peripheral discoverServices:@[[CBUUID UUIDWithString:@"服务UUID"]]];
}

#pragma mark 连接失败回调

- (void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error{
    NSLog(@"%@", error);
}

#pragma mark 取消与外设的连接回调

- (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error{
     NSLog(@"%@", peripheral);
}

4. 获得外围设备的服务

#pragma mark 发现服务回调

- (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error{

     CBService * __nullable findService = nil;
    // 遍历服务
     for (CBService *service in peripheral.services)
     {
         if ([[service UUID] isEqual:[CBUUID UUIDWithString:@"服务UUID"]])
        {
            findService = service;
        }
     }
     if (findService)
         [peripheral discoverCharacteristics:NULL forService:findService];
}

5、获得服务的特征;

#pragma mark 发现特征回调
/**发现特征后,可以根据特征的properties进行:
 *读readValueForCharacteristic、写writeValue、订阅通知setNotifyValue、
 *扫描特征的描述discoverDescriptorsForCharacteristic
 */
- (void)peripheral:(CBPeripheral *)peripheraldidDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error{
    for (CBCharacteristic *characteristic in service.characteristics) {
        if ([characteristic.UUID isEqual:[CBUUID UUIDWithString:@"特征UUID"]]) {
            //读取成功回调didUpdateValueForCharacteristic
             self.characteristic = characteristic;
            //接收一次
            //[peripheral readValueForCharacteristic:characteristic];
            //订阅, 实时接收
             [peripheral setNotifyValue:YES forCharacteristic:characteristic];=
            // 发送下行数据
            NSData *data = [@"带发送的数据"dataUsingEncoding:NSUTF8StringEncoding];
            [self.peripheral writeValue:data forCharacteristic:characteristic type:CBCharacteristicWriteWithResponse];
        }
         //当发现characteristic有descriptor,回调didDiscoverDescriptorsForCharacteristic
         [peripheral discoverDescriptorsForCharacteristic:characteristic];
     }
}

6.从外围设备读取数据

#pragma mark - 获取数据

- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error{
    NSData *data = [characteristic.value dataUsingEncoding:NSUTF8StringEncoding];
}

#pragma mark - 读取外设实时数据

- (void)peripheral:(CBPeripheral *)peripheraldidUpdateNotificationStateForCharacteristic:(CBCharacteristic *)characteristicerror:(NSError *)error{
     if (characteristic.isNotifying) {
         [peripheral readValueForCharacteristic:characteristic];
     } 
     else {
        //这里出错 一般是连接断开了
         NSLog(@"%@", characteristic);
        [self.centralManager cancelPeripheralConnection:peripheral];
     }
}

7. 给外围设备发送(写入)数据

/** 根据获取到的外围设备的写的服务特征值 向蓝牙设备发送数据
 *蓝牙发送数据长度为20字节,待发送数据大于20字节需要分包发送,
 *特别长的数据耗时较长,解决办法在文章的开始
 */
- (void)sendData
{
     NSData *data = [@"待发送数据" dataUsingEncoding:NSUTF8StringEncoding];
     [self.peripheral writeValue:data forCharacteristic:self.characteristic type:CBCharacteristicWriteWithResponse];
}

#pragma mark 数据写入成功回调

- (void)peripheral:(CBPeripheral *)peripheral didWriteValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error{
    NSLog(@"写入成功");
}

8. 停止扫描、断开连接

#pragma mark 断开连接
- (void)disConnectPeripheral{
     /**断开连接后回调didDisconnectPeripheral
      *注意断开后如果要重新扫描这个外设,
      *需要重新调用[self.centralManager scanForPeripheralsWithServices:nil options:nil];
      */
     [self.centralManager cancelPeripheralConnection:self.peripheral];
}

- (void)scanDevice
{
    if (_centralManager == nil) {
        self.centralManager = [[CBCentralManager alloc] initWithDelegate:selfqueue:nil];
         [_deviceDic removeAllObjects];
    }
}

#pragma mark 停止扫描外设

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