An initial demo showcasing the GattClient APIs. Drives an LED service exported by a BLE_LED peripheral. Shows scanning, connections, service-discovery, and reads/writes.

Dependencies:   BLE_API mbed nRF51822

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers main.cpp Source File

main.cpp

00001 /* mbed Microcontroller Library
00002  * Copyright (c) 2006-2015 ARM Limited
00003  *
00004  * Licensed under the Apache License, Version 2.0 (the "License");
00005  * you may not use this file except in compliance with the License.
00006  * You may obtain a copy of the License at
00007  *
00008  *     http://www.apache.org/licenses/LICENSE-2.0
00009  *
00010  * Unless required by applicable law or agreed to in writing, software
00011  * distributed under the License is distributed on an "AS IS" BASIS,
00012  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
00013  * See the License for the specific language governing permissions and
00014  * limitations under the License.
00015  */
00016 
00017 #include "mbed.h"
00018 #include "ble/BLE.h"
00019 #include "ble/DiscoveredCharacteristic.h"
00020 #include "ble/DiscoveredService.h"
00021 
00022 DigitalOut alivenessLED(LED1, 1);
00023 
00024 bool                     triggerLedCharacteristic = false;
00025 DiscoveredCharacteristic ledCharacteristic;
00026 
00027 Ticker ticker;
00028 
00029 void periodicCallback(void) {
00030     alivenessLED = !alivenessLED; /* Do blinky on LED1 while we're waiting for BLE events */
00031 }
00032 
00033 void advertisementCallback(const Gap::AdvertisementCallbackParams_t *params) {
00034     if (params->peerAddr[0] != 0x37) { /* !ALERT! Alter this filter to suit your device. */
00035         return;
00036     }
00037     printf("adv peerAddr[%02x %02x %02x %02x %02x %02x] rssi %d, isScanResponse %u, AdvertisementType %u\r\n",
00038            params->peerAddr[5], params->peerAddr[4], params->peerAddr[3], params->peerAddr[2], params->peerAddr[1], params->peerAddr[0],
00039            params->rssi, params->isScanResponse, params->type);
00040 
00041     BLE::Instance().gap().connect(params->peerAddr, Gap::ADDR_TYPE_RANDOM_STATIC, NULL, NULL);
00042 }
00043 
00044 void serviceDiscoveryCallback(const DiscoveredService *service) {
00045     if (service->getUUID().shortOrLong() == UUID::UUID_TYPE_SHORT) {
00046         printf("S UUID-%x attrs[%u %u]\r\n", service->getUUID().getShortUUID(), service->getStartHandle(), service->getEndHandle());
00047     } else {
00048         printf("S UUID-");
00049         const uint8_t *longUUIDBytes = service->getUUID().getBaseUUID();
00050         for (unsigned i = 0; i < UUID::LENGTH_OF_LONG_UUID; i++) {
00051             printf("%02x", longUUIDBytes[i]);
00052         }
00053         printf(" attrs[%u %u]\r\n", service->getStartHandle(), service->getEndHandle());
00054     }
00055 }
00056 
00057 void characteristicDiscoveryCallback(const DiscoveredCharacteristic *characteristicP) {
00058     printf("  C UUID-%x valueAttr[%u] props[%x]\r\n", characteristicP->getUUID().getShortUUID(), characteristicP->getValueHandle(), (uint8_t)characteristicP->getProperties().broadcast());
00059     if (characteristicP->getUUID().getShortUUID() == 0xa001) { /* !ALERT! Alter this filter to suit your device. */
00060         ledCharacteristic        = *characteristicP;
00061         triggerLedCharacteristic = true;
00062     }
00063 }
00064 
00065 void discoveryTerminationCallback(Gap::Handle_t connectionHandle) {
00066     printf("terminated SD for handle %u\r\n", connectionHandle);
00067 }
00068 
00069 void connectionCallback(const Gap::ConnectionCallbackParams_t *params) {
00070     if (params->role == Gap::CENTRAL) {
00071         BLE::Instance().gattClient().onServiceDiscoveryTermination(discoveryTerminationCallback);
00072         BLE::Instance().gattClient().launchServiceDiscovery(params->handle, serviceDiscoveryCallback, characteristicDiscoveryCallback, 0xa000, 0xa001);
00073     }
00074 }
00075 
00076 void triggerToggledWrite(const GattReadCallbackParams *response) {
00077     if (response->handle == ledCharacteristic.getValueHandle()) {
00078 #if DUMP_READ_DATA
00079         printf("triggerToggledWrite: handle %u, offset %u, len %u\r\n", response->handle, response->offset, response->len);
00080         for (unsigned index = 0; index < response->len; index++) {
00081             printf("%c[%02x]", response->data[index], response->data[index]);
00082         }
00083         printf("\r\n");
00084 #endif
00085 
00086         uint8_t toggledValue = response->data[0] ^ 0x1;
00087         ledCharacteristic.write(1, &toggledValue);
00088     }
00089 }
00090 
00091 void triggerRead(const GattWriteCallbackParams *response) {
00092     if (response->handle == ledCharacteristic.getValueHandle()) {
00093         ledCharacteristic.read();
00094     }
00095 }
00096 
00097 void disconnectionCallback(const Gap::DisconnectionCallbackParams_t *params) {
00098     printf("disconnected\r\n");
00099 }
00100 
00101 /**
00102  * This function is called when the ble initialization process has failed
00103  */
00104 void onBleInitError(BLE &ble, ble_error_t error)
00105 {
00106     /* Initialization error handling should go here */
00107 }
00108 
00109 /**
00110  * Callback triggered when the ble initialization process has finished
00111  */
00112 void bleInitComplete(BLE::InitializationCompleteCallbackContext *params)
00113 {
00114     BLE&        ble   = params->ble;
00115     ble_error_t error = params->error;
00116 
00117     if (error != BLE_ERROR_NONE) {
00118         /* In case of error, forward the error handling to onBleInitError */
00119         onBleInitError(ble, error);
00120         return;
00121     }
00122 
00123     /* Ensure that it is the default instance of BLE */
00124     if(ble.getInstanceID() != BLE::DEFAULT_INSTANCE) {
00125         return;
00126     }
00127  
00128     ble.gap().onConnection(connectionCallback);
00129     ble.gap().onDisconnection(disconnectionCallback);
00130 
00131     ble.gattClient().onDataRead(triggerToggledWrite);
00132     ble.gattClient().onDataWrite(triggerRead);
00133 
00134     ble.gap().setScanParams(500, 400);
00135     ble.gap().startScan(advertisementCallback);
00136 }
00137 
00138 int main(void) {
00139     ticker.attach(periodicCallback, 1);
00140 
00141     BLE &ble = BLE::Instance();
00142     ble.init(bleInitComplete);
00143 
00144     /* SpinWait for initialization to complete. This is necessary because the
00145      * BLE object is used in the main loop below. */
00146     while (ble.hasInitialized()  == false) { /* spin loop */ }
00147 
00148     while (true) {
00149         if (triggerLedCharacteristic && !ble.gattClient().isServiceDiscoveryActive()) {
00150             triggerLedCharacteristic = false;
00151             ledCharacteristic.read(); /* We could have issued this read just as easily from
00152                                        * characteristicDiscoveryCallback(); but
00153                                        * invoking it here demonstrates the use
00154                                        * of isServiceDiscoveryActive() and also
00155                                        * the fact that it is permitted to
00156                                        * operate on application-local copies of
00157                                        * DiscoveredCharacteristic. */
00158         }
00159         ble.waitForEvent();
00160     }
00161 }