this is using the mbed os version 5-13-1

Dependencies:   mbed-http

Files at this revision

API Documentation at this revision

Comitter:
ocomeni
Date:
Thu May 02 21:50:17 2019 +0000
Parent:
102:9748f290a1a5
Child:
104:11e9605093c9
Commit message:
reached cloud hello message in box comms sequence

Changed in this revision

source/ATCmdManager.cpp Show annotated file Show diff for this revision Revisions of this file
source/ATCmdManager.h Show annotated file Show diff for this revision Revisions of this file
source/BleManager.cpp Show annotated file Show diff for this revision Revisions of this file
source/WiFiManager.cpp Show annotated file Show diff for this revision Revisions of this file
source/common_config.h Show annotated file Show diff for this revision Revisions of this file
source/common_types.h Show annotated file Show diff for this revision Revisions of this file
source/debug.cpp Show annotated file Show diff for this revision Revisions of this file
source/debug.h Show annotated file Show diff for this revision Revisions of this file
source/main-https.cpp Show annotated file Show diff for this revision Revisions of this file
source/mbed_memory_status.cpp Show annotated file Show diff for this revision Revisions of this file
source/ublox.h Show annotated file Show diff for this revision Revisions of this file
--- a/source/ATCmdManager.cpp	Wed Apr 24 17:34:17 2019 +0000
+++ b/source/ATCmdManager.cpp	Thu May 02 21:50:17 2019 +0000
@@ -1,9 +1,11 @@
+#include "debug.h"
 #include "ATCmdManager.h"
 #include "common_config.h"
 #include "common_types.h"
 #include "http_request.h"
 #include "mbed_memory_status.h"
 //#include "mbed_memory_status.h"
