How do I get a stat from a UUID in objective-C?

I am developing for BLE in objective-C.

I define the UUID as the following code:

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

      

I want to write a characteristic for a BLE device, following the code, it needs to pass 3 parameters: 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 can I set the characteristic via the above UUID, let it go to the function writeCharacteristic

?

Thanks in advance.

+1


source to share


2 answers


First you need to know what service UUID and what specific UUID for that service you want. Once you have these UUIDs, you can use this logic below to get the correct generic 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;
}

      

+5


source


You need to set up a delegate for the periphery:

peripheral.delegate = self;

      



In didConnectToPeripheral you will find peripheral services. In the peripheral didDiscoverServices callback, you discover the characteristics. In didDiscoverCharacteristics, you then loop through each characteristic and store it 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];
            }
        }
    }
}

      

+1


source







All Articles