assignment

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