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

Revision:
1:e79b40b523b4
Parent:
0:c201f85a188c
--- a/main.cpp	Tue Oct 24 18:13:18 2017 +0000
+++ b/main.cpp	Fri Dec 01 17:15:02 2017 +0000
@@ -17,59 +17,66 @@
 #include "mbed.h"
 #include "ble/BLE.h"
 #include "ble/DiscoveredCharacteristic.h"
-#include "LowPowerTimer.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;
 
-uint16_t latencyTime;
+timestamp_t latencyTime;
 uint8_t toggledValue = 0x1;
 uint8_t counter = 0;
 uint8_t randNumber = 5;
 uint8_t randCount = 10;
-bool connectionValid = false;
 
 static DiscoveredCharacteristic ledCharacteristic;
 static const char PEER_NAME[] = "LED";
-
+static Gap::ConnectionParams_t para;
 
 void periodicCallback(void) 
 { 
-    if(!connectionValid){
+    if(!BLE::Instance().getGapState().connected){
         alivenessLED = !alivenessLED; /* Do blinky on LED1 while waiting for BLE events */ 
         gateLED = 1;    
     }
     counter += 1;
 }
 
-void buttonPressedCallback(void)
+void triggerCallback(void)
 {   
     randCount = 0;
-    if(!connectionValid){
+    if(!BLE::Instance().getGapState().connected){
         //pc.printf("not connected \n");
         return;
     }
     else{
-        if(counter > 5){
+        if(counter > 5 && flagStop.read()){
             alivenessLED = 1;
-            latency.reset();
-            latency.start();
+            //latency.start(); 
+            flagStart = 1;
+            flagStop = 0;
             toggledValue = toggledValue ^ 0x1;
             ledCharacteristic.write(1, &toggledValue);
-            //pc.printf("LED toggled... \n");
+            //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 && connectionValid){
-        buttonPressedCallback();
+    if(randCount > randNumber+1 && BLE::Instance().getGapState().connected){
+    //if(BLE::Instance().getGapState().connected){
+
+        triggerCallback();
         gateLED = !gateLED;
     }      
 }
@@ -82,18 +89,26 @@
         if (record_length == 0) {
             continue;
         }
-        const uint8_t type = params->advertisingData[i + 1];
-        const uint8_t* value = params->advertisingData + i + 2;
+        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) {
+        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] rssi %d, isScanResponse %u, AdvertisementType %u\r\n",
+                    "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], params->rssi, params->isScanResponse, params->type
+                    params->peerAddr[1], params->peerAddr[0], value, params->rssi, params->isScanResponse, params->type
                 );
-                BLE::Instance().gap().connect(params->peerAddr, Gap::ADDR_TYPE_RANDOM_STATIC, NULL, NULL);
+                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;
             }
         }
@@ -103,27 +118,31 @@
 
 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().broadcast());
+    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;
-        connectionValid = true;
     }
 }
 
-void triggerReadCallback(const GattWriteCallbackParams *response) 
+void writeResponseCallback(const GattWriteCallbackParams *response) 
 {
-    if (response->handle == ledCharacteristic.getValueHandle()) {
-        ledCharacteristic.read();
-
-        latency.stop();
-        latencyTime = latency.read_us();
+    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",latencyTime);
-        pc.printf(" us \n");
+        //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");*/
     }
 }
 
@@ -133,6 +152,16 @@
         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");
     }
 }
 
@@ -141,7 +170,6 @@
     pc.printf("disconnected\r\n");
     /* Start scanning and try to connect again */
     BLE::Instance().gap().startScan(advertisementCallback);
-    connectionValid = false;
     counter = 0;
 }
 
@@ -169,30 +197,31 @@
     ble.gap().onDisconnection(disconnectionCallback);
     ble.gap().onConnection(connectionCallback);
 
-    ble.gattClient().onDataWrite(triggerReadCallback);
+    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);
-    pc.printf("Initialization starts... \n");
     
     ticker.attach(periodicCallback, 1); /* Blink LED every second */
     //button.rise(buttonPressedCallback);
-    loop.attach(randCallback, 0.1);
+    loop.attach(randCallback, 0.01);
     srand(time(NULL));
 
     BLE &ble = BLE::Instance();
     ble.init(bleInitComplete);
-    
+    pc.printf("Initialization complete... \n");
+
     counter = 0;
-    latency.reset();
+    //latency.reset();
 
     while (true) {
         ble.waitForEvent();