A sample program demonstrating a small but powerful web server using the Wifly module. This uses several libraries from others, but has a custom version of the WiflyInterface library, with numerous improvement to the mbed standard library.

Dependencies:   SW_HTTPServer WiflyInterface mbed C12832 IniManager

Here's the code

But you also might want to check out the SmartBoard-WiFly project page.

Basic Web Server

  • Serves static files from the selected file system. This is a compile-time setting, and a typical configuration supports gif, jpg, jpeg, ico, png, zip, gz, tar, txt, pdf, htm, and html.
  • It is designed to be small, thereby better supporting the limited resources of an embedded environment.

Advanced Web Services

  • Serves dynamically generated pages, where your software registers for a path, and then everything to that path activates your handler. Your handler then defines the header and body response.
  • Dynamic handlers can process GET query parameters (e.g. /dyn1?sky=blue&grass=green).
  • Dynamic handlers can process POST query parameters, as delivered from submission of a form.
  • Dynamic handlers can protect a resource with user:password access.

Run-Time Configurations

  • File System Support - using either the "local" file system supported by the magic chip, or from either an SD-Card or a USB flash drive.
  • Configurable to the maximum number of dynamic handlers (minimize memory requirements).
  • Configurable to the maximum number of name=value pairs for dynamic handlers (minimize memory requirements).

Compile-Time Configurations

  • Default filename for URL ending in '/' - default is 'index.htm'.
  • Configurable buffer sizes permit minimizing RAM requirements.
  • Configurable header response information.
  • Configurable for which serial port is used to communicate to the WiFly module.
  • Improved security option - to disable telnet access.

Diagnostics

  • API to determine the largest header (to more efficiently size the buffers).
  • API to gather the run-time characteristics - header processing time and content delivery time.

Limitations / Constraints

Known Issues

These are known issues, not yet resolved.

  1. Occasionally fails to serve a page - one test will constantly reload a web page every 30 seconds. It may run for hours, or minutes, then fail to load. Behaviors then are:
    • Hit the reload button in the browser and away it goes.
    • Hit the reload and you'll see the Wifly LEDs energize from the request, but no response by the web server. It appears that the embedded code does not "accept()" the connection in the TCP Socket Server.
      • In this case, the Wifly module has gone through an internal watchdog reset and the configuration parameters are such that it does not gracefully recover. Microchip is aware of this issue, but has not solved it.

Wifly Limitations

  • Single thread - it doesn't respond to overlapping requests (e.g. an embedded image may be requested before the main page completes transfer - the request is lost and the image not shown).
  • Single client - goes along with the single thread, but it doesn't support more than one client at a time.

Smart-Wifly-WebServer

  • Dynamic memory allocation - it does use dynamic memory allocation, which would be discouraged/avoided in many embedded systems. Here it uses it in parsing a request and it releases those resources upon completion of that request. If there is no other dynamic allocation that persists beyond a transaction, it should not cause memory fragmentation. Note that with multi-threading (if this is implemented with an OS), you then have race conditions that could cause fragmentation.

Web Server

Here's the web server in action. A combination of static pages served from the file system and dynamically generated pages.

/media/uploads/WiredHome/swsvr_1.pngPart of the main demo page,
which basically has all the
specifications, configurations, and limitations.
/media/uploads/WiredHome/swsvr_2.pngA zoomed out view of the same page.
/media/uploads/WiredHome/swsvr_3.pngIt would be possible to configure
the server via the web.
/media/uploads/WiredHome/swsvr_4.pngOne of the dynamically generated pages.
This one has parsed the query parameters.
/media/uploads/WiredHome/swsvr_5.pngA simple form which has a dynamic handler on the back end.
Here it takes the value associated with "leds"
and uses that to set the 4 LEDs on the mbed module.
/media/uploads/WiredHome/swsvr_6.pngA dynamic handler can require authentication.
/media/uploads/WiredHome/swsvr_7.pngSuccess!

