HTTP Server with WebSocket Server for GSwifiInterface library Please see: https://mbed.org/users/gsfan/notebook/gswifiinterface_httpd/

Dependencies:   GSwifiInterface SDFileSystem mbed

main.cpp

Committer:
gsfan
Date:
2014-01-30
Revision:
0:93f689e0a0d9

File content as of revision 0:93f689e0a0d9:

/*
 * Please modify "GSwifi_conf.h"
 * ----------
 * //#define CFG_ENABLE_RTOS
 * #define CFG_ENABLE_HTTPD
 * #define CFG_ENABLE_WEBSOCKET
 * //#define CFG_ENABLE_SMTP
 * ----------
 */

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

#define SEC  GSwifi::SEC_WPA_PSK
#define SSID "SSPD"
#define PASS "PASSPHRASE"

Serial pc(USBTX, USBRX);
DigitalOut led1(LED1), led2(LED2), led3(LED3), led4(LED4);
LocalFileSystem local("local");
SDFileSystem sd(p5, p6, p7, p8, "sd");

GSwifi gs(p13, p14, p12, P0_22, p20, NC, 115200); // mbed LPC1768
//GSwifi gs(PTD3, PTD2, NC, PTD5, PTA13); // FRDM KL25Z


void cgi (int cid) {
    int i;
    char buf[100];

    led2 = 1;
    i = gs.recv(cid, buf, sizeof(buf));
    if (i < 0) return;
    buf[i] = 0;
//    pc.printf("CGI %d: %s ? %s '%s' %d\r\n", cid, gs.httpdGetFilename(cid), gs.httpdGetQuerystring(cid), buf, i);

    gs.send(cid, "HTTP/1.1 200 OK\r\n", 17);
    gs.send(cid, "Content-type: text/plain\r\n", 26);
    gs.send(cid, "\r\n", 2);

    gs.send(cid, "BODY: ", 6);
    gs.send(cid, buf, strlen(buf));
    gs.send(cid, "\r\n", 2);
    gs.close(cid);
}

void ws_server (int cid) {
    int i;
    char buf[100];

    led2 = 1;
    i = gs.recv(cid, buf, sizeof(buf));
    if (i < 0) return;
    buf[i] = 0;
    pc.printf("WS %d: '%s' %d\r\n", cid, buf, i);

    gs.wsSend(cid, buf, i);
}

int main () {
    char ip[16], netmask[16], gateway[16];        

    pc.baud(115200);
//    pc.baud(921600);
    printf("HTTP Server...\r\n");
    led1 = 1;
    gs.setAddress(); //Use DHCP
//    gs.setAddress("192.168.1.50", "255.255.255.0", "192.168.1.1", "192.168.1.1");
    gs.setSsid(SEC, SSID, PASS);
    if (gs.join()) return -1; // join the network
//    if (gs.limitedap()) return -1; // access point
    gs.getAddress(ip, netmask, gateway);
    printf("IP Address is %s\r\n", ip);

    printf("ready\r\n");
    gs.httpd();
    gs.httpdAttach("/cgi-bin/", &cgi);
    gs.httpdAttach("/ws/", &ws_server, 1);
    gs.httpdAttach("/test/", "/sd/www/");
    gs.httpdAttach("/", "/local/");

    for (;;) {
        gs.poll();
        if (pc.readable()) {
            if (pc.getc() == 'q') break;
        }

        wait_ms(50);
        led1 = !led1;
        led2 = 0;
    }
    gs.dissociate();
    return 0;
}