我正在为Objective-C开发BLE。
我像下面的代码一样定义UUID:
static NSString *const LEDStateCharacteristicUUID = @"ffffffff-7777-7uj7-a111-d631d00173f4";
我想通过以下代码为BLE设备写特性,需要传递3个参数:1.Data 2.Characteristic 3.type
CBCharacteristic *chara = ??? // how to set the characteristic via above UUID let it can pass to following function?
[peripheral writeValue:data forCharacteristic:chara type:CBCharacteristicWriteWithoutResponse];
如何通过上面的UUID设置特性让它可以传递给writeCharacteristic
函数?
提前致谢。
答案 0 :(得分:5)
首先,您需要了解您想要的服务UUID以及该服务的特征UUID。当您拥有这些UUID时,您可以使用下面的逻辑来获得正确的特征实例:
- (CBCharacteristic *)characteristicWithUUID:(CBUUID *)characteristicUUID forServiceUUID:(CBUUID *)serviceUUID inPeripheral:(CBPeripheral *)peripheral {
CBCharacteristic *returnCharacteristic = nil;
for (CBService *service in peripheral.services) {
if ([service.UUID isEqual:serviceUUID]) {
for (CBCharacteristic *characteristic in service.characteristics) {
if ([characteristic.UUID isEqual:characteristicUUID]) {
returnCharacteristic = characteristic;
}
}
}
}
return returnCharacteristic;
}
答案 1 :(得分:1)
您需要为外围设备设置委托:
peripheral.delegate = self;
在didConnectToPeripheral中,您可以发现外围设备的服务。在外围设备的didDiscoverServices回调中,您可以发现特征。在didDiscoverCharacteristics中,然后循环遍历每个特征并将它们保存在变量中。
- (void)peripheral:(CBPeripheral *)peripheral
didDiscoverCharacteristicsForService:(CBService *)service
error:(NSError *)error
{
if (error) {
NSLog(@"Error discovering characteristics: %@", error.localizedDescription);
} else {
NSLog(@"Discovered characteristics for %@", peripheral);
for (CBCharacteristic *characteristic in service.characteristics) {
if ([characteristic.UUID.UUIDString isEqualToString: LEDStateCharacteristicUUID]) {
// Save a reference to it in a property for use later if you want
_LEDstateCharacteristic = characteristic;
[peripheral writeValue:data forCharacteristic: _LEDstateCharacteristic type:CBCharacteristicWriteWithoutResponse];
}
}
}
}