examples for SimpleSocket/EthernetInterface

Dependencies:   EthernetInterface SimpleSocket mbed-rtos mbed

Files at this revision

API Documentation at this revision

Comitter:
yamaguch
Date:
Mon Feb 04 09:29:18 2013 +0000
Commit message:
modified to use SimpleSocket/EthernetInterface

Changed in this revision

EthernetInterface.lib Show annotated file Show diff for this revision Revisions of this file
SimpleSocket.lib Show annotated file Show diff for this revision Revisions of this file
examples/echoclient.cpp Show annotated file Show diff for this revision Revisions of this file
examples/echoserver.cpp Show annotated file Show diff for this revision Revisions of this file
examples/findbuddy.cpp Show annotated file Show diff for this revision Revisions of this file
examples/httpclient.cpp Show annotated file Show diff for this revision Revisions of this file
examples/multicast.cpp Show annotated file Show diff for this revision Revisions of this file
examples/ntpclient.cpp Show annotated file Show diff for this revision Revisions of this file
examples/ntpclient2.cpp Show annotated file Show diff for this revision Revisions of this file
examples/supertweet.cpp Show annotated file Show diff for this revision Revisions of this file
examples/udpreceiver.cpp Show annotated file Show diff for this revision Revisions of this file
examples/udpsender.cpp Show annotated file Show diff for this revision Revisions of this file
examples/webcontroller.cpp Show annotated file Show diff for this revision Revisions of this file
examples/webserver.cpp Show annotated file Show diff for this revision Revisions of this file
functions.h Show annotated file Show diff for this revision Revisions of this file
main.cpp Show annotated file Show diff for this revision Revisions of this file
mbed-rtos.lib Show annotated file Show diff for this revision Revisions of this file
mbed.bld Show annotated file Show diff for this revision Revisions of this file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/EthernetInterface.lib	Mon Feb 04 09:29:18 2013 +0000
@@ -0,0 +1,1 @@
+http://mbed.org/users/mbed_official/code/EthernetInterface/#a0ee3ae75cfa
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/SimpleSocket.lib	Mon Feb 04 09:29:18 2013 +0000
@@ -0,0 +1,1 @@
+http://mbed.org/users/yamaguch/code/SimpleSocket/#cbc8e17f7043
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/examples/echoclient.cpp	Mon Feb 04 09:29:18 2013 +0000
@@ -0,0 +1,37 @@
+#include "SimpleSocket.h"
+
+void echoclient() {
+    printf("Echo server => ");
+    char server[32];
+    scanf("%s", server);
+
+    ClientSocket socket(server, 1234);
+
+    if (socket) {
+        char message[80] = {};
+        printf("Enter message => ");
+        int c = 0;
+        while (c < ' ' || 0x7E < c)
+            c = getc(stdin);
+        ungetc(c, stdin);
+        for (int i = 0; i < sizeof(message) - 1 && (c = getc(stdin)) >= ' '; i++)
+            message[i] = c;
+
+        socket.printf("%s\r\n", message);
+
+        // wait until data is received
+        while (!socket.available())
+            ;
+        printf("Received: ");
+
+        while (socket.available()) {
+            char buf[128];
+            int len = socket.read(buf, sizeof(buf) - 1);
+            buf[len] = '\0';
+            printf("%s", buf);
+        }
+        printf("\nClosing...\n");
+        socket.close();
+    }
+    printf("Done.\n");
+}
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/examples/echoserver.cpp	Mon Feb 04 09:29:18 2013 +0000
@@ -0,0 +1,23 @@
+#include "SimpleSocket.h"
+
+void echoserver()
+{
+    ServerSocket server(1234);
+
+    printf("server: %s:1234\n", EthernetInterface::getIPAddress());
+
+    while (true) {
+        ClientSocket socket = server.accept();
+
+        if (socket) {
+            while (socket) {
+                char buf[80];
+                int len = socket.read(buf, sizeof(buf));
+                if (len > 0)
+                    socket.write(buf, len);
+            }
+            socket.close();
+        }
+        wait(1.0);
+    }
+}
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/examples/findbuddy.cpp	Mon Feb 04 09:29:18 2013 +0000
@@ -0,0 +1,40 @@
+#include "SimpleSocket.h"
+
+void findbuddy()
+{
+    int myIP[4];
+    sscanf(EthernetInterface::getIPAddress(), "%d.%d.%d.%d", myIP, myIP + 1, myIP + 2, myIP + 3);
+
+    DatagramSocket datagram(7777);
+
+    char buddy[32] = {};
+    int port;
+    for (int i = myIP[3] + 1;; i = (i - myIP[3] + 260) % 10 + myIP[3] + 1) {
+        sprintf(buddy, "%d.%d.%d.%d", myIP[0], myIP[1], myIP[2], i);
+        printf("sending message to %s\n", buddy);
+        datagram.printf("Hello World\n");
+
+        datagram.send(buddy, 7777);
+        // this will not reach target during the first round,
+        // and in order to receive successfully,
+        // timeout must be at least 4 seconds (default = 5.0 seconds)
+        datagram.setTimeout(4.0);
+        if (datagram.receive(buddy, &port) > 0) {
+            char buf[80] = {};
+            int len = datagram.read(buf, sizeof(buf) - 1);
+            printf("received from %s: %s", buddy, buf);
+            break;
+        }
+    }
+
+    for (int i = 0; i < 2; i++) {
+        datagram.printf("There you are!\n");
+        datagram.send(buddy, 7777);
+
+        if (datagram.receive() > 0) {
+            char buf[80] = {};
+            int len = datagram.read(buf, sizeof(buf) - 1);
+            printf("received: %s", buf);
+        }
+    }
+}
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/examples/httpclient.cpp	Mon Feb 04 09:29:18 2013 +0000
@@ -0,0 +1,26 @@
+#include "SimpleSocket.h"
+
+void httpclient() {
+    printf("URL => ");
+    char url[128];
+    scanf("%s", url);
+
+    char hostpart[64], host[64], path[128];
+    int port = 80;
+    sscanf(url, "http://%[^/]%s", hostpart, path);
+    sscanf(hostpart, "%[^:]:%d", host, &port);
+
+    ClientSocket socket(host, port);
+    
+    if (socket) {
+        socket.printf("GET %s HTTP/1.0\r\n\r\n", path);
+
+        while (socket) {
+            if (socket.available()) {
+                char buf[128] = {};
+                socket.read(buf, sizeof(buf) - 1);
+                printf("%s", buf);
+            }
+        }
+    }
+}
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/examples/multicast.cpp	Mon Feb 04 09:29:18 2013 +0000
@@ -0,0 +1,24 @@
+#include "SimpleSocket.h"
+
+void multicast() {
+    Endpoint multicast;
+    multicast.set_address("239.192.1.100", 50000);
+    DatagramSocket datagram(multicast);
+    
+    while (true) {
+        Endpoint host;
+        datagram.setTimeout(1 + (rand() % 5) / 3.0);
+        if (datagram.receive(host) > 0) {
+            int value;
+            datagram.scanf("%d", &value);
+            char *ip = host.get_address();
+            printf("received from %s:%d %d\n", ip, host.get_port(), value);
+        } else {
+            char* message = "12345!";
+            datagram.printf(message);
+            datagram.send(multicast);
+            printf("sent: %s\n", message);
+            wait(1);
+        }
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/examples/ntpclient.cpp	Mon Feb 04 09:29:18 2013 +0000
@@ -0,0 +1,31 @@
+#include "SimpleSocket.h"
+
+void ntpclient() {
+    char *NTP_SERVER = "pool.ntp.org";
+    printf("ntp server = %s\n", NTP_SERVER);
+
+    while (true) {
+        DatagramSocket datagram;
+        char buf[48] = {0x23}; // 00100011 LI(0), Version(4), Mode(3: Client)
+        datagram.write(buf, sizeof(buf));
+        datagram.send(NTP_SERVER, 123);
+        
+        //datagram.setTimeout(5.0);
+        if (datagram.receive() > 0) {
+            if (datagram.read(buf, sizeof(buf)) > 0) {
+                unsigned long seconds = 0;
+                for (int i = 40; i <= 43; i++)
+                    seconds = (seconds << 8) | buf[i];
+                set_time(time_t(seconds - 2208988800ULL));
+                char timestamp[16];
+                time_t jstime = time(NULL) + 9 * 3600;
+                strftime(timestamp, sizeof(timestamp), "%m/%d %X", localtime(&jstime));
+                printf("Time: %s\n", timestamp);
+                break;
+            }
+        } else {
+            printf("no answer\n");
+            wait(1.0);
+        }
+    }
+}
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/examples/ntpclient2.cpp	Mon Feb 04 09:29:18 2013 +0000
@@ -0,0 +1,90 @@
+#include "SimpleSocket.h"
+
+typedef unsigned long long Time64;
+
+Time64 toTime64(char buf[]) {
+    Time64 time64 = 0;
+    for (int i = 0; i < 8; i++) {
+        time64 = (time64 << 8) | buf[i];
+    }
+    return time64;
+}
+
+Time64 toTime64(int usecs) {
+    return Time64(double(usecs) * (1ULL << 32) / 1000000);
+}
+
+void printTime64(char *title, Time64 time64) {
+    unsigned long seconds = (unsigned long) (time64 >> 32);
+    unsigned long subsecs = (unsigned long) (time64 & 0xFFFFFFFFULL);
+    char buf[16];
+
+    time_t jstime = time_t(seconds - 2208988800UL) + 9 * 3600;
+    strftime(buf, sizeof(buf), "%m/%d %X", localtime(&jstime));
+    printf("%s: %s", title, buf);
+    sprintf(buf, "%f\n", (double) subsecs / (1ULL << 32));
+    printf("%s", &buf[1]);
+}
+
+void ntpclient2() {
+    char *NTP_SERVER = "pool.ntp.org";
+    char buf[48] = {0x23};// 00100011 LI(0), Version(4), Mode(3: Client)
+    Timer timer;
+    Time64 adjustedTime = 0;
+
+    for (int count = 0; count < 5; count++) {
+        buf[0] = 0x23;
+        DatagramSocket datagram;
+        datagram.write(buf, sizeof(buf));
+        timer.reset();
+        datagram.send(NTP_SERVER, 123);
+        timer.start();
+        if (datagram.receive() > 0) {
+            int turnaround = timer.read_us();
+            if (datagram.read(buf, sizeof(buf))) {
+                Time64 receivedTime = toTime64(&buf[32]);
+                Time64 transferTime = toTime64(&buf[40]);
+                adjustedTime = toTime64(turnaround / 2) + receivedTime / 2 + transferTime / 2;
+                timer.reset();
+                timer.start();
+                printTime64("transfer", transferTime);
+                printTime64("adjusted", adjustedTime);
+                printf("\n");
+            }
+        } else {
+            wait(5);
+        }
+    }
+
+    float subsecs = (double) (adjustedTime & 0xFFFFFFFFULL) / (1ULL << 32);
+    wait(1 - subsecs);
+    set_time((size_t) ((adjustedTime >> 32) - 2208988800UL) + 1);
+
+    time_t jstime = time(NULL) + 9 * 3600;
+    strftime(buf, sizeof(buf), "%m/%d %X", localtime(&jstime));
+    printf("RTC delta = %6d, %s\n\n", timer.read_us(), buf);
+
+    for (int count = 0; count < 20; count++) {
+        buf[0] = 0x23;
+        DatagramSocket datagram;
+        datagram.write(buf, sizeof(buf));
+        timer.reset();
+        datagram.send(NTP_SERVER, 123);
+        timer.start();
+        if (datagram.receive() > 0) {
+            int turnaround = timer.read_us();
+            if (datagram.read(buf, sizeof(buf))) {
+                Time64 receivedTime = toTime64(&buf[32]);
+                Time64 transferTime = toTime64(&buf[40]);
+                adjustedTime = toTime64(turnaround / 2) + receivedTime / 2 + transferTime / 2;  
+                printTime64("adjusted", adjustedTime);
+                time_t jstime = time(NULL) + 9 * 3600;
+                strftime(buf, sizeof(buf), "%m/%d %X", localtime(&jstime));
+                printf("     RTC: %s\n\n", buf);
+            }
+        } else {
+            wait(5);
+        }
+    }
+
+}
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/examples/supertweet.cpp	Mon Feb 04 09:29:18 2013 +0000
@@ -0,0 +1,84 @@
+#include "SimpleSocket.h"
+#include <ctype.h>
+
+void encodeBase64(char *ibuf, char *obuf);
+int encodeFormUrl(char *s, char *t);
+
+void supertweet() {
+    ClientSocket client("66.180.175.246", 80); // api.supertweet.net
+
+    char user[16], password[16], message[64] = {};
+    printf("user => ");
+    scanf("%s", user);
+    printf("password => ");
+    scanf("%s", password);
+    printf("message => ");
+    int c = 0;
+    while (c < ' ' || 0x7E < c)
+        c = getc(stdin);
+    ungetc(c, stdin);
+    for (int i = 0; i < sizeof(message) - 1 && (c = getc(stdin)) >= ' '; i++)
+        message[i] = c;
+
+    char credential[48], credential2[64], message2[256];
+
+    sprintf(credential, "%s:%s", user, password);
+    encodeBase64(credential, credential2);
+    encodeFormUrl(message, message2);
+
+    const char *request =
+        "POST /1/statuses/update.xml HTTP/1.1\r\n"
+        "Host: api.supertweet.net\r\n"
+        "Authorization: Basic %s\r\n"
+        "Content-Length: %d\r\n"
+        "Content-Type: application/x-www-form-urlencoded\r\n"
+        "\r\n"
+        "status=%s";
+
+    client.printf(request, credential2, strlen(message2) + 7,  message2);
+    printf(request, credential2, strlen(message2) + 7,  message2);
+    printf("\n");
+
+    while (client) {
+        if (client.available()) {
+            while (client.available()) {
+                char response[128] = {};
+                client.read(response, sizeof(response) - 1);
+                printf("%s", response);
+            }
+            client.close();
+        }
+    }
+    printf("\ndone\n");
+}
+
+int encodeFormUrl(char *s, char *t) {
+    char *head = t;
+    for (char c; (c = *s) != 0; s++)
+        switch (c) {
+            case '\r':
+                break;
+            case ' ' :
+                *t++ = '+';
+                break;
+            default:
+                t += sprintf(t, isalnum(c) ? "%c" : (c == '\n') ? "\r%c" : "%%%02X", c);
+        }
+    *t = '\0';
+    return t - head;
+}
+
+void encodeBase64(char ibuf[], int length, char *obuf) {
+    const char BASE64[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
+    int i, j;
+    for (i = j = 0; j < length; j += 3, i += 4) {
+        long a = ibuf[j] << 16 | (j + 1 < length ? ibuf[j + 1] << 8 : 0) | (j + 2 < length ? ibuf[j + 2] : 0);
+        for (int k = 3; k >= 0; k--, a >>= 6)
+            obuf[i + k] = (j + k - 1) < length ? BASE64[a & 63] : '=';
+    }
+    obuf[i] = '\0';
+}
+
+void encodeBase64(char *ibuf, char *obuf) {
+    encodeBase64(ibuf, strlen(ibuf), obuf);
+}
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/examples/udpreceiver.cpp	Mon Feb 04 09:29:18 2013 +0000
@@ -0,0 +1,16 @@
+#include "SimpleSocket.h"
+
+void udpreceiver() {
+    DatagramSocket datagram(7777);
+    datagram.setTimeout(1.0);
+    Endpoint buddy;
+    while (true) {
+        if (datagram.receive(buddy) > 0) {
+            char *ip = buddy.get_address();
+            int port = buddy.get_port();
+            char buf[80] = {};
+            int len = datagram.read(buf, sizeof(buf) - 1);
+            printf("received from %s:%d %s", ip, port, buf);
+        }
+    }
+}
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/examples/udpsender.cpp	Mon Feb 04 09:29:18 2013 +0000
@@ -0,0 +1,27 @@
+#include "SimpleSocket.h"
+
+void udpsender() { 
+    DatagramSocket datagram;
+
+    char message[80] = {};
+    printf("Enter message => ");
+    int c = 0;
+    while (c < ' ' || 0x7E < c)
+        c = getc(stdin);
+    ungetc(c, stdin);
+    for (int i = 0; i < sizeof(message) - 1 && (c = getc(stdin)) >= ' '; i++)
+        message[i] = c;
+
+    int i1, i2, i3, i4;
+    printf("UDP receiver address => ");
+    scanf("%d.%d.%d.%d", &i1, &i2, &i3, &i4);
+
+    for (int i = 0;; i++) {
+        printf("Sending message : %s (%d)\n", message, i);
+        datagram.printf("(%d) %s\n", i, message);
+        char ip[16] = {};
+        sprintf(ip, "%d.%d.%d.%d", i1, i2, i3, i4);
+        datagram.send(ip, 7777);
+        wait(1);
+    }
+}
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/examples/webcontroller.cpp	Mon Feb 04 09:29:18 2013 +0000
@@ -0,0 +1,50 @@
+#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();
+            }
+        }
+    }
+}
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/examples/webserver.cpp	Mon Feb 04 09:29:18 2013 +0000
@@ -0,0 +1,60 @@
+#include "SimpleSocket.h"
+
+void webserver()
+{
+    const char *response0 =
+        "HTTP/1.1 200 OK\r\n"
+        "Content-Type: text/html\r\n"
+        "\r\n"
+        "<META HTTP-EQUIV=\"Refresh\" CONTENT=\"5\">\r\n"
+        "<html>\r\n"
+        "<head>\r\n"
+        "<title>mbed web server</title>\r\n"
+        "</head>\r\n"
+        "<body>\r\n"
+        "<h2>Analog Input</h2>\r\n"
+        "<table cellpadding=\"5\">\r\n";
+
+    const char *response1 =
+        "<tr style=\"background:#ccccff\">"
+        "<th>pin</th><th>value</th>"
+        "</tr>\r\n";
+
+    const char *response2 =
+        "<tr style=\"background:#cccccc\">"
+        "<td>p%d</td><td align=\"center\">%f</td>"
+        "</tr>\r\n";
+
+    const char *response3 =
+        "</table>\r\n"
+        "</body>\r\n"
+        "</html>\r\n";
+
+    ServerSocket server(80);
+
+    printf("webserver: %s\n", EthernetInterface::getIPAddress());
+
+    while (true) {
+        ClientSocket socket = server.accept();
+        while (socket) {
+            if (socket.available()) {
+                while (socket.available())
+                    socket.read();
+                int ret1 = socket.printf(response0);
+                //wait(0.1);
+                int ret2 = socket.printf(response1);
+                //wait(0.1);
+                AnalogIn analogPin[] = {p15, p16, p17, p18, p19, p20};
+                int ret = 0;
+                for (int i = 0; i < 6; i++) {
+                    ret += socket.printf(response2, 15 + i, analogPin[i].read());
+                   // wait(0.1);
+                }
+                int ret3 = socket.printf(response3);
+                //wait(0.1);
+                socket.close();
+                ::printf("len = %d, ret = %d, %d, %d, %d\n", strlen(response1), ret1, ret2, ret, ret3);
+            }
+        }
+    }
+}
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/functions.h	Mon Feb 04 09:29:18 2013 +0000
@@ -0,0 +1,36 @@
+#include "mbed.h"
+
+struct Function {
+    char *name;
+    void (*func)();
+};
+
+void echoserver();
+void echoclient();
+void ntpclient();
+void ntpclient2();
+void supertweet();
+void findbuddy();
+void multicast();
+void httpclient();
+void webserver();
+void webcontroller();
+void udpsender();
+void udpreceiver();
+void supertweet();
+
+Function functions[] = {
+    "Echo Server", echoserver,
+    "Echo Client", echoclient,
+    "NTP Client", ntpclient,
+    "NTP Client2", ntpclient2,
+    "Find Buddy", findbuddy,
+    "Multicast", multicast,
+    "HTTP Client", httpclient,
+    "Web Server", webserver,
+    "Web Controller", webcontroller,
+    "UDP sender", udpsender,
+    "UDP receiver", udpreceiver,
+    "Super Tweet", supertweet,
+    0, 0
+};
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/main.cpp	Mon Feb 04 09:29:18 2013 +0000
@@ -0,0 +1,13 @@
+#include "functions.h"
+
+int main() {
+    for (int i = 0; functions[i].name; i++)
+        printf("[%d] %s\n", i, functions[i]);
+
+    printf("Select => ");
+    int n;
+    scanf("%d", &n);
+    printf("%d was selected, starting %s\n", n,  functions[n].name);
+    
+    functions[n].func();
+}
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mbed-rtos.lib	Mon Feb 04 09:29:18 2013 +0000
@@ -0,0 +1,1 @@
+http://mbed.org/users/mbed_official/code/mbed-rtos/#53e6cccd8782
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mbed.bld	Mon Feb 04 09:29:18 2013 +0000
@@ -0,0 +1,1 @@
+http://mbed.org/users/mbed_official/code/mbed/builds/0954ebd79f59
\ No newline at end of file