iOS从BLE设备读取数据

时间:2013-08-19 14:13:52

标签: ios bluetooth core-bluetooth

我正在尝试从BLE设备读取数据但仍然获得权限错误。可在此处找到演示项目:https://github.com/sergiomtzlosa/CoreBluetooth-Demo(请记住 - 我的代码与此代码略有不同)。

一般情况下连接和读取值没有问题,但有一些特性(必不可少)会给出权限错误。

  

控制台日志:更新错误!!!特征:“未知(< fff4>)”   错误:“不允许阅读”。

因此,当我订阅或读取该特性的数据时,它每次都会向我发送NULL(可能的原因:没有读取权限)。

  

控制台日志:特征:“未知(< fff4>)” - >有价值的:   (空)

以下是代码段:

//Action on discovering services
- (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(@"Discovereddddddddddd service %@", service.UUID);
    [testPeripheral discoverCharacteristics:nil  forService:service];
}
 NSLog(@"didDiscoverServicesEnd");
}

//Action on discovered characteristics
- (void)peripheral:(CBPeripheral *)peripheral
didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error {
NSLog(@"didDiscoverCharacteristicsForService!");
for (CBCharacteristic *characteristic in service.characteristics) {
    NSLog(@"Discovered characteristic %@", characteristic.UUID);
    NSLog(@"---------------------------------------------------");
    NSLog(@"Reading value for characteristic %@", characteristic.UUID);
    [peripheral readValueForCharacteristic:characteristic];
    NSLog(@"+++++++++++++++++++++++++++++++++++++++++++++++++++");
    [peripheral setNotifyValue:YES forCharacteristic:characteristic];
    }
}

//Action on reading value
- (void)peripheral:(CBPeripheral *)peripheral 
didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error{
if (error){
    NSLog(@"Update error!!! Characteristic: %@ with error: %@", characteristic.UUID, [error localizedDescription]);
    return;
}else{
    NSData *data = characteristic.value;
    NSString *str = [NSString stringWithUTF8String:[data bytes]];
    NSLog(@"Characteristic: %@ -> with value: %@", characteristic.UUID, str);
}
}

怎么了?反正有没有克服这个问题?

2 个答案:

答案 0 :(得分:0)

外围设备是嵌入式设备还是其他iOS设备。 我已经看到外围设备的特性必须明确配置为具有读取权限。仅仅因为你发现了一个特征并不意味着你可以阅读它。

答案 1 :(得分:0)

您必须检查您是否具有访问该值的权限,在启动CBC特性时设置权限

"特征值权限 表示特征值的读取,写入和加密权限的值。

typedef enum {
   CBAttributePermissionsReadable = 0x01,
   CBAttributePermissionsWriteable = 0x02,
   CBAttributePermissionsReadEncryptionRequired = 0x04,
   CBAttributePermissionsWriteEncryptionRequired = 0x08,
} CBAttributePermissions;"

https://developer.apple.com/library/ios/documentation/CoreBluetooth/Reference/CBMutableCharacteristic_Class/Reference/CBMutableCharacteristic.html