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

Dependencies:   mbed-http

source/main-https.cpp

Committer:
ocomeni
Date:
2019-05-19
Branch:
PassingRegression
Revision:
116:2296cf274661
Parent:
115:8054dbadfaa0
Child:
117:8fd05113efc1

File content as of revision 116:2296cf274661:

#define MBED_CONF_MBED_TRACE_ENABLE 1

#include "select-demo.h"
#include "debug.h"

#if DEMO == DEMO_HTTPS

#include <events/mbed_events.h>
#include <mbed.h>
#include "ble/BLE.h"
#include "fault_handlers.h"
#include "ATCmdParser.h"


#include "LEDService.h"
#include "ble/services/UARTService.h"
#include "common_config.h"
#include "common_types.h"
#include "ATCmdManager.h"
#include "BleManager.h"
#include "WiFiManager.h"
#include "mbed_memory_status.h"
UARTService *uart;

DigitalOut led1(LED1);
DigitalOut led2(LED2);
DigitalOut led3(LED3);

#define FILE_CODE       "main"
main_states_t mainLoop;
static RawSerial *device; // tx, rx

static app_config_t app_config;
// wifi configuration
//static wifi_config_t wifi_config;
// wifi interface pointer
static WiFiInterface *network;
// wifi manager pointer
static WiFiManager *wiFiManager;

// BLE instance
//BLE& _ble;
BLE& _ble = BLE::Instance();

// BLE configuration
//static ble_config_t ble_config;

// internet/cloud configuration
//internet_config_t internet_config;

const uint8_t pairingPassword[6] = "1101";
// BLE peripheral pointer
static SMDevicePeripheral *peripheral;

const static char     DEVICE_NAME_MAIN[] = "UBLOX-BLE";
char buffer[BUFFER_LEN];
static EventQueue eventQueue_atcmd(/* event count */ 32 * EVENTS_EVENT_SIZE);
static EventQueue eventQueue_wifi(/* event count */ 32 * EVENTS_EVENT_SIZE);
static EventQueue eventQueue_ble(/* event count */ 10 * EVENTS_EVENT_SIZE);

/*  Queue and memory pool for AT to Wifi commands */
static MemoryPool<wifi_cmd_message_t, 16> aT2WiFimPool;
static Queue<wifi_cmd_message_t, 16> aT2WiFiCmdQueue;

/*  Queue and memory pool for WiFi to AT commands */
static MemoryPool<at_resp_message_t, 16> wiFi2ATmPool;
static Queue<at_resp_message_t, 16> wiFi2ATCmdQueue;

/*  Queue and memory pool for AT to WiFi data */
static MemoryPool<wifi_data_msg_t, PQDSZ> aT2WiFiDatamPool;
static Queue<wifi_data_msg_t, PQDSZ> aT2WiFiDataQueue;


/*  Queue and memory pool for WiFi to AT data */
static MemoryPool<at_data_msg_t, PQDSZ> wiFi2ATDatamPool;
static Queue<at_data_msg_t, PQDSZ> wiFi2ATDataQueue;




/* creates three tread objects with different priorities */
//Thread real_time_thread(osPriorityRealtime, 1024, &rt_stk[0]);
//Thread high_prio_thread(osPriorityHigh, 1024, &hp_stk[0]);
//Thread low_prio_thread(osPriorityNormal, 1024, &lp_stk[0]);

#ifdef USE_MAIN_THREAD_STACK
// using main thread stack
unsigned char btle_stk[1024];
unsigned char wifi_stk[8*1024];
unsigned char atcmd_stk[4*1024];
Thread btle_thread(BTLE_THREAD_PRIORITY, 1024, &btle_stk[0]);
Thread wifi_thread(WIFI_THREAD_PRIORITY, 8*1024, &wifi_stk[0]);
Thread atcmd_thread(ATCMD_THREAD_PRIORITY, 4*1024, &atcmd_stk[0]);
#else
// using global heap
Thread btle_thread(BTLE_THREAD_PRIORITY, 4*1024);
Thread wifi_thread(WIFI_THREAD_PRIORITY, 4*1024);
Thread atcmd_thread(ATCMD_THREAD_PRIORITY, 4*1024);
#endif

/* create a semaphore to synchronize the threads */
Semaphore sync_sema;

