Simple code for comunication via TCP between the mbed and PC.

Dependencies:   EthernetInterface SimpleSocket mbed-rtos mbed

Fork of SimpleSocketExamples by Hiroshi Yamaguchi

examples/webcontroller.cpp

Committer:
numeral369
Date:
2014-12-17
Revision:
1:016774025718
Parent:
0:6dc3cfd058c6

File content as of revision 1:016774025718:

#include "SimpleSocket.h"

void webcontroller() {
    const char *response0 =
        "HTTP/1.1 200 OK\r\n"
        "Content-Type: text/html\r\n"
        "\r\n"
        "<html>\r\n"
        "<head><title>mbed LED1 Controller</title></head>\r\n"
        "<body>\r\n"
        "<h4>LED1 Status & Change</h4>\r\n";

    const char *response1 =
        "<form method=\"GET\" action=\"/\">\r\n"
        "<input type=\"radio\" name=\"LED\" value=\"1\" %s onclick=\"submit();\"/>ON\r\n"
        "<input type=\"radio\" name=\"LED\" value=\"0\" %s onclick=\"submit();\"/>OFF\r\n"
        "</form>\r\n";
        
    const char *response2 =
        "</body>\r\n"
        "</html>\r\n";

    DigitalOut led1(LED1);

    ServerSocket server(80);
    
    printf("webcontroller: %s\n", EthernetInterface::getIPAddress());

    while (true) {
        ClientSocket socket = server.accept();
        while (socket) {
            if (socket.available()) {
                char buf[512] = {};
                socket.read(buf, sizeof(buf) - 1);
                printf("\r\n%s\r\n", buf);
                led1 = strncmp("GET /?LED=1", buf, 11) == 0;

                printf("LED1 = %d\r\n\r\n", led1.read());
                printf(response0);
                printf(response1, led1 ? "checked" : "", led1 ? "" : "checked");
                printf(response2);

                socket.printf(response0);
                socket.printf(response1, led1 ? "checked" : "", led1 ? "" : "checked");
                socket.printf(response2);
                socket.close();
            }
        }
    }
}