With this example the latency time of a simple toggle command can be measured. Central device is looking for a peripheral called LED, connects with it and toggles the LED periodically. The time until the service of the peripheral is updated, is measured as latency time

Dependencies:   BLE_API mbed nRF51822

main.cpp

Committer:
Alexgerni
Date:
2017-12-01
Revision:
1:e79b40b523b4
Parent:
0:c201f85a188c

File content as of revision 1:e79b40b523b4:

/* mbed Microcontroller Library
 * Copyright (c) 2006-2015 ARM Limited
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "mbed.h"
#include "ble/BLE.h"
#include "ble/DiscoveredCharacteristic.h"
#include "ble/Gap.h"

DigitalOut alivenessLED(p16, 1);
DigitalOut gateLED(p15,1);
DigitalOut flagStart(p2, 0);
DigitalOut flagStop(p3, 1);


//InterruptIn button(p9);
Serial pc(p5, p4);
Ticker ticker, loop;
Timer latency;

timestamp_t latencyTime;
uint8_t toggledValue = 0x1;
uint8_t counter = 0;
uint8_t randNumber = 5;
uint8_t randCount = 10;

static DiscoveredCharacteristic ledCharacteristic;
static const char PEER_NAME[] = "LED";
static Gap::ConnectionParams_t para;

void periodicCallback(void) 
{ 
    if(!BLE::Instance().getGapState().connected){
        alivenessLED = !alivenessLED; /* Do blinky on LED1 while waiting for BLE events */ 
        gateLED = 1;    
    }
    counter += 1;
}

void triggerCallback(void)
{   
    randCount = 0;
    if(!BLE::Instance().getGapState().connected){
        //pc.printf("not connected \n");
        return;
    }
    else{
        if(counter > 5 && flagStop.read()){
            alivenessLED = 1;
            //latency.start(); 
            flagStart = 1;
            flagStop = 0;
            toggledValue = toggledValue ^ 0x1;
            ledCharacteristic.write(1, &toggledValue);
            //pc.printf("AckStatus = %i \n", AckStatus);
        }    
    }
}

void randCallback(void) 
{   
    //Gap::GapState_t GapInfo; //class Gap with struct GapState_t
    randCount += 1;
    if(randCount > randNumber+1 && BLE::Instance().getGapState().connected){
    //if(BLE::Instance().getGapState().connected){

        triggerCallback();
        gateLED = !gateLED;
    }      
}

void advertisementCallback(const Gap::AdvertisementCallbackParams_t *params) 
{
    for (uint8_t i = 0; i < params->advertisingDataLen; ++i) {

        const uint8_t record_length = params->advertisingData[i];
        if (record_length == 0) {
            continue;
        }
        const uint8_t type = params->advertisingData[i + 1]; // PDU Advertising // AD length 1B / AD type 1B / AD data 0-22B //
        const uint8_t* value = params->advertisingData + i + 2; //pointer adresse + i + 2, so AD data
        const uint8_t value_length = record_length - 1;

        if(type == GapAdvertisingData::COMPLETE_LOCAL_NAME) { //0x09 is type of complete local name
            if ((value_length == sizeof(PEER_NAME)) && (memcmp(value, PEER_NAME, value_length) == 0)) { /* compares name LED with advertisingData*/
                pc.printf(
                    "adv peerAddr[%02x %02x %02x %02x %02x %02x], LocalName %s, rssi %d, isScanResponse %u, AdvertisementType %u\r\n",
                    params->peerAddr[5], params->peerAddr[4], params->peerAddr[3], params->peerAddr[2],
                    params->peerAddr[1], params->peerAddr[0], value, params->rssi, params->isScanResponse, params->type
                );
                printf("\r\n");

                //create wanted ConnectionParameters (defined in nrf51822/target_nrf5/source/nrf5xGap.cpp)
                para.minConnectionInterval = Gap::MSEC_TO_GAP_DURATION_UNITS(100);
                para.maxConnectionInterval = Gap::MSEC_TO_GAP_DURATION_UNITS(100);
                para.slaveLatency = 0;
                para.connectionSupervisionTimeout = 600;
                
                BLE::Instance().gap().connect(params->peerAddr, Gap::ADDR_TYPE_RANDOM_STATIC, &para, NULL);
                break;
            }
        }
        i += record_length;
    }
}

