An example of creating and updating a simple GATT Service using the BLE_API
Dependencies: BLE_API mbed nRF51822 X_NUCLEO_IDB0XA1
This example creates and updates a standard Battery Level service, and a single GATT characteristic that contains the battery level.
Diff: main.cpp
- Revision:
- 17:5afb0e5a48fc
- Parent:
- 16:5cdd04cf1ed4
--- a/main.cpp Sat Jun 20 23:22:18 2015 +0000 +++ b/main.cpp Tue Nov 03 16:03:18 2015 +0000 @@ -18,16 +18,16 @@ #include "BLE.h" #include "BatteryService.h" -BLE ble; - DigitalOut led1(LED1, 1); Ticker t; +BatteryService *batteryService = NULL; +uint8_t batteryLevel = 50; -void disconnectionCallback(Gap::Handle_t handle, Gap::DisconnectionReason_t reason) +void disconnectionCallback(const Gap::DisconnectionCallbackParams_t *disconnectionParams) { - printf("Disconnected handle %u!\n\r", handle); + printf("Disconnected handle %u!\n\r", disconnectionParams->handle); printf("Restarting the advertising process\n\r"); - ble.startAdvertising(); + BLE::Instance(BLE::DEFAULT_INSTANCE).gap().startAdvertising(); // restart advertising } void blink(void) @@ -35,23 +35,39 @@ led1 = !led1; } +void bleInitComplete(BLE::InitializationCompleteCallbackContext *params) +{ + BLE &ble = params->ble; + ble_error_t error = params->error; + Gap& gap = ble.gap(); + + if (error != BLE_ERROR_NONE) { + return; + } + + gap.onDisconnection(disconnectionCallback); + + batteryService = new BatteryService(ble, batteryLevel); + + /* setup advertising */ + gap.accumulateAdvertisingPayload(GapAdvertisingData::BREDR_NOT_SUPPORTED | GapAdvertisingData::LE_GENERAL_DISCOVERABLE); + gap.setAdvertisingType(GapAdvertisingParams::ADV_CONNECTABLE_UNDIRECTED); + gap.setAdvertisingInterval(1000); /* 1000ms; in multiples of 0.625ms. */ + gap.startAdvertising(); +} + int main(void) { - uint8_t batteryLevel = 50; t.attach(blink, 1.0f); printf("Initialising the nRF51822\n\r"); - ble.init(); - ble.onDisconnection(disconnectionCallback); - - BatteryService batteryService(ble, batteryLevel); + BLE& ble = BLE::Instance(BLE::DEFAULT_INSTANCE); + ble.init(bleInitComplete); - /* setup advertising */ - ble.accumulateAdvertisingPayload(GapAdvertisingData::BREDR_NOT_SUPPORTED); - ble.setAdvertisingType(GapAdvertisingParams::ADV_CONNECTABLE_UNDIRECTED); - ble.setAdvertisingInterval(1000); /* 1000ms; in multiples of 0.625ms. */ - ble.startAdvertising(); + /* SpinWait for initialization to complete. This is necessary because the + * BLE object is used in the main loop below. */ + while (ble.hasInitialized() == false) { /* spin loop */ } while (true) { ble.waitForEvent(); // this will return upon any system event (such as an interrupt or a ticker wakeup) @@ -62,6 +78,6 @@ batteryLevel = 20; } - batteryService.updateBatteryLevel(batteryLevel); + batteryService->updateBatteryLevel(batteryLevel); } }