iOS 蓝牙开发和注意点

前言

  • 蓝牙传输所用的框架是<CoreBluetooth/CoreBluetooth.h>
  • 蓝牙链接须要中心管理者和外部设备,咱们所作的开发基本是围绕中心管理来的;
  • 蓝牙设备发过来的每一个数据包,为了保证数据在传输的时候没有丢失,通常须要包头,包尾,校验和
  • 有不少蓝牙协议很复杂,须要把数据转化成二进制进行转化解析,对于高字节,低字节,小端模式,大端模式,符号位,位运算这些基本概念须要了解清楚

1.关于Mac地址的获取

自iOS7以后,苹果不支持获取Mac地址,只能用UUID来标识设备,要注意的是同一个设备在不一样手机上显示的UUID不相同,但有的设备能够经过 “180A”这个服务来发现特征,再来读取 “2A23”这个特征值,能够得到Mac地址。若是你的蓝牙设备不支持这样获取,你能够跟硬件工程师沟通,来得到Mac地址,添加一个获取地址命令或者增长一个含地址的特征值均可以很容易的获取。上面获取地址的前提都是须要先创建链接,若是必定要在扫描的时候得到Mac地址,让硬件工程师把数据写入广播包里,看是否可行;git

2.蓝牙链接流程

若是你不是新手,又不想浪费时间,请直接看第三点 注意点,核心部分github

  • 创建中心设备管理者
  • 扫描外设
  • 链接外设
  • 扫描外设中的服务
  • 扫描外设中的特征
  • 订阅或读取特征值
  • 获取外设中的数据

创建中心设备管理者

// 建立以后会立刻检查蓝牙的状态,nil默认为主线程
self.centralManager = [[CBCentralManager alloc] initWithDelegate:self queue:nil]

蓝牙线程不必去开异步线程,在主线程消耗不了什么性能数组

扫描外设

// 蓝牙状态发生改变,这个方法必定要实现
- (void)centralManagerDidUpdateState:(CBCentralManager *)central
{
    // 蓝牙状态可用
    if (central.state == CBCentralManagerStatePoweredOn) {

        // 若是蓝牙支持后台模式,必定要指定服务,不然在后台断开链接不上,若是不支持,可设为nil, option里的CBCentralManagerScanOptionAllowDuplicatesKey默认为NO, 若是设置为YES,容许搜索到重名,会很耗电
        [self.centralManager scanForPeripheralsWithServices:@[[CBUUID UUIDWithString:kServiceUUID]] options:nil];
    }
}

链接外设

/**
 * 发现设备
 * @param peripheral 设备
 * @param advertisementData 广播内容
 * @param RSSI 信号强度
 */
- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary<NSString *,id> *)advertisementData RSSI:(NSNumber *)RSSI
{
    // 判断是不是你须要链接的设备
    if ([peripheral.name isEqualToString:kPeripheralName]) {
        peripheral.delegate = self;
        // 必定要记得把外设保存起来
        self.selectedPeripheral = peripheral;
        // 开始链接设备
        [self.centralManager connectPeripheral:self.selectedPeripheral options:nil];
    }
}

扫描外设中的服务

/**
 * 已经链接上设备
 */
- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral
{
    // 中止扫描
    [self.centralManager stopScan];
    // 发现服务
    [self.selectedPeripheral discoverServices:nil];
}

扫描外设中的特征

/**
 * 已经发现服务
 */
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error
{
    for (CBService *service in peripheral.services) {
        if ([service.UUID isEqual:[CBUUID UUIDWithString:kServiceUUID]]) {
            // 根据你要的那个服务去发现特性
            [self.selectedPeripheral discoverCharacteristics:nil forService:service];
        }

        // 这里我是根据 180A 用来获取Mac地址,没什么实际做用,可删掉
        if ([service.UUID isEqual:[CBUUID UUIDWithString:@"180A"]]) {
            [self.selectedPeripheral discoverCharacteristics:nil forService:service];
        }
    }
}