Thread atcmd_evt_thread(osPriorityNormal, 1024);
Thread wifi_evt_thread;
#include "network-helper.h"

/* List of trusted root CA certificates
 * currently two: GlobalSign, the CA for os.mbed.com and Let's Encrypt, the CA for httpbin.org
 *
 * To add more root certificates, just concatenate them.
 */
#include "https_certificates.h"

// wifi demo
#include "wifi_demo.h"

Mutex _smutex; // Protect memory access

uint64_t lastTime = 0;
uint64_t now = 0;
uint32_t callCount = 0;


// Wifi-demo
void wifi_demo(NetworkInterface* network){
    int n = wifi_demo_func(network);
    if(n > 0)// error
    {
        dbg_printf(LOG, "\n --- Error running wifi demo --- \n");
    }
}

// Wifi-demo2
void wifi_demo2(){
    //int n = wifi_demo_func(network);
    int n =5;
    if(n > 0)// error
    {
        dbg_printf(LOG, "\n --- Error running wifi demo --- \n");
    }
}


void printWaitAbortKeyPress(int numSecs, const char * printStr=NULL)
{
#ifdef DEBUG_ENABLED
    return
#endif
    dbg_printf(LOG, "%s", printStr);
    dbg_printf(LOG, "Waiting for %d seconds... [press key to abort]\n", numSecs);
    char fmtstr[20];
    for(int i=0;i<numSecs;i++){
        dbg_printf(LOG, "%d", i);
        dbg_printf(LOG, "\n");
        sprintf(fmtstr, "BLE: loop # %d\n", i);
        peripheral->sendBLEUartData(fmtstr);
        wait(0.5);
        //eventQueue_atcmd.dispatch(500);        // Dispatch time - 500msec
        if(device->readable()){
            dbg_printf(LOG, "keypress detected aborting....\n");
            device->getc();
            break;
        }
    }
}



void setupDefaultBleConfig()
{
    strcpy(app_config.ble_config.deviceName, DEVICE_NAME_MAIN);// set BLE device name
    app_config.ble_config.advInterval = 1000;             // set advertising interval to 1 second default
    app_config.ble_config.advTimeout = 0;                 // set advertising timeout to disabled by default
    // This works in C and C++
    memcpy(app_config.ble_config.pairingKey, pairingPassword, 6); // 

    //ble_config.pairingKey = pairingPassword;
}

void setupDefaultWiFiConfig()
{
    strcpy(app_config.wifi_config.ssid, MBED_CONF_APP_WIFI_SSID);
    strcpy(app_config.wifi_config.pass, MBED_CONF_APP_WIFI_PASSWORD);
    app_config.wifi_config.security = NSAPI_SECURITY_WPA_WPA2;
}

void setupDefaultCloudConfig()
{
    strcpy(app_config.internet_config.url, "tcp://https://dev2.dnanudge.io");
    app_config.internet_config.peer_id = 0;
    app_config.internet_config.remote_port = 443; // default HTTPS port
    app_config.internet_config.connectionScheme = ALWAYS_CONNECTED;
}

static int reset_counter = 0;



//#define ENABLE_MEMORY_CHECKS

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++) {
        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);
    dbg_printf(LOG, "Heap size: %lu / %lu bytes\r\n", heap_stats.current_size, heap_stats.reserved_size);
#endif
}

void blinkLEDs()
{
    static int cnt =0;
    cnt++;
    if(cnt == 3){
        cnt = 0;
    }
    if(cnt==0)
        led1 = !led1;
    //wait(1.0);
    if(cnt==1)
        led2 = !led2;
    //wait(1.0);
    if(cnt==2)
        led3 = !led3;
}

void start_BLE()
{
    //_ble = BLE::Instance();
#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()) {
        dbg_printf(LOG, "Filesystem creation failed, will use memory storage\r\n");
    }
#endif
    dbg_printf(LOG, "\r\n PERIPHERAL \r\n\r\n");
    peripheral = new SMDevicePeripheral(_ble, eventQueue_ble, peer_address, 
                                        &app_config.ble_config);

    peripheral->run();
    btle_thread.start(callback(&eventQueue_ble, &EventQueue::dispatch_forever));
}

void stop_BLE()
{
    delete peripheral;
}

