Example of HTTPServer with additional features: * SNTPClient, DST rules * Link status indication * Local or SDCard-based WebServer * RPC-able class * Static and Dynamic HTML page

Dependencies:   mbed

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers main.cpp Source File

main.cpp

00001 // Written by IVA2K
00002 //
00003 // Example of HTTPServer with additional features:
00004 // * SNTP Client (Simple NTP)
00005 // * Link status indication (LED4 or RJ45 socket LED on MBED-BoB2-mod)
00006 // * Local file system (create index.htm page on MBED!)
00007 // * SD-based WebServer
00008 // * RPC-able class (myrpc, allows remote function call that blinks LED1 N times)
00009 // * Static HTML page
00010 // * Dynamic HTML page
00011 //
00012 // Instructions:
00013 // 1  Plug MBED into MBED-BoB2 (or other ETH connector breakout)
00014 // 2  Plug ETH connector into your network (needs DHCP to get IP address and Internet connection)
00015 // 3  Power up MBED using USB cable
00016 // 4  Install MBED serial driver (http://mbed.org/handbook/SerialPC)
00017 // 5  Copy compiled .bin to your MBED (make sure target device selected in the compiler is correct)
00018 // 6  Open terminal on the mbed serial port
00019 // 7  Push MBED reset button
00020 // 8  Terminal will display info message with mac address, followed by IP address (if connection succeeds)
00021 //    in the following items, replace 10.0.0.321 with actual MBED IP address from the terminal
00022 // 9  Open browser and enter the following URL:
00023 //    http://10.0.0.321/rpc/myrpc1/blink,10
00024 // 10 MBED will blink the LED 10 times
00025 // 11 Open browser and enter the following URL:
00026 //    http://10.0.0.321/rpc/myrpc1/gettime
00027 // 12 The browser will show date and time from the MBED synchronized to NTP server
00028 // 13 Open browser and enter the following URL:
00029 //    http://10.0.0.321/static.htm
00030 // 14 The browser will show static HTML page
00031 // 15 Open browser and enter the following URL:
00032 //    http://10.0.0.321/dynamic.htm
00033 // 16 The browser will show dynamic HTML page
00034 // 17 Create a simple index.htm page on the MBED
00035 // 18 Open browser and enter the following URL:
00036 //    http://10.0.0.321
00037 // 19 The browser will show index HTML page
00038 // 20 Create a simple index.htm page on a micro SD card, plug the card into MBED-BoB2
00039 // 21 Open browser and enter the following URL:
00040 //    http://10.0.0.321
00041 // 22 The browser will show index HTML page from SD card
00042 // 23 Optionally, create file "sntp.ini" on MBED or SD card. Copy-paste SNTP configuration from the terminal into this file and modify to your needs.
00043 //
00044 // Notes: there are still some bugs in HTTPServer code. 
00045 // To help fight some of them, copy a valid favicon.ico (a 16x16 icon) file to MBED.
00046 //
00047 
00048 #include "mbed.h"
00049 #include "SDFileSystem.h"
00050 #include "HTTPServer.h"
00051 #include "HTTPRPC.h"
00052 #include "HTTPFS.h"
00053 #include "HTTPStaticPage.h"
00054 #include "HTTPDynamicPage.h"
00055 #include "HTTPLinkStatus.h"
00056 #include "SNTPClient.h"
00057 
00058 #define CLS "\033[2J"
00059 
00060 const char content[] = 
00061 "<HTML>"
00062 "<HEAD>"
00063 "<title>Static Page</title>"
00064 "</HEAD>"
00065 "<BODY>"
00066 "<H1>Hello World</H1>"
00067 "<p>Page generated statically from code.</p>"
00068 "</BODY></HTML>"
00069 ;
00070 
00071 #define MAX_DYNAMIC_CONTENT_LEN     2048
00072 char dynamic_content[MAX_DYNAMIC_CONTENT_LEN];
00073 
00074 const char content_fmt[] = 
00075 "<HTML>"
00076 "<HEAD>"
00077 "<title>Dynamic Page</title>"
00078 "</HEAD>"
00079 "<BODY>"
00080 "<H1>Hello World</H1>"
00081 "<p>Page generated dynamically from code.</p>"
00082 "<p>URL=%s</p>"
00083 "<p>Header Fields=%s</p>"
00084 "</BODY></HTML>"
00085 ;
00086 
00087 DigitalOut led1(LED1, "led1");
00088 DigitalOut led2(LED2, "led2");
00089 DigitalOut led3(LED3, "led3");
00090 DigitalOut led4(LED4, "led4");
00091 DigitalIn sw1(p9, "sw1");
00092 DigitalIn sw2(p10, "sw2");
00093 LocalFileSystem local("local");
00094 SDFileSystem sd(p5, p6, p7, p8, "sd");      // MBED-BoB2
00095 
00096 #include "myrpc.h"
00097 myrpc myrpc1(LED1, "myrpc1");
00098 
00099 extern Ethernet eth;        // eth is defined elsewhere, avoid compiler error.
00100 Serial pc(USBTX, USBRX);
00101 int gDebug=1;
00102 float gWait = 0.005;        // Main loop wait timeout
00103 
00104 HTTPStatus myDynamicPage(HTTPConnection *con, HTTPDynamicPageData *pd) {
00105 #if 0
00106     // Static example. With this, we don't really need HTTPStaticPage
00107     pd->size = 0;    // let it measure our page
00108     pd->page = (char*)content;    // Nothing dynamic about that yet, but we can now get loose here.
00109     pd->page_free = NULL;    // No mem free() needed
00110 #elif 0
00111     // Dynamic example, static buffer
00112     pd->size = sprintf(dynamic_content, content_fmt, con->getURL(), con->getHeaderFields());
00113     pd->page = (char*)dynamic_content;
00114     pd->page_free = NULL;    // No mem free() needed
00115 if(pd->size > sizeof(dynamic_content)) printf("ASSERTION FAILED: %s:%d\r\n", __FILE__, __LINE__);    // Buffer overrun
00116 #else
00117     // Dynamic example, dynamic buffer
00118     int size = sizeof(content_fmt) + 512;    // Just guess how much the data will expand
00119     char *buf = (char *)malloc(size);
00120     if (buf) {
00121         pd->size = sprintf(buf, content_fmt, con->getURL(), con->getHeaderFields());
00122         pd->page = buf;
00123         pd->page_free = &free;    // Use free() when done
00124 if(pd->size > size) printf("ASSERTION FAILED: %s:%d\r\n", __FILE__, __LINE__);    // Buffer overrun
00125 #endif
00126     }
00127     return HTTP_OK;
00128 }
00129 
00130 int main(void) {
00131     char mac[6];
00132     int sw1_old=0, sw2_old=0;
00133     bool use_sd = false;
00134 
00135     led1=1;
00136     led2=1;
00137     led3=1;
00138     led4=1;
00139 
00140     // Start RTC
00141     time_t seconds = time(NULL);
00142     if (seconds == (unsigned)-1 || seconds == 0) {
00143       seconds = 1256729737;     // Set RTC time to Wed, 28 Oct 2009 11:35:37
00144       set_time(seconds);
00145       printf("RTC initialized, start time %d seconds\r\n", seconds);
00146     }
00147 
00148     char *hostname = "mbed";
00149     HTTPServer http(hostname);    // Use DHCP
00150     http.timeout(10000);    // Sets the timout for a HTTP request.  The timout is the time which is allowed to spent between two incomming TCP packets.  If the time is passed the connection will be closed.
00151 
00152     eth.address(mac);
00153     pc.printf(CLS "\r\n\r\nHTTPServer \"%s\" started\r\nMAC %02X:%02X:%02X:%02X:%02X:%02X\r\n%s",
00154         hostname, mac[0], mac[1], mac[2], mac[3], mac[4], mac[5],
00155         gDebug?"Debug is ON\r\n":""
00156     );
00157 
00158     Base::add_rpc_class<AnalogIn>();
00159     Base::add_rpc_class<AnalogOut>();
00160     Base::add_rpc_class<DigitalIn>();
00161     Base::add_rpc_class<DigitalOut>();
00162     Base::add_rpc_class<PwmOut>();
00163     Base::add_rpc_class<Timer>();
00164     Base::add_rpc_class<SPI>();
00165     Base::add_rpc_class<BusOut>();
00166     Base::add_rpc_class<BusIn>();
00167     Base::add_rpc_class<myrpc>();
00168     led1=0;
00169 
00170     // Check if we can use SD card for the web server
00171     FILE *fp = fopen("/sd/index.htm", "r");
00172     if (fp == NULL) {
00173         if (gDebug) printf("DEBUG: No SD card found or no index.htm file - using LocalFilesystem for WebServer.\r\n");
00174     } else {
00175         use_sd = true;
00176         fclose(fp);
00177         if (gDebug) printf("DEBUG: Found SD card with index.htm file - using SD for WebServer.\r\n");
00178     }
00179 
00180     if (0 != SNTPReadIniFile("/sd/sntp.ini") )
00181         SNTPReadIniFile("/local/sntp.ini");
00182     SNTPWriteIniFile(stdout);
00183 
00184 
00185     http.addHandler(new HTTPLinkStatus("/", 
00186 #if MBED_BOB2
00187       p25, p26,         // MBED-BoB2-mods
00188 #else
00189       LED3, LED4,
00190 #endif
00191       0.1,
00192       /*do_urlfile*/ true, /*do_link_printf*/ true, /*do_log_printf*/ false, 
00193       /*log_file*/ ( (gDebug>1) ? (use_sd ? "/sd/httpd.log" : "/local/httpd.log") : NULL)
00194     ));    // Should be the first handler to get a preview of all requests
00195     http.addHandler(new HTTPRPC());
00196     led2=0;
00197 
00198     // Static/Dynamic pages must be installed before FileSystem on /
00199     http.addHandler(new HTTPStaticPage("/static.htm", content, strlen(content)));
00200     http.addHandler(new HTTPDynamicPage("/dynamic.htm", &myDynamicPage));
00201     http.addHandler(new HTTPFileSystemHandler("/", use_sd ? "/sd/" : "/local/"));
00202     led3=0;
00203 
00204 // FIXME: BUG If eth is not plugged, http.bind() hangs!
00205     http.bind();
00206 
00207     SNTPClientInit();
00208     led4 = 0;
00209 
00210     pc.printf("\r");    // Add linefeed for stupid Hyperterminal
00211     while(1) {
00212         http.poll();    // Have to call this method at least every 250ms to let the http server run.
00213         if (sw1 & !sw1_old) {
00214             printf("SW1\r\n");
00215         }
00216         if (sw2 && !sw2_old) {
00217             printf(CLS "SW2\r\n");
00218         }
00219         sw1_old = sw1;
00220         sw2_old = sw2;
00221         wait(gWait);
00222     }
00223 }
00224 
00225 //END