But I've now gone so far beyond that in the current version. Here's what this one can do:

  1. It serves static web pages from a file system. I've only tested with the local file system and an SD card, but should work for any, so long as you remember that the local file system can't read subdirectories.
  2. It can serve dynamically generated web pages. This lets you accept name=value pairs using the URL (using either a GET or POST method). It can also accept them from forms. The demo lets you control the 4 LEDs from a form.
  3. As safely as possible it retrieves your credentials to the Wi-Fi Access Point. After using them, it overwrites that ram so they can't be as easily extracted.
  4. I made a large number of changes to the Wifly driver. It had too short of a timeout and I found quite a number of optimizations for performance and robustness.
  5. I have the start on a security feature - you can configure a resource to require user credentials to access it. The browser typically provides a username and password dialog. Take care however, as it does not support a secure (https) connection, so the credentials are not as securely transferred as I would like.

Optimizations I'd like to do:

  1. speed it up - I'm running the mbed to wifly module interface at 230K, which is about the top speed w/o flow control. There are other places where some time delays remain - I have eliminated a number of them.
  2. make it non-blocking, so other work can happen.
  3. integrate it with the rtos
  4. When a web page has referenced resources (e.g. an image tag), it rarely loads the image on the first try. I think the request for the resource comes in while it is still in the WiflyInterface cleaning up from the last connection. The Wifly module supports only a single connection at a time. I worked around this with a small bit of javascript to load the images after the web page.

But all in all I think it is a good start.

Program prerequisite

Here's the link to the program, but when you open it up, note a few very important items.

  1. Port Numbers listed in the constructor match the SmartBoard Baseboard.
  2. I sped up the communication baud rate to the mbed from the default 9600. Match your terminal program accordingly.
  3. Download this zip. Place it and an unzipped copy into the mbed local file system. These are the demo files.
  4. The typical ssid and password are not shown. See below to set yours.

ssid and password

You need to create a simple text file on your mbed root folder named "config.ini". The easiest way perhaps is to create "config.txt", add the information shown below and then rename it. This will be read at startup to connect you to the network. Something quite simple, like this:

[Wifi]
ssid=your_ssid
pass=your_pass_code

The program

And the program.

Import programSmart-WiFly-WebServer

A sample program demonstrating a small but powerful web server using the Wifly module. This uses several libraries from others, but has a custom version of the WiflyInterface library, with numerous improvement to the mbed standard library.

Examples/DynamicPages.cpp

Committer:
WiredHome
Date:
2015-02-02
Revision:
38:962d71d6dd0e
Parent:
35:87d3577800dc

File content as of revision 38:962d71d6dd0e:

/// Demonstration of dynamic page creation using the Smartware Web Server
///
/// There are a few samples here of the dynamically generated web pages.
/// Read the header above each one for more details.
///
#include "mbed.h"

#include "SW_HTTPServer.h"
#include "DynamicPages.h"

//#define DEBUG "dynP"    /* define DEBUG before "Utility.h" to activate the INFO, WARN, ERR macros. */
#include "Utility.h"


BusOut leds(LED4,LED3,LED2,LED1);       // dynamic page "/dyn2" lets you control these


/// SimplyDynamicPage1
///
/// This web page is generated dynamically as a kind of "bare minimum".
/// It doesn't do much.
///
/// You can see in main how this page was registered.
///
HTTPServer::CallBackResults SuperSimpleDynamicPage(HTTPServer *svr, HTTPServer::CallBackType type, const char * path, const HTTPServer::namevalue *params, int paramcount)
{
    HTTPServer::CallBackResults ret = HTTPServer::ACCEPT_ERROR;
    char contentlen[30];
    char buf[250];

    switch (type) {
        case HTTPServer::SEND_PAGE:
            // This sample drops it all into a local buffer, computes the length,
            // and passes that along as well. This can help the other end with efficiency.
            strcpy(buf, "<html><head><title>Home Page</title></head>\r\n");
            strcat(buf, "<body>\r\n");
            strcat(buf, "<h1>Smart WiFly Web Server</h1>\r\n");
            strcat(buf, "This page was generated dynamically.<br/>\r\n");
            strcat(buf, "<a href='/dyn'>To another dynamically generated page.</a><br/>\r\n");
            strcat(buf, "<a href='/led'>A page to control the LEDs.</a><br/>\r\n");
            strcat(buf, "</body></html>\r\n");
            sprintf(contentlen, "Content-Length: %d\r\n", strlen(buf));
            // Now the actual header response
            svr->header(200, "OK", "Content-Type: text/html\r\n", contentlen);
            // and data are sent
            svr->send(buf);
            ret = HTTPServer::ACCEPT_COMPLETE;
            break;
        case HTTPServer::CONTENT_LENGTH_REQUEST:
            ret = HTTPServer::ACCEPT_COMPLETE;
            break;
        case HTTPServer::DATA_TRANSFER:
            ret = HTTPServer::ACCEPT_COMPLETE;
            break;
        default:
            ret = HTTPServer::ACCEPT_ERROR;
            break;
    }
    return ret;
}


