ios - BLE(蓝牙启用设备)ios

标签 ios bluetooth-lowenergy

如果特性中有多个属性,如何读取和写入值?

例如 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/

相关文章:

iOS 解析 JSON 和 AFNetworking

ios - CoreBluetooth 中央 --> 外设

ios - 如何过滤心率监测器

android - 蓝牙 Gatt 回调不适用于 Lollipop 的新 API

android - 如何防止 BluetoothGattCallback 一次执行多次

android - 多个应用程序可以处理 ibeacon 事件吗

ios - MKOverlayRenderer 使用 CGPath 画线

ios - 对核心数据 UITableview 进行排序

ios - Swift中如何使用Visual Format Language设置约束?

ios - Apple 支付与 Stripe 的集成(调试中的 STPTestPaymentAuthorizationViewController)