see http://mbed.org/users/gsfan/code/GSwifi/

Dependencies:   GSwifi mbed

main.cpp

Committer:
gsfan
Date:
2013-02-26
Revision:
0:7826480a54f0

File content as of revision 0:7826480a54f0:

/*
 * Websocket for GSwifi
 *
 *   mbed WebSocket server / GSwifi client
 *   html access http://sockets.mbed.org/ws/UserName/test/
 *
 *   GSwifi WebSocket server / other client
 *   GSwifi_conf.h: #define GS_USE_WEBSOCKET
 *   ws access ws://IP address/ws/hoge
 */

#include "mbed.h"
#include "GSwifi.h"

#define PORT    80

#define WS_HOST "sockets.mbed.org"
#define WS_URI "/ws/UserName/test/rw"

#define SECURE GSwifi::GSSEC_WPA_PSK
#define SSID "SSID"
#define PASS "PASSPHRASE"

GSwifi gs(p13, p14, p20); // TX, RX, Reset (no flow control)
//GSwifi gs(p13, p14, p12, P0_22, p20, NC, 115200); // TX, RX, CTS, RTS, Reset, Alarm

LocalFileSystem local("local");
Serial pc(USBTX, USBRX);
DigitalOut led1(LED1), led2(LED2);

void ws_server (int cid, GSwifi::GS_httpd *gshttpd) {

    pc.printf("WS_S %d: %s ? %s '%s' %d\r\n", cid, gshttpd->file, gshttpd->query, gshttpd->buf, gshttpd->len);

    gs.wsSend(cid, gshttpd->buf, gshttpd->len);
}

void ws_client (int cid, int len) {
    int n;
    char buf[len + 1];

    n = gs.recv(cid, buf, sizeof(buf));
    buf[n] = 0;
    pc.printf("WS_C %d: %s %d\r\n", cid, buf, n);
}

int main () {
    IpAddr ipaddr, netmask, gateway, nameserver;
    Host host;
    int cid;

    led1 = 1;
    pc.baud(115200);

    pc.printf("connecting...\r\n");
    if (gs.connect(SECURE, SSID, PASS)) {
        return -1;
    }
    gs.getAddress(ipaddr, netmask, gateway, nameserver);
    pc.printf("ip %d.%d.%d.%d\r\n", ipaddr[0], ipaddr[1], ipaddr[2], ipaddr[3]);

    led2 = 1;
    pc.printf("httpd\r\n");
    gs.httpd(PORT);
    gs.attach_httpd("/ws/", &ws_server);
    gs.attach_httpd("/", "/local/");

    host.setName(WS_HOST);
    host.setPort(PORT);
    cid = gs.wsOpen(host, WS_URI, &ws_client);
    if (cid < 0) return -1;
    printf("ws open\r\n");

    for (;;) {
        gs.poll();

        if (pc.readable()) {
            char buf[] = "MBED= ";
            buf[5] = pc.getc();
            if (gs.wsSend(cid, buf, 6, "MASK")) {
                printf("ws error\r\n");
            }
        }

        wait_ms(50);
        led1 = !led1;
        led2 = 0;
    }
}