iOS之蓝牙开发—CoreBluetooth详解二

这里主要向大家简单地讲解一下的通过中心设备对外设硬件进行数据的写入和反馈消息的获取。

在进行讲解之前,我们需要明白以下几点:

1.查看特征的属性:

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

};   在了解了特征的相关属性之后,才可以使用相应的特征进行操作

2.在进行读取:- (void)readValueForCharacteristic:(CBCharacteristic *)characteristic;

          和写入:- (void)writeValue:(NSData *)data forCharacteristic:(CBCharacteristic *)characteristic type:(CBCharacteristicWriteType)type;

          操作后,会分别进入相应的回调方法,

          读取的回调方法:- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(nullableNSError *)error;
          和写入的回调方法:- (void)peripheral:(CBPeripheral *)peripheral didWriteValueForCharacteristic:(CBCharacteristic *)characteristic error:(nullableNSError *)error;

3.通过中心设备向外设硬件写入数据,需要遵循蓝牙协议,一般来讲,中心设备每次向外设发送的数据的大小不要超过20字节,超过的情况下会导致失败;其次每次发送的数据会有一定的校验,还需要确定发送的数据的格式是什么样子的,否则即使是中心设备发出数据,我们通过回调方法得到成功的结果,但实际上数据也是被外设当做错误信息给过滤掉了。


    我们开始进行数据的写入和反馈的读取。一般情况下,我们选择外设的一个可写的特征进行写入,在选择一个可读的特征进行写入的反馈的数据的读取(如果是没有反馈的写入,则直接进行写入,不必考虑反馈的过程)。


首先写入:[peripheralwriteValue:data forCharacteristic:characteristic type:CBCharacteristicWriteWithResponse];

进入写入对应的回调方法:

- (void)peripheral:(CBPeripheral *)peripheral didWriteValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error{

    

    if (error) {

        NSLog(@"数据写入失败: %@",[error localizedDescription]);

    }else{

              NSLog(@"数据写入成功");
       //开始读取反馈
        [peripheral readValueForCharacteristic:characteristic];
    }
进入读取对应的回调方法:

- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error{

    

    if (error){

        NSLog(@"Error updating value for characteristic %@ error: %@", characteristic.UUID, [error localizedDescription]);

        return;

    }

    //拿到此数据来判断是否写入成功

    NSData *addressData = characteristic.value;

    ~~~~~~~

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值