iOS蓝牙开发,踩过的坑

作者: 沙克阿拉卡 | 来源:发表于2020-07-15 20:00 被阅读0次

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

一、特定的使用场景

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];
}

相关文章

  • iOS蓝牙开发,踩过的坑

    近五年做的项目都是和蓝牙有关,网上关于蓝牙开发的文章也比比皆是。此文只是记录我司在实际工作中遇到的一些特定的应用场...

  • Android零散技术点

    Android BLE 蓝牙开发入门 逐步指导新手进行 Android ble 蓝牙的开发,避免踩坑。Androi...

  • iOS-蓝牙4.0开发(踩过的坑)

    前言 来公司整整一年了,做得项目全部涉及蓝牙。坑应该给我踩得差不多了吧,但是一直没有做记录,今天就好好地回顾下项目...

  • iOS 开发踩过的坑

    1、navigationBar的透明问题 如果仅仅把navigationBar的alpha设为0的话,那就相当于把...

  • Android之音频焦点

    Android之音频焦点 车机开发很多应用涉及到音频,音频焦点踩过很多坑,也填过很多坑,蓝牙,多媒体音视频,ipo...

  • iOS开发笔记

    原文请见github上iOS开发笔记 iOS开发笔记 记录了在iOS开发中踩过的坑和一些问题解决 微信的openi...

  • iOS 蓝牙4.0开发踩坑总结

    蓝牙基础 IOS中关于蓝牙的框架其实有四个: (1)GameKit.framework 根据名称我们可以猜出,这是...

  • 【Objective-c】_蓝牙开发

    ios蓝牙开发学习笔记(一)蓝牙概述 ios蓝牙开发学习笔记(二)central角色的实现 ios蓝牙开发学习笔记...

  • iOS 蓝牙开发(框架集成和数据交互)

    最近几个月都在做蓝牙的项目,趁现在有空,就把在蓝牙开发过程中的心得和踩过的坑给记录下来,分享给大家,避免大家在蓝牙...

  • iOS 蓝牙开发(固件升级&空中升级)

    最近几个月都在做蓝牙的项目,趁现在有空,就把在蓝牙开发过程中的心得和踩过的坑给记录下来,分享给大家,避免大家在蓝牙...

网友评论

    本文标题:iOS蓝牙开发,踩过的坑

    本文链接:https://www.haomeiwen.com/subject/sxgjhktx.html