ch8_mbed_websocket_client to sockets.mbed.org
Dependencies: EthernetInterface HTTPD WebSocketClient mbed-rpc mbed-rtos-for-old mbed
Diff: main.cpp
- Revision:
- 0:a24e2b2f8c8f
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/main.cpp Wed Feb 04 03:42:54 2015 +0000 @@ -0,0 +1,120 @@ +#include "mbed.h" +#include "EthernetInterface.h" +#include "HTTPD.h" +#include "Websocket.h" + + + +EthernetInterface *eth; +HTTPD *httpd; + + +Serial pc(USBTX, USBRX); +InterruptIn probe(p8); +LocalFileSystem local("local"); +DigitalOut led1(LED1), led2(LED2),led3(LED3); +Timer timer; +Ticker ticker; + +uint32_t low_time = 0; +//uint32_t low_time = 0; + +void down(); +void up(); + +void tick() +{ + pc.printf("%d us, %f %%\r\n", low_time, low_time / (30.0 * 1000000)); + low_time = 0; + +} + +void down() +{ + probe.rise(&up); + led1 = 0; + timer.start(); +} + +void up() +{ + led1 = 1; + timer.stop(); + probe.fall(&down); + + low_time += timer.read_us(); + timer.reset(); +} + +void callback_api(int id) { + int i, n; + char low_time_buf[256]; + char buf[256]; + + sprintf( low_time_buf, "%f", low_time / (30.0 * 1000000)); + strcpy(buf, "{"); + strcat(buf, "success: true ,"); + strcat(buf, "data: {"); + strcat(buf, "lowpulseoccupancytime: "); + strcat(buf, low_time_buf); + strcat(buf, "}"); + strcat(buf, "}"); + + n = strlen(buf); + i = httpd->receive(id, &buf[n], sizeof(buf) - n); + if (i < 0) return; + i += n; + buf[i] = 0; + printf("API %d %s\r\n", id, buf); + httpd->send(id, buf, i, "Content-Type: text/plain\r\n"); +} + +int main() { + pc.baud(115200); + pc.printf("Dust Sensor test\r\n"); + probe.fall(&down); + ticker.attach(tick, 30); + + printf("HTTP Server...\r\n"); + + eth = new EthernetInterface; + eth->init("192.168.21.23", "255.255.255.0", "192.168.21.2" ); + // eth->init(); + + if (eth->connect()) return -1; + led3 = 1; + + + printf("Connected to websocket server. \r\n"); + + + printf("IP Address is %s\r\n", eth->getIPAddress()); + httpd = new HTTPD; + httpd->attach("/1/mbed/lpc1768/sensor/dust/sen12291p", &callback_api); + httpd->attach("/", "/local/"); + httpd->start(80); + printf("httpd ready\r\n"); + led2 = 1; + + Websocket ws("ws://sockets.mbed.org/ws/mbedschool/viewer"); + // Websocket ws("ws://192.168.21.123:8888"); + + while (!ws.connect()); + // ws.send("echo-protocol"); + while (1) { + + char low_time_buf[256]; + char buf[256]; + sprintf( low_time_buf, "%f", low_time / (30.0 * 1000000)); + + strcpy(buf, "{"); + strcat(buf, "\"lowpulseoccupancytime\":"); + strcat(buf, low_time_buf); + strcat(buf, "}"); + ws.send(buf); + + + wait(1.0); + } + +}