iOS蓝牙

作者: 一个没有记忆的梦 | 来源:发表于2017-06-29 09:48 被阅读0次

    针对我自己做的蓝牙的接收与发送的数据来说明iOS蓝牙的一些知识;
    添加系统的库 <CoreBluetooth/CoreBluetooth.h>
    继承CBPeripheralDelegate, CBCentralManagerDelegate这两个协议
    创建CBCentralManager的对象

    self.manager = [[CBCentralManager alloc] initWithDelegate:self queue:nil];
    self.manager.delegate = self;//继承协议
    

    然后会自动调用检查手机蓝牙是否开启的代理

    //检查手机蓝牙是否开启
    - (void)centralManagerDidUpdateState:(CBCentralManager *)central{
        switch (central.state) {
            case CBCentralManagerStateUnknown:
                 NSLog(@"无蓝牙");
                break;
            case CBCentralManagerStateUnsupported:
                NSLog(@"模拟器不支持蓝牙调试");
                break;
            case CBCentralManagerStateUnauthorized:
                NSLog(@"蓝牙未授权");
                break;
            case CBCentralManagerStatePoweredOff:
                NSLog(@"蓝牙处于关闭状态");
                break;
            case CBCentralManagerStatePoweredOn:{
                NSLog(@"蓝牙已打开");
             //搜索硬件蓝牙
                [self.manager scanForPeripheralsWithServices:nil options:nil];
                break;
            }
            default:
                break;
        }
    }
    
    注:在iOS 10之前如果未开启蓝牙可以通过此方法跳到设置的页面iOS10之后苹果不允许开发者跳到设置的页面所以只能通过用户手动去设置中打开打开
    NSURL *url = [NSURL URLWithString:@"prefs:root=Bluetooth"];  
    if ([[UIApplication sharedApplication]canOpenURL:url]) {  
                  [[UIApplication sharedApplication]openURL:url];  
     } 
    

    在蓝牙打开的那个case的判断里面添加搜索蓝牙

    //如果不加限制既是搜索所有蓝牙
    [self.manager scanForPeripheralsWithServices:nil options:nil];
    

    然后会走搜索到蓝牙的代理方法

    - (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary<NSString *,id> *)advertisementData RSSI:(NSNumber *)RSSI{
    //     NSLog(@"发现设备:%@\n中心设备:%@\n外围设备:%@\n特征数据:%@\n信号数据:%@", peripheral.name, central, peripheral, advertisementData, RSSI);
    //连接蓝牙
    //     [self.manager connectPeripheral:peripheral options:nil];
    }
    

    从搜索到的蓝牙设备中找到自己想要的连接的蓝牙去连接蓝牙

    [self.manager connectPeripheral:peripheral options:nil];
    

    如果连接上蓝牙走如下代理

    //连接蓝牙成功,
    - (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral{
    //蓝牙连接成功之后开始继承CBPeripheralDelegate协议并且搜索蓝牙的服务特征
            self.peripheral.delegate = self;
            [self.peripheral discoverServices:nil];//搜索蓝牙的所有服务特征
    }
    

    如果连接蓝牙失败走下面这个代理

    - (void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(nullable NSError *)error{
    }
    

    搜索到蓝牙的服务特征

    //外围设备寻找服务后
    - (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error{
        [ProgressHUD dismiss];
          //for循环遍历搜索到的所有服务找出自己所需要的服务
            for(CBService *service in self.peripheral.services){
                NSLog(@"[service  UUID].UUIDString:%@", [service  UUID].UUIDString);
                if ([service.UUID isEqual:[CBUUID UUIDWithString:@"ABF6"]]) {
                    [peripheral discoverCharacteristics:nil forService:service];//搜索到服务之后会自动调用
    -(void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error方法
                }
            }
            NSLog(@"发现服务");
    }
    
    //外围设备寻找到特征后
    -(void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error{
        NSLog(@"搜索到特征");
            if (error) {
                NSLog(@"外围设备寻找特征过程中发生错误,错误信息:%@", error.localizedDescription);
            }
            //遍历服务中的特征,找到自己所需要的特征
            for (CBCharacteristic *characteristic in service.characteristics){
                if ([[characteristic UUID] isEqual:[CBUUID UUIDWithString:@"ABF7"]]) {
                    [peripheral setNotifyValue:YES forCharacteristic:characteristic];//此方法之后会自动调用- (void)peripheral:(CBPeripheral *)peripheral didUpdateNotificationStateForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error;方法
                    self.writeCharacteristic = characteristic;
                }
            }
    
    - (void)peripheral:(CBPeripheral *)peripheral didUpdateNotificationStateForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error{
        NSLog(@"tttttt:%@", error);
        if (error == NULL) {
    [self.peripheral writeValue:[XFData sendACK] forCharacteristic:self.writeCharacteristic type:CBCharacteristicWriteWithResponse];//发送数据指令 后面的type:要用CBCharacteristicWriteWithResponse这个不要勿用成CBCharacteristicWriteWithoutResponse
    //在这里面添加和硬件蓝牙交互的指令,也可以在上面的搜索到蓝牙的特征之后添加,有可能会出现bug,亲测!在这里添加只需要和硬件连接上就可以发送指令!也可以自己写个按钮事件,点击按钮去发送指令。蓝牙发送指令成功之后会调用下面的那个方法
        }
    }
    
    //用于检测中心设备向外设写数据是否成功
    - (void)peripheral:(CBPeripheral *)peripheral didWriteValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error{
            if (error) {
                NSLog(@"数据发送失败:%@", error.userInfo);
            }else{
                NSLog(@"数据发送成功%d", ch);//数据发送成功之后会自动调用- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
            }
    }
    
    //此方法是硬件蓝牙发送数据,手机接收数据。在这里处理蓝牙发过来的数据
    - (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error{
        NSData *getData = characteristic.value;//把蓝牙发送过来的数据转换成Data类型,方便处理
    }
    
    //此方法是蓝牙断开连接   如果蓝牙连接之后又断开会回调这个方法,可以在这里处理一些断开蓝牙后的操作
    - (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error{
        NSLog(@"蓝牙断开连接11");
    }
    

    这样整个蓝牙就可以发送和接收数据了!
    注:蓝牙的数据指令可能有所不同我给出我所使用的指令供大家参考

    + (NSData *)get_data:(NSInteger)ch{
        unsigned char command[5] = {0};
        unsigned char *pTmp = NULL;
        pTmp = command;
        *pTmp = 0x15;
        pTmp++;
        *pTmp = 0xAA;
        pTmp++;
        *pTmp = 0x03;
        pTmp++;
        *pTmp = ch;
        pTmp++;
        *pTmp = 0x15^0xAA^0x03^ch;
        pTmp++;
        NSData *data = [[NSData alloc] initWithBytes:&command length:5];
        return data;
    }
    

    蓝牙的可能用到的一些基本属性和方法
    CBService *service 蓝牙的服务
    CBCharacteristic *characteristic蓝牙的特征
    CBUUID *UUID;//蓝牙的唯一标示UUID
    判断蓝牙的状态peripheral.state
    CBPeripheralStateDisconnected = 0,//蓝牙未连接
    CBPeripheralStateConnecting,//蓝牙正在连接
    CBPeripheralStateConnected,//蓝牙已经连接
    CBPeripheralStateDisconnecting NS_AVAILABLE(NA, 9_0),//蓝牙断开连接
    断开蓝牙:- (void)cancelPeripheralConnection:(CBPeripheral *)peripheral;//[self.manager cancelPeripheralConnection:peripheral];
    停止搜索蓝牙:- (void)stopScan;//[self.manager stopScan];
    读取蓝牙的特征- (void)readValueForCharacteristic:(CBCharacteristic *)characteristic;//[peripheral readValueForCharacteristic:characteristic];
    特征值的变化- (void)setNotifyValue:(BOOL)enabled forCharacteristic:(CBCharacteristic *)characteristic;//[peripheral setNotifyValue:YES forCharacteristic:characteristic];

    以上就是我所用到的蓝牙的一些基本内容,和蓝牙的交互没有问题!写的不好,多多见谅!!!

    相关文章

      网友评论

          本文标题:iOS蓝牙

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