http://mbed.org/users/okini3939/notebook/node_websocket/

Dependencies:   EthernetNetIf mbed MbedJSONValue

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers main.cpp Source File

main.cpp

00001 #include "mbed.h"
00002 #include "Websocket.h"
00003 #include "MbedJSONValue.h"
00004 #include "EthernetNetIf.h"
00005 
00006 #define BASE_URL "ws://host.domain.name:8080/"
00007 
00008 DigitalOut myled(LED1);
00009 Serial pc(USBTX, USBRX);
00010 
00011 EthernetNetIf *eth;
00012 Websocket *ws;
00013 
00014 int main() {
00015     int i = 0;
00016     char buf[100];
00017     MbedJSONValue json;
00018     Timer timer;
00019 
00020     eth = new EthernetNetIf();
00021     EthernetErr ethErr = eth->setup();
00022     if (ethErr) {
00023         pc.printf("\r\nERROR %d in setup.\r\n", ethErr);
00024     }
00025 
00026     ws = new Websocket(BASE_URL "test", eth);
00027 
00028     pc.printf("begin\r\n");
00029 
00030     json["hello"] = "mbed";
00031     json["num"] = i;
00032 
00033     while(! ws->connect()) {
00034         pc.printf("cannot connect websocket, retrying...\r\n");
00035         wait(2);
00036     }
00037 
00038     timer.start();
00039     while(1) {
00040         Net::poll();
00041 
00042         if (timer.read_ms() >= 2000) {
00043             json["num"] = i ++;
00044             ws->send((char*)json.serialize().c_str());
00045             timer.reset();
00046             myled = myled ? 0 : 1;
00047        }
00048         
00049         if (ws->read(buf)) {
00050             pc.printf("recv: %s\r\n", buf);
00051         }
00052 
00053         Net::poll();
00054 
00055         if (! ws->connected()) {
00056             pc.printf("disconnected\r\n");
00057             break;
00058         }
00059     }
00060 }