订阅或读取特征值

/**
 * 已经发现特性
 */
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error
{
    for (CBCharacteristic *characteristic in service.characteristics) {
        if ([characteristic.UUID isEqual:[CBUUID UUIDWithString:@"2A23"]]) {
            // 这里是读取Mac地址, 可不要, 数据固定, 用readValueForCharacteristic, 不用setNotifyValue:setNotifyValue
            [self.selectedPeripheral readValueForCharacteristic:characteristic];
        }


        if ([characteristic.UUID isEqual:[CBUUID UUIDWithString:kCharacteristicUUID]]) {
            // 订阅特性,当数据频繁改变时,通常用它, 不用readValueForCharacteristic
            [peripheral setNotifyValue:YES forCharacteristic:characteristic];

            // 获取电池电量
            unsigned char send[4] = {0x5d, 0x08, 0x01, 0x3b};
            NSData *sendData = [NSData dataWithBytes:send length:4];

            // 这里的type类型有两种 CBCharacteristicWriteWithResponse CBCharacteristicWriteWithoutResponse,它的属性枚举能够组合
            [self.selectedPeripheral writeValue:sendData forCharacteristic:characteristic type:CBCharacteristicWriteWithoutResponse];

            /*
             characteristic 属性
             typedef NS_OPTIONS(NSUInteger, CBCharacteristicProperties) {
             CBCharacteristicPropertyBroadcast                                                = 0x01,
             CBCharacteristicPropertyRead                                                    = 0x02,
             CBCharacteristicPropertyWriteWithoutResponse                                    = 0x04,
             CBCharacteristicPropertyWrite                                                    = 0x08,
             CBCharacteristicPropertyNotify                                                    = 0x10,
             CBCharacteristicPropertyIndicate                                                = 0x20,
             CBCharacteristicPropertyAuthenticatedSignedWrites                                = 0x40,
             CBCharacteristicPropertyExtendedProperties                                        = 0x80,
             CBCharacteristicPropertyNotifyEncryptionRequired NS_ENUM_AVAILABLE(NA, 6_0)        = 0x100,
             CBCharacteristicPropertyIndicateEncryptionRequired NS_ENUM_AVAILABLE(NA, 6_0)    = 0x200
             };
             */

            NSLog(@"%@",characteristic);
            // 打印结果为 <CBCharacteristic: 0x1702a2a00, UUID = FFF6, properties = 0x16, value = (null), notifying = NO>

            //  个人结果 为 0x16  (0x08 & 0x16)结果不成立, (0x04 & 0x16)结果成立,那写入类型就是 CBCharacteristicPropertyWriteWithoutResponse
        }
    }
}

获取外设中的数据

/**
 * 数据更新的回调
 */
- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
{
    // 这里收到的数据都是16进制,有两种转换,一种就直接转字符串,另外一种是转byte数组,看用哪一种方便

    // 直接转字符串
    NSString *orStr = characteristic.value.description;
    NSString *str = [orStr substringWithRange:NSMakeRange(1, orStr.length - 2)];
    NSString *dataStr = [str stringByReplacingOccurrencesOfString:@" " withString:@""];
    NSLog(@"dataStr = %@",dataStr);

    // 转Byte数组
    Byte *byte = (Byte *)characteristic.value.bytes;

    //_______________________________________________________________________________________________________________
    // 解析你的协议,附几个解协议或许能用到的函数
}

设备链接断开

