美文网首页
iOS 蓝牙开发相关知识-02

iOS 蓝牙开发相关知识-02

作者: 哔哩哔哩智能喵 | 来源:发表于2017-01-18 22:39 被阅读199次
    #import "ViewController.h"
    #import <CoreBluetooth/CoreBluetooth.h>
    @interface ViewController () <CBCentralManagerDelegate,CBPeripheralDelegate>
    /** 中心管理者 */
    @property(nonatomic,strong)CBCentralManager * cbManager ;
    /** 外设 */
    @property(nonatomic,strong)CBPeripheral * cbPeripheral ;
    @property(nonatomic,strong)CBCharacteristic * cbchar1 ;
    @property(nonatomic,strong)CBCharacteristic * cbchar2 ;
    @end
    
    @implementation ViewController
    
    - (void)viewDidLoad {
        [super viewDidLoad];
        [self cbManager];
        /**
         在ios10中需要在plist添加新的字段来获取蓝牙的访问权限
         <key>NSBluetoothPeripheralUsageDescription</key>
         <string>App需要您的同意,才能访问蓝牙</string>
         */
    }
    -(CBCentralManager *)cbManager
    {
        if (_cbManager ==nil) {
            _cbManager = [[CBCentralManager alloc]initWithDelegate:self queue:dispatch_get_main_queue()];
        }
        return _cbManager;
    }
    //�1.检查蓝牙状态
    -(void)centralManagerDidUpdateState:(CBCentralManager *)central
    {
        switch (central.state) {
            case CBCentralManagerStatePoweredOn:
                [central scanForPeripheralsWithServices:nil options:nil];
                NSLog(@"蓝牙开启");
    
                break;
            case CBCentralManagerStatePoweredOff:
                NSLog(@"蓝牙状态关闭");
            case CBCentralManagerStateUnknown:
                NSLog(@"蓝牙状态为止");
                break;
            case CBCentralManagerStateResetting:
                NSLog(@"蓝牙状态重置");
                break;
            case CBCentralManagerStateUnsupported:
                NSLog(@"不支持蓝牙");
                break;
            case CBCentralManagerStateUnauthorized:
                NSLog(@"蓝牙未经授权");
                break;
        }
    }
    //2.app扫描到外设会进入该方法
    -(void)centralManager:(CBCentralManager *)central
    didDiscoverPeripheral:(CBPeripheral *)peripheral
        advertisementData:(NSDictionary *)advertisementData
                     RSSI:(NSNumber *)RSSI
    {
        //判断蓝牙的名称,因官方没有SDK无法获取MAC地址,暂时以外设的名字连接 ABS是绝对值宏,因扫描到的外设信号都是"-",[如果无法判断蓝牙的名称可以从app stroe下一个蓝牙助手就可以看到附近的蓝牙设备]
        if ([peripheral.name hasPrefix:@"Bioland-BGM"]&&(ABS(RSSI.integerValue)>20)){
            self.cbPeripheral = peripheral;
            //app开始连接外设
            [self.cbManager connectPeripheral:self.cbPeripheral options:nil];
        }
    }
    //2.1扫描到services调用该方法
    -(void)peripheral:(CBPeripheral *)peripheral
    didDiscoverServices:(NSError *)error
    {
        for (CBService *service in peripheral.services) {
            NSLog(@"%@",service.UUID);
            [peripheral discoverCharacteristics:nil forService:service];
        }
    }
    //2.2扫描到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;
        }
        //从service中遍历所有的特征
        for (CBCharacteristic *characteristic in service.characteristics) {
            //获取Characteristic的值,读到数据会进入方法:-(void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
            [peripheral readValueForCharacteristic:characteristic];
            NSLog(@"characteristic= %@",characteristic);
            
            //搜索Characteristic的Descriptors,读到数据会进入方法:-(void)peripheral:(CBPeripheral *)peripheral didDiscoverDescriptorsForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
            [peripheral discoverDescriptorsForCharacteristic:characteristic];
            
            NSLog(@"Characteristic.Descriptors =%@",characteristic);
            //判断特征值中的uuid如果包含1001就订阅这个特征,订阅后会收到返回值
            //每个外设的特征不是相同的需要参照硬件商提供的蓝牙开发文档
            if ([characteristic.UUID isEqual:[CBUUID UUIDWithString:@"1001"]]) {
                self.cbchar1 = characteristic;
                [self.cbPeripheral setNotifyValue:YES forCharacteristic:characteristic];
            }
            if ([characteristic.UUID isEqual:[CBUUID UUIDWithString:@"1002"]]) {
                self.cbchar2 = characteristic;
                [self.cbPeripheral  setNotifyValue:YES forCharacteristic:characteristic];
            }
        }
    }
    //3.中心管理者连接外设成功时会调用该方法
    -(void)centralManager:(CBCentralManager *)central
     didConnectPeripheral:(CBPeripheral *)peripheral
    {
        self.cbPeripheral.delegate = self;
        [self.cbPeripheral discoverServices:nil];
        NSLog(@"连接成功");
    }
    //4.搜索到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(@"详情 uuid:%@",d.UUID);
        }
    }
    //4.1获取外设的Characteristicsde值,在这个方法中外设会把我们订阅的特征的值以16进制的格式返回,只要打印就可以看到具体的详情值。
    -(void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
    {
        NSLog(@"peripheral:%@   characteristic.description:%@---%@",peripheral.description,characteristic.description,error.description);
    }
    //4.2获取Characteristics的 descriptor的值
    - (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForDescriptor:(nonnull CBDescriptor *)descriptor error:(nullable NSError *)error
    {
        //打印出DescriptorsUUID 和value
        //这个descriptor都是对于characteristic的描述,一般都是字符串,所以这里我们转换成字符串去解析
        NSLog(@"descriptor.UUID:%@ value:%@",descriptor.UUID, descriptor.value);
    }
    // 5.将数据写入特征,自定义方法
    -(void)XC_writeCharacteristic:(CBPeripheral *)peripheral
                characteristic:(CBCharacteristic *)characteristic
                         value:(NSData *)value
    {
        /*
         打印出特征的权限(characteristic.properties),可以看到有很多种,这是一个NS_OPTIONS的枚举,可以是多个值
         常见的又read,write,noitfy,indicate.知道这几个基本够用了,前俩是读写权限,后俩都是通知,俩不同的通知方式
         */
        NSLog(@"characteristic.properties:%lu", (unsigned long)characteristic.properties);
        //只有 characteristic.properties 有write的权限才可以写
        if(characteristic.properties & CBCharacteristicPropertyWrite){
            [peripheral writeValue:value forCharacteristic:characteristic type:CBCharacteristicWriteWithResponse];
        }else{
            NSLog(@"该字段不可写!");
        }
    }
    //5.1写入数据后的回调
    - (void)peripheral:(CBPeripheral *)peripheral
    didWriteValueForCharacteristic:(CBCharacteristic *)
    characteristic error:(nullable NSError *)error
    {
        //获取特征中1002的特征值
        [self.cbperipheral readValueForCharacteristic:self.cbchar2];
        if (error) {
            NSLog(@"erro = %@",error.description);
        }
    }
    // 6.设置通知
    - (void)XC_peripheral:(CBPeripheral *)peripheral setNotifyForCharacteristic:(CBCharacteristic *)characteristic
    {
        // 设置通知, 数据会进入 peripheral:didUpdateValueForCharacteristic:error:方法
        [peripheral setNotifyValue:YES forCharacteristic:characteristic];
    }
    
    //5.1写入数据后的回调
    - (void)peripheral:(CBPeripheral *)peripheral
    didWriteValueForCharacteristic:(CBCharacteristic *)
    characteristic error:(nullable NSError *)error
    {
        //获取特征中1002的特征值
        [self.cbperipheral readValueForCharacteristic:self.cbchar2];
        if (error) {
            NSLog(@"erro = %@",error.description);
        }
    }
    
    // 6.1取消通知
    - (void)XC_peripheral:(CBPeripheral *)peripheral cancelNotifyForCharacteristic:(CBCharacteristic *)characteristic
    {
        [peripheral setNotifyValue:NO forCharacteristic:characteristic];
    }
    // 7.断开连接
    - (void)XC_cbManger:(CBCentralManager *)cbManger stopScanAndDisConnectWithPeripheral:(CBPeripheral *)
    peripheral
    {
        // 停止扫描
        [cbManger stopScan];
        // 断开连接
        [cbManger cancelPeripheralConnection:peripheral];
    }
    //除了以上函数的实现定义还需要对蓝牙失败�操作做响应不然会app会直接崩溃
    //外设链接失败
    -(void)centralManager:(CBCentralManager *)central
    didFailToConnectPeripheral:(CBPeripheral *)peripheral
                    error:(NSError *)error
    {
        NSLog(@"外设链接失败 = %@",error);
    }
    //外设断开连接
    - (void)centralManager:(CBCentralManager *)central
    didDisconnectPeripheral:(CBPeripheral *)peripheral
                     error:(NSError *)error
    {
        NSLog(@"外设断开链接 = %@",error);
    }
    @end
    
    

    (http://www.jianshu.com/p/d71d493d9e8a)

    相关文章

      网友评论

          本文标题:iOS 蓝牙开发相关知识-02

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