void characteristicDiscoveryCallback(const DiscoveredCharacteristic *characteristicP) 
{
    pc.printf("  C UUID-%x valueAttr[%u] props[%x]\r\n", characteristicP->getUUID().getShortUUID(), characteristicP->getValueHandle(), (uint8_t)characteristicP->getProperties().read());
    if (characteristicP->getUUID().getShortUUID() == 0xa001) { /* LED characteristic of device (Read/Write) */
        ledCharacteristic        = *characteristicP;
    }
}

void writeResponseCallback(const GattWriteCallbackParams *response) 
{
    if (response->handle == ledCharacteristic.getValueHandle()) { //handle is ID of connection
        //ledCharacteristic.read();
        //latency.stop();
        flagStart = 0;
        flagStop = 1;
        //latencyTime = latency.read_high_resolution_us();
        //latency.reset();

        //pc.printf("ledCharacteristic: %d %d\r\n",response->data[0],response->data[1]);
        //pc.printf("Latency Time: %d us \n",latencyTime);
        //writeVal(latencyTime);
        randNumber = rand()%10;    //number between 0 and 9
        /*pc.printf("triggerRead: handle %u, writeOp %u \r\n", response->connHandle, response->writeOp);
            for (unsigned index = 0; index < response->len; index++) {
                 printf("%c[%02x]", response->data[index], response->data[index]);
            }
        pc.printf("\r\n");*/
    }
}

void connectionCallback(const Gap::ConnectionCallbackParams_t *params) 
{
    if (params->role == Gap::CENTRAL) {
        BLE &ble = BLE::Instance();
        //ble.gattClient().onServiceDiscoveryTermination(discoveryTerminationCallback);
        ble.gattClient().launchServiceDiscovery(params->handle, NULL, characteristicDiscoveryCallback, 0xa000, 0xa001);
        
        uint16_t slaveLat = params->connectionParams->slaveLatency;
        uint16_t maxConnectionInt = params->connectionParams->maxConnectionInterval;
        uint16_t minConnectionInt = params->connectionParams->minConnectionInterval;
        uint16_t connectionTimeout = params->connectionParams->connectionSupervisionTimeout;

        pc.printf("slaveLatency %u, minConnection %u, maxConnection %u, connectionTimeout %u \n", slaveLat, minConnectionInt, maxConnectionInt, connectionTimeout);
        pc.printf("handle %u, role %u \n", params->handle, params->role);
        pc.printf("connected\r\n");
        pc.printf("\r\n");
    }
}

void disconnectionCallback(const Gap::DisconnectionCallbackParams_t *) 
{
    pc.printf("disconnected\r\n");
    /* Start scanning and try to connect again */
    BLE::Instance().gap().startScan(advertisementCallback);
    counter = 0;
}

void onBleInitError(BLE &ble, ble_error_t error)
{
   /* Initialization error handling should go here */
}

void bleInitComplete(BLE::InitializationCompleteCallbackContext *params)
{
    BLE&        ble   = params->ble;
    ble_error_t error = params->error;

    if (error != BLE_ERROR_NONE) {
        /* In case of error, forward the error handling to onBleInitError */
        onBleInitError(ble, error);
        return;
    }

    /* Ensure that it is the default instance of BLE */
    if (ble.getInstanceID() != BLE::DEFAULT_INSTANCE) {
        return;
    }

    ble.gap().onDisconnection(disconnectionCallback);
    ble.gap().onConnection(connectionCallback);

    ble.gattClient().onDataWritten(writeResponseCallback);

    // scan interval: 400ms and scan window: 400ms.
    // Every 400ms the device will scan for 400ms
    // This means that the device will scan continuously.
    ble.gap().setScanParams(400, 400);
    ble.gap().startScan(advertisementCallback);
    
}


int main(void) {
    pc.baud(115200);
    
    ticker.attach(periodicCallback, 1); /* Blink LED every second */
    //button.rise(buttonPressedCallback);
    loop.attach(randCallback, 0.01);
    srand(time(NULL));

    BLE &ble = BLE::Instance();
    ble.init(bleInitComplete);
    pc.printf("Initialization complete... \n");

    counter = 0;
    //latency.reset();

    while (true) {
        ble.waitForEvent();
    }
}