如果特征中有多个属性,如何读取和写入值?
例如LED颜色为RGB:
特性: LED颜色UUID:7A5A0011-D04B-48EB-B3FA-32EB4F0FFAC4 RGB格式的LED颜色和强度。名称绿色名称蓝色格式 无符号8位整数访问读取,写入值0 - 255格式 无符号8位整数访问读取,写入值0 - 255名称红色 格式化无符号8位整数访问读取,写入值0 - 255
那么如何读取/写入RGB的值?使用下面的代码我只得到一个值
if ([service.UUID isEqual:[CBUUID UUIDWithString:LED_Service_UUID]]){
for (CBCharacteristic *aChar in service.characteristics) {
/********* Characteristic: LED Link***************/
NSLog(@"%@",aChar.UUID);
if ([aChar.UUID isEqual:[CBUUID UUIDWithString: LED_CHAR_COLOR_UUID]]) {
[peripheral readValueForCharacteristic:aChar];
NSLog(@"%@%@%@",aChar.value,aChar.value,aChar.value);
}
答案 0 :(得分:0)
if ([aChar.UUID isEqual:[CBUUID UUIDWithString: LED_CHAR_COLOR_UUID]])
{
_colorCharacteristic = aChar; //It's a property, save it
[peripheral readValueForCharacteristic:aChar];
}
这应该触发委托方法:peripheral:didUpdateValueForCharacteristic:error:
。
在里面,它:
if ([characteristic UUID] isEqual:[CBUUID UUIDWithString: LED_CHAR_COLOR_UUID]])
{
NSData *valueData = [characteristic value];
}
对于每个组件(红色,绿色,蓝色,强度):
int aComponent;
NSData *aComponentData = [valueData subdataWithRange:NSMakeRange(0, 2)]; //Range to be defined for each components
[aComponentData getBytes:&aComponent length:sizeof(aComponent)];
NSLog(@"aComponent: %d", aComponent);
然后,您可以使用UIColor
从每个组件创建colorWithRed:green:blue:alpha:
。
要编写,您必须再次使用NSData
来查看所使用的格式。
uint8_t colorValues [] = {redValue, greenValue, blueValue, intensityValue};
NSData *data = [NSData dataWithBytes:colorValues length:sizeof(colorValues)];
[_peripheral writeValue:yourValueData forCharacteristic:_colorCharacteristic type: CBCharacteristicWriteWithResponse];` //(or `CBCharacteristicWriteWithoutResponse` depending on the doc of your device).