美文网首页
iOS CoreBluetooth开发

iOS CoreBluetooth开发

作者: Realank | 来源:发表于2016-07-18 17:40 被阅读456次

    本文主要参考如下链接:
    http://blog.csdn.net/pony_maggie/article/details/26740237
    http://blog.csdn.net/VictorMoKai/article/details/42395669
    http://blog.csdn.net/m372897500/article/details/50662976

    iOS 蓝牙介绍

    蓝牙协议本身经历了从1.0到4.0的升级演变, 最新的4.0以其低功耗著称,所以一般也叫BLE(Bluetoothlow energy)。

    iOS 有两个框架支持蓝牙与外设连接。一个是 ExternalAccessory。从iOS3.0就开始支持,也是在iPhone4S出来之前用的比较多的一种模式,但是它有个不好的地方,External Accessory需要拿到苹果公司的MFI认证。

    另一个框架则是本文要介绍的CoreBluetooth,在iphone4s开始支持,专门用于与BLE设备通讯(因为它的API都是基于BLE的)。这个不需要MFI,并且现在很多蓝牙设备都支持4.0,所以也是在IOS比较推荐的一种开发方法。

    CoreBluetooth介绍

    CoreBluetooth框架的核心其实是两个东西,Peripheral和Central, 可以理解成外设和中心。其中Peripheral外设相当于Socket编程中的Server服务端,Central中心相当于Client客户端。


    你可以理解外设是一个广播数据的设备,它开始告诉外面的世界说它这儿有一些数据,并且能提供一些服务。另一边中心开始扫描周边有没有合适的设备,如果发现后,会和外设做连接请求,一旦连接确定后,两个设备就可以传输数据了。

    在iOS6之后,iOS 设备可以是外设,也可以是中心,就像Socket编程中一样,你可以是服务端也可以是客户端,但与Socket不同的是不能在同时间扮演两个角色。

    服务(service)和特征(characteristic)

    每个蓝牙4.0的设备都是通过服务和特征来展示自己的,一个设备必然包含一个或多个服务,每个服务下面又包含若干个特征。特征是与外界交互的最小单位。比如说,智能音响设备,用服务A标识播放模块,特征A1来表示播放上一首,特征A2来表示播放下一首;服务B标识设置模块,特征B1设置彩灯颜色。这样做的目的主要为了模块化。

    服务和特征都是用UUID来唯一标识的,UUID的概念如果不清楚请自行google,国际蓝牙组织为一些很典型的设备(比如测量心跳和血压的设备)规定了标准的service UUID。

    CoreBluetooth框架的核心其实是两个东西,peripheral和central, 可以理解成外设和中心。对应他们分别有一组相关的API和类,如下图所示:


    上面说了设备可以是外设,也可以是中心,也就是 本地中心->远程外设 、本地外设->远程中心,
    不过在智能家居开发中,大部分硬件蓝牙都是担任外设的角色,也就是说我们应用只要扮演中心即可了。

    本地中心与远程外设

    在中心这边,由CBCentralManager对象管理本地中心,来发现或连接远程外设。此时
    正在连接的外设用CBPeripheral 对象表示。

    远程外设的数据由CBService和CBCharacteristic对象表示
    当你与远程外设CBPeripheral对象进行数据交互时,是由一个服务与特征操作的。


    实现细节

    作为一个中心要实现完整的通讯,一般要经过这样几个步骤:

    1. 建立中心角色
    1. 扫描外设(discover)
    2. 连接外设(connect)
    3. 扫描外设中的服务和特征(discover)
      -获取外设的services
      -获取外设的Characteristics,获取Characteristics的值,获取Characteristics的Descriptor和Descriptor的值
    4. 与外设做数据交互(explore and interact)
    5. 订阅Characteristic的通知
    6. 断开连接(disconnect)
    1.导入CoreBluetooth头文件,建立主设备管理类,设置主设备委托

    首先在我自己类的头文件中要包含CoreBluetooth的头文件,并继承两个协议<CBCentralManagerDelegate,CBPeripheralDelegate>,代码如下:

    #import <CoreBluetooth/CoreBluetooth.h>  
    @interface ViewController (){  
            //系统蓝牙设备管理对象,可以把他理解为主设备,通过他,可以去扫描和链接外设  
            CBCentralManager *manager;  
    }  
      
    - (void)viewDidLoad {  
            [super viewDidLoad];  
            /* 
             设置主设备的委托,CBCentralManagerDelegate 
                必须实现的: 
                - (void)centralManagerDidUpdateState:(CBCentralManager *)central;//主设备状态改变的委托,在初始化CBCentralManager的适合会打开设备,只有当设备正确打开后才能使用 
                其他选择实现的委托中比较重要的: 
                - (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI; //找到外设的委托 
                - (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral;//连接外设成功的委托 
                - (void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error;//外设连接失败的委托 
                - (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error;//断开外设的委托 
            */  
             //初始化并设置委托和线程队列,最好一个线程的参数可以为nil,默认会就main线程  
             manager = [[CBCentralManager alloc]initWithDelegate:self queue:dispatch_get_main_queue()];  
    }
    
    2. 扫描外设(discover),扫描外设的方法我们放在centralManager成功打开的委托中,因为只有设备成功打开,才能开始扫描,否则会报错。
    
    -(void)centralManagerDidUpdateState:(CBCentralManager *)central{
        switch (central.state){
            case CBCentralManagerStateUnknown:
                NSLog(@">>>CBCentralManagerStateUnknown");
                _statusLabel.text = @"CBCentralManagerStateUnknown";
                break;
            case CBCentralManagerStateResetting:
                NSLog(@">>>CBCentralManagerStateResetting");
                _statusLabel.text = @"CBCentralManagerStateResetting";
                break;
            case CBCentralManagerStateUnsupported:
                NSLog(@">>>CBCentralManagerStateUnsupported");
                _statusLabel.text = @"CBCentralManagerStateUnsupported";
                break;
            case CBCentralManagerStateUnauthorized:
                NSLog(@">>>CBCentralManagerStateUnauthorized");
                _statusLabel.text = @"CBCentralManagerStateUnauthorized";
                break;
            case CBCentralManagerStatePoweredOff:
                NSLog(@">>>CBCentralManagerStatePoweredOff");
                _statusLabel.text = @"CBCentralManagerStatePoweredOff";
                break;
            case CBCentralManagerStatePoweredOn:
            {
                NSLog(@">>>CBCentralManagerStatePoweredOn");
                _statusLabel.text = @"CBCentralManagerStatePoweredOn";
                //开始扫描周围的外设
                /*第一个参数nil就是扫描周围所有的外设,扫描到外设后会进入
                 - (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI;
              */
                NSDictionary * dic = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:false],CBCentralManagerScanOptionAllowDuplicatesKey, nil];
                [manager scanForPeripheralsWithServices:nil options:dic];
            }
                break;
            default:
                break;
        }
        
    }
    
    - (BOOL)addBtPeripheralToArray:(CBPeripheral*)peripheral{
        if (![_btPeripheralsArray containsObject:peripheral] && peripheral.name.length > 0) {
            for (CBPeripheral* existPeripheral in _btPeripheralsArray) {
                if ([existPeripheral.identifier.UUIDString isEqualToString:peripheral.identifier.UUIDString]) {
                    return NO;
                }
            }
            
            [_btPeripheralsArray addObject:peripheral];
            return YES;
        }
        return NO;
    }
    
    //扫描到设备会进入方法
    -(void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI{
        
        NSLog(@"扫描到设备:%@",peripheral.name);
        if ([self addBtPeripheralToArray:peripheral]) {
            [_btListView reloadData];
        }
    
        
    }
    
    3. 连接外设(connect)

    在刚刚存入数组的外设中选择一个外设,然后调用tryToConnectPeripheral方法

    - (void)tryToConnectPeripheral:(CBPeripheral*)peripheral{
        //接下来可以连接设备
        //接下连接我们的测试设备,如果你没有设备,可以下载一个app叫lightbule的app去模拟一个设备
    
        /*
         一个主设备最多能连7个外设,每个外设最多只能给一个主设备连接,连接成功,失败,断开会进入各自的委托
         - (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral;//连接外设成功的委托
         - (void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error;//外设连接失败的委托
         - (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error;//断开外设的委托
         */
        //连接设备
        _statusLabel.text = @"连接中。。。";
        [manager connectPeripheral:peripheral options:nil];
    
    }
    

    尝试连接后,CoreBluetooth会把连接状态通过代理发送给调用者

    //连接到Peripherals-成功
    - (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral
    {
        NSLog(@">>>连接到名称为(%@)的设备-成功",peripheral.name);
        
        //设置的peripheral委托CBPeripheralDelegate
        //@interface ViewController : UIViewController
        [peripheral setDelegate:self];
        //扫描外设Services,成功后会进入方法:-(void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error{
        [peripheral discoverServices:nil];
        
    }
    
    //连接到Peripherals-失败
    -(void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error
    {
        NSLog(@">>>连接到名称为(%@)的设备-失败,原因:%@",[peripheral name],[error localizedDescription]);
    }
    
    //Peripherals断开连接
    - (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error{
        NSLog(@">>>外设连接断开连接 %@: %@\n", [peripheral name], [error localizedDescription]);
        
    }
    
    4. 扫描外设中的服务和特征(discover)

    设备连接成功后,就可以扫描设备的服务了,同样是通过委托形式,扫描到结果后会进入委托方法。
    但是这个委托已经不再是主设备的委托(CBCentralManagerDelegate),而是外设的委托(CBPeripheralDelegate),这个委托包含了主设备与外设交互的许多回调方法,包括获取services,获取characteristics,获取characteristics的值,获取characteristics的Descriptor,和Descriptor的值,写数据,读rssi,用通知的方式订阅数据等等。

    4.1 获取外设的services
    //扫描到Services
    -(void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error{
        NSLog(@">>>扫描到服务:%@",peripheral.services);
        NSLog(@"***begin<%s>***",__func__);
        if (error)
        {
            NSLog(@">>>Discovered services for %@ with error: %@", peripheral.name, [error localizedDescription]);
            return;
        }
        
        for (CBService *service in peripheral.services) {
            NSLog(@"UUID: %@",service.UUID);
            //扫描每个service的Characteristics,扫描到后会进入方法: -(void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error
            [peripheral discoverCharacteristics:nil forService:service];
        }
        NSLog(@"***end***");
        
    }
    
    4.2 获取外设的Characteristics,获取Characteristics的值,获取Characteristics的Descriptor和Descriptor的值
    //扫描到Characteristics
    -(void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error{
        
        
        if (error)
        {
            NSLog(@"error Discovered characteristics for %@ with error: %@", service.UUID, [error localizedDescription]);
            return;
        }
        
        //获取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];
        }
    
    }
    
    //获取的charateristic的值
    -(void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error{
        //打印出characteristic的UUID和值
        //!注意,value的类型是NSData,具体开发时,会根据外设协议制定的方式去解析数据
    
        NSLog(@"characteristic uuid:%@  value:%@",characteristic.UUID,characteristic.value);
    
    }
    
    //搜索到Characteristic的Descriptors
    -(void)peripheral:(CBPeripheral *)peripheral didDiscoverDescriptorsForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error{
        
        //打印出Characteristic和他的Descriptors
    
        NSLog(@"characteristic uuid:%@",characteristic.UUID);
        for (CBDescriptor *d in characteristic.descriptors) {
            NSLog(@"Descriptor uuid:%@",d.UUID);
        }
    
        
    }
    //获取到Descriptors的值
    -(void)peripheral:(CBPeripheral *)peripheral didUpdateValueForDescriptor:(CBDescriptor *)descriptor error:(NSError *)error{
        //打印出DescriptorsUUID 和value
        //这个descriptor都是对于characteristic的描述,一般都是字符串,所以这里我们转换成字符串去解析
    
        NSLog(@"characteristic uuid:%@  value:%@",[NSString stringWithFormat:@"%@",descriptor.UUID],descriptor.value);
    
    }
    
    
    
    
    5. 把数据写到Characteristic中
    
    //写数据
    -(void)writeCharacteristic:(CBPeripheral *)peripheral
                characteristic:(CBCharacteristic *)characteristic
                         value:(NSData *)value{
        
        //打印出 characteristic 的权限,可以看到有很多种,这是一个NS_OPTIONS,就是可以同时用于好几个值,常见的有read,write,notify,indicate,知知道这几个基本就够用了,前连个是读写权限,后两个都是通知,两种不同的通知方式。
        /*
         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(@"%lu", (unsigned long)characteristic.properties);
        
        
        //只有 characteristic.properties 有write的权限才可以写
        if(characteristic.properties & CBCharacteristicPropertyWrite){
            /*
             最好一个type参数可以为CBCharacteristicWriteWithResponse或type:CBCharacteristicWriteWithResponse,区别是是否会有反馈
             */
            [peripheral writeValue:value forCharacteristic:characteristic type:CBCharacteristicWriteWithResponse];
        }else{
            NSLog(@"该字段不可写!");
        }
        
        
    }
    - (void)peripheral:(CBPeripheral *)peripheral didWriteValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error{
    
        NSLog(@"characteristic uuid:%@ error:%@",characteristic.UUID,error);
        
    }
    
    6 订阅Characteristic的通知

    通常,与蓝牙设备的交互是这样进行的:
    监听A特性(订阅Characteristic的通知)->写B特性来请求数据->请求的数据从A特性返回。
    这时,就需要我们订阅通知,订阅通知以后,如果有数据更新,didUpdateValueForCharacteristic就会被调用

    
    //设置通知
    -(void)notifyCharacteristic:(CBPeripheral *)peripheral
                 characteristic:(CBCharacteristic *)characteristic{
        //设置通知,数据通知会进入:didUpdateValueForCharacteristic方法
        [peripheral setNotifyValue:YES forCharacteristic:characteristic];
        
    }
    
    //取消通知
    -(void)cancelNotifyCharacteristic:(CBPeripheral *)peripheral
                       characteristic:(CBCharacteristic *)characteristic{
        
        [peripheral setNotifyValue:NO forCharacteristic:characteristic];
    }
    
    7 断开连接(disconnect)
    //停止扫描并断开连接
    -(void)disconnectPeripheral:(CBCentralManager *)centralManager
                     peripheral:(CBPeripheral *)peripheral{
        //停止扫描
        [centralManager stopScan];
        //断开连接
        [centralManager cancelPeripheralConnection:peripheral];
    }
    
    

    相关文章

      网友评论

          本文标题:iOS CoreBluetooth开发

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