How to get the characteristic from UUID in objecti

2019-08-06 02:15发布

问题:

I am developing for BLE in objective-C.

I define the UUID like the following code:

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

I want to write characteristic to BLE device by following code , it need to pass 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];

How to set the characteristic via above UUID let it can pass to writeCharacteristic function?

Thanks in advance.

回答1:

First you need to know what service UUID and what characteristic UUID from this service you want. When you have these UUIDs you can use this logic below to get the right characteristic instance:

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


回答2:

You need to set a delegate for the peripheral:

peripheral.delegate = self;

In didConnectToPeripheral you discover the peripheral's services. In the peripheral's didDiscoverServices callback you then discover characteristics. In didDiscoverCharacteristics you then loop through each characteristic and save them in a variable.

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