Hardware Reference
In-Depth Information
Looking Up Characteristics Associated with Services
Core Bluetooth creates a CBService object for each discovered service by calling did
DiscoverServices . The following code discovers characteristics (see “Service and
Characteristic Discovery” on page 69 ) and stores them in an array of CBCharacteris
tic objects using the discoverCharacteristics method from the CBPeripheral class:
- ( void ) peripheral: ( CBPeripheral *) peripheral
didDiscoverServices: ( NSError *) error
{
// sort through each service and discover chararacteristics
// associated with each
for ( CBService * service in peripheral . services )
{
NSLog ( @ "Discovered service: %@" , service . UUID );
// discover characteristics associated with each service
[ peripheral discoverCharacteristics: nil forService: service ];
}
}
Use caution if you pass nil as a parameter to [peripheral discoverServices:nil]
and [peripheral discoverCharacteristics:nil forService:service] , because
the iOS device will then try to discover all the services and all the characteristics on the
peripheral. This can waste battery power and time if the remote peripheral implements
many more services and associated characteristics than the ones you're looking for.
That's not a problem in this case, because we're implementing only the ones of interest
on the peripheral side. But if it could be a problem in your particular application, use
lists of services and characteristics instead.
Once the services of interest and the associated characteristics are discovered, you need
to read the characteristic's values and make them available to the app. You can get the
values directly using the readValueForCharacteristic: method, which is a good ap‐
proach if the remote peripheral characteristic is static.
However, if the characteristic changes over time, as the battery level does, you should
use the BLE notifications feature, described in “Server-Initiated Updates” on page 72 .
When this is done for the battery level characteristic, the application will be notified
only when the value of the battery level changes. This avoids periodically polling the
remote peripheral for changes, which can be hard on the battery life of the central iOS
device because it creates unnecessary radio traffic.
You enable BLE notifications for a particular characteristic on the remote peripheral
using the setNotifyValue:forCharacteristic: method (which writes to the
corresponding CCCD on the peripheral, as explained in “Client Characteristic Config‐
uration Descriptor” on page 62 ), as shown in the following code for the battery level
Search WWH ::




Custom Search