Modify the BLE LED Control so that it toggles the LED on the other board only if you keep the button pressed

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 <events/mbed_events.h>
00018 #include <mbed.h>
00019 #include "ble/BLE.h"
00020 #include "ble/DiscoveredCharacteristic.h"
00021 #include "ble/DiscoveredService.h"
00022 
00023 DigitalOut alivenessLED(LED1, 1);
00024 static DiscoveredCharacteristic ledCharacteristic;
00025 static bool triggerLedCharacteristic;
00026 static const char PEER_NAME[] = "LED_RED";
00027 InterruptIn button(USER_BUTTON);
00028 static uint8_t toggledValue = 0x0;
00029 
00030 static EventQueue eventQueue(/* event count */ 16 * EVENTS_EVENT_SIZE);
00031 
00032 void periodicCallback(void) {
00033     alivenessLED = !alivenessLED; /* Do blinky on LED1 while we're waiting for BLE events */
00034 }
00035 
00036 void advertisementCallback(const Gap::AdvertisementCallbackParams_t *params) {
00037     // parse the advertising payload, looking for data type COMPLETE_LOCAL_NAME
00038     // The advertising payload is a collection of key/value records where
00039     // byte 0: length of the record excluding this byte
00040     // byte 1: The key, it is the type of the data
00041     // byte [2..N] The value. N is equal to byte0 - 1
00042     for (uint8_t i = 0; i < params->advertisingDataLen; ++i) {
00043 
00044         const uint8_t record_length = params->advertisingData[i];
00045         if (record_length == 0) {
00046             continue;
00047         }
00048         const uint8_t type = params->advertisingData[i + 1];
00049         const uint8_t* value = params->advertisingData + i + 2;
00050         const uint8_t value_length = record_length - 1;
00051 
00052         if(type == GapAdvertisingData::COMPLETE_LOCAL_NAME) {
00053             if ((value_length == sizeof(PEER_NAME)) && (memcmp(value, PEER_NAME, value_length) == 0)) {
00054                 printf(
00055                     "adv peerAddr[%02x %02x %02x %02x %02x %02x] rssi %d, isScanResponse %u, AdvertisementType %u\r\n",
00056                     params->peerAddr[5], params->peerAddr[4], params->peerAddr[3], params->peerAddr[2],
00057                     params->peerAddr[1], params->peerAddr[0], params->rssi, params->isScanResponse, params->type
00058                 );
00059                 BLE::Instance().gap().connect(params->peerAddr, Gap::ADDR_TYPE_RANDOM_STATIC, NULL, NULL);
00060                 break;
00061             }
00062         }
00063         i += record_length;
00064     }
00065 }
00066 
00067 void serviceDiscoveryCallback(const DiscoveredService *service) {
00068     if (service->getUUID().shortOrLong() == UUID::UUID_TYPE_SHORT) {
00069         printf("S UUID-%x attrs[%u %u]\r\n", service->getUUID().getShortUUID(), service->getStartHandle(), service->getEndHandle());
00070     } else {
00071         printf("S UUID-");
00072         const uint8_t *longUUIDBytes = service->getUUID().getBaseUUID();
00073         for (unsigned i = 0; i < UUID::LENGTH_OF_LONG_UUID; i++) {
00074             printf("%02x", longUUIDBytes[i]);
00075         }
00076         printf(" attrs[%u %u]\r\n", service->getStartHandle(), service->getEndHandle());
00077     }
00078 }
00079 
00080 void updateLedCharacteristic(void) {
00081     if (!BLE::Instance().gattClient().isServiceDiscoveryActive()) {
00082         ledCharacteristic.read();
00083     }
00084 }
00085 
00086 void characteristicDiscoveryCallback(const DiscoveredCharacteristic *characteristicP) {
00087     printf("  C UUID-%x valueAttr[%u] props[%x]\r\n", characteristicP->getUUID().getShortUUID(), characteristicP->getValueHandle(), (uint8_t)characteristicP->getProperties().broadcast());
00088     if (characteristicP->getUUID().getShortUUID() == 0xa001) { /* !ALERT! Alter this filter to suit your device. */
00089         ledCharacteristic        = *characteristicP;
00090         triggerLedCharacteristic = true;
00091     }
00092 }
00093 
00094 void discoveryTerminationCallback(Gap::Handle_t connectionHandle) {
00095     printf("terminated SD for handle %u\r\n", connectionHandle);
00096     if (triggerLedCharacteristic) {
00097         triggerLedCharacteristic = false;
00098         eventQueue.call(updateLedCharacteristic);
00099     }
00100 }
00101 
00102 void connectionCallback(const Gap::ConnectionCallbackParams_t *params) {
00103     if (params->role == Gap::CENTRAL) {
00104         BLE &ble = BLE::Instance();
00105         ble.gattClient().onServiceDiscoveryTermination(discoveryTerminationCallback);
00106         ble.gattClient().launchServiceDiscovery(params->handle, serviceDiscoveryCallback, characteristicDiscoveryCallback, 0xa000, 0xa001);
00107     }
00108 }
00109 
00110 void triggerToggledWrite(const GattReadCallbackParams *response) {
00111     if (response->handle == ledCharacteristic.getValueHandle()) {
00112         printf("triggerToggledWrite: handle %u, offset %u, len %u\r\n", response->handle, response->offset, response->len);
00113         for (unsigned index = 0; index < response->len; index++) {
00114             printf("%c[%02x]", response->data[index], response->data[index]);
00115         }
00116         printf("\r\n");
00117 
00118         ledCharacteristic.write(1, &toggledValue);
00119     }
00120 }
00121 
00122 void triggerRead(const GattWriteCallbackParams *response) {
00123     if (response->handle == ledCharacteristic.getValueHandle()) {
00124         ledCharacteristic.read();
00125     }
00126 }
00127 
00128 void disconnectionCallback(const Gap::DisconnectionCallbackParams_t *) {
00129     printf("disconnected\r\n");
00130     /* Start scanning and try to connect again */
00131     BLE::Instance().gap().startScan(advertisementCallback);
00132 }
00133 
00134 void onBleInitError(BLE &ble, ble_error_t error)
00135 {
00136    /* Initialization error handling should go here */
00137 }
00138 
00139 void printMacAddress()
00140 {
00141     /* Print out device MAC address to the console*/
00142     Gap::AddressType_t addr_type;
00143     Gap::Address_t address;
00144     BLE::Instance().gap().getAddress(&addr_type, address);
00145     printf("DEVICE MAC ADDRESS: ");
00146     for (int i = 5; i >= 1; i--){
00147         printf("%02x:", address[i]);
00148     }
00149     printf("%02x\r\n", address[0]);
00150 }
00151 
00152 void bleInitComplete(BLE::InitializationCompleteCallbackContext *params)
00153 {
00154     BLE&        ble   = params->ble;
00155     ble_error_t error = params->error;
00156 
00157     if (error != BLE_ERROR_NONE) {
00158         /* In case of error, forward the error handling to onBleInitError */
00159         onBleInitError(ble, error);
00160         return;
00161     }
00162 
00163     /* Ensure that it is the default instance of BLE */
00164     if (ble.getInstanceID() != BLE::DEFAULT_INSTANCE) {
00165         return;
00166     }
00167 
00168     ble.gap().onDisconnection(disconnectionCallback);
00169     ble.gap().onConnection(connectionCallback);
00170     
00171     ble.gattClient().onDataRead(triggerToggledWrite);
00172     ble.gattClient().onDataWrite(triggerRead);
00173 
00174     // scan interval: 400ms and scan window: 400ms.
00175     // Every 400ms the device will scan for 400ms
00176     // This means that the device will scan continuously.
00177     ble.gap().setScanParams(400, 400);
00178     ble.gap().startScan(advertisementCallback);
00179 
00180     printMacAddress();
00181 }
00182 
00183 void scheduleBleEventsProcessing(BLE::OnEventsToProcessCallbackContext* context) {
00184     BLE &ble = BLE::Instance();
00185     eventQueue.call(Callback<void()>(&ble, &BLE::processEvents));
00186 }
00187 
00188 void btn_on (){
00189     toggledValue = 0x1;
00190 }
00191 
00192 void btn_off (){
00193     toggledValue = 0x0;
00194 }
00195 
00196 int main()
00197 {
00198     triggerLedCharacteristic = false;
00199     eventQueue.call_every(500, periodicCallback);
00200     
00201     button.fall(&btn_on);
00202     button.rise(&btn_off);
00203 
00204     BLE &ble = BLE::Instance();
00205     ble.onEventsToProcess(scheduleBleEventsProcessing);
00206     ble.init(bleInitComplete);
00207 
00208     eventQueue.dispatch_forever();
00209 
00210     return 0;
00211 }