如果特性中有多个属性,如何读取和写入值?
例如 LED 颜色为 RGB:
Characteristic: LED Color UUID: 7A5A0011-D04B-48EB-B3FA-32EB4F0FFAC4 LED color and intensity in RGB format. Name Green Name Blue Format unsigned 8-bit integer Access read, write Value 0 - 255 Format unsigned 8-bit integer Access read, write Value 0 - 255 Name Red Format unsigned 8-bit integer Access read, write Value 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);
}
最佳答案
if ([aChar.UUID isEqual:[CBUUID UUIDWithString: LED_CHAR_COLOR_UUID]])
{
_colorCharacteristic = aChar; //It's a property, save it
[peripheral readValueForCharacteristic:aChar];
}
这应该会触发委托(delegate)方法:
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).
关于ios - BLE(蓝牙启用设备)ios,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30367781/