如何从 objective-C 中的 UUID 获取特征?

How to get the characteristic from UUID in objective-C?

我正在 objective-C 开发 BLE。

我定义 UUID 如下代码:

    static NSString *const LEDStateCharacteristicUUID = @"ffffffff-7777-7uj7-a111-d631d00173f4";

我想通过以下代码将特征写入BLE设备,它需要传递3 parameter: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函数?

提前致谢。

您需要为外设设置委托:

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];
            }
        }
    }
}

首先你需要知道你想要的是什么服务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;
}