Web Socket connection (MBED is client side)

Dependencies:   EthernetNetIf MbedJSONValue mbed

Fork of WebSocket_test by Suga koubou

main.cpp

Committer:
sura0111
Date:
2016-03-22
Revision:
2:7b3b7d65240f
Parent:
1:6d42db5e8ace

File content as of revision 2:7b3b7d65240f:

#include "mbed.h"
#include "Websocket.h"
#include "MbedJSONValue.h"
#include "EthernetNetIf.h"
#include <string>

// Connection setup DeviceName, DeviceToConnect, Password, BaseUrl, RealURL
char* thisDevice = "client2";
char* connectedDevice = "client1";
char* API_KEY = "0000";
char* BASE_URL = "ws://0.0.0.0:8001/?";
char URL[255];

// MBED Inputs & Outputs
DigitalOut dout(p14); //trigger signal for check
Serial pc(USBTX, USBRX); // tx, rx
AnalogIn volume(p15); //volume
// LED
PwmOut led1(LED1);
PwmOut led2(LED2);
DigitalOut led[] = {(p5),(p6),(p7), (LED3), (LED4)};

// Ethernet variables
EthernetNetIf *eth;
Websocket *ws;

bool readFlag = false;
char buf[255] = {0};
MbedJSONValue json;

// Init
void initData(void);
void initArray(unsigned int* array, int count);
// Websocket timeout
Timeout wsTout;
// WS Connection functions
void wsConnection();
void wsflip();

int main() {
    wsConnection();
    led[3] = 1;
    led[4] = 1;
    while(1){
        if(readFlag){
            if(json["edata"].size()>0){
                led1 = json["edata"]["0"].get<int>()/100.0;
                led2 = json["edata"]["1"].get<int>()/100.0;
            };
            if(json["mdata"].size()>0){
                for(int i=0; i<3; i++){
                    led[i] = json["mdata"][i].get<int>();
                }
            };
            readFlag=false;
            // if(json["option"].size()>0){
            //   s = json["option"].serialize();
            //};
        }
    }
}
void wsConnection (){
    
    // URL Setup
    strcpy(URL, BASE_URL);
    strcat(URL, "API_KEY=");
    strcat(URL, API_KEY);
    strcat(URL, "&NAME=");
    strcat(URL, thisDevice);
    strcat(URL, "&TO=");
    strcat(URL, connectedDevice);
    
    //Ethernet setup
    eth = new EthernetNetIf();
    EthernetErr ethErr = eth->setup();
    if(ethErr){ pc.printf("\r\nElectro-tactile display: Error %d in setup. \r\n", ethErr);}
    
    ws = new Websocket(URL, eth);
    pc.printf("\r\nElectro-tactile display: ON\r\n");
    while(!ws->connect()) { pc.printf("Electro-tactile display: Connecting...\r\n"); wait(1);}
    // Message after connection succeeded
    pc.printf("Connection succeeded\r\n");
    ws->send("Electro-Tactile Display Connected");
    wsflip();
}
void wsflip(){
    Net::poll();  
    // when data received
    readFlag = ws->read(buf);
    parse(json, buf);
    Net::poll();
    if(!ws->connected()) pc.printf("Disconnected\r\n"); 
    else wsTout.attach(&wsflip, 0.005);
}
void initArray(unsigned int* array, int count){
    for(int i=0; i<count; i++) { array[i]=0;}
}