- (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error
{
    // 让它自动重连
    [self.centralManager scanForPeripheralsWithServices:@[[CBUUID UUIDWithString:kServiceUUID]] options:nil];
}

这是系统代理方法,若是要主动断开须要调用 - (void)cancelPeripheralConnection:(CBPeripheral *)peripheral; 这个方法框架

写入数据成功的回调

- (void)peripheral:(CBPeripheral *)peripheral didWriteValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
{
        // 读取数据
    [self.selectedPeripheral readValueForCharacteristic:characteristic];
}

若是类型是CBCharacteristicWriteWithoutResponse,不会走这个方法;异步

3.注意点,核心部分,请仔细看

  1. 作蓝牙前必定要去商城下个LightBlue,一个设备有不少服务,服务中又有不少特性,特性中又分读的,写的等,有了LightBlue,你能够很快的找到你须要的特性;函数


    LightBlue截图


    从上图中咱们能够清晰的看到每一个服务中又多少个特性,特性的属性Read、Write、Write Without Response、Notify等也标明的很清楚,工具

  2. 通常的蓝牙都要支持重连和后台运行,若是扫描设备的时候,用这个方法- (void)scanForPeripheralsWithServices:options:没有指定特定的服务,而是用nil代替,设备在后台断开的时候是不会重连的;性能

  3. 蓝牙是能够同时链接多个外部设备ui

  4. 关于readValueForCharacteristicsetNotifyValue:forCharacteristic: 的区别, readValueForCharacteristic适合用来读取数据不怎么更新的特征值, 若是获取的数据是常常更新的,那就 必定要用setNotifyValue:forCharacteristic:来订阅这个特征;线程

  5. 当咱们写入命令时writeValue:forCharacteristic:type:,这个type类型到时是用CBCharacteristicWriteWithResponse仍是用CBCharacteristicWriteWithoutResponse会有疑惑,先看一下特性属性的枚举,它们是能够组合的

    /*
          typedef NS_OPTIONS(NSUInteger, CBCharacteristicProperties) {
          CBCharacteristicPropertyBroadcast                                                = 0x01,
          CBCharacteristicPropertyRead                                                    = 0x02,
          CBCharacteristicPropertyWriteWithoutResponse                                    = 0x04,
          CBCharacteristicPropertyWrite                                                    = 0x08,
          CBCharacteristicPropertyNotify                                                    = 0x10,
          CBCharacteristicPropertyIndicate                                                = 0x20,
          CBCharacteristicPropertyAuthenticatedSignedWrites                                = 0x40,
          CBCharacteristicPropertyExtendedProperties                                        = 0x80,
          CBCharacteristicPropertyNotifyEncryptionRequired NS_ENUM_AVAILABLE(NA, 6_0)        = 0x100,
          CBCharacteristicPropertyIndicateEncryptionRequired NS_ENUM_AVAILABLE(NA, 6_0)    = 0x200
          };

    再来看看我打印的两个特征值,第一个是获取Mac地址的特性,另外一个是获取数据的特性
    <CBCharacteristic: 0x1700b8ae0, UUID = System ID, properties = 0x2, value = (null), notifying = NO>
    <CBCharacteristic: 0x1702a2a00, UUID = FFF6, properties = 0x16, value = (null), notifying = NO>
    第一个0x2对应只可读, 第二个 (0x16 & 0x08)不成立,(0x16 & 0x04)成立,因此用CBCharacteristicWriteWithoutResponse,并且这个特征值还可读,能够通知

  6. 代理方法- (void)centralManagerDidUpdateState:(CBCentralManager *)central;必定要调用,不然会报错,这个方法只要设置中心设备的代理以后,就必定会走,咱们最开始的扫描外设应放在这个方法里;

  7. 对因而否要单首创建一个工具类来获取蓝牙数据,若是只是一个界面须要用到蓝牙数据,我以为彻底不必,若是是多个界面的话,最好仍是建立一个工具类。

  8. 若是蓝牙支持要支持后台模式,只须要去把蓝牙后台模式打开


    后台运行蓝牙


    记住只要勾选Uses Bluetooth LE accessories就好了,别勾选Acts As a Bluetooth LE accessory,除非你把你的手机当作外部设备使用;

简单又详细的Demo地址

 
做者:alenpaulkevin连接:http://www.jianshu.com/p/0ccfd53fc559來源:简书著做权归做者全部。商业转载请联系做者得到受权,非商业转载请注明出处。
相关文章
相关标签/搜索