Write a proximity-aware Mbed-based LED scanner!

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