ssssss

CushionSock.cpp

Committer:
3116redtrain
Date:
2016-12-17
Revision:
0:01a2e92d2924
Child:
1:e6addce35f93

File content as of revision 0:01a2e92d2924:

#include "CushionSock.h"

CushionSock::CushionSock(char * hostAndPort){
    eth = new EthernetNetIf();
    EthernetErr ethErr = eth->setup();
    if (ethErr) {
        printf("\r\nERROR %d in setup.\r\n", ethErr);
    }
    printf("hostandport %s\n", hostAndPort);
    
    ws = new Websocket(hostAndPort, eth);

    printf("begin\r\n");

    MESS_STOP = 0x01;
    MESS_START = 0x02;
    MESS_SIT = 0x11;
    MESS_FRUST = 0x12;
    MESS_TEST =0x21;
    type_name[MESS_STOP]="stop";
    type_name[MESS_START]="start";
    type_name[MESS_SIT]="status_sit";
    type_name[MESS_FRUST]="status_frust";
    type_name[MESS_TEST]="test";
    name_type["stop"]=MESS_STOP;
    name_type["start"]=MESS_START;
    name_type["status_sit"]=MESS_SIT;
    name_type["status_frust"]=MESS_FRUST;
    name_type["test"]=MESS_TEST;
    
    printf("websock init\n");
     int failcount=0;
     
     while(! ws->connect()) {
        failcount++;
        if(failcount>10){
            printf("cannot connect failed.\n");
            break;
        }
        printf("cannot connect websocket, retrying...\n");
        wait(2);
    }
}

    
bool CushionSock::connect(){
     
     return true;
}
  
int CushionSock::mess_send(int type, char * msg){
    string name=type_name[type];
    MbedJSONValue json;
    json["name"]=name.c_str();
    json["value"]=msg;
    ws->send((char*)json.serialize().c_str());
    return 1;
} 
    
int CushionSock::mess_recv(char * msg){
    picojson::value v;
    char recv[256];
    if (ws->read(recv)) {
        int type;
        string name;
        string sbuf(recv);
        const char * crecv=sbuf.c_str();
        string err = picojson::parse(v,crecv,crecv+strlen(crecv));
        if(!err.empty())
            return -1;
        name=v.get("name").get<string>();
        strncpy(msg,v.get("value").get<string>().c_str(),256);
        type=name_type[name];
        return type;
    }else{
        return -1;
    }
}
 
bool CushionSock::is_connected(){
    return ws->connected();
}

bool CushionSock::close(){
    return ws->close();
}