Example program to create IoT devices for a local network, which connect to a local server.

Dependencies:   WebSocketClient WiflyInterface mbed messages

This code is used in the second part of my Internet of Things (IoT) blog post available here. The code is fairly simple, but its real value is in its reliability. I have worked hard to try to make the wireless connection as reliable, and as fast, as possible. There are a few lines of code that must be modified before it will work correctly, and those are described in the following Wiki pages.

It is designed to work with a Python WebSocket Server running on a PC, the source code of which is available here.

Once operating with the server, each microcontroller, or IoT device, will broadcast a counter and its internal temperature to your WebSocket Server.

source/globals.cpp

Committer:
defrost
Date:
2016-10-04
Revision:
2:7abdaa5a9209
Parent:
1:4403f2ed1c1f
Child:
3:f20e114eb2ee

File content as of revision 2:7abdaa5a9209:

// ***************
// * globals.cpp *
// ***************
//
// Created: 2015/03/19
// By: Damien Frost

#include "mbed.h"
#include "globals.h"

//#define DEBUG
#define INFOMESSAGES
#define WARNMESSAGES
#define ERRMESSAGES
#define FUNCNAME "GBL"
#include "messages.h"

char* wifissid = "SC";
char* wifipassword = "smartcellshield";

Serial          pc(USBTX, USBRX);
InterruptIn     UIBut1(USER_BUTTON);
Timer           DisplayTimer;
DigitalOut      Led(LED1);

WiflyInterface eth(D8, D2, D6, LED1, wifissid, wifipassword, WPA2);

int ReconnectAttempts = 0;
int SendCounter = 0;
extern int IoT_ID = 0;
float TempSensor = 0.0f;

Websocket ws;


int SetupNetwork(int Tries){
    // Initialize the interface.
    // If no param is passed to init() then DHCP will be used on connect()
    int s = eth.init();
    int attempts = 1;
       
        wait(1);
        if (s != NULL) {
            ERR("Could not initialise. Halting!");
            exit(0);
        }
    
        INFO("Connecting to: %s", wifissid);
        DBG("Getting IP address...");
        
        while (1) {
            // Connect to network:
            s = eth.connect();
            // If connection fails, retry for 5 attempts:
            if (s == false || s < 0) {
                INFO("Could not connect to network. Retrying!");
                attempts++;
                wait(1);
            } else {
                
                break;
            }
            if(attempts > Tries){
                ERR("Network connection failed after %d attempts", Tries);
                return 0;
            }
        }
        INFO("Connected to: %s", wifissid);
        INFO("Got IP address: %s", eth.getIPAddress());
        IotStatus.SetFlag(SF_WIRELESSCONNECTED);
        return 1;
    
}

void SendNetworkData(void){
    char msg_buffer[CHARMSGBUFF];
    int intresult;    
    
    if(IotStatus.CheckFlag(SF_SERVERCONNECTED)){
        sprintf(msg_buffer, "%d,%d,%.5f", IoT_ID, SendCounter,TempSensor);
        INFO("Sending: %s", msg_buffer);    // When this line is commented out, the mbed never tries to reconnect to the server after one try. SUPER. Keeping this here also uses precious CPU time
        intresult = ws.send(msg_buffer);
    }else{
        intresult = -1;
    }
    DBG("intresult: %d", intresult);
        
    if(intresult < 0){
        // Clear a status flag:
        IotStatus.ClearFlag(SF_SERVERCONNECTED);
        // Check to see if the wireless is still connected:
        DBG("Checking network status...");
        if(eth.checkNetworkStatus() != 3){
            IotStatus.ClearFlag(SF_WIRELESSCONNECTED);
            // Connect to the wireless network:
            if(IotStatus.CheckFlag(SF_AUTOCONNECT)){
                INFO("Reconnecting to Network...");
                if(SetupNetwork(1)>0){
                    IotStatus.SetFlag(SF_WIRELESSCONNECTED);
                    INFO("Connected to Network.");
                }else{
                    WARN("Could not re-connect to the wireless network.");
                }
            }
        }else{
            DBG("Network connected.");
        }
        
        if(IotStatus.CheckFlag(SF_AUTOCONNECT) && IotStatus.CheckFlag(SF_WIRELESSCONNECTED)){
            // Server connection was closed, try to reconnect:
            INFO("Reconnecting to Websocket Server on ws://%s:%d/ws...", SERVER_IP, WS_PORT);
            if(!ws.connect()){
                WARN("Could not connect to the server again...");
                IotStatus.ClearFlag(SF_SERVERCONNECTED);
                ReconnectAttempts++;
                if(ReconnectAttempts > 4){
                    INFO("Failed after %d reconnect attempts. Resetting the Wifi Shield...", ReconnectAttempts);
                    SetupNetwork(1);
                    ReconnectAttempts = 0;
                }
            }else{
                INFO("Connected to ws://%s:%d/ws", SERVER_IP, WS_PORT);
                // Set a status flag:
                IotStatus.SetFlag(SF_SERVERCONNECTED);
            }
        }
    }

    return;
}

void ReceiveNetworkData(unsigned int * wifi_cmd, unsigned int * var, float * value){
    char msg_buffer[CHARMSGBUFF];
    char msg_buffer2[CHARMSGBUFF];
    int resp;
    if(IotStatus.CheckFlag(SF_SERVERCONNECTED)){
        // Check for data on the websocket:
        resp = ws.readmsg(msg_buffer);
        if(resp == 1){
            INFO("Received: %s", msg_buffer);
            sscanf(msg_buffer, "%d,%s", wifi_cmd, msg_buffer2);
            if(*wifi_cmd == CHANGEVAR_WIFI_CMD){
                // Get two more values:
                sscanf(msg_buffer2, "%d,%f", var, value);
            }else{
                // Get one:
                sscanf(msg_buffer2, "%f", value);
            }
        }else if(resp == -1){
            // Connection to the server is lost:
            IotStatus.ClearFlag(SF_SERVERCONNECTED);
        }else{
            //DBG("Did not receive anything :(\n\r");
            *wifi_cmd = NO_WIFI_CMD;
            *var = 0;
            *value = 0.0f;
        }
    }
    return;
}

void ModifyVariable(unsigned int wifi_var, float wifi_data){
    // modifies something in the SCS Controller:
    switch(wifi_var){
        case CV_LED:
            
            break;
        
        default:
            break;
    }
    return;
}