+#define FILE_CODE       "atcmd"
 
 ATCmdManager::ATCmdManager(PinName tx, PinName rx, SMDevicePeripheral *blePeripheral, 
                            events::EventQueue &event_queue, WiFiManager *wifi, 
@@ -38,11 +40,13 @@
 
 { 
 // constructor
-    _serial.set_baud(DEFAULT_BAUD_RATE);
+    _serial.set_baud(2*DEFAULT_BAUD_RATE);
+    //Flow flowCtrl = Flow::Disabled;
+    //_serial.set_flow_control(mbed::SerialBase::Disabled);
     _parser.debug_on(debug);
     _parser.set_delimiter("\r\n");
-    _parser.send("+STARTUP\r\n");
-    _parser.oob("AT\n", callback(this, &ATCmdManager::_oob_ok_hdlr));
+    _parser.send("+STARTUP\r\n\r\n");
+    _parser.oob("AT\r", callback(this, &ATCmdManager::_oob_ok_hdlr));
     _parser.oob("ATE0", callback(this, &ATCmdManager::_oob_echo_off));
     _parser.oob("ATE1", callback(this, &ATCmdManager::_oob_echo_on));
     _parser.oob("AT+UMRS", callback(this, &ATCmdManager::_oob_uart_setup));
@@ -67,6 +71,7 @@
     //_parser.oob("AT+UBTPM", callback(this, &ATCmdManager::_oob_ok_hdlr));
     //_parser.oob("AT+UWSCD=", callback(this, &ATCmdManager::_oob_disconnectWiFiNetwork));
     _parser.oob("AT+UDDRP", callback(this, &ATCmdManager::_oob_setupInternetConnection));
+    _parser.oob("AT+UWSC=0,0,0", callback(this, &ATCmdManager::_oob_ok_hdlr));
     _parser.oob("AT+UWSC=0,2", callback(this, &ATCmdManager::_oob_setWiFiSSID));
     _parser.oob("AT+UWSC=0,8", callback(this, &ATCmdManager::_oob_setWiFiPWD));
     _parser.oob("AT+UWSC=0,5", callback(this, &ATCmdManager::_oob_setWiFiSecurity));
@@ -74,19 +79,22 @@
     _parser.oob("AT+UWSSTAT", callback(this, &ATCmdManager::_oob_WiFiNetworkStatus));
     
     //_parser.oob("AT+UWSC=0,5", callback(this, &ATCmdManager::_oob_sendHttpMessage));
- 
-    printf("\n --- ATCmdManager constructor completed ---\n");
+    //sendAtConfirmation("Testing:: +UBTLE:2\r\nOK\r\n");
+    dbg_printf(LOG, "\n --- ATCmdManager constructor completed ---\n");
     at_resp = AT_RESP_NONE;
     dataMode = AT_CMD_DATA_MODE;
     debug_flag = 0;
     _event_queue.call_in(10, &print_heap_and_isr_stack_info);
     //print_heap_and_isr_stack_info();
     _event_queue.call_every(3600000,&print_memory_info);
+#ifdef BOX_UBLOX_DEMO_TESTING
+    check_for_at_cmd = false;
+#endif
 }
 
 
 void ATCmdManager::runMain(){
-    printf("\r\n [ATCMD MAN]  Thread Id = %X\r\n", (uint32_t)ThisThread::get_id());
+    dbg_printf(LOG, "\r\n [ATCMD MAN]  Thread Id = %X\r\n", (uint32_t)ThisThread::get_id());
     while(true){
         _process_oob(UBLOX_ODIN_W2_RECV_TIMEOUT, true);
         wait_ms(MAIN_LOOP_WAIT_TIME_MS); // allow BTLE/WiFi some time 
@@ -100,7 +108,7 @@
         dequeueWiFidataResponse();
         if(debug_flag>0){
             //debug_flag--;
-            printf(" back to ProcessResponses in Main loop... at_resp = %d\r\n", at_resp);
+            dbg_printf(LOG, " back to ProcessResponses in Main loop... at_resp = %d\r\n", at_resp);
         }
         char * respStr;
         //if(at_resp > AT_COMMAND_FAILED)
@@ -109,13 +117,13 @@
             case AT_RESP_NONE:
                 if(debug_flag>0){
                     debug_flag--;
-                    printf(" In IDLE state \r\n");
+                    dbg_printf(LOG, " In IDLE state \r\n");
                 }
                 // IDLE response state
                 break;
             case AT_SCAN_RESP:
                 // AT_SCAN_RESP response state
-                printf("\n [ATCMD MAN] WIFI SCAN RESPONSE RECEIVED!!\r\n");
+                dbg_printf(LOG, "\n [ATCMD MAN] WIFI SCAN RESPONSE RECEIVED!!\r\n");
                 //_smutex.lock();
                 //sendAtConfirmation(OK_RESP);   //_parser.send(OK_RESP);
                 //_smutex.unlock();
@@ -125,7 +133,7 @@
                 break;
             case AT_DETAILED_SCAN_RESP:
                 // AT_DETAILED_SCAN_RESP response state
-                printf("\n [ATCMD MAN] WIFI DETAILED SCAN RESPONSE RECEIVED!!\r\n");
+                dbg_printf(LOG, "\n [ATCMD MAN] WIFI DETAILED SCAN RESPONSE RECEIVED!!\r\n");
                 //_smutex.lock();
                 //sendAtConfirmation(OK_RESP);   //_parser.send(OK_RESP);
                 //_smutex.unlock();
@@ -136,9 +144,9 @@
             case AT_CONNECT_RESP:  
             {
                 // AT_CONNECT_RESP response state 
-                printf("\n [ATCMD MAN] WIFI CONNECT RESPONSE RECEIVED!!\r\n");
+                dbg_printf(LOG, "\n [ATCMD MAN] WIFI CONNECT RESPONSE RECEIVED!!\r\n");
                 //_smutex.lock();
-                //sendAtConfirmation(OK_RESP);   //_parser.send(OK_RESP);
+                sendAtConfirmation(OK_RESP);   //_parser.send(OK_RESP);
                 respStr = (char *) resp_data->buffer;
                 sendAtConfirmationFreeMpool(respStr);
                 char * urc = new char[20];
@@ -152,7 +160,7 @@
             case AT_DISCONNECT_RESP:  
                 // AT_DISCONNECT_RESP response state 
                 //////_smutex.lock();
-                printf("\n [ATCMD MAN] WIFI DISCONNECT RESPONSE RECEIVED!!\r\n");
+                dbg_printf(LOG, "\n [ATCMD MAN] WIFI DISCONNECT RESPONSE RECEIVED!!\r\n");
                 //_smutex.lock();
                 //sendAtConfirmation(OK_RESP);   //_parser.send(OK_RESP);
                 //_smutex.unlock();
@@ -163,7 +171,7 @@
             case AT_CONFIG_RESP:  
                 // AT_CONFIG_RESP response state 
                 //////_smutex.lock();
-                printf("\n [ATCMD MAN] WIFI CONFIG RESPONSE RECEIVED!!\r\n");
+                dbg_printf(LOG, "\n [ATCMD MAN] WIFI CONFIG RESPONSE RECEIVED!!\r\n");
                 //_smutex.lock();
                 sendAtConfirmation(OK_RESP);   //_parser.send(OK_RESP);
                 //_smutex.unlock();
@@ -172,7 +180,7 @@
             case AT_NETWORK_STATUS_RESP:  
                 // AT_CONFIG_RESP response state 
                 //////_smutex.lock();
-                printf("\n [ATCMD MAN] NETWORK STATUS RESPONSE RECEIVED!!\r\n");
+                dbg_printf(LOG, "\n [ATCMD MAN] NETWORK STATUS RESPONSE RECEIVED!!\r\n");
                 respStr = (char *) resp_data->buffer;
                 sendAtConfirmationFreeMpool(respStr);
                 at_resp = AT_RESP_NONE;
@@ -180,14 +188,14 @@
             case AT_WIFI_STATUS_RESP:  
                 // AT_CONFIG_RESP response state 
                 //////_smutex.lock();
-                printf("\n [ATCMD MAN] WIFI RESPONSE RECEIVED!!\r\n");
+                dbg_printf(LOG, "\n [ATCMD MAN] WIFI RESPONSE RECEIVED!!\r\n");
                 respStr = (char *) resp_data->buffer;
                 sendAtConfirmationFreeMpool(respStr);
                 at_resp = AT_RESP_NONE;
                 break;
             case AT_INTERNET_CONFIG_RESP:  
                 // AT_CONFIG_RESP response state 
-                printf("\n [ATCMD MAN] WIFI INTERNET_CONFIG RESPONSE RECEIVED!!\r\n");
+                dbg_printf(LOG, "\n [ATCMD MAN] WIFI INTERNET_CONFIG RESPONSE RECEIVED!!\r\n");
                 //_smutex.lock();
                 sendAtConfirmation(OK_RESP);   //_parser.send(OK_RESP);
                 //_smutex.unlock();
@@ -197,7 +205,7 @@
                 break;
             case AT_HTTPS_RESP:  
                 // AT_HTTP_RESP response state 
-                printf("\n [ATCMD MAN] WIFI HTTPS RESPONSE RECEIVED!!\r\n");
+                dbg_printf(LOG, "\n [ATCMD MAN] WIFI HTTPS RESPONSE RECEIVED!!\r\n");
                 return_response();
                 //_smutex.lock();
                 sendAtConfirmation(OK_RESP);   //_parser.send(OK_RESP);
@@ -206,7 +214,7 @@
                 break;
             case AT_HTTPS_RESP_DOWNLOAD:  
                 // AT_HTTPS_RESP_DOWNLOAD response state 
-                printf("\n [ATCMD MAN] WIFI HTTPS DOWNLOAD RESPONSE RECEIVED!!\r\n");
+                dbg_printf(LOG, "\n [ATCMD MAN] WIFI HTTPS DOWNLOAD RESPONSE RECEIVED!!\r\n");
                 return_response(true); // set download paramter to true
                 //_smutex.lock();
                 sendAtConfirmation(OK_RESP);   //_parser.send(OK_RESP);
@@ -215,16 +223,16 @@
                 break;
             case AT_HTTP_RESP:  
                 // AT_HTTP_RESP response state 
-                printf("\n [ATCMD MAN] WIFI HTTP RESPONSE RECEIVED!!\r\n");
+                dbg_printf(LOG, "\n [ATCMD MAN] WIFI HTTP RESPONSE RECEIVED!!\r\n");
                 return_response(); 
                 //_smutex.lock();
-                sendAtConfirmation(OK_RESP);   //_parser.send(OK_RESP);
+                //sendAtConfirmation(OK_RESP);   //_parser.send(OK_RESP);
                 //_smutex.unlock();
                 at_resp = AT_RESP_NONE;
                 break;
             case AT_HTTP_RESP_DOWNLOAD:  
                 // AT_HTTP_RESP response state 
-                printf("\n [ATCMD MAN] WIFI HTTP RESPONSE RECEIVED!!\r\n");
+                dbg_printf(LOG, "\n [ATCMD MAN] WIFI HTTP RESPONSE RECEIVED!!\r\n");
                 return_response(true); // set download paramter to true
                 //_smutex.lock();
                 //sendAtConfirmation(OK_RESP);   //_parser.send(OK_RESP);
@@ -234,7 +242,7 @@
             case CONNECT_EVENT:  
             {
                 // Connect Event state 
-                printf("\n [ATCMD MAN] CONNECT EVENT RECEIVED!!\r\n");
+                dbg_printf(LOG, "\n [ATCMD MAN] CONNECT EVENT RECEIVED!!\r\n");
                 sendConnectEvent(resp_data->buffer, resp_data->dataLen);
                 at_resp = AT_RESP_NONE;
                 break;
@@ -242,7 +250,7 @@
             case AT_EVENT:  
             {
                 // AT Event state 
-                printf("\n [ATCMD MAN] AT EVENT RECEIVED!!\r\n");
+                dbg_printf(LOG, "\n [ATCMD MAN] AT EVENT RECEIVED!!\r\n");
                 respStr = (char *) resp_data->buffer;
                 sendAtEvent(respStr);
                 at_resp = AT_RESP_NONE;
@@ -251,7 +259,7 @@
             case AT_COMMAND_FAILED:  
             {
                 // AT_HTTP_RESP response state 
-                printf("\n [ATCMD MAN] WIFI COMMAND FAILED!!\r\n");
+                dbg_printf(LOG, "\n [ATCMD MAN] WIFI COMMAND FAILED!!\r\n");
                 //_smutex.lock();
                 //_parser.send("\r\nNACK\r\n");
                 //_smutex.unlock();
@@ -263,7 +271,7 @@
             default:
                  //UNKNOWN response state
                 //_smutex.lock();
-                printf("\n [ATCMD MAN] UNKNOWN RESPONSE RECEIVED!!\r\n");
+                dbg_printf(LOG, "\n [ATCMD MAN] UNKNOWN RESPONSE RECEIVED!!\r\n");
                 sendAtConfirmationFreeMpool(ERROR_RESP);   //_parser.send(OK_RESP);
                 //_smutex.unlock();
                 at_resp = AT_RESP_NONE;
@@ -283,10 +291,10 @@
 void ATCmdManager::printBufferInHex(uint8_t *buf, int pLen)
 {
     for(int i =0;i<pLen;i++){
-        if(i%8==0) printf("\n[%3d]",i);
-        printf("%02x ", buf[i]);
+        if(i%8==0) dbg_printf(LOG, "\n[%3d]",i);
+        dbg_printf(LOG, "%02x ", buf[i]);
     }
-    printf("\n");
+    dbg_printf(LOG, "\n");
 }
 
 bool ATCmdManager::validate(edm_header_t edm_header)
@@ -339,14 +347,14 @@
     char * nxtPtr = strPtr;
     char * outPtr;
     char * bodyPtr = p2+4;
-    printf("\nstrPtr address= %x",strPtr);
-    printf("\np2 address= %x", p2);
+    dbg_printf(LOG, "\nstrPtr address= %x",strPtr);
+    dbg_printf(LOG, "\np2 address= %x", p2);
     for(int i = 0; i < 5; i++){
         if(i == 0)// firstline scan method uri and http_ver
         {
             n = sscanf(nxtPtr,"%s %s %s", s1, s2, s3);
             if(n!=3) return false; // error in input abort
-            printf("\nmethod = %s\nuri = %s\nhttp_ver = %s",s1, s2, s3 );
+            dbg_printf(LOG, "\nmethod = %s\nuri = %s\nhttp_ver = %s",s1, s2, s3 );
             //http_req.method = str2HttpMethod(s1.c_str());
             http_req->method = str2HttpMethod(s1);
             http_req->request_URI = (char *) http_req->buffer; // point 1st string to start of buffer
@@ -355,10 +363,10 @@
             http_req->http_version = http_req->request_URI + len; // point 2nd string to after 1st
             len = strlen(s3)+1;
             strncpy(http_req->http_version, s3, len);
-            printf("\nhttp_request 1st line:\n method = %d\nuri = %s\nhttp_ver = %s",http_req->method, 
+            dbg_printf(LOG, "\nhttp_request 1st line:\n method = %d\nuri = %s\nhttp_ver = %s",http_req->method, 
                                                                       http_req->request_URI, 
                                                                       http_req->http_version );
-            printf("\nhttp_request str ptrs\nuri = %X\nhttp_ver = %X",http_req->request_URI, 
+            dbg_printf(LOG, "\nhttp_request str ptrs\nuri = %X\nhttp_ver = %X",http_req->request_URI, 
                                                                       http_req->http_version );
             outPtr = http_req->http_version + len; // point output buffer ptr to after 2nd string
         }
@@ -368,26 +376,26 @@
             if(n!=2) return false; // error in input abort
             p = strstr(s1,":");
             *p = NULL;
-            printf("\nname = %s value = %s",s1, s2);
+            dbg_printf(LOG, "\nname = %s value = %s",s1, s2);
             if(strstr(s1, "Host")!= NULL){
                 http_req->hostName = outPtr;
                 len = strlen(s2)+1;                
                 strncpy(outPtr, s2, len);
-                printf("\nname = %s value = %s",s1, outPtr);
+                dbg_printf(LOG, "\nname = %s value = %s",s1, outPtr);
                 outPtr += len; // point output buffer ptr to after current string
             }
             else if(strstr(s1, "Accept")!= NULL){
                 http_req->AcceptVal = outPtr;
                 len = strlen(s2)+1;                
                 strncpy(outPtr, s2, len);
-                printf("\nname = %s value = %s",s1, outPtr);
+                dbg_printf(LOG, "\nname = %s value = %s",s1, outPtr);
                 outPtr += len; // point output buffer ptr to after current string
             }
             else if(strstr(s1, "Content-Type")!= NULL){
                 http_req->contentType = outPtr;
                 len = strlen(s2)+1;                
                 strncpy(outPtr, s2, len);
-                printf("\nname = %s value = %s",s1, outPtr);
+                dbg_printf(LOG, "\nname = %s value = %s",s1, outPtr);
                 outPtr += len; // point output buffer ptr to after current string
             }
             else if(strstr(s1, "Content-Length")!= NULL){
@@ -395,31 +403,31 @@
                 http_req->contentLen = outPtr;
                 len = strlen(s2)+1;                
                 strncpy(outPtr, s2, len);
-                printf("\nname = %s value = %s",s1, outPtr);
+                dbg_printf(LOG, "\nname = %s value = %s",s1, outPtr);
                 outPtr += len; // point output buffer ptr to after current string
             }
             
-            printf("\noutPtr = %X len = %d\n", outPtr, len);
+            dbg_printf(LOG, "\noutPtr = %X len = %d\n", outPtr, len);
         }
         nxtPtr = strstr(nxtPtr, "\r\n")+2; // goto next line
         if(nxtPtr >= p2) break;
     }
     // print header from http_req_struct
-    printf("\nhttp request header: \n %s\n", http_req->buffer);
+    dbg_printf(LOG, "\nhttp request header: \n %s\n", http_req->buffer);
     int bodyLen = edm_hdr.payloadLen -(p2+7-strPtr);
-    printf("\nLen = %d\n", bodyLen);
+    dbg_printf(LOG, "\nLen = %d\n", bodyLen);
     http_req->body = (uint8_t *) outPtr;
     memcpy(outPtr, bodyPtr, bodyLen);
     if(bodyLen > 10){
-        printf("\n Message Body:\n");
+        dbg_printf(LOG, "\n Message Body:\n");
         printBufferInHex(http_req->body, bodyLen);
     }
     outPtr += bodyLen; // move output pointer to end output (header + body)
     // package and send on wifi data queue
     data_msg.wifi_cmd = WIFI_CMD_SEND_HTTPS_REQ;
-    printf("\nsizeof(http_req) on population = %d\n", sizeof(*http_req));
+    dbg_printf(LOG, "\nsizeof(http_req) on population = %d\n", sizeof(*http_req));
     data_msg.dataLen = (uint8_t *)outPtr - http_req->buffer;//sizeof(http_request_t);
-    printf("\ndata_msg.dataLen = %d\n", data_msg.dataLen);
+    dbg_printf(LOG, "\ndata_msg.dataLen = %d\n", data_msg.dataLen);
     // queue next data request
     queueWiFiDataRequest(data_msg);
     return true;
@@ -433,7 +441,7 @@
     if(dataMode == AT_EXT_DATA_MODE)
     {
         int n;
-        //if(cnt++ % 10 == 0)printf("In EDM mode\n");
+        //if(cnt++ % 10 == 0)dbg_printf(LOG, "In EDM mode\n");
         uint8_t edm[EDM_HDR_LEN];
         char cmdType[16];
         // Poll for edm packets
@@ -458,10 +466,10 @@
                 pT = 1;
                 strcpy(cmdType, "AT REQUEST");
             }
-            //printf("%d bytes read! : type = %s\n", n, cmdType2str(edm_hdr.payloadID));
-            printf("%d bytes read! : CMD type = %s\n", n, cmdType);
+            //dbg_printf(LOG, "%d bytes read! : type = %s\n", n, cmdType2str(edm_hdr.payloadID));
+            dbg_printf(LOG, "%d bytes read! : CMD type = %s\n", n, cmdType);
             if(n==(EDM_HDR_LEN-pT))
-            printf("Start = %d, payloadID = %d len = %d chan_id = %d\n", edm_hdr.startByte, 
+            dbg_printf(LOG, "Start = %d, payloadID = %d len = %d chan_id = %d\n", edm_hdr.startByte, 
                                                                          edm_hdr.payloadID, 
                                                                          edm_hdr.payloadLen,
                                                                          edm_hdr.channel_id);
@@ -472,7 +480,7 @@
                     //_parser.process_oob();
                     while (_parser.process_oob() && all) {
                         if(debug_flag>0){
-                            printf("finished queuing WIFI CONNECT CMD -- back to process_oob loop \r\n");
+                            dbg_printf(LOG, "finished queuing WIFI CONNECT CMD -- back to process_oob loop \r\n");
                         }
                     }
                     break;
@@ -484,9 +492,9 @@
                     rx_buf_ptr[pLen-1] = 0x00; // clear last byte so the readback value is as expected
                     n = _parser.read((char *)rx_buf_ptr, pLen);
                     if(n == -1) break; // timeout!
-                    printf("%d bytes read - expected %d!\n", n, pLen);
+                    dbg_printf(LOG, "%d bytes read - expected %d!\n", n, pLen);
                     printBufferInHex(rx_buf_ptr, pLen);
-                    printf("rx_buf_ptr[pLen-1] = %0x\n",rx_buf_ptr[pLen-1]);
+                    dbg_printf(LOG, "rx_buf_ptr[pLen-1] = %0x\n",rx_buf_ptr[pLen-1]);
                     if(rx_buf_ptr[pLen-1] != EDM_STOP_BYTE) {
                         _smutex.lock();
                         _parser.send("ERR");
@@ -498,18 +506,18 @@
                     switch(edm_hdr.payloadID)
                     {
                         case CONNECT_EVENT_ID:
-                            printf("Connection Event received!\n");
+                            dbg_printf(LOG, "Connection Event received!\n");
                             break;
                         case DISCONNECT_EVENT_ID:
-                            printf("DISCONNECT_EVENT received!\n");
+                            dbg_printf(LOG, "DISCONNECT_EVENT received!\n");
                             break;
                         case DATA_EVENT_ID:
-                            printf("DATA_EVENT received!\n");
+                            dbg_printf(LOG, "DATA_EVENT received!\n");
                             break;
                         case DATA_COMMAND_ID:
                         {
-                            printf("DATA_COMMAND received!\n");
-                            sendAtConfirmation(OK_RESP);   //_parser.send(OK_RESP);
+                            dbg_printf(LOG, "DATA_COMMAND received!\n");
+                            //sendAtConfirmation(OK_RESP);   //_parser.send(OK_RESP);
                             if(createHttpRequest() == true){
                                 //_smutex.lock();
                                 //sendAtConfirmation(OK_RESP);   //sendAtConfirmation(OK_RESP);   //_parser.send(OK_RESP);
@@ -523,20 +531,20 @@
                             free(rx_buf_ptr);
                             rx_buf_ptr = NULL;
                             int stop = Kernel::get_ms_count();
-                            printf("\n Time Elapsed = %d\n", stop-start);
+                            dbg_printf(LOG, "\n Time Elapsed = %d\n", stop-start);
                             break;
                         }
                         case AT_REQUEST_ID:
-                            printf("AT_REQUEST received!\n");
+                            dbg_printf(LOG, "AT_REQUEST received!\n");
                             break;
                         case AT_CONFIRMATION_ID:
-                            printf("AT_CONFIRMATION received!\n");
+                            dbg_printf(LOG, "AT_CONFIRMATION received!\n");
                             break;
                         case AT_EVENT_ID:
-                            printf("AT_EVENT received!\n");
+                            dbg_printf(LOG, "AT_EVENT received!\n");
                             break;
                         default:
-                            printf("UNKNOWN MESSAGE received!\n");
+                            dbg_printf(LOG, "UNKNOWN MESSAGE received!\n");
                             break;
                     }
                 }
@@ -552,17 +560,64 @@
     {
         // Poll for inbound packets
         static int msgCnt = 0;
+        static char * ATCMD = new char[32];
+        int n = 0;
+#ifdef BOX_UBLOX_DEMO_TESTING
+        if(check_for_at_cmd)
+        {
+            while (n>=0 && all) {
+                n = readAtCommandString(ATCMD, 32);
+                if(strstr(ATCMD,"AT\r") != NULL)
+                {
+                    _oob_ok_hdlr();
+                    check_for_at_cmd = false;
+                    break;
+                }
+            }
+        }
+        else
+#endif
+        {
         while (_parser.process_oob() && all) {
-                        printf("inbound message found... msgCnt = %d \r\n", ++msgCnt);
+                        dbg_printf(LOG, "inbound message found... msgCnt = %d \r\n", ++msgCnt);
                         if(debug_flag>0){
-                            printf("finished queuing WIFI CONNECT CMD -- back to process_oob loop \r\n");
+                            dbg_printf(LOG, "finished queuing WIFI CONNECT CMD -- back to process_oob loop \r\n");
                         }
         }
+        }
     }        
     set_timeout();
 }
 
 
+int ATCmdManager::readAtCommandString(char *strbuf, size_t bufLen)
+{
+    int n;
+    bool atstr_found = false;
+    int i = 0;
+    while(n != -1)
+    {
+        char c;
+        n = _parser.read(&c, 1);
+        if(n)
+        strbuf[i++] = c;
+        if(c=='\r')
+        {
+            strbuf[i++] = NULL; // terminate string and exit
+            atstr_found = true;
+            break;
+        }
+    }
+    if(atstr_found)
+    {
+        return i;
+    }
+    else
+    {
+        return -1;
+    }
+}
+
 // OOB message handlers
 void ATCmdManager::_oob_startup_hdlr(){
 }
@@ -599,23 +654,31 @@
 #endif
 }
 
-
+#define TTP_DEBUGGING
 void ATCmdManager::_oob_uart_setup(){
     int uOpts[NUM_UART_OPTIONS];
     //if(_parser.recv("=%d,%d,%d,%d,%d,%d", &uOpts[0], &uOpts[1], &uOpts[2], &uOpts[3], &uOpts[4], &uOpts[5])) {
     if(_parser.scanf("=%d,%d,%d,%d,%d,%d", &uOpts[0], &uOpts[1], &uOpts[2], &uOpts[3], &uOpts[4], &uOpts[5]) >0) {
-        printf("\nATCmdParser: Uart Options=%d,%d,%d,%d,%d,%d\n", uOpts[0], uOpts[1], uOpts[2], uOpts[3], uOpts[4], uOpts[5]);
+        dbg_printf(LOG, "\nATCmdParser: Uart Options=%d,%d,%d,%d,%d,%d\n", uOpts[0], uOpts[1], uOpts[2], uOpts[3], uOpts[4], uOpts[5]);
+        //printf("\nATCmdParser: Uart Options=%d,%d,%d,%d,%d,%d\n", uOpts[0], uOpts[1], uOpts[2], uOpts[3], uOpts[4], uOpts[5]);
        //AT+UMRS=230400,2,8,1,1,1
-        printf("\n Changing Baud Rate to %d\n", uOpts[0]);
+        dbg_printf(LOG, "\n Changing Baud Rate to %d\n", uOpts[0]);
+#ifdef TTP_DEBUGGING
+    sendAtConfirmation(OK_RESP);
+#else
 
         sendAtConfirmation(OK_RESP);   //_parser.send(OK_RESP);
         wait(0.1);
         _serial.set_baud(uOpts[0]);
         wait(0.1);
-        printf("\n Baud Rate now %d\n", uOpts[0]);
+        dbg_printf(LOG, "\n Baud Rate now %d\n", uOpts[0]);
+#endif
+#ifdef BOX_UBLOX_DEMO_TESTING
+    check_for_at_cmd = true;
+#endif
 
     } else {
-        printf("\nATCmdParser: Retrieving Uart Options failed");
+        dbg_printf(LOG, "\nATCmdParser: Retrieving Uart Options failed");
     }
 }
 
@@ -628,8 +691,9 @@
 void ATCmdManager::_oob_echo_off()
 {
     //_smutex.lock();
-    printf("\n Received ATEO OOB command!!\n");
-    printf("\n turning echo OFF!!\n");
+    dbg_printf(LOG, "\n Received ATEO OOB command!!\n");
+    dbg_printf(LOG, "\n turning echo OFF!!\n");
+    //printf("\n turning echo OFF!!\n");
     _parser.debug_on(false);
     sendAtConfirmation(OK_RESP);   //_parser.send(OK_RESP);
     //_smutex.unlock();
@@ -639,8 +703,8 @@
 void ATCmdManager::_oob_echo_on()
 {
     //_smutex.lock();
-    printf("\n Received ATE1 OOB command!!\n");
-    printf("\n turning echo ON!!\n");
+    dbg_printf(LOG, "\n Received ATE1 OOB command!!\n");
+    dbg_printf(LOG, "\n turning echo ON!!\n");
     _parser.debug_on(true);
     sendAtConfirmation(OK_RESP);   //_parser.send(OK_RESP);
     //_smutex.unlock();
@@ -649,32 +713,33 @@
 
 void ATCmdManager::_oob_data_mode(){
     //_smutex.lock();
-    printf("\n Received EDM mode command!!\n");
-    if(_parser.scanf("%d", &dataMode) >0) {
-        printf("\nATCmdParser: Data mode=%d\r\n", dataMode);
+    dbg_printf(LOG, "\n Received EDM mode command!!\n");
+    int dmode;
+    if(_parser.scanf("%d", &dmode) >0) {
+        dbg_printf(LOG, "\nATCmdParser: Data mode=%d\r\n", dataMode);
         sendAtConfirmation(OK_RESP);   //_parser.send(OK_RESP);
-        switch(dataMode)
+        switch(dmode)
         {
             case 0:
-                printf("\nATCmdParser: Command Mode request received\n");
+                dbg_printf(LOG, "\nATCmdParser: Command Mode request received\n");
                 dataMode = AT_CMD_DATA_MODE;
                 break;
             case 1:
-                printf("\nATCmdParser: Data Mode request received\n");
+                dbg_printf(LOG, "\nATCmdParser: Data Mode request received\n");
                 dataMode = AT_STD_DATA_MODE;
                 break;
             case 2:
-                printf("\nATCmdParser: Extended data Mode request received\n");
+                dbg_printf(LOG, "\nATCmdParser: Extended data Mode request received\n");
                 dataMode = AT_EXT_DATA_MODE;
                 _event_queue.call_in(10, &print_heap_and_isr_stack_info);
                 //print_heap_and_isr_stack_info();
                 break;
             default:
-                printf("\nATCmdParser: ERROR - UNKNOWN DATA MODE RECEIVED!!! \n");
+                dbg_printf(LOG, "\nATCmdParser: ERROR - UNKNOWN DATA MODE RECEIVED!!! \n");
                 break;
         }
     } else {
-        printf("\nATCmdParser: Retrieving Uart Options failed\n");
+        dbg_printf(LOG, "\nATCmdParser: Retrieving Uart Options failed\n");
     }
     //_smutex.unlock();
 }
@@ -686,17 +751,17 @@
         switch(bleOrWifi)
         {
             case 1:
-                printf("\nATCmdParser: BLE MAC Address request received");
+                dbg_printf(LOG, "\nATCmdParser: BLE MAC Address request received");
                 break;
             case 2:
-                printf("\nATCmdParser: WiFi MAC Address request received");
+                dbg_printf(LOG, "\nATCmdParser: WiFi MAC Address request received");
                 break;
             default:
-                printf("\nATCmdParser: ERROR - UNKNOWN MAC ADDRESS REQUEST RECEIVED!!! \n");
+                dbg_printf(LOG, "\nATCmdParser: ERROR - UNKNOWN MAC ADDRESS REQUEST RECEIVED!!! \n");
                 break;
         }
     } else {
-        printf("\nATCmdParser: Retrieving Uart Options failed");
+        dbg_printf(LOG, "\nATCmdParser: Retrieving Uart Options failed");
     }
     sendAtConfirmation(OK_RESP);   //_parser.send(OK_RESP);
     //_smutex.unlock();
@@ -704,23 +769,24 @@
 
 void ATCmdManager::_oob_get_ble_role(){
     //_smutex.lock();
-    printf("\n Received get BLE role command!!\n");
-    sendAtConfirmation(OK_RESP);   //_parser.send(OK_RESP);
+    dbg_printf(LOG, "\n Received get BLE role command!!\n");
+    //printf("\n Received get BLE role command!!\n");
+    sendAtConfirmation("+UBTLE:2\r\nOK\r\n");   //_parser.send(OK_RESP);
     //_smutex.unlock();
 }
 
 void ATCmdManager::_oob_ena_ble_peri(){
     //_smutex.lock();
-    printf("\n Received enable BLE Peripheral command!!\n");
+    dbg_printf(LOG, "\n Received enable BLE Peripheral command!!\n");
     sendAtConfirmation(OK_RESP);   //_parser.send(OK_RESP);
     //_smutex.unlock();
 }
 
 void ATCmdManager::_oob_reboot(){
     //_smutex.lock();
-    printf("\n Received reboot command!!\n");
+    dbg_printf(LOG, "\n Received reboot command!!\n");
     sendAtConfirmation(OK_RESP);   //_parser.send(OK_RESP);
-    _parser.send("System Resetting....\n");
+    //_parser.send("System Resetting....\n");
     system_reset();
     //_smutex.unlock();
 }
@@ -756,7 +822,7 @@
 
 void ATCmdManager::_oob_scanWiFiNetworks(){
     //_smutex.lock();
-    printf("\n Received scanWiFiNetworks command!!\n");
+    dbg_printf(LOG, "\n Received scanWiFiNetworks command!!\n");
     sendAtConfirmation(OK_RESP);   //_parser.send(OK_RESP);
     //_smutex.unlock();
     wifi_cmd_t cmd = WIFI_CMD_SCAN;
@@ -773,8 +839,8 @@
     int aId; // interface id for request
     _parser.recv("%d,%d", &if_id, &aId);
     //_smutex.lock();
-    printf("\n Received WiFi Configuration Action command %d %d!!\r\n", if_id, aId);
-    sendAtConfirmation(OK_RESP);   //_parser.send(OK_RESP);
+    dbg_printf(LOG, "\n Received WiFi Configuration Action command %d %d!!\r\n", if_id, aId);
+    //sendAtConfirmation(OK_RESP);   //_parser.send(OK_RESP);
     if(if_id == WIFI_CONFIG_ID && aId <5){
         wifi_cmd_t cmd;
         action_id_t action_id = (action_id_t) aId;
@@ -787,14 +853,14 @@
                 break;
             case WIFI_CONFIG_ACTIVATE:
                 cmd = WIFI_CMD_CONNECT;
-                printf("\n About to Queue wifi cmd = %d!!\n", cmd);
+                dbg_printf(LOG, "\n About to Queue wifi cmd = %d!!\n", cmd);
                 //_smutex.unlock();
                 // queue next command
                 queueWiFiCommand(cmd);
                 break;
             case WIFI_CONFIG_DEACTIVATE:
                 cmd = WIFI_CMD_DISCONNECT;
-                printf("\n About to Queue wifi cmd = %d!!\n", cmd);
+                dbg_printf(LOG, "\n About to Queue wifi cmd = %d!!\n", cmd);
                 //_smutex.unlock();
                 // queue next command
                 queueWiFiCommand(cmd);
@@ -804,7 +870,7 @@
         }
     }
     if(debug_flag>0){
-        printf("finished queuing WIFI CONNECT CMD \r\n");
+        dbg_printf(LOG, "finished queuing WIFI CONNECT CMD \r\n");
     }
     return;
 }
@@ -813,7 +879,7 @@
 void ATCmdManager::_oob_disconnectWiFiNetwork()
 {
     //_smutex.lock();
-    printf("\n Received WiFi Disconnect command!!\n");
+    dbg_printf(LOG, "\n Received WiFi Disconnect command!!\n");
     sendAtConfirmation(OK_RESP);   //_parser.send(OK_RESP);
     wifi_cmd_t cmd = WIFI_CMD_DISCONNECT;
     //_smutex.unlock();
@@ -829,15 +895,19 @@
     int n;
     internet_config_t internet_config;
     //_smutex.lock();
-    printf("sizeof internet_config_t = %d\n", sizeof(internet_config_t));
+    dbg_printf(LOG, "sizeof internet_config_t = %d\n", sizeof(internet_config_t));
     n = ReadBytes((uint8_t *)str, MAX_URL_LEN);
     str[n]=NULL;
-    printf("\n read string = %s , n = %d\n", str, n);
+    dbg_printf(LOG, "\n read string = %s , n = %d\n", str, n);
     //n = sscanf(str, "=%1d,%199[^,],%1d", &(uint8_t)internet_config.peer_id, 
     n = sscanf(str, "=%1d,%99[^,],%1d", &internet_config.peer_id, 
                                          url, //internet_config.url,    
                                         &internet_config.connectionScheme);
+#ifdef BOX_UBLOX_DEMO_TESTING
+    char *p = strstr(url,"/https:"); 
+#else
     char *p = strstr(url,"\""); 
+#endif
     if(p!=NULL)
     {
         strncpy(internet_config.url, &p[1], strlen(url));
@@ -848,24 +918,24 @@
     {
         strncpy(internet_config.url, url, strlen(url)+1);
     }
-    printf("\n read string = %s , n = %d -- strlen(url) = %d\n", internet_config.url, n, strlen(internet_config.url));
+    dbg_printf(LOG, "\n read string = %s , n = %d -- strlen(url) = %d\n", internet_config.url, n, strlen(internet_config.url));
     if(n>0) 
     {
-        printf("peer_id = %1d, url = %s, connScheme = %1d\n", internet_config.peer_id, 
+        dbg_printf(LOG, "peer_id = %1d, url = %s, connScheme = %1d\n", internet_config.peer_id, 
                                                               internet_config.url, 
                                                               internet_config.connectionScheme);
         // package and send on wifi data queue
         wifi_data_msg_t data_msg; 
         data_msg.wifi_cmd = WIFI_CMD_INTERNET_CONFIG;
         data_msg.dataLen = sizeof(internet_config_t); // + strlen(internet_config.url);
-        printf("\n url size = %d url str = %s\n",strlen(internet_config.url), internet_config.url );
+        dbg_printf(LOG, "\n url size = %d url str = %s\n",strlen(internet_config.url), internet_config.url );
         memcpy(data_msg.buffer,&internet_config, data_msg.dataLen);
-        sendAtConfirmation(OK_RESP);   //_parser.send(OK_RESP);
+        //sendAtConfirmation(OK_RESP);   //_parser.send(OK_RESP);
         // queue next data request
         queueWiFiDataRequest(data_msg);
         print_memory_info();
     } else {
-        printf("\n[ATCMD MAN]: internet configuration failed %d fields parsed \r\n", n);
+        dbg_printf(LOG, "\n[ATCMD MAN]: internet configuration failed %d fields parsed \r\n", n);
         _parser.send("NAK\n");
     }
     //_smutex.unlock();
@@ -919,19 +989,19 @@
     wifi_config_t wifi_cfg = init_wifi_config();
     //_smutex.lock();
     n = readStringBytes((uint8_t *)wifi_cfg.ssid, 32);
-    printf("[ATCMD MAN]: number of bytes read = %d\n", n);
+    dbg_printf(LOG, "[ATCMD MAN]: number of bytes read = %d\n", n);
     if(n>0) 
     {
-        printf("[ATCMD MAN]: wifi_cfg.ssid = %s\n", wifi_cfg.ssid);
+        dbg_printf(LOG, "[ATCMD MAN]: wifi_cfg.ssid = %s\n", wifi_cfg.ssid);
         // package and send on wifi data queue
         wifi_data_msg_t data_msg;
         data_msg.wifi_cmd = WIFI_CMD_CONFIG;
         data_msg.dataLen = sizeof(wifi_config_t);
         memcpy(data_msg.buffer,&wifi_cfg, data_msg.dataLen);
-        sendAtConfirmation(OK_RESP);   //_parser.send(OK_RESP);
+        //sendAtConfirmation(OK_RESP);   //_parser.send(OK_RESP);
         queueWiFiDataRequest(data_msg);
     } else {
-        printf("\n[ATCMD MAN]: wifi configuration failed  \n");
+        dbg_printf(LOG, "\n[ATCMD MAN]: wifi configuration failed  \n");
         _parser.send("NAK\n");
     }
     //_smutex.unlock();
@@ -946,16 +1016,16 @@
     n = readStringBytes((uint8_t *)wifi_cfg.pass, 32);
     if(n>0) 
     {
-        printf("ATCMD MAN]: wifi_cfg.pass = %s\n", "****************");
+        dbg_printf(LOG, "ATCMD MAN]: wifi_cfg.pass = %s\n", "****************");
         // package and send on wifi data queue
         wifi_data_msg_t data_msg;
         data_msg.wifi_cmd = WIFI_CMD_CONFIG;
         data_msg.dataLen = sizeof(wifi_config_t);
         memcpy(data_msg.buffer,&wifi_cfg, data_msg.dataLen);
-        sendAtConfirmation(OK_RESP);   //_parser.send(OK_RESP);
+        //sendAtConfirmation(OK_RESP);   //_parser.send(OK_RESP);
         queueWiFiDataRequest(data_msg);
     } else {
-        printf("\n[ATCMD MAN]: wifi configuration failed  \n");
+        dbg_printf(LOG, "\n[ATCMD MAN]: wifi configuration failed  \n");
         _parser.send("NAK\n");
     }
     //_smutex.unlock();
@@ -970,16 +1040,16 @@
     _smutex.unlock();
     if(n>0) 
     {
-        printf("ATCMD MAN]: wifi_cfg.security = %s\n", sec2str(wifi_cfg.security));
+        dbg_printf(LOG, "ATCMD MAN]: wifi_cfg.security = %s\n", sec2str(wifi_cfg.security));
         // package and send on wifi data queue
         wifi_data_msg_t data_msg;
         data_msg.wifi_cmd = WIFI_CMD_CONFIG;
         data_msg.dataLen = sizeof(wifi_config_t);
         memcpy(data_msg.buffer,&wifi_cfg, data_msg.dataLen);
-        sendAtConfirmation(OK_RESP);   //_parser.send(OK_RESP);
+        //sendAtConfirmation(OK_RESP);   //_parser.send(OK_RESP);
         queueWiFiDataRequest(data_msg);
     } else {
-        printf("\n[ATCMD MAN]: wifi configuration failed  \n");
+        dbg_printf(LOG, "\n[ATCMD MAN]: wifi configuration failed  \n");
         _smutex.lock();
         _parser.send("NAK\n");
         _smutex.unlock();
@@ -994,11 +1064,11 @@
     uint8_t if_id; // interface id for request
     _parser.scanf(",%d", &if_id);
     //_smutex.lock();
-    printf("\n Received Get Network Status command!!\n");
-    sendAtConfirmation(OK_RESP);   //_parser.send(OK_RESP);
+    dbg_printf(LOG, "\n Received Get Network Status command!!\n");
+    //sendAtConfirmation(OK_RESP);   //_parser.send(OK_RESP);
     if(if_id == WIFI_INTERFACE_ID){
         wifi_cmd_t cmd = WIFI_CMD_NETWORK_STATUS;
-        printf("\n About to Queue wifi cmd = %d!!\n", cmd);
+        dbg_printf(LOG, "\n About to Queue wifi cmd = %d!!\n", cmd);
         //_smutex.unlock();
         // queue next command
         queueWiFiCommand(cmd);
@@ -1010,10 +1080,10 @@
 void ATCmdManager::_oob_WiFiNetworkStatus()
 {
     //_smutex.lock();
-    printf("\n Received Get WiFi Network Status command!!\n");
-    sendAtConfirmation(OK_RESP);   //_parser.send(OK_RESP);
+    dbg_printf(LOG, "\n Received Get WiFi Network Status command!!\n");
+    //sendAtConfirmation(OK_RESP);   //_parser.send(OK_RESP);
     wifi_cmd_t cmd = WIFI_CMD_WIFI_STATUS;
-    printf("\n About to Queue wifi cmd = %d!!\n", cmd);
+    dbg_printf(LOG, "\n About to Queue wifi cmd = %d!!\n", cmd);
     //_smutex.unlock();
     // queue next command
     queueWiFiCommand(cmd);
@@ -1029,7 +1099,7 @@
     n = _parser.scanf(",%d", &wifi_cfg.security);
     if(n>0) 
     {
-        printf("ATCMD MAN]: wifi_cfg.security = %s\n", sec2str(wifi_cfg.security));
+        dbg_printf(LOG, "ATCMD MAN]: wifi_cfg.security = %s\n", sec2str(wifi_cfg.security));
         // package and send on wifi data queue
         wifi_data_msg_t data_msg;
         data_msg.wifi_cmd = WIFI_CMD_CONFIG;
@@ -1038,7 +1108,7 @@
         queueWiFiDataRequest(data_msg);
         sendAtConfirmation(OK_RESP);   //_parser.send(OK_RESP);
     } else {
-        printf("\n[ATCMD MAN]: wifi configuration failed  \n");
+        dbg_printf(LOG, "\n[ATCMD MAN]: wifi configuration failed  \n");
         _parser.send("NAK\n");
     }
     */
@@ -1047,17 +1117,17 @@
 }
 
 bool  ATCmdManager::queueWiFiCommand(wifi_cmd_t cmd){
-    printf("[ATCMD MAN] about to be queued with wifi_cmd = %d\n", cmd);
+    dbg_printf(LOG, "[ATCMD MAN] about to be queued with wifi_cmd = %d\n", cmd);
 #ifndef USE_MALLOC_FOR_COMMAND_MEMORY_POOL
     wifi_cmd_message_t *wifiCmd = _aT2WiFimPool->alloc();
     if(wifiCmd == NULL){
-        printf("[ATCMD MAN] queued memory allocation failed\n");
+        dbg_printf(LOG, "[ATCMD MAN] queued memory allocation failed\n");
         return false;
     }
 #else
     wifi_cmd_message_t *wifiCmd = (wifi_cmd_message_t *) malloc(sizeof(wifi_cmd_message_t));
     if(wifiCmd == NULL){
-        printf("[ATCMD MAN] try malloc() : queued memory allocation failed\n");
+        dbg_printf(LOG, "[ATCMD MAN] try malloc() : queued memory allocation failed\n");
         //_event_queue.call_in(10, &print_memory_info);
         _event_queue.call_in(10, &print_heap_and_isr_stack_info);
         //print_memory_info();
@@ -1067,7 +1137,7 @@
 #endif
     wifiCmd->wifi_cmd            = cmd;
     _aT2WiFiCmdQueue->put(wifiCmd);
-    printf("[ATCMD MAN] queued wifi_cmd = %d\n", wifiCmd->wifi_cmd);
+    dbg_printf(LOG, "[ATCMD MAN] queued wifi_cmd = %d\n", wifiCmd->wifi_cmd);
     if((int)cmd == 5)
     debug_flag = 3;
     return true;
@@ -1076,14 +1146,14 @@
 bool  ATCmdManager::dequeueATresponse(){
     if(debug_flag>0){
         debug_flag--;
-        printf("Called dequeueATresponse after WIFI CONNECT CMD \r\n");
+        dbg_printf(LOG, "Called dequeueATresponse after WIFI CONNECT CMD \r\n");
     }
     if(at_resp != AT_RESP_NONE) return false; // busy
     osEvent evt = _wiFi2ATCmdQueue->get(0);
     if(evt.status == osEventMessage){
         at_resp_message_t *resp = (at_resp_message_t*)evt.value.p;
         setNextResponse(resp->at_resp);
-        printf("[ATCMD MAN] dequeued AT CMD : at_resp = %d\n", resp->at_resp);
+        dbg_printf(LOG, "[ATCMD MAN] dequeued AT CMD : at_resp = %d\n", resp->at_resp);
 #ifndef USE_MALLOC_FOR_COMMAND_MEMORY_POOL
         _wiFi2ATmPool->free(resp);
         resp = NULL;
@@ -1104,7 +1174,7 @@
     wifiData->dataLen        = data_req.dataLen;
     memcpy(wifiData->buffer, data_req.buffer, data_req.dataLen);
     _aT2WiFiDataQueue->put(wifiData);
-    printf("[ATCMD MAN] queued data size = %d : wifi_cmd = %d\n", data_req.dataLen, data_req.wifi_cmd);
+    dbg_printf(LOG, "[ATCMD MAN] queued data size = %d : wifi_cmd = %d\n", data_req.dataLen, data_req.wifi_cmd);
     //free(&data_req);
     return true;
 }
@@ -1112,14 +1182,14 @@
 bool  ATCmdManager::dequeueWiFidataResponse(){
     if(debug_flag>0){
         debug_flag--;
-        printf("Called dequeueWiFidataResponse after WIFI CONNECT CMD \r\n");
+        dbg_printf(LOG, "Called dequeueWiFidataResponse after WIFI CONNECT CMD \r\n");
     }
     if(at_resp != AT_RESP_NONE) return false; // busy
     osEvent evt = _wiFi2ATDataQueue->get(0);
     if(evt.status == osEventMessage){
         resp_data = (at_data_msg_t*)evt.value.p;
         setNextResponse(resp_data->at_resp);
-        printf("[ATCMD MAN] dequeued data size = %d : at_resp = %d\n", resp_data->dataLen, resp_data->at_resp);
+        dbg_printf(LOG, "[ATCMD MAN] dequeued data size = %d : at_resp = %d\n", resp_data->dataLen, resp_data->at_resp);
         _event_queue.call_in(10, &print_heap_and_isr_stack_info);
         //print_heap_and_isr_stack_info();
     }
@@ -1227,10 +1297,10 @@
 void ATCmdManager::return_response(bool download) {
     char * resp = (char *) resp_data->buffer;
     //_smutex.lock();
-    printf("\n[ATCMD MAN] received response:\n");
+    dbg_printf(LOG, "\n[ATCMD MAN] received response:\n");
     if(download == false) // not download must be ascii header
     {
-        printf("%.*s\r\n", resp_data->dataLen, resp);
+        dbg_printf(LOG, "%.*s\r\n", resp_data->dataLen, resp);
     }
     else // dump payload as hex
     {
--- a/source/ATCmdManager.h	Wed Apr 24 17:34:17 2019 +0000
+++ b/source/ATCmdManager.h	Thu May 02 21:50:17 2019 +0000
@@ -15,6 +15,7 @@
 
 #define OK_RESP    "\r\nOK\r\n"
 #define ERROR_RESP "\r\nERROR\r\n"
+#define BOX_UBLOX_DEMO_TESTING
 extern void print_memory_info();
 class ATCmdManager {
 public:
@@ -69,6 +70,9 @@
     edm_header_t   edm_hdr;
     uint8_t        *rx_buf_ptr;
     int            debug_flag;
+#ifdef BOX_UBLOX_DEMO_TESTING
+    bool           check_for_at_cmd;
+#endif
     
     // OOB processing
     void _process_oob(uint32_t timeout, bool all);
@@ -121,6 +125,7 @@
     void        sendAtConfirmationFreeMpool(const char *buf);
     void        sendAtEvent(const char *buf);
     void        sendConnectEvent(const uint8_t *buf, int len);
+    int         readAtCommandString(char *strbuf, size_t bufLen);
     
     /**
     * Allows timeout to be changed between commands
--- a/source/BleManager.cpp	Wed Apr 24 17:34:17 2019 +0000
+++ b/source/BleManager.cpp	Thu May 02 21:50:17 2019 +0000
@@ -16,6 +16,7 @@
 
 #include <events/mbed_events.h>
 #include <mbed.h>
+#include "debug.h"
 #include "common_config.h"
 #include "ble/BLE.h"
 #include "ble/services/UARTService.h"
@@ -25,6 +26,7 @@
 #include "LittleFileSystem.h"
 #include "HeapBlockDevice.h"
 #endif //MBED_CONF_APP_FILESYSTEM_SUPPORT
+#define FILE_CODE       "btle"
 
 
 static const uint8_t DEVICE_NAME[] = "SM_device";
@@ -78,7 +80,7 @@
 /** Start BLE interface initialisation */
 void SMDevice::run()
 {
-    printf("\r\n [BTLE MAN]  Thread Id = %X\r\n", (uint32_t)ThisThread::get_id());
+    dbg_printf(LOG, "\r\n [BTLE MAN]  Thread Id = %X\r\n", (uint32_t)ThisThread::get_id());
 
     ble_error_t error;
 
@@ -91,7 +93,7 @@
 
 
     if (_ble.hasInitialized()) {
-        printf("Ble instance already initialised.\r\n");
+        dbg_printf(LOG, "Ble instance already initialised.\r\n");
         return;
     }
 
@@ -109,7 +111,7 @@
     error = _ble.init(this, &SMDevice::on_init_complete);
 
     if (error) {
-        printf("Error returned by BLE::init.\r\n");
+        dbg_printf(LOG, "Error returned by BLE::init.\r\n");
         return;
     }
 
@@ -122,7 +124,7 @@
 {
     if (_ble.hasInitialized()) {
         _ble.shutdown();
-        printf("Shutting down BLE Instance...\r\n");
+        dbg_printf(LOG, "Shutting down BLE Instance...\r\n");
         _event_queue.break_dispatch();
     }
 }
@@ -136,7 +138,7 @@
 void SMDevice::pairingRequest(
     ble::connection_handle_t connectionHandle
 ) {
-    printf("Pairing requested - authorising\r\n");
+    dbg_printf(LOG, "Pairing requested - authorising\r\n");
     _ble.securityManager().acceptPairingRequest(connectionHandle);
 }
 
@@ -146,9 +148,9 @@
     SecurityManager::SecurityCompletionStatus_t result
 ) {
     if (result == SecurityManager::SEC_STATUS_SUCCESS) {
-        printf("Pairing successful\r\n");
+        dbg_printf(LOG, "Pairing successful\r\n");
     } else {
-        printf("Pairing failed\r\n");
+        dbg_printf(LOG, "Pairing failed\r\n");
     }
 }
 
@@ -159,11 +161,11 @@
     ble::link_encryption_t result
 ) {
     if (result == ble::link_encryption_t::ENCRYPTED) {
-        printf("Link ENCRYPTED\r\n");
+        dbg_printf(LOG, "Link ENCRYPTED\r\n");
     } else if (result == ble::link_encryption_t::ENCRYPTED_WITH_MITM) {
-        printf("Link ENCRYPTED_WITH_MITM\r\n");
+        dbg_printf(LOG, "Link ENCRYPTED_WITH_MITM\r\n");
     } else if (result == ble::link_encryption_t::NOT_ENCRYPTED) {
-        printf("Link NOT_ENCRYPTED\r\n");
+        dbg_printf(LOG, "Link NOT_ENCRYPTED\r\n");
     }
 
 #ifdef DEMO_BLE_SECURITY
@@ -184,7 +186,7 @@
     ble_error_t error;
 
     if (event->error) {
-        printf("Error during the initialisation\r\n");
+        dbg_printf(LOG, "Error during the initialisation\r\n");
         return;
     }
 
@@ -203,14 +205,14 @@
     );
 
     if (error) {
-        printf("Error during init %d\r\n", error);
+        dbg_printf(LOG, "Error during init %d\r\n", error);
         return;
     }
 
     error = _ble.securityManager().preserveBondingStateOnReset(true);
 
     if (error) {
-        printf("Error during preserveBondingStateOnReset %d\r\n", error);
+        dbg_printf(LOG, "Error during preserveBondingStateOnReset %d\r\n", error);
     }
 
 #if MBED_CONF_APP_FILESYSTEM_SUPPORT
@@ -218,7 +220,7 @@
     error = _ble.gap().enablePrivacy(true);
 
     if (error) {
-        printf("Error enabling privacy\r\n");
+        dbg_printf(LOG, "Error enabling privacy\r\n");
     }
 
     Gap::PeripheralPrivacyConfiguration_t configuration_p = {
@@ -245,7 +247,7 @@
     Gap::AddressType_t addr_type;
     Gap::Address_t addr;
     _ble.gap().getAddress(&addr_type, addr);
-    printf("Device address: %02x:%02x:%02x:%02x:%02x:%02x\r\n",
+    dbg_printf(LOG, "Device address: %02x:%02x:%02x:%02x:%02x:%02x\r\n",
            addr[5], addr[4], addr[3], addr[2], addr[1], addr[0]);
 
     /* when scanning we want to connect to a peer device so we need to
@@ -267,9 +269,9 @@
  *  in our case it ends the demonstration. */
 void SMDevice::on_disconnect(const Gap::DisconnectionCallbackParams_t *event)
 {
-    printf("Disconnected\r\n");
+    dbg_printf(LOG, "Disconnected\r\n");
 #ifndef DEMO_BLE_SECURITY
-    printf("Restarting advertising...\r\n");
+    dbg_printf(LOG, "Restarting advertising...\r\n");
     _ble.gap().startAdvertising();
 #else
     _event_queue.break_dispatch();
@@ -280,7 +282,7 @@
  * scanning or connection initiation */
 void SMDevice::on_timeout(const Gap::TimeoutSource_t source)
 {
-    printf("Unexpected timeout - aborting\r\n");
+    dbg_printf(LOG, "Unexpected timeout - aborting\r\n");
     _event_queue.break_dispatch();
 }
 
@@ -319,10 +321,10 @@
     if ((uart != NULL) && (params->handle == uart->getTXCharacteristicHandle())) {
         uint16_t bytesRead = params->len;
 
-        printf("received %u bytes\n\r ", bytesRead);
+        dbg_printf(LOG, "received %u bytes\n\r ", bytesRead);
 
         if(bytesRead >= 255){
-            printf("Overflow command %u n\r ", bytesRead);
+            dbg_printf(LOG, "Overflow command %u n\r ", bytesRead);
             bytesRead = 255;
         }
 
@@ -333,8 +335,8 @@
 
         buffer[index++] = 0;
 
-        printf("Data : %s ",buffer);
-        printf("\r\n");
+        dbg_printf(LOG, "Data : %s ",buffer);
+        dbg_printf(LOG, "\r\n");
         /* start echo in 50 ms */
         _event_queue.call_in(50, this, &SMDevice::EchoBleUartReceived);
         //_event_queue.call(EchoBleUartReceived);
@@ -364,7 +366,7 @@
      if(gapState.connected){
          strncpy(connStr, " Connected ", 20);
      }
-     printf("\n Advertising Status = %s\n Connection Status = %s\n", advStr, connStr);
+     dbg_printf(LOG, "\n Advertising Status = %s\n Connection Status = %s\n", advStr, connStr);
      
 }
 
@@ -412,7 +414,7 @@
     //error = _ble.gap().setAdvertisingPayload(advertising_data);
 
     if (error) {
-        printf("Error during Gap::setAdvertisingPayload\r\n");
+        dbg_printf(LOG, "Error during Gap::setAdvertisingPayload\r\n");
         return;
     }
 
@@ -428,11 +430,11 @@
     error = _ble.gap().startAdvertising();
 
     if (error) {
-        printf("Error during Gap::startAdvertising.\r\n");
+        dbg_printf(LOG, "Error during Gap::startAdvertising.\r\n");
         return;
     }
 
-    printf("Please connect to device\r\n");
+    dbg_printf(LOG, "Please connect to device\r\n");
 
     /** This tells the stack to generate a pairingRequest event
      * which will require this application to respond before pairing
@@ -451,7 +453,7 @@
      * during the next demonstration */
     memcpy(_peer_address, connection_event->peerAddr, sizeof(_peer_address));
 
-    printf("Connected to: %02x:%02x:%02x:%02x:%02x:%02x\r\n",
+    dbg_printf(LOG, "Connected to: %02x:%02x:%02x:%02x:%02x:%02x\r\n",
             _peer_address[5], _peer_address[4], _peer_address[3],
             _peer_address[2], _peer_address[1], _peer_address[0]);
 
@@ -469,10 +471,10 @@
     );
 
     if (error) {
-        printf("Error during SM::setLinkSecurity %d\r\n", error);
+        dbg_printf(LOG, "Error during SM::setLinkSecurity %d\r\n", error);
         return;
     }
-    printf("SM::setLinkSecurity setup\r\n");
+    dbg_printf(LOG, "SM::setLinkSecurity setup\r\n");
 }
 
 void SMDevicePeripheral::stopAdvertising()
@@ -481,10 +483,10 @@
         ble_error_t error;
         error = _ble.gap().stopAdvertising();;
         if(error){
-            printf(" Error stopping advertising...\r\n");
+            dbg_printf(LOG, " Error stopping advertising...\r\n");
             return;
         }
-        printf("Stopping advertising...\r\n");
+        dbg_printf(LOG, "Stopping advertising...\r\n");
         //_event_queue.break_dispatch();
     }
 }
@@ -494,10 +496,10 @@
         ble_error_t error;
         error = _ble.gap().startAdvertising();
         if(error){
-            printf(" Error Restarting advertising...\r\n");
+            dbg_printf(LOG, " Error Restarting advertising...\r\n");
             return;
         }
-        printf("Restarting advertising...\r\n");
+        dbg_printf(LOG, "Restarting advertising...\r\n");
         //_event_queue.break_dispatch();
     }
 }
@@ -515,14 +517,14 @@
      * and scan requests responses */
     ble_error_t error = _ble.gap().startScan(this, &SMDeviceCentral::on_scan);
 
-    printf("Please advertise\r\n");
+    dbg_printf(LOG, "Please advertise\r\n");
 
-    printf("Scanning for: %02x:%02x:%02x:%02x:%02x:%02x\r\n",
+    dbg_printf(LOG, "Scanning for: %02x:%02x:%02x:%02x:%02x:%02x\r\n",
            _peer_address[5], _peer_address[4], _peer_address[3],
            _peer_address[2], _peer_address[1], _peer_address[0]);
 
     if (error) {
-        printf("Error during Gap::startScan %d\r\n", error);
+        dbg_printf(LOG, "Error during Gap::startScan %d\r\n", error);
         return;
     }
 }
@@ -544,11 +546,11 @@
         );
 
         if (error) {
-            printf("Error during Gap::connect %d\r\n", error);
+            dbg_printf(LOG, "Error during Gap::connect %d\r\n", error);
             return;
         }
 
-        printf("Connecting... ");
+        dbg_printf(LOG, "Connecting... ");
 
         /* we may have already scan events waiting
          * to be processed so we need to remember
@@ -571,10 +573,10 @@
     /* in this example the local device is the master so we request pairing */
     error = _ble.securityManager().requestPairing(_handle);
 
-    printf("Connected\r\n");
+    dbg_printf(LOG, "Connected\r\n");
 
     if (error) {
-        printf("Error during SM::requestPairing %d\r\n", error);
+        dbg_printf(LOG, "Error during SM::requestPairing %d\r\n", error);
         return;
     }
 
@@ -607,7 +609,7 @@
 
     if (err) {
         /* Reformat if we can't mount the filesystem */
-        printf("No filesystem found, formatting...\r\n");
+        dbg_printf(LOG, "No filesystem found, formatting...\r\n");
 
         err = fs.reformat(&bd);
 
@@ -629,19 +631,19 @@
     /* if filesystem creation fails or there is no filesystem the security manager
      * will fallback to storing the security database in memory */
     if (!create_filesystem()) {
-        printf("Filesystem creation failed, will use memory storage\r\n");
+        dbg_printf(LOG, "Filesystem creation failed, will use memory storage\r\n");
     }
 #endif
 
     while(1) {
         {
-            printf("\r\n PERIPHERAL \r\n\r\n");
+            dbg_printf(LOG, "\r\n PERIPHERAL \r\n\r\n");
             SMDevicePeripheral peripheral(ble, queue, peer_address);
             peripheral.run();
         }
 
         {
-            printf("\r\n CENTRAL \r\n\r\n");
+            dbg_printf(LOG, "\r\n CENTRAL \r\n\r\n");
             SMDeviceCentral central(ble, queue, peer_address);
             central.run();
         }
--- a/source/WiFiManager.cpp	Wed Apr 24 17:34:17 2019 +0000
+++ b/source/WiFiManager.cpp	Thu May 02 21:50:17 2019 +0000
@@ -1,5 +1,7 @@
+#include "debug.h"
 #include "WiFiManager.h"
 #include "common_config.h"
+#define FILE_CODE       "wifi"
 
 
 WiFiManager::WiFiManager(wifi_config_t wifi_config, WiFiInterface *wifi, 
@@ -63,7 +65,7 @@
     atData->dataLen        = at_resp.dataLen;
     memcpy(atData->buffer, at_resp.buffer, at_resp.dataLen);
     _wiFi2ATDataQueue->put(atData);
-    printf("[WIFI MAN] queued data size = %d : at_resp = %d\n", at_resp.dataLen, at_resp.at_resp);
+    dbg_printf(LOG, "[WIFI MAN] queued data size = %d : at_resp = %d\n", at_resp.dataLen, at_resp.at_resp);
     return true;
 }
 
@@ -72,7 +74,7 @@
 void WiFiManager::runMain(){
     nsapi_error_t error;
     bool result;
-    printf("\r\n [WIFI MAN]  Thread Id = %X\r\n", (uint32_t)ThisThread::get_id());
+    dbg_printf(LOG, "\r\n [WIFI MAN]  Thread Id = %X\r\n", (uint32_t)ThisThread::get_id());
     while(true){
         dequeueWiFiCommands();
         dequeueATdataResponse();
@@ -102,7 +104,7 @@
                 }
                 wifiCmd = WIFI_CMD_NONE;
                 if(is_connected==false){
-                    printf("[WIFI MAN] +++ WIFI CONNECTION TIMEOUT +++ \r\n");
+                    dbg_printf(LOG, "[WIFI MAN] +++ WIFI CONNECTION TIMEOUT +++ \r\n");
                     //queueATresponse(AT_COMMAND_FAILED);
                     responseString = (char *) malloc(100);
                     sprintf(responseString, "\r\n+UUTIMEOUT\r\n");
@@ -139,14 +141,14 @@
                 wifiCmd = WIFI_CMD_NONE;
                 break;
             case WIFI_CMD_SEND_HTTPS_REQ:
-                printf("before call to send http request \n");
+                dbg_printf(LOG, "before call to send http request \n");
                 print_memory_info();
                 result = createHttpsRequest();
                 if(result == false)
                 {
                     sendATresponseString(AT_COMMAND_FAILED);
                 }
-                printf("after call to send http request \n");
+                dbg_printf(LOG, "after call to send http request \n");
                 print_memory_info();
                 wifiCmd = WIFI_CMD_NONE;
                 break;
@@ -178,7 +180,7 @@
     {
         if(!queueResult){
             wait_count++;
-            printf("ATCMD Queue full waiting %d ms so far...\n", wait_count*10);
+            dbg_printf(LOG, "ATCMD Queue full waiting %d ms so far...\n", wait_count*10);
             wait_ms(10);
         }
         queueResult = queueWiFiDataResponse(*at_data_resp);
@@ -205,13 +207,13 @@
         if(!queueResult){
             wait_count++;
             wait_ms(10);
-            printf("ATCMD Queue full waited %d ms so far...\n", wait_count*10);
+            dbg_printf(LOG, "ATCMD Queue full waited %d ms so far...\n", wait_count*10);
         }
         queueResult = queueWiFiDataResponse(*at_data_resp);
     }while(queueResult == false);
     delete at_data_resp;
     at_data_resp = NULL;
-    printf("[WIFI-MAN] sendATresponseBytes completed successfully\r\n");
+    dbg_printf(LOG, "[WIFI-MAN] sendATresponseBytes completed successfully\r\n");
 }                                            
 
 
@@ -248,12 +250,12 @@
 
 bool WiFiManager::setNextCommand(wifi_cmd_t cmd)
 {
-    printf("\n [WIFI-MAN] About to set next WiFi manager command to %d\n", cmd);
+    dbg_printf(LOG, "\n [WIFI-MAN] About to set next WiFi manager command to %d\n", cmd);
     if(wifiCmd == WIFI_CMD_NONE){
         wifiCmd = cmd;
         return true; // success
     }
-    printf("\n [WIFI-MAN] Busy : current state = %d \n", wifiCmd);
+    dbg_printf(LOG, "\n [WIFI-MAN] Busy : current state = %d \n", wifiCmd);
     return false; // wiFiManager busy
 }
 
@@ -280,9 +282,9 @@
 nsapi_size_or_error_t WiFiManager::scanNetworks()
 {
     nsapi_error_t error;
-    printf("\n [WIFI-MAN] About to start scan for WiFi networks\n");
+    dbg_printf(LOG, "\n [WIFI-MAN] About to start scan for WiFi networks\n");
     lastScanCount = network->scan(NULL, 0);
-    printf("\n [WIFI-MAN] Scan for WiFi networks completed - \n");
+    dbg_printf(LOG, "\n [WIFI-MAN] Scan for WiFi networks completed - \n");
     return lastScanCount;
 }
 
@@ -297,7 +299,7 @@
     //count = wiFiManager->scanNetworks();
     if (count <= 0) {
         //_smutex.lock();
-        printf("[WIFI-MAN] scan() failed with return value: %d\n", count);
+        dbg_printf(LOG, "[WIFI-MAN] scan() failed with return value: %d\n", count);
         //_smutex.unlock();
         return 0;
     }
@@ -306,16 +308,16 @@
     ap = new WiFiAccessPoint[count];
     count = network->scan(ap, count);
     if (count <= 0) {
-        printf("[WIFI-MAN] scan() failed with return value: %d\n", count);
+        dbg_printf(LOG, "[WIFI-MAN] scan() failed with return value: %d\n", count);
         return 0;
     }
 
     for (int i = 0; i < count; i++) {
-        printf("[WIFI-MAN]: %s secured: %s BSSID: %hhX:%hhX:%hhX:%hhx:%hhx:%hhx RSSI: %hhd Ch: %hhd\n", ap[i].get_ssid(),
+        dbg_printf(LOG, "[WIFI-MAN]: %s secured: %s BSSID: %hhX:%hhX:%hhX:%hhx:%hhx:%hhx RSSI: %hhd Ch: %hhd\n", ap[i].get_ssid(),
                sec2str(ap[i].get_security()), ap[i].get_bssid()[0], ap[i].get_bssid()[1], ap[i].get_bssid()[2],
                ap[i].get_bssid()[3], ap[i].get_bssid()[4], ap[i].get_bssid()[5], ap[i].get_rssi(), ap[i].get_channel());
     }
-    printf("[WIFI-MAN]  %d networks available.\n", count);
+    dbg_printf(LOG, "[WIFI-MAN]  %d networks available.\n", count);
 
     delete[] ap;
     return count;
@@ -334,7 +336,7 @@
 void WiFiManager::set_WIFI_SSID(char * wifi_ssid)
 {
     strcpy(wifi_config.ssid, wifi_ssid);
-    printf("[WIFI-MAN]  wifi_ssid set to %s\n", wifi_config.ssid);
+    dbg_printf(LOG, "[WIFI-MAN]  wifi_ssid set to %s\n", wifi_config.ssid);
     https_connection_active = false; // reset whenever any of the security credentials change
     delete socket;
 }
@@ -343,7 +345,7 @@
 void WiFiManager::set_WIFI_PASSWORD(char * wifi_pass)
 {
     strcpy(wifi_config.pass, wifi_pass);
-    printf("[WIFI-MAN]  wifi_pass set to %s\n", "****************");
+    dbg_printf(LOG, "[WIFI-MAN]  wifi_pass set to %s\n", "****************");
     https_connection_active = false; // reset whenever any of the security credentials change
     delete socket;
 }
@@ -352,7 +354,7 @@
 void WiFiManager::set_WIFI_SECURITY(nsapi_security_t wifi_security)
 {
     wifi_config.security = wifi_security;
-    printf("[WIFI-MAN]  wifi_security set to %s\n", sec2str(wifi_config.security));
+    dbg_printf(LOG, "[WIFI-MAN]  wifi_security set to %s\n", sec2str(wifi_config.security));
     https_connection_active = false; // reset whenever any of the security credentials change
     delete socket;
 }
@@ -365,7 +367,7 @@
                                          NSAPI_UNSPEC);
     if(value_or_error >= NSAPI_ERROR_OK) // success
     {
-        printf("[WIFI-MAN] hostname translation successful value_or_error = %d\r\n", value_or_error);
+        dbg_printf(LOG, "[WIFI-MAN] hostname translation successful value_or_error = %d\r\n", value_or_error);
         //strcpy(responseString, UDDRP_WRITE_OK);
         //printBufferInHex(responseBytes, HOSTNAME_RESPONSE_LEN);
         //sendATresponseBytes(CONNECT_EVENT, HOSTNAME_RESPONSE_LEN);
@@ -373,7 +375,7 @@
     else // -ve number means error
     {
         responseString = (char *) malloc(20);
-        printf("[WIFI-MAN] hostname translation failed\r\n");
+        dbg_printf(LOG, "[WIFI-MAN] hostname translation failed\r\n");
         strcpy(responseString, UDDRP_ERROR);
         sendATresponseString(AT_COMMAND_FAILED);
     }
@@ -387,8 +389,8 @@
     strncpy(internet_config.url,internet_cfg->url, strlen(internet_cfg->url)+1);
     internet_config.connectionScheme = internet_cfg->connectionScheme;
     free_DataMsg();
-    printf("[WIFI MAN] Internet configuration setup completed\n"); 
-    printf("peer_id = %1d, url = %s, connScheme = %1d\n", internet_config.peer_id, 
+    dbg_printf(LOG, "[WIFI MAN] Internet configuration setup completed\n"); 
+    dbg_printf(LOG, "peer_id = %1d, url = %s, connScheme = %1d\n", internet_config.peer_id, 
                                                       internet_config.url, 
                                                       internet_config.connectionScheme);
     if(https_connection_active)
@@ -468,8 +470,9 @@
                 sprintf(nextStrPtr, "\r\n%s,::\r\n", NETWORK_STATUS);
                 break;
         }
-        nextStrPtr += strlen(nextStrPtr) +1; // progress to end of current string
+        nextStrPtr += strlen(nextStrPtr) ; // progress to end of current string
     }
+    sprintf(nextStrPtr, "%s", UDDRP_WRITE_OK);
 }
 
 
@@ -511,8 +514,9 @@
                 sprintf(nextStrPtr, "\r\n%s,::\r\n", WIFI_NETWORK_STATUS);
                 break;
         }
-        nextStrPtr += strlen(nextStrPtr) +1; // progress to end of current string
+        nextStrPtr += strlen(nextStrPtr) ; // progress to end of current string
     }
+    sprintf(nextStrPtr, "%s", UDDRP_WRITE_OK);
 }
 
 
@@ -527,7 +531,7 @@
 
 void WiFiManager::status_callback(nsapi_event_t status, intptr_t param)
 {
-    printf("[WIFI-MAN] about call callback... \r\n");
+    dbg_printf(LOG, "[WIFI-MAN] about call callback... \r\n");
     _event_queue.call_in(50, this, &WiFiManager::status_callback_event, status, param);
     //status_callback_event(status, param);
 }
@@ -537,13 +541,13 @@
     //}
     switch(param) {
         case NSAPI_STATUS_LOCAL_UP:
-            printf("[WIFI-MAN] Local IP address set!\r\n");
-            printf("[WIFI-MAN] IP address: %s\n", network->get_ip_address());
+            dbg_printf(LOG, "[WIFI-MAN] Local IP address set!\r\n");
+            dbg_printf(LOG, "[WIFI-MAN] IP address: %s\n", network->get_ip_address());
             break;
         case NSAPI_STATUS_GLOBAL_UP:
-            printf("Global IP address set!\r\n");
-            printf("[WIFI-MAN] IP address: %s\n", network->get_ip_address());
-            printf("[WIFI-MAN] Connected to the network %s\n", wifi_config.ssid);
+            dbg_printf(LOG, "Global IP address set!\r\n");
+            dbg_printf(LOG, "[WIFI-MAN] IP address: %s\n", network->get_ip_address());
+            dbg_printf(LOG, "[WIFI-MAN] Connected to the network %s\n", wifi_config.ssid);
             responseString = (char *) malloc(MAX_RESPONSE_STRING_LEN); 
             sprintf(responseString, "\r\n%s%d,%s,%d\r\n", WIFI_LINK_ENABLED, 
                                                           WIFI_CHANNEL,
@@ -553,8 +557,8 @@
             is_connected = true;
             break;
         case NSAPI_STATUS_DISCONNECTED:
-            printf("No connection to network!\r\n");
-            printf("\n [WIFI-MAN] No connection to network!\n");
+            dbg_printf(LOG, "No connection to network!\r\n");
+            dbg_printf(LOG, "\n [WIFI-MAN] No connection to network!\n");
             is_connected = false;
             //queueATresponse(AT_DISCONNECT_RESP);
             // attempt reconnection if always connected scheme is set
@@ -566,10 +570,10 @@
             }
             break;
         case NSAPI_STATUS_CONNECTING:
-            printf("Connecting to network!\r\n");
+            dbg_printf(LOG, "Connecting to network!\r\n");
             break;
         default:
-            printf("Not supported");
+            dbg_printf(LOG, "Not supported");
             break;
     }
 }
@@ -585,29 +589,29 @@
 nsapi_error_t WiFiManager::connect()
 {
     nsapi_error_t error;
-    printf("\n [WIFI-MAN] About to connect to WiFi network\n");
+    dbg_printf(LOG, "\n [WIFI-MAN] About to connect to WiFi network\n");
     network->attach(callback(this, &WiFiManager::status_callback));
     error = network->set_blocking(false);
     if(error)
     {
-        printf("\n [WIFI-MAN] Could not set non-blocking mode for Wifi -- aborting!! - \n");
+        dbg_printf(LOG, "\n [WIFI-MAN] Could not set non-blocking mode for Wifi -- aborting!! - \n");
         return error;
     }
-    printf("[WIFI-MAN] Connecting to network ssid = %s passwd = %s  security = %s \r\n", 
+    dbg_printf(LOG, "[WIFI-MAN] Connecting to network ssid = %s passwd = %s  security = %s \r\n", 
                                                     wifi_config.ssid, 
                                                     "****************", 
                                                     sec2str(wifi_config.security));
     error = network->connect(wifi_config.ssid,
                      wifi_config.pass,
                      wifi_config.security);
-    printf("[WIFI-MAN] network->connect called. error = %d\r\n", error);
+    dbg_printf(LOG, "[WIFI-MAN] network->connect called. error = %d\r\n", error);
     return error;
 }
 
 
 void WiFiManager::gethostbyname_callback(nsapi_error_t result, SocketAddress *address)
 {
-    printf("gethostbyname_callback called... result = %d \r\n", result);
+    dbg_printf(LOG, "gethostbyname_callback called... result = %d \r\n", result);
     responseBytes = (uint8_t *) malloc(HOSTNAME_RESPONSE_LEN);
     int i = 0;
     responseBytes[i++] = IPv4_CONNECTION; // connect type IPv4
@@ -671,10 +675,10 @@
 void WiFiManager::sendResponseDownloadData(at_cmd_resp_t at_cmd, const uint8_t * buf, int bufLen)
 {    
 
-    //printf("before call to new at_data_msg_t \n");
+    //dbg_printf(LOG, "before call to new at_data_msg_t \n");
     //print_memory_info();
     at_data_resp = new at_data_msg_t;
-    //printf("after call to new at_data_msg_t \n");
+    //dbg_printf(LOG, "after call to new at_data_msg_t \n");
     //print_memory_info();
     at_data_resp->at_resp = at_cmd;
     size_t bufSize = sizeof(at_data_resp->buffer);
@@ -686,26 +690,26 @@
     do {
         if(!queueResult){
             wait_count++;
-            printf("[WIFI-MAN] ATCMD Queue full waiting %d ms so far...\n", wait_count*10);
+            dbg_printf(LOG, "[WIFI-MAN] ATCMD Queue full waiting %d ms so far...\n", wait_count*10);
             wait_ms(10);
         }
         else {            
             if(http_response_hdr_sent == false && chunkNum==1){ // only do this for first chunk
                 bool status = copyResponseHdr2Queue(buf);  
                 if(status == true){
-                    printf("[WIFI-MAN] Http Response header copied to response buffer [bytes = %d] \r\n",at_data_resp->dataLen);
+                    dbg_printf(LOG, "[WIFI-MAN] Http Response header copied to response buffer [bytes = %d] \r\n",at_data_resp->dataLen);
                     hdrLen =  at_data_resp->dataLen;
                     http_response_hdr_sent = true;  
                 } 
                 else {     
-                    printf("[WIFI-MAN] Http Response header copy failed\r\n");
+                    dbg_printf(LOG, "[WIFI-MAN] Http Response header copy failed\r\n");
                 }
             }
             int cpyLen = (bufLen - pos) > bufSize? bufSize : (bufLen - pos) ;
-            printf("[WIFI-MAN] Http Response body [bytes = %d] \r\n",cpyLen);
+            dbg_printf(LOG, "[WIFI-MAN] Http Response body [bytes = %d] \r\n",cpyLen);
             at_data_resp->dataLen += cpyLen;
             memcpy(&at_data_resp->buffer[hdrLen], &buf[pos], cpyLen);
-            printf("[WIFI-MAN] Http Response header and body copied to response buffer [bytes = %d] \r\n",at_data_resp->dataLen);
+            dbg_printf(LOG, "[WIFI-MAN] Http Response header and body copied to response buffer [bytes = %d] \r\n",at_data_resp->dataLen);
         }
         queueResult = queueWiFiDataResponse(*at_data_resp);
         if(queueResult){ 
@@ -714,7 +718,7 @@
             hdrLen = 0; 
         }
     }while(queueResult ==  false || pos < bufLen);
-    printf("[WIFI-MAN] response data queued - deleting data memory\r\n");
+    dbg_printf(LOG, "[WIFI-MAN] response data queued - deleting data memory\r\n");
     delete at_data_resp;
     at_data_resp = NULL;
 }
@@ -746,10 +750,10 @@
     int hdrLen = (const char*) buf -hdrPtr;
     // copy header 
     memcpy(at_data_resp->buffer, (const uint8_t *) hdrPtr, hdrLen);
-    printf("[i = %d] This is the header\r\n%s\r\n", i, hdrPtr);
+    dbg_printf(LOG, "[i = %d] This is the header\r\n%s\r\n", i, hdrPtr);
     if(hdrFound == false)
     {
-        printf("[WIFI-MAN] copy failed: HTTP header not found!!\r\n");
+        dbg_printf(LOG, "[WIFI-MAN] copy failed: HTTP header not found!!\r\n");
         return false;
     }
     at_data_resp->dataLen = hdrLen;
@@ -774,8 +778,8 @@
     numChars = sprintf(msgPtr, "\r\n\r\n");
     msgPtr += numChars;
     // print out generated header
-    printf("[WiFi MAN] generated response header:\n");
-    printf("%s\r\n", (char *)at_data_resp->buffer);
+    dbg_printf(LOG, "[WiFi MAN] generated response header:\n");
+    dbg_printf(LOG, "%s\r\n", (char *)at_data_resp->buffer);
     // calculate header length 
     at_data_resp->dataLen = (msgPtr - (char *)at_data_resp->buffer);
     
@@ -787,7 +791,7 @@
     {
         if(!queueResult){
             wait_count++;
-            printf("ATCMD Queue full waiting %d ms so far...\n", wait_count*10);
+            dbg_printf(LOG, "ATCMD Queue full waiting %d ms so far...\n", wait_count*10);
             wait_ms(10);
         }
         queueResult = queueWiFiDataResponse(*at_data_resp);
@@ -800,24 +804,24 @@
 void WiFiManager::printBufferInHex(uint8_t *buf, int pLen)
 {
     for(int i =0;i<pLen;i++){
-        if(i%8==0) printf("\n[%3d]",i);
-        printf("%02x ", buf[i]);
+        if(i%8==0) dbg_printf(LOG, "\n[%3d]",i);
+        dbg_printf(LOG, "%02x ", buf[i]);
     }
-    printf("\n");
+    dbg_printf(LOG, "\n");
 }
 
 //#define TRY_PRINTF
 
 void WiFiManager::body_callback(const char *at, uint32_t length) {    
-    printf("\n Chunked response: Chunk %d : Total Bytes = %d\n", chunkNum , length);
+    dbg_printf(LOG, "\n Chunked response: Chunk %d : Total Bytes = %d\n", chunkNum , length);
     chunkNum++;
     if(http_response == NULL)
     {
-        printf("[WIFI-MAN] response pointer NULL!!\r\n");
+        dbg_printf(LOG, "[WIFI-MAN] response pointer NULL!!\r\n");
     }
     else
     {
-        printf("[WIFI-MAN] response pointer NULL not!!\r\n");
+        dbg_printf(LOG, "[WIFI-MAN] response pointer NULL not!!\r\n");
     }
     sendResponseDownloadData(AT_HTTPS_RESP_DOWNLOAD, (uint8_t *)at, length);
 }
@@ -835,36 +839,36 @@
     r = socket->open(network);
     if(r != NSAPI_ERROR_OK)
     { 
-        printf("TLS open failed!!\n");
+        dbg_printf(LOG, "TLS open failed!!\n");
         return false;
     }
-    printf("TLS open passed!!\n");
+    dbg_printf(LOG, "TLS open passed!!\n");
     r = socket->set_root_ca_cert(SSL_CA_PEM);
     if(r != NSAPI_ERROR_OK)
     { 
-        printf("TLS set_root_ca_cert failed!!\n");
+        dbg_printf(LOG, "TLS set_root_ca_cert failed!!\n");
         socket->close();
-        printf("closing TLS socket!!\n");
+        dbg_printf(LOG, "closing TLS socket!!\n");
         return false;
     }
-    printf("TLS set_root_ca_cert passed!!\n");
+    dbg_printf(LOG, "TLS set_root_ca_cert passed!!\n");
     r = socket->connect(hostName, 443);
     if(r != NSAPI_ERROR_OK)
     { 
         char errstr[100];
         mbedtls_strerror(r, errstr, 100);
-        printf("TLS connect failed for hostname %s -- ERROR = %s !!\n", hostName, errstr);
+        dbg_printf(LOG, "TLS connect failed for hostname %s -- ERROR = %s !!\n", hostName, errstr);
         socket->close();
         return false;
     }
-    printf("TLS connection successful for https site :  %s\n", hostName);
+    dbg_printf(LOG, "TLS connection successful for https site :  %s\n", hostName);
     return true;
 }
 
 
 void WiFiManager::updateRemotePeerDetails()
 {
-    printf("Updating internet_config... \r\n");
+    dbg_printf(LOG, "Updating internet_config... \r\n");
     nsapi_error_t error;
     SocketAddress * address = new SocketAddress;
     error = socket->getpeername(address);   
@@ -886,27 +890,27 @@
 #else
     http_response_hdr_sent = true;
 #endif    
-    printf("\n[WIFI MAN] Http Request received:\n");
+    dbg_printf(LOG, "\n[WIFI MAN] Http Request received:\n");
     http_req_cfg = (http_request_t *) data_msg->buffer;
-    printf("\n[WIFI MAN] uri = %s\n", http_req_cfg->request_URI);
-    printf("\n[WIFI MAN] internet cfg url = %s\n", internet_config.url);
+    dbg_printf(LOG, "\n[WIFI MAN] uri = %s\n", http_req_cfg->request_URI);
+    dbg_printf(LOG, "\n[WIFI MAN] internet cfg url = %s\n", internet_config.url);
     char full_url[100];
     char host[60] ;
     strncpy(full_url,internet_config.url, strlen(internet_config.url)+1);
     strncpy(host,http_req_cfg->hostName, strlen(http_req_cfg->hostName)+1);
     strncat(full_url, http_req_cfg->request_URI, strlen(http_req_cfg->request_URI)+1);
-    printf("\n[WIFI MAN] server url+uri = %s\n", full_url);
-    printf("\n[WIFI MAN] Host = %s\n", http_req_cfg->hostName);
-    printf("\n[WIFI MAN] Accept = %s\n", http_req_cfg->AcceptVal);
-    printf("\n[WIFI MAN] Content-Type = %s\n", http_req_cfg->contentType);
-    printf("\n[WIFI MAN] contentLenstr = %s\n", http_req_cfg->contentLen);
+    dbg_printf(LOG, "\n[WIFI MAN] server url+uri = %s\n", full_url);
+    dbg_printf(LOG, "\n[WIFI MAN] Host = %s\n", http_req_cfg->hostName);
+    dbg_printf(LOG, "\n[WIFI MAN] Accept = %s\n", http_req_cfg->AcceptVal);
+    dbg_printf(LOG, "\n[WIFI MAN] Content-Type = %s\n", http_req_cfg->contentType);
+    dbg_printf(LOG, "\n[WIFI MAN] contentLenstr = %s\n", http_req_cfg->contentLen);
                                            
     int bodyLen;
     sscanf(http_req_cfg->contentLen, "%d", &bodyLen);
-    printf("contenLenstr = %s bodyLen = %d\n", http_req_cfg->contentLen, bodyLen);
+    dbg_printf(LOG, "contenLenstr = %s bodyLen = %d\n", http_req_cfg->contentLen, bodyLen);
     
     if(bodyLen > 10){
-        printf("\n [WIFI MAN] Message Body:\n");
+        dbg_printf(LOG, "\n [WIFI MAN] Message Body:\n");
         printBufferInHex(http_req_cfg->body, bodyLen);
     }
     if(strstr(internet_config.url, "http:")!=NULL) // http request
@@ -917,9 +921,9 @@
                                        callback(this, &WiFiManager::body_callback));
         setHttpHeader("Host", http_req_cfg->hostName);
         setHttpHeader("Accept", http_req_cfg->AcceptVal);
-        printf("http_req_cfg->method = %d\n", http_req_cfg->method);
+        dbg_printf(LOG, "http_req_cfg->method = %d\n", http_req_cfg->method);
         if(http_req_cfg->method == HTTP_GET){
-            printf("HTTP_GET -- ignoring body\n");
+            dbg_printf(LOG, "HTTP_GET -- ignoring body\n");
             //setHttpHeader("Content-Type", http_req_cfg->contentType);
             //setHttpHeader("Content-Length", http_req_cfg->contentLen);
             http_response = http_request->send(NULL, 0);
@@ -933,13 +937,13 @@
         if (!http_response) {
             char buf[100];
             mbedtls_strerror(http_request->get_error(), buf, 100);
-            printf("HttpRequest failed (error code %s)\n", buf);
-            //printf("HttpsRequest failed (error code %d)\n", https_request->get_error());
+            dbg_printf(LOG, "HttpRequest failed (error code %s)\n", buf);
+            //dbg_printf(LOG, "HttpsRequest failed (error code %d)\n", https_request->get_error());
             delete http_request; // free the memory
             return false;
         }
         delete http_request; // free the memory
-        printf("\n----- HTTP POST response -----\n");
+        dbg_printf(LOG, "\n----- HTTP POST response -----\n");
     }
     else
     {
@@ -952,9 +956,9 @@
 #endif
             if(tlsResult == false){
                  delete socket;
-                 printf("TLS Socket connection failed - deleting data msg\r\n");
+                 dbg_printf(LOG, "TLS Socket connection failed - deleting data msg\r\n");
                  free_DataMsg();
-                 printf("data msg deleted \r\n");
+                 dbg_printf(LOG, "data msg deleted \r\n");
                  return false;
             }
             // update remote peer details after socket connection
@@ -962,8 +966,9 @@
             // send socket connection event before proceeding to send https request
             // give about 2 ms
             _event_queue.call_in(2, this, &WiFiManager::sendSocketConnectionEvent);
-            //printf("[create https] TLS connection successful for https site :  %s\n", host);
-            //printf("after call to createTLSconnection \n");
+            return true;
+            //dbg_printf(LOG, "[create https] TLS connection successful for https site :  %s\n", host);
+            //dbg_printf(LOG, "after call to createTLSconnection \n");
             //print_memory_info();
         }        
         // Pass in `socket`, instead of `network` as first argument, and omit the `SSL_CA_PEM` argument
@@ -981,9 +986,9 @@
                                          callback(this, &WiFiManager::body_callback));
 #endif        
 #ifdef TESTING_HTTPS
-        printf("http_req_cfg->method = %d\n", http_req_cfg->method);
+        dbg_printf(LOG, "http_req_cfg->method = %d\n", http_req_cfg->method);
         if(http_req_cfg->method == HTTP_GET){
-            printf("HTTP_GET -- ignoring body\n");
+            dbg_printf(LOG, "HTTP_GET -- ignoring body\n");
             setHttpsHeader("Host", http_req_cfg->hostName);
             setHttpsHeader("Accept", http_req_cfg->AcceptVal);
             //setHttpHeader("Content-Type", http_req_cfg->contentType);
@@ -991,23 +996,23 @@
             http_response = https_request->send(NULL, 0);
         }
         else{
-            printf("about to setup https headers\r\n");
+            dbg_printf(LOG, "about to setup https headers\r\n");
             setHttpsHeader("Host", http_req_cfg->hostName);
             setHttpsHeader("Accept", http_req_cfg->AcceptVal);
             setHttpsHeader("Content-Type", http_req_cfg->contentType);
             setHttpsHeader("Content-Length", http_req_cfg->contentLen);
-            printf("https headers setup - about to send request\r\n");
+            dbg_printf(LOG, "https headers setup - about to send request\r\n");
             mbedtls_ssl_context* tlsContext ;
             tlsContext = socket->get_ssl_context();
             mbedtls_ssl_config * tlsConfig;
             tlsConfig = socket->get_ssl_config();
             if(tlsContext != NULL)
             {
-                printf("current TLS tlsContext is not null [%d] \r\n", tlsContext->state);
+                dbg_printf(LOG, "current TLS tlsContext is not null [%d] \r\n", tlsContext->state);
             }
             else
             {
-                printf("TLS Context is NULL \r\n");
+                dbg_printf(LOG, "TLS Context is NULL \r\n");
             }
             //_wmutex.lock();
             http_response = https_request->send(http_req_cfg->body, bodyLen);
@@ -1027,7 +1032,7 @@
         if (!http_response) {
             char buf[100];
             mbedtls_strerror(https_request->get_error(), buf, 100);
-            printf("HttpsRequest failed (error code %s)\n", buf);
+            dbg_printf(LOG, "HttpsRequest failed (error code %s)\n", buf);
             delete https_request; // free the memory
             https_request = NULL;
             https_connection_active = false; // reset true whenever connection fails
@@ -1038,7 +1043,7 @@
             return false;
         }
         https_connection_active = true; // set true whenever connection succeeds
-        printf("\n----- HTTPS POST response -----\r\n");
+        dbg_printf(LOG, "\n----- HTTPS POST response -----\r\n");
     }
     if(http_response != NULL){
 
@@ -1051,11 +1056,11 @@
 #endif    
         //delete http_response; // free the response memory
         //http_response = NULL;
-        //printf("deleted http_response\r\n");
+        //dbg_printf(LOG, "deleted http_response\r\n");
     }
     free_DataMsg();
     delete https_request; // free the request & response memory
-    printf("deleted https_request\r\n");
+    dbg_printf(LOG, "deleted https_request\r\n");
     https_request = NULL;
     http_response = NULL;
     return true;
--- a/source/common_config.h	Wed Apr 24 17:34:17 2019 +0000
+++ b/source/common_config.h	Thu May 02 21:50:17 2019 +0000
@@ -9,7 +9,7 @@
 #define WIFI_THREAD_PRIORITY osPriorityHigh
 #define ATCMD_THREAD_PRIORITY osPriorityRealtime
 #ifndef UBLOX_ODIN_W2_RECV_TIMEOUT
-#define UBLOX_ODIN_W2_RECV_TIMEOUT    100
+#define UBLOX_ODIN_W2_RECV_TIMEOUT    5
 #endif
 #define USE_MALLOC_FOR_COMMAND_MEMORY_POOL
 #define WIFI_CONNECT_TIMEOUT_SECS 10
@@ -39,6 +39,7 @@
 #define HTTP_HEADER_START_LINE    "HTTP/1.1 "
 #define HTTP_HEADER_CONTENT_TYPE  "Content-Type:"
 #define HTTP_HEADER_CONTENT_LEN   "Content-Length:"
+//#define ENABLE_MEMORY_CHECKS
 
 typedef enum
 {
--- a/source/common_types.h	Wed Apr 24 17:34:17 2019 +0000
+++ b/source/common_types.h	Thu May 02 21:50:17 2019 +0000
@@ -28,7 +28,7 @@
     uint8_t   pairingKey[6];  /* pairing Key */
 } ble_config_t;
 
-/** ble configuration structure
+/** wifi configuration structure
 */
 typedef struct  {
     char             ssid[MAX_SSID_LEN]; /* WiFi SSID */
@@ -36,7 +36,7 @@
     nsapi_security_t security;  /* WiFi security */
 } wifi_config_t;
 
-/** ble configuration structure
+/** application configuration structure
 */
 typedef struct  {
     wifi_config_t wifi_config; /* wifi configuration */
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/source/debug.cpp	Thu May 02 21:50:17 2019 +0000
@@ -0,0 +1,366 @@
+/**
+******************************************************************************
+* @file         debug.c
+* @brief        Source file containing logic responsible for:
+* @details
+*
+******************************************************************************
+* @author       TTP
+* @copyright (c) 2017 TTP (The Technology Partnership) plc
+*
+******************************************************************************
+*/
+
+//-------- Includes ----------------------------------------------------------//
+
+#include "debug.h"
+#include <mbed.h>
+//#include "clocks.h"
+
+//-------- Defines -----------------------------------------------------------//
+
+#define FILE_CODE       "dbgm"
+#define ERROR       "err"
+
+#define DBG_RX_BUFFER_SIZE_BYTES        (1024)
+#define DBG_RX_BUFFER_MASK              (DBG_RX_BUFFER_SIZE_BYTES - 1)
+
+#define DBG_TX_BUFFER_SIZE_BYTES        (1024) 
+
+#if (DBG_RX_BUFFER_SIZE_BYTES & DBG_RX_BUFFER_MASK)
+    #error Rx buffer size is not power of 2
+#endif
+
+//-------- Constants & enums -------------------------------------------------//
+
+
+//-------- Structs & typedefs ------------------------------------------------//
+
+//-------- Global Variables --------------------------------------------------//
+
+/**
+*@brief         Global array of length ::DBG_TX_BUFFER_SIZE_BYTES to store
+*               the current debug print statement of the firmware. 
+*/
+static char g_dbg_buffer[DBG_TX_BUFFER_SIZE_BYTES];
+
+//-------- Static Variables --------------------------------------------------//
+
+static const char dbg_tx_terminate_string[] = {'\n', '\r'}; ///<Array of characters representing the terminate sequence of a debug transmit string
+
+static uint8_t current_debug_level; ///<Variable keeping track of the current debug level
+
+static char fw_ver_string[REL_FW_VER_STRING_LEN_BYTES + SVN_FW_VER_STRING_LEN_BYTES];
+static uint8_t fw_ver_bytes[5];
+
+static data_mode_e dbg_data_mode;
+
+//Rx buffer to be used for both ASCII and binary mode
+static uint8_t dbg_rx_buffer[DBG_RX_BUFFER_SIZE_BYTES];
+static volatile uint16_t dbg_rx_pos;
+static volatile uint32_t dbg_rx_count;
+static volatile uint16_t dbg_rx_cmd_count;
+
+//static char g_dbg_buffer[DBG_TX_BUFFER_SIZE_BYTES];
+
+//-------- Static function prototypes ----------------------------------------//
+
+static void set_fw_ver_string(void);
+static void set_fw_ver_bytes(void);
+static char get_rx_byte_from_buffer(void);
+static const char* debug_level_to_string(uint8_t debug_level);
+
+//-------- Function implementations ------------------------------------------//
+#ifdef BOX_MICRO_CODE
+static inline void disable_dbg_rx_intrup(void)
+{
+  __HAL_PCD_DISABLE(&hpcd_USB_OTG_FS);
+}
+
+static inline void enable_dbg_rx_intrup(void)
+{
+  __HAL_PCD_ENABLE(&hpcd_USB_OTG_FS);
+}
+#endif
+/**
+* @brief        Starting function to supervise the
+*               - Initialisation of UART2 responsible for acting as the debug port for the firmware
+*               - Initialisation of the UART2 transmit and receive buffers
+*               - Initial read from UART2
+*
+* @param        None 
+* @retval       None 
+*/
+void initialise_debug(void)
+{   
+  memset(g_dbg_buffer, 0, sizeof(g_dbg_buffer));
+  
+  //. Set the version strings
+  set_fw_ver_string();
+  set_fw_ver_bytes();
+  
+  current_debug_level = NONE; //(LOG | ERR | TXT | DBG); // 
+  dbg_data_mode = DATA_ASCII;
+  dbg_rx_pos = 0;
+  dbg_rx_count = 0;
+  dbg_rx_cmd_count = 0;
+}
+
+/**
+* @brief
+* @param
+* @param
+* @retval
+*/
+const char* get_dbg_tx_terminate_string(void)
+{
+  if (dbg_data_mode == DATA_ASCII)
+  { 
+    return dbg_tx_terminate_string;
+  }
+  else
+  {  
+    return NULL;
+  }
+}
+
+/**
+* @brief
+* @param
+* @param
+* @retval
+*/
+uint8_t get_dbg_tx_terminate_string_len(void)
+{
+  if (dbg_data_mode == DATA_ASCII)
+  {  
+    return sizeof(dbg_tx_terminate_string);
+  }
+  else
+  {  
+    return 0;
+  }
+}
+
+static const char* debug_level_to_string(uint8_t debug_level)
+{
+  switch(debug_level)
+  {
+  case LOG:
+    return "LOG";
+      
+  case ERR:
+    return "ERR";
+    
+  case DBG:
+    return "DBG";
+    
+  case TXT:
+    return "TXT";
+      
+  default:
+    return "INV"; //Invalid
+  }
+}
+
+
+//void dbg_printf(uint8_t debug_level, ...)
+//{
+//    dbg_print(FILE_CODE, __LINE__, debug_level, ...);
+//}
+void dbg_printf(uint8_t debug_level, const char *text, ...)
+{
+  //const char *file_code, uint16_t line_number,
+                
+  if (current_debug_level & debug_level)
+  {
+    //Re-init the gloabl debug buffer  
+    memset(g_dbg_buffer, 0, sizeof(g_dbg_buffer));
+    uint16_t len_bytes = 0;
+    
+    if (debug_level != TXT)
+    {
+      sprintf(g_dbg_buffer, "|%s|%10u|", debug_level_to_string(debug_level), Kernel::get_ms_count());
+      len_bytes = strlen(g_dbg_buffer);
+    }
+    
+    va_list args;
+    va_start(args, text); 
+    vsnprintf(&g_dbg_buffer[len_bytes], (sizeof(g_dbg_buffer) - len_bytes - 2), text, args);
+    printf("%s", g_dbg_buffer);
+    va_end(args);
+    
+    len_bytes = strlen(g_dbg_buffer);
+    g_dbg_buffer[len_bytes++] = '\r';
+    g_dbg_buffer[len_bytes++] = '\n';
+#ifdef WRITE_TO_FILE_ENABLED   
+    if (debug_level == LOG || debug_level == ERROR)
+    {
+      write_to_file(SYS_LOG, (const uint8_t *)g_dbg_buffer, len_bytes);
+    }
+    
+    if (dbg_data_mode == DATA_ASCII)
+    {
+      transmit_bytes_over_usb((uint8_t *)g_dbg_buffer, len_bytes);    
+    }
+#endif
+  }
+}
+
+/**
+    Function used to send data during firmware update (in binary mode)
+*/
+#ifdef WRITE_TO_FILE_ENABLED  
+void debug_send_data(uint8_t *pData, uint16_t length)
+{
+  transmit_bytes_over_usb(pData, length);
+}
+#endif
+
+/**
+* @brief        Function to set the debug level. Currently only 2 debug levels
+*               are provided as mentioned in ::debug_log_level_e.
+*               LOG is constantly enabled
+*
+* @param        (uint8_t) debug_level  
+* @retval       None
+*/
+void set_debug_level(uint8_t debug_level)
+{
+  current_debug_level = (LOG | ERR | TXT | debug_level);
+  dbg_printf(LOG, "Current debug level set to %02x", current_debug_level);
+}
+
+/**
+* @brief        Function to get the current debug level set. 
+*
+* @param        None 
+* @retval       (uint8_t) current_debug_level
+*/
+uint8_t get_debug_level(void)
+{
+  return current_debug_level;
+}
+
+/**
+* @brief        Function to set the micro firmware version 
+*               Firmware version follows the following format: 
+*               major.minor.patch.svn_revision
+*               
+*               If 'svnversion' is not installed on the machine, the svn
+*               revision is returned null. In that instance, the svn revision
+*               is set to n.a
+*
+* @param        None 
+* @retval       None
+*/
+static void set_fw_ver_string(void)
+{
+  memset(fw_ver_string, 0, sizeof(fw_ver_string));
+  
+  memcpy(fw_ver_string, REL_FW_VER_STRING, REL_FW_VER_STRING_LEN_BYTES);
+  
+  uint8_t rel_fw_string_len_bytes = strlen(REL_FW_VER_STRING);
+  
+  fw_ver_string[rel_fw_string_len_bytes] = '.';
+#ifdef BOX_MICRO_CODE   
+  if (strlen(SVN_FW_VERSION_STRING) == 0)
+  {
+    //svnversion is not installed on the machine
+    memcpy(&fw_ver_string[rel_fw_string_len_bytes + 1], "n.a", 4);
+  }
+  else
+  {
+    memcpy(&fw_ver_string[rel_fw_string_len_bytes + 1], SVN_FW_VERSION_STRING, SVN_FW_VER_STRING_LEN_BYTES);
+  }
+#endif
+}
+
+/**
+* @brief        Function to get the firmware version 
+*
+* @param        None 
+* @retval       (const char *) fw_ver_string
+*/
+const char* get_fw_ver_string(void)
+{
+  return fw_ver_string;
+}
+
+static void set_fw_ver_bytes(void)
+{
+  memset(fw_ver_bytes, 0, sizeof(fw_ver_bytes));
+  
+  uint16_t val = 0;
+  sscanf(fw_ver_string, "%hhx.%hhx.%hhx.%hx", &fw_ver_bytes[0], &fw_ver_bytes[1], &fw_ver_bytes[2], &val);
+  
+  fw_ver_bytes[3] = (val >> 8) & 0xff;
+  fw_ver_bytes[4] = val & 0xff;
+}
+
+const uint8_t* get_fw_ver_bytes(void)
+{
+  return fw_ver_bytes;
+}
+
+void debug_setDataMode(data_mode_e mode)
+{  
+  dbg_data_mode = mode;
+}
+
+void print_debug_hex(const uint8_t* p_buffer, uint16_t len)
+{
+  //print out the rxvd EDM bytes  
+  
+  uint16_t quo = len / 8;
+  uint16_t rem = len % 8;
+  
+  uint16_t i = 0;
+  uint16_t j = 0;
+  for (i = 0; i < quo; i++)
+  { 
+    dbg_printf(LOG, "[%3d]: %02x %02x %02x %02x %02x %02x %02x %02x", j,
+                    p_buffer[j + 0], p_buffer[j + 1], p_buffer[j + 2], p_buffer[j + 3],
+                    p_buffer[j + 4], p_buffer[j + 5], p_buffer[j + 6], p_buffer[j + 7]);
+    j += 8;
+  }
+  
+  if (rem == 7)
+  {
+    dbg_printf(LOG, "[%3d]: %02x %02x %02x %02x %02x %02x %02x", j,
+                    p_buffer[j + 0], p_buffer[j + 1], p_buffer[j + 2], p_buffer[j + 3],
+                    p_buffer[j + 4], p_buffer[j + 5], p_buffer[j + 6]);      
+  }
+  else if (rem == 6)
+  { 
+    dbg_printf(LOG, "[%3d]: %02x %02x %02x %02x %02x %02x", j,
+                    p_buffer[j + 0], p_buffer[j + 1], p_buffer[j + 2], p_buffer[j + 3],
+                    p_buffer[j + 4], p_buffer[j + 5]);     
+  }
+  else if (rem == 5)
+  {
+    dbg_printf(LOG, "[%3d]: %02x %02x %02x %02x %02x", j,
+                    p_buffer[j + 0], p_buffer[j + 1], p_buffer[j + 2], p_buffer[j + 3],
+                    p_buffer[j + 4]);      
+  }
+  else if (rem == 4)
+  {
+    dbg_printf(LOG, "[%3d]: %02x %02x %02x %02x", j,
+                    p_buffer[j + 0], p_buffer[j + 1], p_buffer[j + 2], p_buffer[j + 3]);   
+  }
+  else if (rem == 3)
+  {
+    dbg_printf(LOG, "[%3d]: %02x %02x %02x", j,
+                    p_buffer[j + 0], p_buffer[j + 1], p_buffer[j + 2]);      
+  }
+  else if (rem == 2)
+  {
+    dbg_printf(LOG, "[%3d]: %02x %02x", j, p_buffer[j + 0], p_buffer[j + 1]);     
+  }
+  else if (rem == 1)
+  {
+    dbg_printf(LOG, "[%3d]: %02x", j, p_buffer[j]);    
+  }  
+
+  dbg_printf(LOG, ""); 
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/source/debug.h	Thu May 02 21:50:17 2019 +0000
@@ -0,0 +1,96 @@
+/**
+********************************************************************************
+* @file         debug.h
+* @brief        Header file containing API for debug.c
+*
+********************************************************************************
+* @author       TTP
+* @copyright(c) 2017 TTP (The Technology Partnership) plc
+*
+********************************************************************************
+*/
+
+#ifndef DEBUG_H
+#define DEBUG_H
+
+//-------- Includes ----------------------------------------------------------//
+
+#include <string.h>
+#include <stdio.h>
+#include <stdint.h>
+#include <stdlib.h>
+#include <stdarg.h>
+#include <math.h>
+
+//-------- Defines -----------------------------------------------------------//
+
+#define SVN_FW_VER_STRING_LEN_BYTES     12
+#define REL_FW_VER_STRING_LEN_BYTES     12
+#define FW_VER_STRING_LEN_BYTES         SVN_FW_VER_STRING_LEN_BYTES + REL_FW_VER_STRING_LEN_BYTES
+
+#define REL_FW_VER_STRING               "1.0.0" //used by a fixed size array !
+
+#define DBG_RX_CMDDATA_SIZE_BYTES       32   
+
+//#define dbg_printf(debug_level, ...) dbg_print(FILE_CODE, __LINE__, debug_level, __VA_ARGS__)
+
+//-------- Constants & enums -------------------------------------------------//
+
+/**
+* @brief        Enumeration of the different data modes allowed
+*/
+typedef enum 
+{
+    DATA_ASCII,
+    DATA_FLASH,
+    DATA_ASCII_BINARY,     // Mode for doing flash verification
+    DATA_SD_CARD           // Data is for SD Card    
+      
+} data_mode_e;
+
+/**
+* @brief        Enumeration of the different debug log levels allowed
+*/
+typedef enum
+{
+  NONE          = 0x00,         
+  LOG           = 0x01,         
+  ERR           = 0x02,
+  DBG           = 0x04, 
+  TXT           = 0x08,
+  
+} debug_log_level_e;
+
+
+//-------- Structs & typedefs ------------------------------------------------//
+
+//-------- Global variables --------------------------------------------------//
+
+//--- Global function prototypes ----------------------------------------//
+
+void initialise_debug(void);
+
+void set_debug_level(uint8_t debug_level);
+
+uint8_t get_debug_level(void);
+
+//extern UART_HandleTypeDef* get_uart2_address(void);
+
+const char* get_dbg_tx_terminate_string(void);
+
+uint8_t get_dbg_tx_terminate_string_len(void);
+
+const char* get_fw_ver_string(void);
+
+const uint8_t* get_fw_ver_bytes(void);
+
+void debug_setDataMode(data_mode_e mode);
+
+void print_debug_hex(const uint8_t* p_buf, uint16_t len);
+
+void dbg_printf(uint8_t debug_level, const char *text, ...);
+//void dbg_printf(uint8_t debug_level, ...);
+//----------------------------------------------------------------------------//
+
+#endif /* DEBUG_H */
+
--- a/source/main-https.cpp	Wed Apr 24 17:34:17 2019 +0000
+++ b/source/main-https.cpp	Thu May 02 21:50:17 2019 +0000
@@ -1,6 +1,7 @@
 #define MBED_CONF_MBED_TRACE_ENABLE 1
 
 #include "select-demo.h"
+#include "debug.h"
 
 #if DEMO == DEMO_HTTPS
 
@@ -11,6 +12,7 @@
 #include "fault_handlers.h"
 //#include "BLE.h"
 #include "ATCmdParser.h"
+
 //#include "BLEDevice.h"
 
 #include "LEDService.h"
@@ -26,6 +28,7 @@
 DigitalOut alivenessLED(LED1, 0);
 DigitalOut actuatedLED(LED2, 0);
 
+#define FILE_CODE       "main"
 
 static RawSerial *device; // tx, rx
 
@@ -126,7 +129,7 @@
        // perform free memory check
     int blockSize = 16;
     int i = 1;
-    printf("Checking memory with blocksize %d char ...\n", blockSize);
+    dbg_printf(LOG, "Checking memory with blocksize %d char ...\n", blockSize);
     while (true) {
         char *p = (char *) malloc(i * blockSize);
         if (p == NULL)
@@ -134,7 +137,7 @@
         free(p);
         ++i;
     }
-    printf("Ok for %d char\n", (i - 1) * blockSize);
+    dbg_printf(LOG, "Ok for %d char\n", (i - 1) * blockSize);
     _smutex.unlock();
 
 }
@@ -163,12 +166,12 @@
     
     if(uartCharRcvCount == 0)
     {
-        device->printf("\nFirst Call to UART attach callback!!\n");
+        dbg_printf(LOG, "\nFirst Call to UART attach callback!!\n");
     }
     else if(uartCharRcvCount >= uartExpectedRcvCount)
     {
-        device->printf("\nNumber of Received Bytes = %d\n\n", uartCharRcvCount);
-        device->printf("--- Writing back received bytes --- \n");
+        dbg_printf(LOG, "\nNumber of Received Bytes = %d\n\n", uartCharRcvCount);
+        dbg_printf(LOG, "--- Writing back received bytes --- \n");
         int n;
         n = WriteUartBytes(RxBuffer, TX_BUFFER_LEN, uartCharRcvCount);
         UartBusy = false;
@@ -198,16 +201,16 @@
 void BackGndUartRead(uint8_t * rxBuffer, size_t bufSize, int rxLen)
 {
     UartBusy = true;
-    device->printf("Setting up background UART read -  rxLen = %d\n", rxLen);
+    dbg_printf(LOG, "Setting up background UART read -  rxLen = %d\n", rxLen);
     uartCharRcvCount = 0;
     if(rxLen > bufSize)
     {
         rxLen = bufSize;
     }
     uartExpectedRcvCount = rxLen;
-    device->printf("\nattaching to device UART\n\n");
+    dbg_printf(LOG, "\nattaching to device UART\n\n");
     device->attach(&UartRxcallback_ex);
-    device->printf("\nBackground UART read setup completed\n\n");
+    dbg_printf(LOG, "\nBackground UART read setup completed\n\n");
 }
 
 int ReadUartBytes(uint8_t * rxBuffer, size_t bufSize, int rxLen, bool echo)
@@ -230,19 +233,19 @@
 
 void checkUartReceive()
 {
-    //device->printf("Hello World!\n\r");
+    //dbg_printf(LOG, "Hello World!\n\r");
     char cbuf[100];
     int rxCnt=0;
     while(device->readable()) {
-        //device->printf("uartCharRcvCount = %d\n\r", uartCharRcvCount++);
+        //dbg_printf(LOG, "uartCharRcvCount = %d\n\r", uartCharRcvCount++);
         cbuf[rxCnt++] = device->getc();
         //putc(getc() + 1); // echo input back to terminal
     }
     cbuf[rxCnt] = NULL;
     if(rxCnt > 0)
     {
-        device->printf("received %d chars\n", rxCnt);
-        device->printf("%s\n", cbuf);
+        dbg_printf(LOG, "received %d chars\n", rxCnt);
+        dbg_printf(LOG, "%s\n", cbuf);
     }
 
 }
@@ -258,7 +261,7 @@
     lastTime = now;
     now = Kernel::get_ms_count();
     callCount++;
-    device->printf("\nHello : %d secs elapsed : CallCount = %d \n", uint32_t(now - lastTime), callCount);
+    dbg_printf(LOG, "\nHello : %d secs elapsed : CallCount = %d \n", uint32_t(now - lastTime), callCount);
 }
 
 
@@ -275,7 +278,7 @@
     int n = wifi_demo_func(network);
     if(n > 0)// error
     {
-        device->printf("\n --- Error running wifi demo --- \n");
+        dbg_printf(LOG, "\n --- Error running wifi demo --- \n");
     }
 }
 
@@ -285,16 +288,16 @@
     int n =5;
     if(n > 0)// error
     {
-        device->printf("\n --- Error running wifi demo --- \n");
+        dbg_printf(LOG, "\n --- Error running wifi demo --- \n");
     }
 }
 
 void printWait(int numSecs)
 {
-    printf("Waiting for %d seconds...\n", numSecs);
+    dbg_printf(LOG, "Waiting for %d seconds...\n", numSecs);
     for(int i=0;i<numSecs;i++){
-        printf("%d", i);
-        printf("\n");
+        dbg_printf(LOG, "%d", i);
+        dbg_printf(LOG, "\n");
         wait(0.5);
         eventQueue.dispatch(500);        // Dispatch time - 500msec
     }
@@ -302,17 +305,17 @@
 
 void printWaitAbortKeyPress(int numSecs)
 {
-    printf("Waiting for %d seconds... [press key to abort]\n", numSecs);
+    dbg_printf(LOG, "Waiting for %d seconds... [press key to abort]\n", numSecs);
     char fmtstr[20];
     for(int i=0;i<numSecs;i++){
-        printf("%d", i);
-        printf("\n");
+        dbg_printf(LOG, "%d", i);
+        dbg_printf(LOG, "\n");
         sprintf(fmtstr, "BLE: loop # %d\n", i);
         peripheral->sendBLEUartData(fmtstr);
         wait(0.5);
         eventQueue.dispatch(500);        // Dispatch time - 500msec
         if(device->readable()){
-            printf("keypress detected aborting....\n");
+            dbg_printf(LOG, "keypress detected aborting....\n");
             device->getc();
             break;
         }
@@ -344,59 +347,24 @@
 
 
 
-#define MAX_LOOP_COUNT 3
-int ble_security_main()
-{
-    BLE& _ble = BLE::Instance();
-    events::EventQueue queue;
-
-#if MBED_CONF_APP_FILESYSTEM_SUPPORT
-    /* if filesystem creation fails or there is no filesystem the security manager
-     * will fallback to storing the security database in memory */
-    if (!create_filesystem()) {
-        printf("Filesystem creation failed, will use memory storage\r\n");
-    }
-#endif
-    int loopCount = 0; 
-    while(1) {
-        {
-            printf("\r\n PERIPHERAL \r\n\r\n");
-            SMDevicePeripheral peripheral(_ble, queue, peer_address, ble_config);
-            peripheral.run();
-            return 0;
-        }
-        if(loopCount >= MAX_LOOP_COUNT)
-        {
-            return 0;
-        }
-
-        {
-            printf("\r\n CENTRAL \r\n\r\n");
-            SMDeviceCentral central(_ble, queue, peer_address, ble_config);
-            central.run();
-        }
-        loopCount++;
-        printf("loop Cycle #%d\r\n", loopCount);
-    }
-
-    return 0;
-}
 
 void print_memory_info() {
+#ifdef ENABLE_MEMORY_CHECKS
     // allocate enough room for every thread's stack statistics
     int cnt = osThreadGetCount();
     mbed_stats_stack_t *stats = (mbed_stats_stack_t*) malloc(cnt * sizeof(mbed_stats_stack_t));
  
     cnt = mbed_stats_stack_get_each(stats, cnt);
     for (int i = 0; i < cnt; i++) {
-        printf("Thread: 0x%lX, Stack size: %lu / %lu\r\n", stats[i].thread_id, stats[i].max_size, stats[i].reserved_size);
+        dbg_printf(LOG, "Thread: 0x%lX, Stack size: %lu / %lu\r\n", stats[i].thread_id, stats[i].max_size, stats[i].reserved_size);
     }
     free(stats);
  
     // Grab the heap statistics
     mbed_stats_heap_t heap_stats;
     mbed_stats_heap_get(&heap_stats);
-    printf("Heap size: %lu / %lu bytes\r\n", heap_stats.current_size, heap_stats.reserved_size);
+    dbg_printf(LOG, "Heap size: %lu / %lu bytes\r\n", heap_stats.current_size, heap_stats.reserved_size);
+#endif
 }
 
 //#define DISABLE_WIFI
@@ -405,21 +373,20 @@
 #define BLE_STOP_START_ADV_SCAN_DEMO
 #define SKIP_WIFI_CONNECT_DEMO
 #define PAUSE_SECONDS   0
-#define PAUSE_SECONDS_BLE 2
+#define PAUSE_SECONDS_BLE 0
 int main() {
-    //print_all_thread_info();
-    //print_heap_and_isr_stack_info();
+    initialise_debug();
 #ifdef MBED_MAJOR_VERSION
-    printf("Mbed OS version %d.%d.%d\n\n", MBED_MAJOR_VERSION, MBED_MINOR_VERSION, MBED_PATCH_VERSION);
+    dbg_printf(LOG, "Mbed OS version %d.%d.%d\n\n", MBED_MAJOR_VERSION, MBED_MINOR_VERSION, MBED_PATCH_VERSION);
 #endif
     
     reset_counter++;
     print_memory_info();
-    printf("\r\n ++++++ PROGRAM STARTING -- reset count = %d ++++++ \r\n", reset_counter);
-    device = new RawSerial(USBTX, USBRX, DEFAULT_BAUD_RATE);
+    dbg_printf(LOG, "\r\n ++++++ PROGRAM STARTING -- reset count = %d ++++++ \r\n", reset_counter);
+    device = new RawSerial(USBTX, USBRX, 2*DEFAULT_BAUD_RATE);
     //device = new RawSerial(PA_9, PA_10, DEFAULT_BAUD_RATE);
     
-    printf("*** HELLO MESSAGE *** \n %s", (char *)&hello_msg[6]);
+    dbg_printf(LOG, "*** HELLO MESSAGE *** \n %s", (char *)&hello_msg[6]);
     setupDefaultWiFiConfig();
     setupDefaultBleConfig();
     BLE& _ble = BLE::Instance();
@@ -428,11 +395,11 @@
     /* if filesystem creation fails or there is no filesystem the security manager
      * will fallback to storing the security database in memory */
     if (!create_filesystem()) {
-        printf("Filesystem creation failed, will use memory storage\r\n");
+        dbg_printf(LOG, "Filesystem creation failed, will use memory storage\r\n");
     }
 #endif
     print_memory_info();
-    printf("\r\n PERIPHERAL \r\n\r\n");
+    dbg_printf(LOG, "\r\n PERIPHERAL \r\n\r\n");
     peripheral = new SMDevicePeripheral(_ble, queue, peer_address, ble_config);
     print_memory_info();
 
@@ -447,7 +414,7 @@
 #ifdef DISABLE_WIFI_DEMO
     network = WiFiInterface::get_default_instance();
     if (!network) {
-        printf("ERROR: No WiFiInterface found.\n");
+        dbg_printf(LOG, "ERROR: No WiFiInterface found.\n");
     }
     wiFiManager = new WiFiManager(wifi_config, network, 
                                   eventQueue,
@@ -459,19 +426,19 @@
 #else
     NetworkInterface* network = connect_to_default_network_interface();
     int stop = Kernel::get_ms_count();
-    device->printf("\n The Wifi Network scan took %d ms or %4.1f seconds\n", (stop - start), (float)((stop - start)/1000.0));
+    dbg_printf(LOG, "\n The Wifi Network scan took %d ms or %4.1f seconds\n", (stop - start), (float)((stop - start)/1000.0));
     // run on separate thread;
     evt_thread.start(callback(wifi_demo, network));
     evt_thread.join(); 
     network->disconnect(); 
     delete network;
-    device->printf("\n Wifi-Demo completed - restarting BLE  \n\n");
+    dbg_printf(LOG, "\n Wifi-Demo completed - restarting BLE  \n\n");
 #endif /// endif DISABLE_WIFI_DEMO
 
 #else
-    device->printf("\n Wifi Demo disabled so just waiting it out...  \n\n");
+    dbg_printf(LOG, "\n Wifi Demo disabled so just waiting it out...  \n\n");
     printWait(2); // lets wait for a minute before turning BLE back on
-    device->printf("\n ++++++ restarting BLE ++++++ \n\n");
+    dbg_printf(LOG, "\n ++++++ restarting BLE ++++++ \n\n");
 #endif  /// endif DISABLE_WIFI
     printWaitAbortKeyPress(PAUSE_SECONDS);
     //peripheral->startAdvertising();
@@ -481,72 +448,72 @@
         device->putc(i);
     }
     reportGapState();
-    device->printf("\n\n\nEnter # of expected bytes: ");
+    dbg_printf(LOG, "\n\n\nEnter # of expected bytes: ");
     ReadUartBytes(RxBuffer, RX_BUFFER_LEN, 4, true);
     uint8_t rxLen = (uint8_t) (100*(RxBuffer[0]-'0') + 10*(RxBuffer[1]-'0') + (RxBuffer[2]-'0')) %256;
-    device->printf("\n\nExpected # of Received Bytes = %d\n", rxLen);
+    dbg_printf(LOG, "\n\nExpected # of Received Bytes = %d\n", rxLen);
     BackGndUartRead(RxBuffer, RX_BUFFER_LEN, (int) rxLen);
 
-    device->printf("\n Waiting for 5 seconds ");
+    dbg_printf(LOG, "\n Waiting for 5 seconds ");
     printWait(5);
-    device->printf("\n Waiting finished!!!\n Now waiting for expected bytes to be received \n\n");
+    dbg_printf(LOG, "\n Waiting finished!!!\n Now waiting for expected bytes to be received \n\n");
     while(UartBusy){
         wait(0.1);
     }
 #endif 
 
-    device->printf("\r\n++++++ Press key for Wifi demo test ++++++ \r\n");
+    dbg_printf(LOG, "\r\n++++++ Press key for Wifi demo test ++++++ \r\n");
     printWaitAbortKeyPress(PAUSE_SECONDS);
 #ifndef SKIP_WIFI_SCAN_DEMO
-    device->printf("\r\n++++++ Test WiFi Manager Network Scan ++++++ \r\n");
+    dbg_printf(LOG, "\r\n++++++ Test WiFi Manager Network Scan ++++++ \r\n");
     int count;
     count = wiFiManager->scanNetworks();
     if (count <= 0) {
-        device->printf("scan() failed with return value: %d\n", count);
+        dbg_printf(LOG, "scan() failed with return value: %d\n", count);
     }
     else {
-        device->printf("\r\n++++++ Test WiFi Scan found %d networks ++++++ \r\n ++++ SUCCESS ++++\r\n", count);
+        dbg_printf(LOG, "\r\n++++++ Test WiFi Scan found %d networks ++++++ \r\n ++++ SUCCESS ++++\r\n", count);
     }
 #endif    
 
 #ifndef SKIP_WIFI_CONNECT_DEMO
-    device->printf("\r\n++++++ Test WiFi Manager Network connect ++++++ \r\n");
+    dbg_printf(LOG, "\r\n++++++ Test WiFi Manager Network connect ++++++ \r\n");
     nsapi_error_t werror;
     werror = wiFiManager->connect();
     if (werror < 0) {
-        device->printf("connect() failed with return value: %d\n", werror);
+        dbg_printf(LOG, "connect() failed with return value: %d\n", werror);
     }
     else {
-        device->printf("\r\n++++++ Test WiFi connect SUCCESSFUL ++++++ \r\n");
+        dbg_printf(LOG, "\r\n++++++ Test WiFi connect SUCCESSFUL ++++++ \r\n");
     }
     if(!werror) // connect successful - test dicsonnection
     {
-        device->printf("\r\n++++++ Test WiFi Manager Network disconnect ++++++ \r\n");
+        dbg_printf(LOG, "\r\n++++++ Test WiFi Manager Network disconnect ++++++ \r\n");
         werror = wiFiManager->disconnect();
         if (werror) {
-            device->printf("disconnect() failed with return value: %d\n", werror);
+            dbg_printf(LOG, "disconnect() failed with return value: %d\n", werror);
         }
         else {
-            device->printf("\r\n++++++ Test WiFi disconnect SUCCESSFUL ++++++ \r\n");
+            dbg_printf(LOG, "\r\n++++++ Test WiFi disconnect SUCCESSFUL ++++++ \r\n");
         }
     }
 #endif    
     //wiFiManager->runMain();
-    device->printf("\r\n++++++++++++++++++++++++++++++++++++++++++++++++++++++++ \r\n");
-    device->printf("\r\n++++++++++++++++++++++++++++++++++++++++++++++++++++++++ \r\n");
-    device->printf("\r\n++++++++++++++++++++++++++++++++++++++++++++++++++++++++ \r\n");
-    device->printf("\r\n++++++ Test WiFi Manager Network scan from thread ++++++ \r\n");
-    device->printf("\r\n++++++++++++++++++++++++++++++++++++++++++++++++++++++++ \r\n");
-    device->printf("\r\n++++++++++++++++++++++++++++++++++++++++++++++++++++++++ \r\n");
-    device->printf("\r\n++++++++++++++++++++++++++++++++++++++++++++++++++++++++ \r\n");
+    dbg_printf(LOG, "\r\n++++++++++++++++++++++++++++++++++++++++++++++++++++++++ \r\n");
+    dbg_printf(LOG, "\r\n++++++++++++++++++++++++++++++++++++++++++++++++++++++++ \r\n");
+    dbg_printf(LOG, "\r\n++++++++++++++++++++++++++++++++++++++++++++++++++++++++ \r\n");
+    dbg_printf(LOG, "\r\n++++++ Test WiFi Manager Network scan from thread ++++++ \r\n");
+    dbg_printf(LOG, "\r\n++++++++++++++++++++++++++++++++++++++++++++++++++++++++ \r\n");
+    dbg_printf(LOG, "\r\n++++++++++++++++++++++++++++++++++++++++++++++++++++++++ \r\n");
+    dbg_printf(LOG, "\r\n++++++++++++++++++++++++++++++++++++++++++++++++++++++++ \r\n");
     wifi_thread.start(callback(wiFiManager, &WiFiManager::runMain));
-    printf("\r\n after starting wifi thread \r\n");
+    dbg_printf(LOG, "\r\n after starting wifi thread \r\n");
     print_memory_info();
     // dispatch event queue on event thread
-    printf("\r\n [MAIN THREAD]  Thread Id = %X\r\n", (uint32_t)ThisThread::get_id());
-    printf("\r\n [EVENT THREAD]  Thread Id = %X\r\n", (uint32_t)evt_thread.get_id());
+    dbg_printf(LOG, "\r\n [MAIN THREAD]  Thread Id = %X\r\n", (uint32_t)ThisThread::get_id());
+    dbg_printf(LOG, "\r\n [EVENT THREAD]  Thread Id = %X\r\n", (uint32_t)evt_thread.get_id());
     evt_thread.start(callback(&eventQueue, &EventQueue::dispatch_forever));
-    device->printf("\r\n++++++ Starting ATCmdmanager ++++++ \r\n");
+    dbg_printf(LOG, "\r\n++++++ Starting ATCmdmanager ++++++ \r\n");
     ATCmdManager *aTCmdManager = new ATCmdManager(USBTX, USBRX, peripheral, 
                                                 eventQueue, wiFiManager, 
                                                 &aT2WiFimPool, &aT2WiFiCmdQueue,
@@ -556,7 +523,7 @@
                                                 false);
     //aTCmdManager->runMain();
     atcmd_thread.start(callback(aTCmdManager, &ATCmdManager::runMain));
-    printf("\r\n after starting atcmd thread \r\n");
+    dbg_printf(LOG, "\r\n after starting atcmd thread \r\n");
     print_memory_info();
     //SCB->SHCSR |= 0x00070000;//Enable fault handler.
     //wiFiManager->runMain();
--- a/source/mbed_memory_status.cpp	Wed Apr 24 17:34:17 2019 +0000
+++ b/source/mbed_memory_status.cpp	Thu May 02 21:50:17 2019 +0000
@@ -1,488 +1,490 @@
-/*
-    mbed Memory Status Helper
-    Copyright (c) 2017 Max Vilimpoc
-
-    Permission is hereby granted, free of charge, to any person obtaining a copy
-    of this software and associated documentation files (the "Software"), to deal
-    in the Software without restriction, including without limitation the rights
-    to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-    copies of the Software, and to permit persons to whom the Software is
-    furnished to do so, subject to the following conditions:
-
-    The above copyright notice and this permission notice shall be included in
-    all copies or substantial portions of the Software.
-
-    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-    AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-    OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-    THE SOFTWARE.
-*/
-
-/**
- * Purpose: Print out thread info and other useful details using
- *          only raw serial access.
- *
- * Based on mbed_board.c's error printing functionality, minus
- * pulling in all the printf() code.
- */
-
-// Not great having to pull in all of mbed.h just to get the MBED_VERSION macro,
-// but it's the only way to do it for both pre- and post-5.4 releases
-//
-// If you're only supporting something newer than 5.4, you could use this alone:
-// #include "platform/mbed_version.h"
-//
-// platform/mbed_version.h says:
-// 999999 is default value for development version (master branch)
-
-#include "mbed.h"
-
-// Critical sections header file renamed in mbed OS 5.4 release
-// See: https://github.com/ARMmbed/mbed-os/commit/aff49d8d1e3b5d4dc18286b0510336c36ae9603c
-
-#ifndef MBED_VERSION
-#warning "You're probably using an unsupported version of mbed older than 5.2."
-#endif
-
-#if   MBED_VERSION >= 50400
-#include "platform/mbed_critical.h"
-#elif MBED_VERSION >= 50200
-#include "platform/critical.h"
-#endif
-
-#include "platform/mbed_stats.h"
-
-#if !MBED_STACK_STATS_ENABLED
-#warning MBED_STACK_STATS_ENABLED != 1, so there will be no stack usage measurements.
-#endif
-
-#ifndef DEBUG_ISR_STACK_USAGE
-#define DEBUG_ISR_STACK_USAGE  0
-#endif
-
-#ifndef DEBUG_MEMORY_CONTENTS
-#define DEBUG_MEMORY_CONTENTS  0
-#endif
-
-#define OUTPUT_SERIAL          1
-#define OUTPUT_RTT             0
-#define OUTPUT_SWO             0
-
-#if DEBUG_ISR_STACK_USAGE
-#include "compiler_abstraction.h"
-
-// Value is sprayed into all of the ISR stack at boot time.
-static const uint32_t ISR_STACK_CANARY = 0xAFFEC7ED; // AFFECTED
-
-// Refers to linker script defined symbol, may not be available
-// on all platforms.
-extern uint32_t __StackLimit;
-extern uint32_t __StackTop;
-
-void fill_isr_stack_with_canary(void)
-{
-    uint32_t * bottom = &__StackLimit;
-    uint32_t * top    = (uint32_t *) GET_SP();
-
-    for (; bottom < top; bottom++)
-    {
-        *bottom = ISR_STACK_CANARY;
-    }
-}
-#endif // DEBUG_ISR_STACK_USAGE
-
-#if OUTPUT_SERIAL && DEVICE_SERIAL
-#include "hal/serial_api.h"
-
-extern int      stdio_uart_inited;
-extern serial_t stdio_uart;
-
-static void output_serial_init(void)
-{
-    if (!stdio_uart_inited)
-    {
-        serial_init(&stdio_uart, STDIO_UART_TX, STDIO_UART_RX);
-        serial_baud(&stdio_uart, 115200); // This is hard coded.
-    }
-}
-
-static void output_serial_print_label(const char * label)
-{
-#if MBED_VERSION < 50902
-    // After mbed OS 5.9.2, this locks up the system.
-    core_util_critical_section_enter();
-#endif
-
-    output_serial_init();
-
-    while (*label) serial_putc(&stdio_uart, *label++);
-
-#if MBED_VERSION < 50902
-    core_util_critical_section_exit();
-#endif
-}
-#endif // OUTPUT_SERIAL && DEVICE_SERIAL
-
-#if OUTPUT_RTT
-#include "RTT/SEGGER_RTT.h"
-
-enum
-{
-    DEFAULT_RTT_UP_BUFFER = 0
-};
-
-static void output_rtt_init(void)
-{
-    static int initialized = 0;
-
-    if (!initialized)
-    {
-        SEGGER_RTT_ConfigUpBuffer(DEFAULT_RTT_UP_BUFFER, NULL, NULL, 0, SEGGER_RTT_MODE_NO_BLOCK_TRIM);
-
-        initialized = 1;
-    }
-}
-
-static void output_rtt_print_label(const char * label)
-{
-    output_rtt_init();
-    SEGGER_RTT_WriteString(DEFAULT_RTT_UP_BUFFER, label);
-}
-#endif // OUTPUT_RTT
-
-#if OUTPUT_SWO
-#if defined (NRF52) && !defined (ENABLE_SWO)
-  #error "You need to enable SWO using `-D ENABLE_SWO` on the mbed compile command line."
-#endif
-
-#ifdef NRF52
-#include "nrf.h"
-#endif
-
-static void output_swo_init(void)
-{
-    static int initialized = 0;
-
-    if (!initialized)
-    {
-        NRF_CLOCK->TRACECONFIG = (NRF_CLOCK->TRACECONFIG & ~CLOCK_TRACECONFIG_TRACEPORTSPEED_Msk) |
-            (CLOCK_TRACECONFIG_TRACEPORTSPEED_4MHz << CLOCK_TRACECONFIG_TRACEPORTSPEED_Pos);
-
-        ITM->TCR |= 1;
-        ITM->TER |= 1;
-
-        initialized = 1;
-    }
-}
-
-static void output_swo_print_label(const char * label)
-{
-    output_swo_init();
-    while (*label) ITM_SendChar(*label++);
-}
-#endif // OUTPUT_SWO
-
-static void nway_print_label(const char * label)
-{
-#if OUTPUT_SERIAL
-    output_serial_print_label(label);
-#endif
-
-#if OUTPUT_RTT
-    output_rtt_print_label(label);
-#endif
-
-#if OUTPUT_SWO
-    output_swo_print_label(label);
-#endif
-}
-
-static const char HEX[] = "0123456789ABCDEF";
-
-static void debug_print_u32(uint32_t u32)
-{
-    char output[9] = {0};
-
-    // Always printed as big endian.
-    output[0] = HEX[(((uint32_t) u32 & 0xf0000000) >> 28)];
-    output[1] = HEX[(((uint32_t) u32 & 0x0f000000) >> 24)];
-    output[2] = HEX[(((uint32_t) u32 & 0x00f00000) >> 20)];
-    output[3] = HEX[(((uint32_t) u32 & 0x000f0000) >> 16)];
-    output[4] = HEX[(((uint32_t) u32 & 0x0000f000) >> 12)];
-    output[5] = HEX[(((uint32_t) u32 & 0x00000f00) >>  8)];
-    output[6] = HEX[(((uint32_t) u32 & 0x000000f0) >>  4)];
-    output[7] = HEX[(((uint32_t) u32 & 0x0000000f) >>  0)];
-
-    nway_print_label(output);
-}
-
-static void debug_print_pointer(const void * pointer)
-{
-    debug_print_u32((uint32_t) pointer);
-}
-
-#define DPL(X) nway_print_label((X))
-
-#if (defined (MBED_CONF_RTOS_PRESENT) && (MBED_CONF_RTOS_PRESENT != 0))
-#include "cmsis_os.h"
-
-// cmsis_os.h provides some useful defines:
-//
-// For mbed OS 5.4 and lower,  osCMSIS == 0x10002U (see: rtos/rtx/TARGET_CORTEX_M)
-// For mbed OS 5.5 and higher, osCMSIS == 0x20001U (see: rtos/TARGET_CORTEX/rtx{4|5})
-//
-// Starting in mbed OS 5.5, a new RTOS layer was introduced with a different API.
-
-#if (osCMSIS < 0x20000U)
-    // Temporarily #undef NULL or the compiler complains about previous def.
-    #undef NULL
-    #include "rt_TypeDef.h"
-#else
-    #include "rtx_lib.h"
-    // #include <stdlib.h>  // Include if you need malloc() / free() below. (probably better for non-C99 compilers)
-#endif
-
-#if (osCMSIS < 0x20000U)
-
-// No public forward declaration for this.
-extern "C" P_TCB rt_tid2ptcb (osThreadId thread_id);
-
-static void print_thread_info(osThreadId threadId)
-{
-    if (!threadId) return;
-
-    osEvent event;
-
-    P_TCB tcb = rt_tid2ptcb(threadId);
-
-    DPL("    stack ( start: ");
-    debug_print_pointer(tcb->stack);
-
-    event = _osThreadGetInfo(threadId, osThreadInfoStackSize);
-
-    DPL(" end: ");
-    debug_print_pointer(((uint8_t *) tcb->stack + event.value.v)); // (tcb->priv_stack)));
-
-    DPL(" size: ");
-    debug_print_u32(event.value.v);
-
-    event = _osThreadGetInfo(threadId, osThreadInfoStackMax);
-    DPL(" used: ");
-    debug_print_u32(event.value.v);
-
-
-    DPL(" ) ");
-
-    DPL("thread ( id: ");
-    debug_print_pointer(threadId);
-
-    event = _osThreadGetInfo(threadId, osThreadInfoEntry);
-    DPL(" entry: ");
-    debug_print_pointer(event.value.p);
-
-    DPL(" )\r\n");
-}
-
-void print_all_thread_info(void)
-{
-    osThreadEnumId enumId   = _osThreadsEnumStart();
-    osThreadId     threadId = (osThreadId) NULL; // Can't use nullptr yet because mbed doesn't support C++11.
-
-    while ((threadId = _osThreadEnumNext(enumId)))
-    {
-        print_thread_info(threadId);
-    }
-
-    _osThreadEnumFree(enumId);
-}
-
-#else
-
-static void print_thread_info(osThreadId threadId)
-{
-    // Refs: rtx_lib.h - #define os_thread_t osRtxThread_t
-    //       rtx_os.h  - typedef struct osRtxThread_s { } osRtxThread_t
-
-    if (!threadId) return;
-
-    os_thread_t * tcb = (os_thread_t *) threadId;
-
-    uint32_t stackSize = osThreadGetStackSize(threadId);
-    uint32_t stackUsed = osThreadGetStackSpace(threadId);
-
-    DPL("    stack ( start: ");
-    debug_print_pointer(tcb->stack_mem);
-
-    DPL(" end: ");
-    debug_print_pointer((uint8_t *) tcb->stack_mem + stackSize);
-
-    DPL(" size: ");
-    debug_print_u32(stackSize);
-
-    DPL(" used: ");
-    debug_print_u32(stackSize - stackUsed);
-
-    DPL(" ) ");
-
-    DPL("thread ( id: ");
-    debug_print_pointer(threadId);
-
-    DPL(" entry: ");
-    debug_print_u32(tcb->thread_addr);
-
-    DPL(" name: ");
-    DPL(osThreadGetName(threadId) ? osThreadGetName(threadId) : "unknown");
-
-    DPL(" )\r\n");
-}
-
-void print_all_thread_info(void)
-{
-    // Refs: mbed_stats.c - mbed_stats_stack_get_each()
-
-    uint32_t     threadCount = osThreadGetCount();
-    osThreadId_t threads[threadCount]; // g++ will throw a -Wvla on this, but it is likely ok.
-
-    // osThreadId_t * threads = malloc(sizeof(osThreadId_t) * threadCount);
-    // MBED_ASSERT(NULL != threads);
-
-    memset(threads, 0, threadCount * sizeof(osThreadId_t));
-
-    // This will probably only work if the number of threads remains constant
-    // (i.e. the number of thread control blocks remains constant)
-    //
-    // This is probably the case on a deterministic realtime embedded system
-    // with limited SRAM.
-
-    osKernelLock();
-
-    threadCount = osThreadEnumerate(threads, threadCount);
-
-    for (uint32_t i = 0; i < threadCount; i++)
-    {
-        // There seems to be a Heisenbug when calling print_thread_info()
-        // inside of osKernelLock()!
-
-        // This error may appear on the serial console:
-        // mbed assertation failed: os_timer->get_tick() == svcRtxKernelGetTickCount(), file: .\mbed-os\rtos\TARGET_CORTEX\mbed_rtx_idle.c
-
-        // The RTOS seems to be asserting an idle constraint violation due
-        // to the slowness of sending data through the serial port, but it
-        // does not happen consistently.
-        print_thread_info(threads[i]);
-    }
-
-    osKernelUnlock();
-
-    // free(threads);
-}
-
-#endif
-
-void print_current_thread_id(void)
-{
-    DPL("Current thread: ");
-    debug_print_pointer(osThreadGetId());
-    DPL("\r\n");
-}
-#endif // MBED_CONF_RTOS_PRESENT
-
-#if DEBUG_MEMORY_CONTENTS
-static void print_memory_contents(const uint32_t * start, const uint32_t * end)
-{
-    uint8_t line = 0;
-
-    for (; start < end; start++)
-    {
-        if (0 == line)
-        {
-            debug_print_pointer(start);
-            DPL(": ");
-        }
-
-        debug_print_u32(*start);
-
-        line++;
-
-        if (16 == line)
-        {
-            DPL("\r\n");
-            line = 0;
-        }
-    }
-}
-#endif
-
-extern uint32_t mbed_stack_isr_size;
-
-#if DEBUG_ISR_STACK_USAGE
-uint32_t calculate_isr_stack_usage(void)
-{
-    for (const uint32_t * stack = &__StackLimit; stack < &__StackTop; stack++)
-    {
-        if (*stack != ISR_STACK_CANARY)
-        {
-            return (uint32_t) &__StackTop - (uint32_t) stack;
-        }
-    }
-
-    return mbed_stack_isr_size;
-}
-#endif
-
-void print_heap_and_isr_stack_info(void)
-{
-    extern unsigned char * mbed_heap_start;
-    extern uint32_t        mbed_heap_size;
-
-    extern unsigned char * mbed_stack_isr_start;
-
-    mbed_stats_heap_t      heap_stats;
-
-    mbed_stats_heap_get(&heap_stats);
-
-    DPL("     heap ( start: ");
-    debug_print_pointer(mbed_heap_start);
-
-    DPL(" end: ");
-    debug_print_pointer(mbed_heap_start + mbed_heap_size);
-
-    DPL(" size: ");
-    debug_print_u32(mbed_heap_size);
-
-    DPL(" used: ");
-    debug_print_u32(heap_stats.max_size);
-
-    DPL(" )  alloc ( ok: ");
-    debug_print_u32(heap_stats.alloc_cnt);
-
-    DPL("  fail: ");
-    debug_print_u32(heap_stats.alloc_fail_cnt);
-
-    DPL(" )\r\n");
-
-    DPL("isr_stack ( start: ");
-    debug_print_pointer(mbed_stack_isr_start);
-
-    DPL(" end: ");
-    debug_print_pointer(mbed_stack_isr_start + mbed_stack_isr_size);
-
-    DPL(" size: ");
-    debug_print_u32(mbed_stack_isr_size);
-
-#if DEBUG_ISR_STACK_USAGE
-    DPL(" used: ");
-    debug_print_u32(calculate_isr_stack_usage());
-#endif
-
-    DPL(" )\r\n");
-
-#if DEBUG_MEMORY_CONTENTS
-    // Print ISR stack contents.
-    print_memory_contents(&__StackLimit, &__StackTop);
-#endif
-}
+/*
+    mbed Memory Status Helper
+    Copyright (c) 2017 Max Vilimpoc
+
+    Permission is hereby granted, free of charge, to any person obtaining a copy
+    of this software and associated documentation files (the "Software"), to deal
+    in the Software without restriction, including without limitation the rights
+    to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+    copies of the Software, and to permit persons to whom the Software is
+    furnished to do so, subject to the following conditions:
+
+    The above copyright notice and this permission notice shall be included in
+    all copies or substantial portions of the Software.
+
+    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+    AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+    OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+    THE SOFTWARE.
+*/
+
+/**
+ * Purpose: Print out thread info and other useful details using
+ *          only raw serial access.
+ *
+ * Based on mbed_board.c's error printing functionality, minus
+ * pulling in all the printf() code.
+ */
+
+// Not great having to pull in all of mbed.h just to get the MBED_VERSION macro,
+// but it's the only way to do it for both pre- and post-5.4 releases
+//
+// If you're only supporting something newer than 5.4, you could use this alone:
+// #include "platform/mbed_version.h"
+//
+// platform/mbed_version.h says:
+// 999999 is default value for development version (master branch)
+
+#include "mbed.h"
+
+// Critical sections header file renamed in mbed OS 5.4 release
+// See: https://github.com/ARMmbed/mbed-os/commit/aff49d8d1e3b5d4dc18286b0510336c36ae9603c
+
+#ifndef MBED_VERSION
+#warning "You're probably using an unsupported version of mbed older than 5.2."
+#endif
+
+#if   MBED_VERSION >= 50400
+#include "platform/mbed_critical.h"
+#elif MBED_VERSION >= 50200
+#include "platform/critical.h"
+#endif
+
+#include "platform/mbed_stats.h"
+
+#if !MBED_STACK_STATS_ENABLED
+#warning MBED_STACK_STATS_ENABLED != 1, so there will be no stack usage measurements.
+#endif
+
+#ifndef DEBUG_ISR_STACK_USAGE
+#define DEBUG_ISR_STACK_USAGE  0
+#endif
+
+#ifndef DEBUG_MEMORY_CONTENTS
+#define DEBUG_MEMORY_CONTENTS  0
+#endif
+
+#define OUTPUT_SERIAL          1
+#define OUTPUT_RTT             0
+#define OUTPUT_SWO             0
+
+#if DEBUG_ISR_STACK_USAGE
+#include "compiler_abstraction.h"
+
+// Value is sprayed into all of the ISR stack at boot time.
+static const uint32_t ISR_STACK_CANARY = 0xAFFEC7ED; // AFFECTED
+
+// Refers to linker script defined symbol, may not be available
+// on all platforms.
+extern uint32_t __StackLimit;
+extern uint32_t __StackTop;
+
+void fill_isr_stack_with_canary(void)
+{
+    uint32_t * bottom = &__StackLimit;
+    uint32_t * top    = (uint32_t *) GET_SP();
+
+    for (; bottom < top; bottom++)
+    {
+        *bottom = ISR_STACK_CANARY;
+    }
+}
+#endif // DEBUG_ISR_STACK_USAGE
+
+#if OUTPUT_SERIAL && DEVICE_SERIAL
+#include "hal/serial_api.h"
+
+extern int      stdio_uart_inited;
+extern serial_t stdio_uart;
+
+static void output_serial_init(void)
+{
+    if (!stdio_uart_inited)
+    {
+        serial_init(&stdio_uart, STDIO_UART_TX, STDIO_UART_RX);
+        serial_baud(&stdio_uart, 115200); // This is hard coded.
+    }
+}
+
+static void output_serial_print_label(const char * label)
+{
+#if MBED_VERSION < 50902
+    // After mbed OS 5.9.2, this locks up the system.
+    core_util_critical_section_enter();
+#endif
+
+    output_serial_init();
+
+    while (*label) serial_putc(&stdio_uart, *label++);
+
+#if MBED_VERSION < 50902
+    core_util_critical_section_exit();
+#endif
+}
+#endif // OUTPUT_SERIAL && DEVICE_SERIAL
+
+#if OUTPUT_RTT
+#include "RTT/SEGGER_RTT.h"
+
+enum
+{
+    DEFAULT_RTT_UP_BUFFER = 0
+};
+
+static void output_rtt_init(void)
+{
+    static int initialized = 0;
+
+    if (!initialized)
+    {
+        SEGGER_RTT_ConfigUpBuffer(DEFAULT_RTT_UP_BUFFER, NULL, NULL, 0, SEGGER_RTT_MODE_NO_BLOCK_TRIM);
+
+        initialized = 1;
+    }
+}
+
+static void output_rtt_print_label(const char * label)
+{
+    output_rtt_init();
+    SEGGER_RTT_WriteString(DEFAULT_RTT_UP_BUFFER, label);
+}
+#endif // OUTPUT_RTT
+
+#if OUTPUT_SWO
+#if defined (NRF52) && !defined (ENABLE_SWO)
+  #error "You need to enable SWO using `-D ENABLE_SWO` on the mbed compile command line."
+#endif
+
+#ifdef NRF52
+#include "nrf.h"
+#endif
+
+static void output_swo_init(void)
+{
+    static int initialized = 0;
+
+    if (!initialized)
+    {
+        NRF_CLOCK->TRACECONFIG = (NRF_CLOCK->TRACECONFIG & ~CLOCK_TRACECONFIG_TRACEPORTSPEED_Msk) |
+            (CLOCK_TRACECONFIG_TRACEPORTSPEED_4MHz << CLOCK_TRACECONFIG_TRACEPORTSPEED_Pos);
+
+        ITM->TCR |= 1;
+        ITM->TER |= 1;
+
+        initialized = 1;
+    }
+}
+
+static void output_swo_print_label(const char * label)
+{
+    output_swo_init();
+    while (*label) ITM_SendChar(*label++);
+}
+#endif // OUTPUT_SWO
+
+static void nway_print_label(const char * label)
+{
+#if OUTPUT_SERIAL
+    output_serial_print_label(label);
+#endif
+
+#if OUTPUT_RTT
+    output_rtt_print_label(label);
+#endif
+
+#if OUTPUT_SWO
+    output_swo_print_label(label);
+#endif
+}
+
+static const char HEX[] = "0123456789ABCDEF";
+
+static void debug_print_u32(uint32_t u32)
+{
+    char output[9] = {0};
+
+    // Always printed as big endian.
+    output[0] = HEX[(((uint32_t) u32 & 0xf0000000) >> 28)];
+    output[1] = HEX[(((uint32_t) u32 & 0x0f000000) >> 24)];
+    output[2] = HEX[(((uint32_t) u32 & 0x00f00000) >> 20)];
+    output[3] = HEX[(((uint32_t) u32 & 0x000f0000) >> 16)];
+    output[4] = HEX[(((uint32_t) u32 & 0x0000f000) >> 12)];
+    output[5] = HEX[(((uint32_t) u32 & 0x00000f00) >>  8)];
+    output[6] = HEX[(((uint32_t) u32 & 0x000000f0) >>  4)];
+    output[7] = HEX[(((uint32_t) u32 & 0x0000000f) >>  0)];
+
+    nway_print_label(output);
+}
+
+static void debug_print_pointer(const void * pointer)
+{
+    debug_print_u32((uint32_t) pointer);
+}
+
+#define DPL(X) nway_print_label((X))
+
+#if (defined (MBED_CONF_RTOS_PRESENT) && (MBED_CONF_RTOS_PRESENT != 0))
+#include "cmsis_os.h"
+
+// cmsis_os.h provides some useful defines:
+//
+// For mbed OS 5.4 and lower,  osCMSIS == 0x10002U (see: rtos/rtx/TARGET_CORTEX_M)
+// For mbed OS 5.5 and higher, osCMSIS == 0x20001U (see: rtos/TARGET_CORTEX/rtx{4|5})
+//
+// Starting in mbed OS 5.5, a new RTOS layer was introduced with a different API.
 
+#if (osCMSIS < 0x20000U)
+    // Temporarily #undef NULL or the compiler complains about previous def.
+    #undef NULL
+    #include "rt_TypeDef.h"
+#else
+    #include "rtx_lib.h"
+    // #include <stdlib.h>  // Include if you need malloc() / free() below. (probably better for non-C99 compilers)
+#endif
+
+#if (osCMSIS < 0x20000U)
+
+// No public forward declaration for this.
+extern "C" P_TCB rt_tid2ptcb (osThreadId thread_id);
+
+static void print_thread_info(osThreadId threadId)
+{
+    if (!threadId) return;
+
+    osEvent event;
+
+    P_TCB tcb = rt_tid2ptcb(threadId);
+
+    DPL("    stack ( start: ");
+    debug_print_pointer(tcb->stack);
+
+    event = _osThreadGetInfo(threadId, osThreadInfoStackSize);
+
+    DPL(" end: ");
+    debug_print_pointer(((uint8_t *) tcb->stack + event.value.v)); // (tcb->priv_stack)));
+
+    DPL(" size: ");
+    debug_print_u32(event.value.v);
+
+    event = _osThreadGetInfo(threadId, osThreadInfoStackMax);
+    DPL(" used: ");
+    debug_print_u32(event.value.v);
+
+
+    DPL(" ) ");
+
+    DPL("thread ( id: ");
+    debug_print_pointer(threadId);
+
+    event = _osThreadGetInfo(threadId, osThreadInfoEntry);
+    DPL(" entry: ");
+    debug_print_pointer(event.value.p);
+
+    DPL(" )\r\n");
+}
+
+void print_all_thread_info(void)
+{
+    osThreadEnumId enumId   = _osThreadsEnumStart();
+    osThreadId     threadId = (osThreadId) NULL; // Can't use nullptr yet because mbed doesn't support C++11.
+
+    while ((threadId = _osThreadEnumNext(enumId)))
+    {
+        print_thread_info(threadId);
+    }
+
+    _osThreadEnumFree(enumId);
+}
+
+#else
+
+static void print_thread_info(osThreadId threadId)
+{
+    // Refs: rtx_lib.h - #define os_thread_t osRtxThread_t
+    //       rtx_os.h  - typedef struct osRtxThread_s { } osRtxThread_t
+
+    if (!threadId) return;
+
+    os_thread_t * tcb = (os_thread_t *) threadId;
+
+    uint32_t stackSize = osThreadGetStackSize(threadId);
+    uint32_t stackUsed = osThreadGetStackSpace(threadId);
+
+    DPL("    stack ( start: ");
+    debug_print_pointer(tcb->stack_mem);
+
+    DPL(" end: ");
+    debug_print_pointer((uint8_t *) tcb->stack_mem + stackSize);
+
+    DPL(" size: ");
+    debug_print_u32(stackSize);
+
+    DPL(" used: ");
+    debug_print_u32(stackSize - stackUsed);
+
+    DPL(" ) ");
+
+    DPL("thread ( id: ");
+    debug_print_pointer(threadId);
+
+    DPL(" entry: ");
+    debug_print_u32(tcb->thread_addr);
+
+    DPL(" name: ");
+    DPL(osThreadGetName(threadId) ? osThreadGetName(threadId) : "unknown");
+
+    DPL(" )\r\n");
+}
+
+void print_all_thread_info(void)
+{
+    // Refs: mbed_stats.c - mbed_stats_stack_get_each()
+
+    uint32_t     threadCount = osThreadGetCount();
+    osThreadId_t threads[threadCount]; // g++ will throw a -Wvla on this, but it is likely ok.
+
+    // osThreadId_t * threads = malloc(sizeof(osThreadId_t) * threadCount);
+    // MBED_ASSERT(NULL != threads);
+
+    memset(threads, 0, threadCount * sizeof(osThreadId_t));
+
+    // This will probably only work if the number of threads remains constant
+    // (i.e. the number of thread control blocks remains constant)
+    //
+    // This is probably the case on a deterministic realtime embedded system
+    // with limited SRAM.
+
+    osKernelLock();
+
+    threadCount = osThreadEnumerate(threads, threadCount);
+
+    for (uint32_t i = 0; i < threadCount; i++)
+    {
+        // There seems to be a Heisenbug when calling print_thread_info()
+        // inside of osKernelLock()!
+
+        // This error may appear on the serial console:
+        // mbed assertation failed: os_timer->get_tick() == svcRtxKernelGetTickCount(), file: .\mbed-os\rtos\TARGET_CORTEX\mbed_rtx_idle.c
+
+        // The RTOS seems to be asserting an idle constraint violation due
+        // to the slowness of sending data through the serial port, but it
+        // does not happen consistently.
+        print_thread_info(threads[i]);
+    }
+
+    osKernelUnlock();
+
+    // free(threads);
+}
+
+#endif
+
+void print_current_thread_id(void)
+{
+    DPL("Current thread: ");
+    debug_print_pointer(osThreadGetId());
+    DPL("\r\n");
+}
+#endif // MBED_CONF_RTOS_PRESENT
+
+#if DEBUG_MEMORY_CONTENTS
+static void print_memory_contents(const uint32_t * start, const uint32_t * end)
+{
+    uint8_t line = 0;
+
+    for (; start < end; start++)
+    {
+        if (0 == line)
+        {
+            debug_print_pointer(start);
+            DPL(": ");
+        }
+
+        debug_print_u32(*start);
+
+        line++;
+
+        if (16 == line)
+        {
+            DPL("\r\n");
+            line = 0;
+        }
+    }
+}
+#endif
+
+extern uint32_t mbed_stack_isr_size;
+
+#if DEBUG_ISR_STACK_USAGE
+uint32_t calculate_isr_stack_usage(void)
+{
+    for (const uint32_t * stack = &__StackLimit; stack < &__StackTop; stack++)
+    {
+        if (*stack != ISR_STACK_CANARY)
+        {
+            return (uint32_t) &__StackTop - (uint32_t) stack;
+        }
+    }
+
+    return mbed_stack_isr_size;
+}
+#endif
+
+void print_heap_and_isr_stack_info(void)
+{
+#ifdef ENABLE_MEMORY_CHECKS
+    extern unsigned char * mbed_heap_start;
+    extern uint32_t        mbed_heap_size;
+
+    extern unsigned char * mbed_stack_isr_start;
+
+    mbed_stats_heap_t      heap_stats;
+
+    mbed_stats_heap_get(&heap_stats);
+
+    DPL("     heap ( start: ");
+    debug_print_pointer(mbed_heap_start);
+
+    DPL(" end: ");
+    debug_print_pointer(mbed_heap_start + mbed_heap_size);
+
+    DPL(" size: ");
+    debug_print_u32(mbed_heap_size);
+
+    DPL(" used: ");
+    debug_print_u32(heap_stats.max_size);
+
+    DPL(" )  alloc ( ok: ");
+    debug_print_u32(heap_stats.alloc_cnt);
+
+    DPL("  fail: ");
+    debug_print_u32(heap_stats.alloc_fail_cnt);
+
+    DPL(" )\r\n");
+
+    DPL("isr_stack ( start: ");
+    debug_print_pointer(mbed_stack_isr_start);
+
+    DPL(" end: ");
+    debug_print_pointer(mbed_stack_isr_start + mbed_stack_isr_size);
+
+    DPL(" size: ");
+    debug_print_u32(mbed_stack_isr_size);
+
+#if DEBUG_ISR_STACK_USAGE
+    DPL(" used: ");
+    debug_print_u32(calculate_isr_stack_usage());
+#endif
+
+    DPL(" )\r\n");
+
+#if DEBUG_MEMORY_CONTENTS
+    // Print ISR stack contents.
+    print_memory_contents(&__StackLimit, &__StackTop);
+#endif
+#endif
+}
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/source/ublox.h	Thu May 02 21:50:17 2019 +0000
@@ -0,0 +1,237 @@
+/**
+********************************************************************************
+* @file         bluetooth.h
+* @brief        Header file containing API for bluetooth.c
+*
+********************************************************************************
+* @author       TTP
+* @copyright (c) 2017 TTP (The Technology Partnership) plc
+*
+********************************************************************************
+*/
+
+#ifndef BLUETOOTH_H
+#define BLUETOOTH_H
+
+//-------- Includes ----------------------------------------------------------//
+
+//-------- Defines -----------------------------------------------------------//
+
+#define SEND_BLE_RESPONSE               0
+#define DO_NOT_SEND_BLE_RESPONSE        1
+
+#define UBLOX_BLE_NAME_BYTES            24
+#define UBLOX_BLE_FW_VERSION_LEN_BYTES  9
+
+#define UBLOX_DEFAULT_1_BAUD_RATE       115200
+#define UBLOX_DEFAULT_2_BAUD_RATE       230400 
+#define UBLOX_MICRO_BAUD_RATE           230400  //115200 //230400
+
+//-------- Constants & enums -------------------------------------------------//
+
+/**
+* @brief        Enumeration of the different modes of the Bluetooth state machine
+*/
+typedef enum
+{
+  UBLOX_IN_CMD_MODE             = 0,    ///<0
+  UBLOX_IN_DATA_MODE            = 1,    ///<1
+  UBLOX_IN_EDM_MODE             = 2,
+  UBLOX_IN_UPGRADE_MODE         = 3,
+  
+} ublox_modes_e;
+
+typedef enum
+{
+  //NC = Not Connected
+  //C = Connected
+  //A = Active
+  //NA = Not Active
+  //E = Error
+  //NE = No Error
+  
+  BLE_LINK_A            = 0x01,
+  BLE_LINK_NA           = 0x00,
+  
+  BLE_PEER_C            = 0x02,
+  BLE_PEER_NC           = 0x00, 
+  
+  WIFI_LINK_A           = 0x04,
+  WIFI_LINK_NA          = 0x00,          
+  
+  WIFI_STATION_C        = 0x08,
+  WIFI_STATION_NC       = 0x00,
+  
+  CLOUD_E               = 0x10,
+  CLOUD_NE              = 0x00,
+  
+  CAP_E                 = 0x20,
+  CAP_NE                = 0x00
+  
+} comms_led_state_e;
+
+/**
+* @brief        Enumeration of the User to Base Unit BLE primitives. 
+*               Primitives here imply the first byte of a message that is transmitted
+*/
+typedef enum
+{
+  START_PCR                     = 'a',          ///<a - 0x61 - 97(d)
+  STOP_PCR                      = 'b',          ///<b - 0x62 - 98(d)
+  GET_BU_SOFTWARE_DETAILS       = 'c',          ///<c - 0x63 - 99(d)
+  GET_CURRENT_PCR_STATE         = 'd',          ///<d - 0x64 - 100(d)
+  GET_HEALTH_SENSOR_READINGS    = 'e',          ///<e - 0x65 - 101(d)
+  HANDLE_PICTURES               = 'f',          ///<f - 0x66 - 102(d)
+  SET_PCR_LED_INTENSITY         = 'o',          ///<o - 0x6F - 111(d) 
+  RESET_MICRO                   = '*',          ///<* - 0x2a - 42(d)
+  BLE_HANDSHAKE                 = '@',          ///<@ - 0x40 - 100(d)
+  TOGGLE_BU_SAFETY_CHECKS       = 'z',          ///<z - 0x7a - 122(d) 
+  EPOCH_TIMESTAMP               = '%',          ///<% - 0x25 - 37(d)
+  ODIN_CHIP_CONTROL                = '/'   ///</ - 0X2F - 47(d)
+  
+} user_to_bu_ble_primitives_e;
+
+/**
+* @brief        Enumeration of the Base Unit BLE to User primitives. 
+*               Primitives here imply the first byte of a message that is transmitted
+*/
+typedef enum
+{
+  PCR_STARTED                   = 'A',          ///<A - 0x41 - 65(d)
+  BASE_UNIT_DETAILS             = 'B',          ///<B - 0x42 - 66(d)
+  PCR_CURRENT_STATE             = 'C',          ///<C - 0x43 - 67(d)
+  TRIGGER_CAMERA                = 'D',          ///<D - 0x44 - 68(d)
+  SENSOR_READINGS               = 'E',          ///<E - 0x45 - 69(d)
+  TIMESTAMP_RESPONSE            = 'F',          ///<F - 0x46 - 70(d)
+  WIFI_CONFIG_RESP              = 'G',          ///<G - 0x47
+  
+  START_OF_BLE_MESSAGE          = 'X',          ///<X - 0x58 - 88(d)
+  
+  BASE_UNIT_NOTIFICATION        = 'Y',          ///<Y - 0x59 - 89(d)
+  BASE_UNIT_ERROR               = 'Z',          ///<Z - 0x5A - 90(d)
+  
+} bu_to_user_ble_primitives_e;
+
+//-------- Structs & typedefs ------------------------------------------------//
+
+
+//-------- Global variables --------------------------------------------------//
+
+
+//-------- Global function prototypes ----------------------------------------//
+
+extern void initialise_ublox_module(void);
+extern void reset_ublox_module(void);
+extern UART_HandleTypeDef* get_uart3_address(void);
+
+extern uint8_t* get_uart3_tx_buffer(void);
+extern void MX_UART3_Init(void);
+extern void MX_UART3_DeInit(void);
+extern void change_uart3_baud_rate(uint32_t baud_rate);
+
+extern uint8_t is_ublox_module_configured(void);
+
+extern HAL_StatusTypeDef write_bytes_to_ublox_uart3(uint8_t *p_buffer, uint16_t len_bytes);
+extern void process_uart3_interrupt_rx_data(void);
+extern void process_ublox_uart3_rx_msgs(void);
+
+extern void transmit_picture_req_to_ble_user(uint8_t cycle_no, uint8_t cam_pic_id);
+extern void transmit_base_unit_error(uint8_t system_error);
+extern void transmit_base_unit_notification(uint8_t system_notification);
+
+extern void process_start_pcr_req(uint8_t output_choice);
+extern void process_stop_pcr_req(uint8_t output_choice);
+extern void get_bu_software_details(uint8_t output_choice);
+extern void get_current_pcr_state(uint8_t output_choice);
+extern void transmit_health_sensor_readings(void);
+
+extern void transmit_ublox_config_msg(void);
+
+extern void read_one_byte_from_uart3(void);
+
+extern void change_ublox_current_mode(uint8_t mode);
+
+extern void reset_ublox_rx_buffer(void);
+
+extern void process_ublox_at_event_pkt(const uint8_t* rx_data, uint16_t len_bytes);
+
+extern void set_wifi_link_conn_status(uint8_t status);
+
+extern uint8_t is_wifi_link_connected(void);
+
+extern void set_ble_chan_conn_status(uint8_t status);
+
+extern uint8_t is_ble_chan_connected(void);
+
+extern void set_ble_peer_status(uint8_t status);
+
+extern void set_ble_chan_id(uint8_t chan_id);
+
+extern uint8_t get_ble_chan_id(void);
+
+extern void set_ble_peer_id(uint8_t peer_id);
+
+extern uint8_t get_ble_peer_id(void);
+
+extern uint8_t is_ble_peer_connected(void);
+
+extern uint8_t is_wifi_chan_connected(void);
+
+extern uint8_t is_wifi_peer_connected(void);
+
+extern void set_wifi_chan_id(uint8_t chan_id);
+
+extern uint8_t get_wifi_chan_id(void);
+
+extern void set_wifi_peer_id(uint8_t peer_id);
+
+extern uint8_t get_wifi_peer_id(void);
+
+extern void set_wifi_chan_conn_status(uint8_t status);
+
+extern void set_wifi_peer_status(uint8_t status);
+
+extern void process_ublox_data_event_pkt(const uint8_t* rx_data, uint16_t len_bytes);
+
+extern void send_message_over_ble(const uint8_t* p_message, uint8_t len_bytes);
+
+extern uint8_t update_ublox_firmware(void);
+
+extern uint8_t configure_wifi_link(void);
+
+extern uint8_t activate_wifi_link(void);
+
+extern uint8_t deactivate_wifi_link(void);
+
+extern uint8_t store_wifi_ssid(const char *ssid);
+
+extern uint8_t store_wifi_pwd(const char *pwd);
+
+extern uint8_t write_wifi_details_to_sd(void);
+
+extern uint8_t store_web_addr(const char *web_addr);
+
+extern uint8_t write_web_addr_to_sd(void);
+
+extern const uint8_t* get_ublox_fw_ver_bytes(void);
+
+extern void set_comms_indicator_leds();
+
+extern void set_cloud_conn_error_status(uint8_t status);
+
+extern void set_capsule_conn_error_status(uint8_t status);
+
+extern void set_wifi_link_active_status(uint8_t status);
+
+extern void read_wifi_details_from_sd(void);
+
+extern void read_cloud_details_from_sd(void);
+
+extern void print_wifi_details(void);
+
+extern void print_cloud_details(void);
+
+//----------------------------------------------------------------------------//
+
+#endif /* BLUETOOTH_H */
+