HTTP Server upon new mbed Ethernet Interface. Based on original code by Henry Leinen.

Dependencies:   EthernetInterface mbed-rtos mbed

Fork of HTTP_server by pablo gindel

Files at this revision

API Documentation at this revision

Comitter:
pabloxid
Date:
Mon Aug 05 05:51:16 2013 +0000
Parent:
3:27b3a889b327
Commit message:
Some minor changes

Changed in this revision

HTTPServer.cpp Show annotated file Show diff for this revision Revisions of this file
HTTPServer.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
--- a/HTTPServer.cpp	Tue Jul 30 04:37:09 2013 +0000
+++ b/HTTPServer.cpp	Mon Aug 05 05:51:16 2013 +0000
@@ -25,6 +25,8 @@
     socketServer.set_blocking (true);
 
     path = _path;
+    msg = NULL;
+    cliente = NULL;
 
 }
 
@@ -32,18 +34,14 @@
 
 int HTTPServer::poll () {
 
-    int retvalue;
-
     cliente = new TCPSocketConnection;
     cliente->set_blocking (false, TIMEOUT);
 
-    retvalue = socketServer.accept (*cliente);
+    int retvalue = socketServer.accept (*cliente);
 
     if (retvalue == OK) {
-
         // a new connection was received
         INFO("Client (IP=%s) is connected !", cliente->get_address());
-
         msg = new HTTPMsg;     // estructura para decodificar y alojar el mensaje
 
         retvalue = pollConnection (); // esto parsea y llena las cosas contenidas en msg
@@ -51,13 +49,13 @@
         if (retvalue == OK) {
             // Handle the request
             INFO("Handling request !");
-            handleRequest ();
+
+            handleRequest ();    // handling request
+
         }
-
         delete msg;
-
     } else {  // retvalue == ERROR
-        INFO("No connection\n");
+        ERR("Error accepting client");
     }
 
     delete cliente;
@@ -69,11 +67,10 @@
 
 int HTTPServer::pollConnection () {
 
-    int received = 0;
     INFO("Waiting for new data in connection");
 
     // Try receiving request line
-    received = receiveLine ();
+    int received = receiveLine ();
 
     if (received == ERROR) {
         // there was an error, probably the connection was closed, so close this connection as well
@@ -84,6 +81,10 @@
     // Request has not yet been received, so try it
     received = parseRequest ();
 
+    /*alternative (fast) parse request method:
+     * ret = sscanf(buffer, "%s %s HTTP/%*d.%*d", request, uri);
+     */
+
     if (received == ERROR) {
         // Invalid content received, so close the connection
         INFO("Invalid message received, so sending negative response and closing connection !");
@@ -100,7 +101,7 @@
         if (received == EMPTY) {
             // there was an empty line, so the headers section is complete
             INFO("Request Header was received completely. Performing request.");
-            received = 0;
+            received = OK;
             break;
         } else {
             // parse header field
@@ -118,12 +119,6 @@
 
     buffer[0] = 0;
 
-    if (!cliente->is_connected()) {
-        error("NOT Connected anymore");
-        return ERROR;
-    }
-
-    Timer tm;
     int i;
 
     //  Try to receive up to the max number of characters
@@ -132,11 +127,8 @@
         //  Check that - if no character was currently received - the timeout period is reached.
         if (c == 0 || c == -1) {
             //  no character was read, so check if operation timed out
-            if (tm.read_ms() > 2*TIMEOUT) {
-                //  Operation timed out
-                INFO("Timeout occured in function 'receiveLine'.");
-                return ERROR;
-            }
+            ERR("Timeout occured in function 'receiveLine'.");
+            return ERROR;
         }
         //  Check if line terminating character was received
         if (buffer[i] == '\n') {break;}
@@ -245,14 +237,14 @@
     char* argname = NULL;
     char* valuename = NULL;
     for (int i=0; i<buflen; i++) {
-        if (args_start == -1) { // args section not yet found
+        if (args_start == -1) {  // args section not yet found
             if (uri_buffer[i] == '?') {  // starts with a question mark, so got it
                 uri_buffer[i] = 0;
-                args_start = i; //  set the start of the args section
+                args_start = i;  // set the start of the args section
                 INFO("Argument section found !");
             }
-        } else { // search arg-value touples
-            if (argname == NULL) {    // arg-name found ?
+        } else {                    // search arg-value touples
+            if (argname == NULL) {     // arg-name found ?
                 if (uri_buffer[i] == '=') {
                     // yes, separate the arg-name
                     uri_buffer[i] = 0;
@@ -329,11 +321,10 @@
 
         startResponse (200, size);                  // response: 200 = HTTP_Ok
         while (!feof(file) && !ferror(file)) {
+            // TODO: handle filesystem errors too
             int count = fread (buffer, 1, CHUNK_SIZE, file);
             INFO("Processing Response (%d bytes)!", count);
-            if (cliente->send_all (buffer, count) != count) {
-                WARN ("Unsent bytes left !");                  // TODO: handle filesystem errors
-            }
+            tcpsend (buffer, count);
         }
         INFO("Ending Response !");
 
@@ -353,12 +344,13 @@
     // Try receive the body data, if there is any
     if (msg->body_length > 0) {
 
-        INFO("Receiving body data.");
-        if (msg->body_length > BUFFER_SIZE) {error ("OutOfMemory");}
+        char post_buffer [msg->body_length];
+
+        INFO("Receiving body data. (%i bytes)", msg->body_length);
 
         int bytes_read = 0;
         while (bytes_read < msg->body_length) {
-            int result = cliente->receive_all(buffer+bytes_read, msg->body_length-bytes_read);
+            int result = cliente->receive_all(post_buffer+bytes_read, msg->body_length-bytes_read);
             if (result == ERROR) {
                 WARN("Error receiving body data.");
                 break;
@@ -367,17 +359,16 @@
         }
 
         INFO("Body data received.");
-
+    
         // do something
-        // use the url_decode routine :)
-
+        // use the url_decode function :)
+            
         INFO("Done !\n");
+        
         return handleGetRequest();
-            
+        
     } else {
-        
         ERR("POST data not found !");
-    
     }
 
     return 404;
--- a/HTTPServer.h	Tue Jul 30 04:37:09 2013 +0000
+++ b/HTTPServer.h	Mon Aug 05 05:51:16 2013 +0000
@@ -32,15 +32,15 @@
 #include <map>
 
 #define BUFFER_SIZE     256       // all-purpose buffer
-#define TIMEOUT         800
+#define TIMEOUT         500
 #define OK              0
 #define ERROR           -1
 #define EMPTY           -2
 #define MIN_LONG        3
 #define CHUNK_SIZE      256
 
-#define DEBUG 0
-#include "../debug.h"
+#define DEBUG 2
+#include "debug.h"
 
 enum RequestType {
      HTTP_RT_GET,        /*!< GET request */
@@ -88,26 +88,32 @@
     void handleError (int errorCode);
 
     int tcpsend (const char* text, int param) {
-        //if (cliente == NULL) {return ERROR;}
         sprintf (buffer, text, param);
-        int len = strlen (buffer);
-        if (cliente->send_all (buffer, len) == len) {
-            return OK;
-        } else {
+        return tcpsend (buffer, strlen (buffer));
+    }
+
+    int tcpsend (const char* text) {
+        return tcpsend ((char*)text, strlen (text));
+    }
+
+    /*int tcpsend (char* buf, int len) {
+        int sent = 0;
+        while (sent<len) {
+            sent += cliente->send (buf+sent, len-sent);
+            if (sent == ERROR) {
+                WARN("Unsent bytes left !");
+                return ERROR;
+            }
+        }
+        return OK;
+    }*/
+
+    int tcpsend (char* buf, int len) {
+        if (cliente->send_all (buf, len) != len) {
             WARN("Unsent bytes left !");
             return ERROR;
         }
-    }
-
-    int tcpsend (const char* text) {
-        //if (cliente == NULL) {return ERROR;}
-        int len = strlen (text);
-        if (cliente->send_all ((char*)text, len) == len) {
-            return OK;
-        } else {
-            WARN("Unsent bytes left !");
-            return ERROR;
-        }
+        return OK;
     }
 
 public:
@@ -124,4 +130,5 @@
 void url_decode (char *str);
 
 
+
 #endif //__HTTPSERVER_H__
--- a/main.cpp	Tue Jul 30 04:37:09 2013 +0000
+++ b/main.cpp	Mon Aug 05 05:51:16 2013 +0000
@@ -16,17 +16,13 @@
     eth.connect();
     printf("IP Address is %s\n", eth.getIPAddress());
     
-    Timer onesec;
-    onesec.start();
-
     Thread httpsvr( &http_thread );
 
     while (true) {
 
-        if (onesec.read() > 1) {
-            onesec.reset();
-            led1 = 1-led1;
-        }
+        led1 = 1-led1;
+        
+        Thread::wait (1000);
         
     }