/// SimplyDynamicPage
///
/// This web page is generated dynamically and fills in part of the information from
/// data extracted from the URL as a query string. It also shows some additional
/// information - memory stats, server stats and so forth.
///
/// You can see in main how this page was registered.
///
HTTPServer::CallBackResults SimpleDynamicPage(HTTPServer *svr, HTTPServer::CallBackType type, const char * path, const HTTPServer::namevalue *params, int paramcount)
{
    static unsigned int pageCounter = 0;
    char buf[150];
    HTTPServer::CallBackResults ret = HTTPServer::ACCEPT_ERROR;
    HTTPServer::SW_PerformanceData perfData;
    //Wifly * w = svr->GetWifly()->getInstance();

    switch (type) {
        case HTTPServer::SEND_PAGE:
            INFO("dt: %d, %s", type, path);
            if (strcmp("true", svr->GetParameter("Reset")) == 0)
                svr->ResetPerformanceData();
            // Send the header
            svr->header(200, "OK", "Content-Type: text/html\r\n");

            // Send top of the page
            svr->send(
                "<html><head><title>Dynamic Page</title><meta http-equiv='refresh' content='15'></head>\r\n"
                "<body>\r\n"
                "<h1>Smart WiFly Web Server</h1>\r\n"
                "This page was generated dynamically. Create your own name=value pairs on the URL "
                "which uses the GET method.<br/>\r\n");

            sprintf(buf, "This page has been accessed %d times.<br/>\r\n", ++pageCounter);
            svr->send(buf);
            
            // Show Passed-in parameters
            svr->send("<h2>Query Parameters:</h2><blockquote>\r\n");
            sprintf(buf, "%d parameters passed to {%s}:<br/>\r\n", paramcount, path);
            svr->send(buf);
            // show each of the parameters passed on the URL
            for (int i=0; i<paramcount; i++) {
                sprintf(buf, "%d: %s = %s<br/>\r\n", i, params[i].name, params[i].value);
                svr->send(buf);
            }
            svr->send("</blockquote>\r\n");

            // Show Memory Stats
            svr->send(
                "<h2>System Statistics:</h2><blockquote>\r\n"
                "<table border='1'><tr><td>Parameter</td><td>Description</td></tr>\r\n");
            sprintf(buf,"<tr><td align='right'>%d</td><td>Free memory</td></tr>\r\n", Free());
            svr->send(buf);
            sprintf(buf,"<tr><td align='right'>%d</td><td>Max Header size</td></tr>\r\n", svr->GetMaxHeaderSize());
            svr->send(buf);
            //sprintf(buf,"<tr><td align='right'>%3.2f</td><td>Wifly SW version</td></tr>\r\n", w->getWiflyVersion());
            //svr->send(buf);
            //sprintf(buf,"<tr><td align='right'><font size='-1'>%s</font></td><td>Wifly Version Information</td></tr>\r\n", w->getWiflyVersionString());
            //svr->send(buf);
            svr->send("</table>\r\n");
            svr->send("</blockquote>\r\n");

            // Show Web Server Performance metrics
            svr->GetPerformanceData(&perfData);
            svr->send("<h2>Web Server Performance Metrics</h2><blockquote>\r\n");
            svr->send("<table border='1'><tr><td>avg time (uS)</td><td>samples</td><td>max time (uS)</td><td>description</td></tr>\r\n");

            sprintf(buf, "<tr><td align='right'>%d</td><td align='right'>%d</td><td align='right'>%d</td><td>%s</td></tr>\r\n",
                    (unsigned long)(perfData.ConnectionAccepted.TotalTime_us / perfData.ConnectionAccepted.Samples),
                    perfData.ConnectionAccepted.Samples,
                    (unsigned long)(perfData.ConnectionAccepted.MaxTime_us),
                    "Connection Accepted");
            svr->send(buf);

            sprintf(buf, "<tr><td align='right'>%d</td><td align='right'>%d</td><td align='right'>%d</td><td>%s</td></tr>\r\n",
                    (unsigned long)(perfData.HeaderParsed.TotalTime_us / perfData.HeaderParsed.Samples),
                    perfData.HeaderParsed.Samples,
                    (unsigned long)(perfData.HeaderParsed.MaxTime_us),
                    "Header Parsed");
            svr->send(buf);
            
            sprintf(buf, "<tr><td align='right'>%d</td><td align='right'>%d</td><td align='right'>%d</td><td>%s</td></tr>\r\n",
                    (unsigned long)(perfData.ResponseSent.TotalTime_us / perfData.ResponseSent.Samples),
                    perfData.ResponseSent.Samples,
                    (unsigned long)(perfData.ResponseSent.MaxTime_us),
                    "Response Sent");
            svr->send(buf);
            
            sprintf(buf, "<tr><td align='right'>%d</td><td align='right'>%d</td><td align='right'>%d</td><td>%s</td></tr>\r\n",
                    (unsigned long)(perfData.ConnectionClosed.TotalTime_us / perfData.ConnectionClosed.Samples),
                    perfData.ConnectionClosed.Samples,
                    (unsigned long)(perfData.ConnectionClosed.MaxTime_us),
                    "Connection Closed");
            svr->send(buf);

            svr->send(
                "<tr><td colspan='3'>&nbsp;</td><td><a href='?Reset=false'>Reload</a>"
                " <a href='?Reset=true'>Reset Metrics</a></td></tr>\r\n"
                "</table>\r\n"
                "</blockquote>\r\n");

            // Send bottom of the page
            svr->send("<br/><a href='/'>back to main</a></body></html>\r\n");
            ret = HTTPServer::ACCEPT_COMPLETE;
            break;
        case HTTPServer::CONTENT_LENGTH_REQUEST:
            INFO("dt: %d, %s", type, path);
            ret = HTTPServer::ACCEPT_COMPLETE;
            break;
        case HTTPServer::DATA_TRANSFER:
            INFO("dt: %d, %s", type, path);
            ret = HTTPServer::ACCEPT_COMPLETE;
            break;
        default:
            INFO("dt: %d, %s", type, path);
            ret = HTTPServer::ACCEPT_ERROR;
            break;
    }
    return ret;
}