void start_WiFi()
{
    wiFiManager = new WiFiManager(&app_config.wifi_config, network, 
                                  &app_config.internet_config,
                                  eventQueue_wifi,
                                  &aT2WiFimPool, &aT2WiFiCmdQueue,
                                  &wiFi2ATmPool, &wiFi2ATCmdQueue,
                                  &aT2WiFiDatamPool, &aT2WiFiDataQueue,
                                  &wiFi2ATDatamPool, &wiFi2ATDataQueue
                                  );
    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");
    wifi_thread.start(callback(wiFiManager, &WiFiManager::runMain));
    dbg_printf(LOG, "\r\n after starting wifi thread \r\n");
    printWaitAbortKeyPress(120, "Wait after WiFi Manager dispatch\r\n");
    // dispatch wifi event queue on event thread
    wifi_evt_thread.start(callback(&eventQueue_wifi, &EventQueue::dispatch_forever));
}

void stop_WiFi()
{
    delete network;
}


void trigger_start_BLE()
{
    mainLoop = START_BLE;
}


void trigger_stop_BLE()
{
    mainLoop = STOP_BLE;
}


void trigger_start_WiFi()
{
    mainLoop = START_WIFI;
}


void trigger_stop_WiFi()
{
    mainLoop = STOP_WIFI;
}



#define STARTUP_DEBUG_ENABLE
//#define AUTO_START_BLE_MANAGER
//#define AUTO_START_WIFI_MANAGER
#define PAUSE_SECONDS   0
#define PAUSE_SECONDS_BLE 0
int main() {
    device = new RawSerial(USBTX, USBRX, 2*DEFAULT_BAUD_RATE);
    uint8_t debug_level = (LOG | ERR | TXT | DBG);
    initialise_debug(debug_level);
#ifdef MBED_MAJOR_VERSION
    dbg_printf(LOG, "Mbed OS version %d.%d.%d\n\n", MBED_MAJOR_VERSION, MBED_MINOR_VERSION, MBED_PATCH_VERSION);
#endif
    
    reset_counter++;
    dbg_printf(LOG, "\r\n ++++++ PROGRAM STARTING -- reset count = %d ++++++ \r\n", reset_counter);
    setupDefaultWiFiConfig();
    setupDefaultBleConfig();
#ifdef AUTO_START_BLE_MANAGER
    //btle_thread.start(callback(peripheral, &SMDevicePeripheral::run));
    start_BLE();
    printWaitAbortKeyPress(120, "Wait after BLE dispatch\r\n");
#endif
    //int start = Kernel::get_ms_count();
#ifdef AUTO_START_WIFI_MANAGER
    start_WiFi();
    printWaitAbortKeyPress(120, "Wait after WiFi instantiation\r\n");
#endif
    // dispatch atcmd event queue on event thread
    atcmd_evt_thread.start(callback(&eventQueue_atcmd, &EventQueue::dispatch_forever));
    dbg_printf(LOG, "\r\n++++++ Starting ATCmdmanager ++++++ \r\n");
    ATCmdManager *aTCmdManager = new ATCmdManager(USBTX, USBRX, peripheral, 
                                                eventQueue_atcmd, wiFiManager, 
                                                &aT2WiFimPool, &aT2WiFiCmdQueue,
                                                &wiFi2ATmPool, &wiFi2ATCmdQueue,
                                                &aT2WiFiDatamPool, &aT2WiFiDataQueue,
                                                &wiFi2ATDatamPool, &wiFi2ATDataQueue,
                                                false);
    atcmd_thread.start(callback(aTCmdManager, &ATCmdManager::runMain));
    dbg_printf(LOG, "\r\n after starting atcmd thread \r\n");
    print_memory_info();
#ifdef STARTUP_DEBUG_ENABLE
    initialise_debug(NONE);
#endif
    while(1)
    {
        switch(mainLoop)
        {
            case MAIN_IDLE:
                break;
            case START_BLE:
                start_BLE();
                mainLoop = MAIN_IDLE;
                break;
            case START_WIFI:
                start_WiFi();
                mainLoop = MAIN_IDLE;
                break;
            case STOP_BLE:
                stop_BLE();
                mainLoop = MAIN_IDLE;
                break;
            case STOP_WIFI:
                stop_WiFi();
                mainLoop = MAIN_IDLE;
                break;
            default:
                mainLoop = MAIN_IDLE;
                break;
        }
        wait(0.1);
    }
}

#endif