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