/// SimplyDynamicForm
///
/// This web page is generated dynamically and fills in part of the information from
/// data extracted from the URL. It also generates a web form, and allows you to
/// update the data in the form using the POST method. This one also updates the
/// leds on the mbed module based on the form submission, so demonstrates a very
/// simple interaction with the hardware.
///
/// You can see in main how this page was registered.
///
HTTPServer::CallBackResults SimpleDynamicForm(HTTPServer *svr, HTTPServer::CallBackType type, const char * path, const HTTPServer::namevalue *params, int paramcount)
{
    char buf[150];
    const char * p1, *p2;
    HTTPServer::CallBackResults ret = HTTPServer::ACCEPT_ERROR;

    switch (type) {
        case HTTPServer::CONTENT_LENGTH_REQUEST:
            INFO("dt: %d, %s", type, path);
            // this callback asks this handler if it will accept a data transfer.
            ret = HTTPServer::ACCEPT_COMPLETE;
            break;
            
        case HTTPServer::SEND_PAGE:
            INFO("dt: %d, %s", type, path);
            // set the LEDs based on a passed in parameter.
            p1 = svr->GetParameter("leds");
            p2 = svr->GetPostParameter("leds");
            if (p1)
                leds = atoi(p1);
            else if (p2)
                leds = atoi(p2);

            // send the header
            svr->header(200, "OK", svr->GetSupportedType(".htm"));  //svr->header(200, "OK", "Content-Type: text/html\r\n");
            // send some data
            svr->send("<html><head><title>Dynamic Page</title></head>\r\n");
            svr->send("<body>\r\n");
            svr->send("<h1>Smart WiFly Web Server</h1>\r\n");
            svr->send("This form was generated dynamically. You can add name=value pairs on the URL "
                      "which will show up in the form, but the form is submitted using POST method.<br/>\r\n");
            svr->send("Hint: <a href='/led?leds=7&sky=Blue&car=Jaguar'>leds=7&sky=Blue&car=Jaguar</a> turns on"
                      " 3 of the 4 blue leds on the mbed and passes a couple other parameters.<br/>\r\n");
            sprintf(buf, "%d parameters passed to {%s}:<br/>\r\n", paramcount, path);
            svr->send(buf);
            
            // Create a user form for which they can post changes
            sprintf(buf, "POST Form: <form method='post' action='%s'>\r\n", path);
            //sprintf(buf, "<form method='post' enctype='multipart/form-data' action='%s'>\r\n", path); // not supported
            svr->send(buf);
            // show the parameters in a nice format
            svr->send("<table>\r\n");
            
            for (int i=0; i<svr->GetParameterCount(); i++) {
                HTTPServer::namevalue * p = svr->GetParameter(i);
                sprintf(buf, "<tr><td>%d</td><td>%s</td><td><input type='text' name='%s' value='%s'></td></tr>\r\n", 
                    i, p->name, p->name, p->value);
                svr->send(buf);
            }
            for (int i=0; i<svr->GetPostParameterCount(); i++) {
                HTTPServer::namevalue * p = svr->GetPostParameter(i);
                sprintf(buf, "<tr><td>%d</td><td>%s</td><td><input type='text' name='%s' value='%s'></td></tr>\r\n", 
                    i, p->name, p->name, p->value);
                svr->send(buf);
            }

            //svr->send("<tr><td>&nbsp;</td><td>File</td><td><input type='file' name='InFile' size='40'></td></tr>\r\n");
            svr->send("<tr><td>&nbsp;</td><td colspan='2'><input type='submit' value='submit'><input type='reset' value='clear'></td></tr>\r\n");
            svr->send("</table>\r\n");
            svr->send("</form>\r\n");

            // Create a user form for which they can post changes
            sprintf(buf, "GET Form: <form method='get' action='%s'>\r\n", path);
            //sprintf(buf, "<form method='post' enctype='multipart/form-data' action='%s'>\r\n", path); // not supported
            svr->send(buf);
            // show the parameters in a nice format
            svr->send("<table>\r\n");
            for (int i=0; i<paramcount; i++) {
                sprintf(buf, "<tr><td>%d</td><td>%s</td><td><input type='text' name='%s' value='%s'></td></tr>\r\n", 
                    i, 
                    params[i].name, params[i].name, params[i].value);
                svr->send(buf);
            }
            //svr->send("<tr><td>&nbsp;</td><td>File</td><td><input type='file' name='InFile' size='40'></td></tr>\r\n");
            svr->send("<tr><td>&nbsp;</td><td colspan='2'><input type='submit' value='submit'><input type='reset' value='clear'></td></tr>\r\n");
            svr->send("</table>\r\n");
            svr->send("</form>\r\n");

            svr->send("<br/><a href='/'>Back to main</a></body></html>\r\n");
            ret = HTTPServer::ACCEPT_COMPLETE;
            break;
            
        case HTTPServer::DATA_TRANSFER:
            INFO("dt: %d, %s", type, path);
            ret = HTTPServer::ACCEPT_COMPLETE;
            break;
            
        default:
            INFO("dt: %d, %s", type, path);
            ret = HTTPServer::ACCEPT_ERROR;
            break;
    }
    return ret;
}