iOS 蓝牙浅析

作者: captain_Lu | 来源:发表于2016-08-05 18:05 被阅读619次

    概述

    iOS中提供了4个框架用于实现蓝牙连接

    • 1.GameKit.framework(用法简单)

      • 只能用于iOS设备之间的同个应用内连接,多用于游戏(eg.拳皇,棋牌类),从iOS7开始过期
    • 2.MultipeerConnectivity.framework(代替1)

      • 只能用于iOS设备之间的连接,从iOS7开始引入,主要用于非联网状态下,通过wifi或者蓝牙进行文件共享(仅限于沙盒的文件),多用于附近无网聊天
    • 3.ExternalAccessory.framework(MFi)

      • 可用于第三方蓝牙设备交互,但是蓝牙设备必须经过苹果MFi认证(国内很少)
    • 4.CoreBluetooth.framework(时下热门)

      • 可用于第三方蓝牙设备交互,必须要支持蓝牙4.0
      • 硬件至少是4s,系统至少是iOS6
      • 蓝牙4.0以低功耗著称,一般也叫BLE(Bluetooth Low Energy)
      • 目前应用比较多的案例:运动手环,嵌入式设备,智能家居

    设计到的系统/框架

    • HealthKit/物联网HomeKit/wathOS1,2/iBeacon
      注 如果需要使用homekit进行开发的话,协议必须是https,https消耗性能很厉害,因此对硬件的要求相对就比较高

    重点讲解CoreBluetooth

    • BLE:(Bluetooth low energy)蓝牙4.0设备因为低耗电,也叫BLE
    • peripheral,central:外设和中心设备,发起链接的是central(一般是指手机app),被链接的设备是peripheral(运动手环)
    • service and characteristic:(服务和特征)每个设备会提供服务和特征,类似于服务端的API,但是结构不同.每个设备会有很多服务,每个服务中包含很多字段,这些字段的权限一般分为读(read),写(write),通知(notify)几种,就是我们连接设备后具体需要操作的内容
    • Description:每个characteristic可以对应一个或者多个Description用于描述characteristic的信息或属性(eg.范围,计量单位)

    蓝牙基础知识

    • CoreBluetooth框架的核心其实是俩东西:peripheral和central,对应他们分别有一组相关的API和类


      ble_01.png
    • 这两组api分别对应不同的业务常见:左侧叫中心模式,就是以你的app作为中心,连接其他的外设的场景;而右侧称为外设模式,使用手机作为外设连接其他中心设备操作的场景,左侧为一般公司所采取的开发模式
    • 服务和特征(service and characteristic)
    • 每个设备都会有1个or多个服务
    • 每个服务里都会有1个or多个特征
    • 特征就是具体键值对,提供数据的地方
    • 每个特征属性分为:读,写,通知等等

    BLE中心模式流程

    • 1.建立中心角色
    • 2.扫描外设(Discover Peripheral)
    • 3.连接外设(Connect Peripheral)
    • 4.扫描外设中的服务和特征(Discover Services And Characteristics)
    • 4.1 获取外设的services
    • 4.2 获取外设的Characteristics,获取characteristics的值,,获取Characteristics的Descriptor和Descriptor的值
    • 5.利用特征与外设做数据交互(Explore And Interact)
    • 6.订阅Characteristic的通知
    • 7.断开连接(Disconnect)

    蓝牙设备的状态

    • 1.待机状态(standby):设备没有传输和发送数据,并且没有连接到任何外设
    • 2.广播状态(Advertiser):周期性广播状态
      3.扫描状态(Scanner):主动搜索正在广播的设备
      4.发起链接状态(Initiator):主动向扫描设备发起连接
      5.主设备(Master):作为主设备连接到其它设备.
      6.从设备(Slave):作为从设备链接到其它设备

    蓝牙和版本使用限制

    蓝牙2.0:越狱设备
    BLE:iOS6以上
    MFI认证设备:无限制

    中心模式流程

    • 1.建立中心角色
    • 2.扫描外设(Discover Peripheral)
    • 3.连接外设(Connect Peripheral)
    • 4.扫描外设中的服务和特征(Discover Services And Characteristics)
    • 4.1 获取外设的services
    • 4.2 获取外设的Characteristics,获取characteristics的值,,获取Characteristics的Descriptor和Descriptor的值
    • 5.利用特征与外设做数据交互(Explore And Interact)
    • 6.订阅Characteristic的通知
    • 7.断开连接(Disconnect)
    1.建立中心角色

    导入头文件

    #import <CoreBluetooth/CoreBluetooth.h>
    

    创建中心设备管理者

    - (CBCentralManager *)manager
    {
        if (_manager == nil) {
            _manager = [[CBCentralManager alloc]initWithDelegate:self queue:dispatch_get_main_queue() options:nil];
            _manager.delegate = self;
        }
        return _manager;
    }
    
    2.扫描外设(Discover Peripheral)

    只有设备成功打开,才能开始扫描,否则会报错

    /**
     *  中心管理者状态改变, 在初始化CBCentralManager的时候会打开设备,只有当设备正确打开后才能使用
     *
     *  @param central 中心管理设备
     */
    - (void)centralManagerDidUpdateState:(CBCentralManager *)central
    {
        //    CBCentralManagerStateUnknown = 0,
        //    CBCentralManagerStateResetting,
        //    CBCentralManagerStateUnsupported,
        //    CBCentralManagerStateUnauthorized,
        //    CBCentralManagerStatePoweredOff,
        //    CBCentralManagerStatePoweredOn,
        switch (central.state) {
            case CBCentralManagerStateUnknown:
                break;
            case CBCentralManagerStateResetting:
                break;
            case CBCentralManagerStateUnsupported:
                break;
            case CBCentralManagerStateUnauthorized:
                break;
            case CBCentralManagerStatePoweredOff:
                break;
            case CBCentralManagerStatePoweredOn:
            {
                NSLog(@"CBCentralManagerStatePoweredOn");
                //搜索外设
                [self.manager scanForPeripheralsWithServices:nil//通过某些服务筛选外设
                                                     options:nil];//条件
            }
                break;
            default:
                break;
        }
    }
    
    3.连接外设(Connect Peripheral)
    /**
     *  搜索成功的回调
     *
     *  @param central           中心设备管理
     *  @param peripheral        外设
     *  @param advertisementData 外设设备携带的数据
     *  @param RSSI              信号强度
     */
    - (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary<NSString *, id> *)advertisementData RSSI:(NSNumber *)RSSI
    {
        NSLog(@"%@----%@----%@----%@",central,peripheral,advertisementData,RSSI);
        //需要对连接到的外设进行过滤
        /*
         1.信号强度(40以上才能连接)
         2.通过设备名(设备字符串前缀)
         */
        //找到指定的设备,并保存外设
        self.peripheral = peripheral;
        //使用中心设备连接外设
        [self.manager connectPeripheral:self.peripheral options:nil];
    }
    /**
     *  外设连接成功
     *
     *  @param central    中心设备管理
     *  @param peripheral 连接到的外设
     */
    - (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral
    {
        //连接成功后可以进行数据交互
    }
    
    /**
     *  外设连接失败
     *
     *  @param central    中心设备管理
     *  @param peripheral 连接的外设
     *  @param error      失败的原因
     */
    - (void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(nullable NSError *)error
    {
    
    }
    
    /**
     *  丢失连接
     *
     *  @param central    中心管理设备
     *  @param peripheral 连接的外设
     *  @param error      错误信息
     */
    - (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(nullable NSError *)error
    {
    
    }
    
    4.扫描外设中的服务和特征(Discover Services And Characteristics)

    设备链接成功后,就可以扫描设备的服务(services)了,同样是通过代理,扫描到结果后会触发某代理方法.
    注意:此时CBCentralManagerDelegate已经不能满足需求,需要新的CBPeripheralDelegate来搞定.
    该协议中包含了central与peripheral的许多回调方法
    (eg.:获取services,获取characteristics,获取characteristics的值,获取characteristics的Descriptor以及Descriptor的值,写数据,读RSSI,用通知的方式订阅数据等等).

    4.1 获取外设的services
    首先设置外设的代理,并搜寻services
    然后在代理方法peripheral:didDiscoverServices:中遍历services

    // 外设连接成功
    - (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral
    {
        NSLog(@"%s, line = %d", __FUNCTION__, __LINE__);
        NSLog(@">>>连接到名称为(%@)的设备-成功",peripheral.name);
        //设置的peripheral代理CBPeripheralDelegate
        //@interface ViewController : UIViewController<CBCentralManagerDelegate,CBPeripheralDelegate>
        [peripheral setDelegate:self];
    
        //扫描外设Services,成功后会进入方法:-(void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error{
        [peripheral discoverServices:nil];
        /*
         Discovers the specified services of the peripheral.
         An array of CBUUID objects that you are interested in. Here, each CBUUID object represents a UUID that identifies the type of service you want to discover.
         */
    }
    #pragma mark - CBPeripheralDelegate
    // 发现外设的service
    - (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error
    {
        if (error)
        {
            NSLog(@">>>Discovered services for %@ with error: %@", peripheral.name, [error localizedDescription]);
            return;
        }
        for (CBService *service in peripheral.services) {
            NSLog(@"service.UUID = %@", service.UUID);
            //扫描每个service的Characteristics,扫描到后会进入方法: -(void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error
            [peripheral discoverCharacteristics:nil forService:service];
        }
    }
    

    4.2 获取外设的characteris,获取Characteristics的值,获取Characteristics的Descriptor以及Descriptor的值

    // 外设发现service的特征
    - (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error
    {
        if (error)
        {
            NSLog(@"error Discovered characteristics for %@ with error: %@", service.UUID, [error localizedDescription]);
            return;
        }
        for (CBCharacteristic *characteristic in service.characteristics)
        {
            NSLog(@"service:%@ 的 Characteristic: %@",service.UUID,characteristic.UUID);
        }
    
    #warning noCodeFor 优化,分开写是为了让大家看注释清晰,并不符合编码规范
        //获取Characteristic的值,读到数据会进入方法:-(void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
        for (CBCharacteristic *characteristic in service.characteristics){
            [peripheral readValueForCharacteristic:characteristic]; // 外设读取特征的值
        }
    
        //搜索Characteristic的Descriptors,读到数据会进入方法:-(void)peripheral:(CBPeripheral *)peripheral didDiscoverDescriptorsForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
        for (CBCharacteristic *characteristic in service.characteristics){
            [peripheral discoverDescriptorsForCharacteristic:characteristic]; // 外设发现特征的描述
        }
    }
    
    // 获取characteristic的值
    - (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(nonnull CBCharacteristic *)characteristic error:(nullable NSError *)error
    {
        //打印出characteristic的UUID和值
        //!注意,value的类型是NSData,具体开发时,会根据外设协议制定的方式去解析数据
        NSLog(@"%s, line = %d, characteristic.UUID:%@  value:%@", __FUNCTION__, __LINE__, characteristic.UUID, characteristic.value);
    }
    // 获取Characteristics的 descriptor的值
    - (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForDescriptor:(nonnull CBDescriptor *)descriptor error:(nullable NSError *)error
    {
        //打印出DescriptorsUUID 和value
        //这个descriptor都是对于characteristic的描述,一般都是字符串,所以这里我们转换成字符串去解析
        NSLog(@"%s, line = %d, descriptor.UUID:%@ value:%@", __FUNCTION__, __LINE__, descriptor.UUID, descriptor.value);
    }
    // 发现特征Characteristics的描述Descriptor
    - (void)peripheral:(CBPeripheral *)peripheral didDiscoverDescriptorsForCharacteristic:(nonnull CBCharacteristic *)characteristic error:(nullable NSError *)error
    {
        NSLog(@"%s, line = %d", __FUNCTION__, __LINE__);
        for (CBDescriptor *descriptor in characteristic.descriptors) {
            NSLog(@"descriptor.UUID:%@",descriptor.UUID);
        }
    }
    
    5.写数据到特征中
    // 5.将数据写入特征(自定义方法,为了看的更清楚,没别的意思)
    - (void)yf_peripheral:(CBPeripheral *)peripheral writeData:(NSData *)data forCharacteristic:(CBCharacteristic *)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
        };
         打印出特征的权限(characteristic.properties),可以看到有很多种,这是一个NS_OPTIONS的枚举,可以是多个值
         常见的又read,write,noitfy,indicate.知道这几个基本够用了,前俩是读写权限,后俩都是通知,俩不同的通知方式
         */
        NSLog(@"%s, line = %d, characteristic.properties:%d", __FUNCTION__, __LINE__, characteristic.properties);
    
        // 只有特征的properties中有写的属性时候,才写
        if (characteristic.properties & CBCharacteristicPropertyWrite) {
            // 这句才是正宗的核心代码
            [peripheral writeValue:data forCharacteristic:characteristic type:CBCharacteristicWriteWithResponse];
        }
    }
    
    6.订阅特征的通知
    // 设置通知
    - (void)yf_peripheral:(CBPeripheral *)peripheral setNotifyForCharacteristic:(CBCharacteristic *)characteristic
    {
        // 设置通知, 数据会进入 peripheral:didUpdateValueForCharacteristic:error:方法
        [peripheral setNotifyValue:YES forCharacteristic:characteristic];
    }
    // 取消通知
    - (void)yf_peripheral:(CBPeripheral *)peripheral cancelNotifyForCharacteristic:(CBCharacteristic *)characteristic
    {
        [peripheral setNotifyValue:NO forCharacteristic:characteristic];
    }
    
    7.断开连接
    - (void)yf_cMgr:(CBCentralManager *)cMgr stopScanAndDisConnectWithPeripheral:(CBPeripheral *)peripheral
    {
        // 停止扫描
        [manager stopScan];
        // 断开连接
        [manager cancelPeripheralConnection:peripheral];
    }
    

    相关文章

      网友评论

        本文标题:iOS 蓝牙浅析

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