MODIFIED from mbed official WiflyInterface (interface for Roving Networks Wifly modules). Numerous performance and reliability improvements (see the detailed documentation). Also, tracking changes in mbed official version to retain functional parity.

Dependents:   Smart-WiFly-WebServer PUB_WiflyInterface_Demo

Fork of WiflyInterface by mbed official

Resources

Derivative from mbed Official

  • Documentation update, improved consistency, documented parameters that were inadvertently omitted.
  • Avoid c++ string handling, which causes dynamic allocation and free, side effect, fewer CPU cycles spent for same purpose.
  • Fixed socket APIs to support non-blocking mode.
  • Increase communication baud-rate to Wifly module
  • sendCommand - added retries for improved robustness.
  • setConnectionState - method to force the connection state (used by TCPSocketServer)
  • gethostbyname - added a length parameter to the size of the buffer being written
  • flushIn - a private method to flush the input buffer
  • Changed the timeout from 500 to 2500 msec for commands - measured some at 700 to 850 msec.
  • Performance improvements - reduced some unnecessary delays.
  • Added additional security options for the wi-fi connection (that are supported by the WiFly module).
  • Added setSecurity API which permits revising the security when connecting to, or selecting from, one of several access points.
  • Improved DEBUG interface (slightly more consistent printout).
  • gathers information from the Wifly module on reboot (SW version info), which permits customizing behavior based on Wifly capabilities (like the improved security).
  • Avoid potential for recursive crash (if exit fails, it calls sendcommand, which calls exit...)
  • Update to support permissible SSID and PassCode lengths.

Robustness testing

I've had some mixed behavior with the Wifly module, some of which seems to be traceable to the module itself, and some in my derivative code. The result, after running for minutes, hours, sometimes days, it hangs and I have to reset the module.

To test, I created a fairly simple test program -

  • check for Watchdog induced reset and count it.
  • initialize the Watchdog for 60 sec timeout.
  • Init the Wifly interface and connect to my network.
  • Wait 10 seconds and force mbed_reset().

If the Watchdog induces the restart, then it is pretty clear that either:

  • The communications hung with the Wifly module causing the failure.
  • The Wifly module decided to go unresponsive.

If it gets to the end, it typically takes about 4 to 6 seconds for the boot and connect, then the 10 second delay.

But I can't really pin down the root cause easily. My strongest theory is that the Wifly module has rebooted, and since I don't store the high baud rate I configure it for, it resets back to 9600.

Also, one of the objectives for my revised send( ) is to avoid the c++ string, as that can fragment memory, and it wasn't very well bounded in behavior.

Latest tests:

Warm BootsWatchdog EventsNotes
100's30An early version of my derivative WiflyInterface, including my derivative of "send( )" API. Let's call this version 0.1.
26684My derivative WiflyInterface, but with the mbed official "send( )" API. Much improved. This was over the course of about 12 hours.
24003Most recent derivative - incremental change to "send( )", but this relative number does not rule out the Wifly module itself.

I think with these numbers, +/- 1 means that the changes have had no measurable effect. Which is good, since this incremental change eliminates the c++ string handling.

Test Software

This is pieces of a test program, clipped and copied to here. What I have compiled and run for hours and hours is almost exactly what you see. This uses this simple Watchdog library.

#include "mbed.h"
#include "WiflyInterface.h"
#include "Watchdog.h"

Serial pc(USBTX, USBRX);

Watchdog wd;
extern "C" void mbed_reset();

// Pinout for SmartBoard
WiflyInterface wifly(p9, p10, p30, p29, "ssid", "pass", WPA);

int main() {
    pc.baud(460800);                         // I like a snappy terminal
    
    wd.Configure(60.0);                     // Set time limit for the test to 1 minute
    LPC_RTC->GPREG0++;                      // Count boots here
    if (wd.WatchdogCausedReset()) {
        LPC_RTC->GPREG1++;                  // Count Watchdog events here
        pc.printf("\r\n\r\nWatchdog event.\r\n");
    }
    pc.printf("\r\nWifly Test: %d boots, %d watchdogs. %s %s\r\n", LPC_RTC->GPREG0, LPC_RTC->GPREG1, __DATE__, __TIME__);
    
    wifly.init(); // use DHCP
    pc.printf("Connect...  ");
    while (!wifly.connect());               // join the network
    pc.printf("Address is %s.  ", wifly.getIPAddress());
    pc.printf("Disconnect...  ");
    wifly.disconnect();
    pc.printf("OK. Reset in 10 sec...\r\n");
    wait(10);
    if (pc.readable()) {
        if (pc.getc() == 'r') {             // secret 'r'eset of the counters
            LPC_RTC->GPREG0 = 0;
            LPC_RTC->GPREG1 = 0;
            pc.printf("counters reset\r\n");
        }
    }
    mbed_reset();                           // reset here indicates successful communication
}

Files at this revision

API Documentation at this revision

Comitter:
WiredHome
Date:
Thu Sep 05 22:56:33 2013 +0000
Parent:
33:25958bf80481
Child:
35:2dc12224cbd6
Commit message:
Major change is in how to checks for expected response. Prior code used the C++ string method of concatenation, which could continue to allocate memory to exhaustion, even if it was only interested in a few character response.

Changed in this revision

Socket/Socket.cpp Show annotated file Show diff for this revision Revisions of this file
Socket/TCPSocketServer.cpp Show annotated file Show diff for this revision Revisions of this file
Socket/TCPSocketServer.h Show annotated file Show diff for this revision Revisions of this file
Wifly/Wifly.cpp Show annotated file Show diff for this revision Revisions of this file
Wifly/Wifly.h Show annotated file Show diff for this revision Revisions of this file
--- a/Socket/Socket.cpp	Sun Sep 01 19:17:15 2013 +0000
+++ b/Socket/Socket.cpp	Thu Sep 05 22:56:33 2013 +0000
@@ -27,8 +27,8 @@
 
 void Socket::set_blocking(bool blocking, unsigned int timeout) {
     _blocking = blocking;
-    if (timeout < 10)
-        _timeout = 10;
+    if (timeout < 1)
+        _timeout = 1;
     else
         _timeout = timeout;
 }
--- a/Socket/TCPSocketServer.cpp	Sun Sep 01 19:17:15 2013 +0000
+++ b/Socket/TCPSocketServer.cpp	Thu Sep 05 22:56:33 2013 +0000
@@ -19,27 +19,31 @@
 #include "TCPSocketServer.h"
 #include <string>
 
-TCPSocketServer::TCPSocketServer() {}
+TCPSocketServer::TCPSocketServer()
+{
+    acceptIndex = 0;
+}
 
 // Server initialization
-int TCPSocketServer::bind(int port) {
+int TCPSocketServer::bind(int port)
+{
     char cmd[20];
-    
+
     // set TCP protocol
     wifi->setProtocol(TCP);
-    
+
     // set local port
     sprintf(cmd, "set i l %d\r", port);
     if (!wifi->sendCommand(cmd, "AOK"))
         return -1;
-    
+
     // save
     if (!wifi->sendCommand("save\r", "Stor"))
         return -1;
-    
+
     // reboot
     wifi->reboot();
-    
+
     // connect the network
     if (wifi->isDHCP()) {
         if (!wifi->sendCommand("join\r", "DHCP=ON", NULL, 10000))
@@ -48,28 +52,42 @@
         if (!wifi->sendCommand("join\r", "Associated", NULL, 10000))
             return -1;
     }
-        
+
     // exit
     wifi->exit();
-    
+
     wait(0.2);
     wifi->flush();
     return 0;
 }
 
-int TCPSocketServer::listen(int backlog) {
+int TCPSocketServer::listen(int backlog)
+{
     if (backlog != 1)
         return -1;
     return 0;
 }
 
-
-int TCPSocketServer::accept(TCPSocketConnection& connection) {
-    int nb_available = 0, pos = 0;
+// sometimes simply "*OPEN*"
+// and sometimes a prior connection closes too "*CLOS**OPEN*"
+// when accepting a connection from a browser, it can be
+// *CLOS**OPEN*GET / HTTP/1.1
+// The point here is to remove everything to the left
+// of, and including, "*OPEN*".
+//
+// The c++ string operation has a potential problem in that
+// it will keep allocating memory (see "str += c;") until
+// the pattern is satisfied. And since we know exactly what 
+// it is looking for a less memory intensive method works.
+int TCPSocketServer::accept(TCPSocketConnection& connection)
+{
+    int nb_available = 0;
+    //pos = 0;
     char c;
-    string str;
-    bool o_find = false;
-    
+    //string str;
+    //bool o_find = false;
+    const char OPEN[] = "*OPEN*";   // seeking this to accept
+
     acceptTimerStart();
     while (1) {
         nb_available = wifi->readable();
@@ -77,6 +95,18 @@
             return -1;
         for (int i = 0; i < nb_available; i++) {
             c = wifi->getc();
+#if 1
+            if (c == OPEN[acceptIndex]) {
+                acceptIndex++;
+                if (acceptIndex == strlen(OPEN)) {
+                    wifi->setConnectionState(true);
+                    acceptIndex = 0;    // for next pass
+                    return 0;
+                }
+            } else {
+                acceptIndex = 0;
+            }
+#else
             if (c == '*') {
                 o_find = true;
             }
@@ -85,10 +115,11 @@
                 pos = str.find("*OPEN*");
                 if (pos != string::npos) {
                     wifi->setConnectionState(true);
-                    wifi->flush();
+                    //wifi->flush(); // don't remove more
                     return 0;
                 }
             }
+#endif
         }
     }
 }
--- a/Socket/TCPSocketServer.h	Sun Sep 01 19:17:15 2013 +0000
+++ b/Socket/TCPSocketServer.h	Thu Sep 05 22:56:33 2013 +0000
@@ -43,8 +43,12 @@
     int listen(int backlog=1);
     
     /** Accept a new connection.
-    \param connection A TCPSocketConnection instance that will handle the incoming connection.
-    \return 0 on success, -1 on failure.
+    *
+    * For the Wifly module, this looks for *OPEN* in the stream, and
+    * then indicates success.
+    *
+    * \param connection A TCPSocketConnection instance that will handle the incoming connection.
+    * \return 0 on success, -1 on failure.
     */
     int accept(TCPSocketConnection& connection);
     
@@ -53,6 +57,7 @@
     
     void acceptTimerStart();
     bool acceptTimeout();
+    int acceptIndex;
 };
 
 #endif
--- a/Wifly/Wifly.cpp	Sun Sep 01 19:17:15 2013 +0000
+++ b/Wifly/Wifly.cpp	Thu Sep 05 22:56:33 2013 +0000
@@ -53,7 +53,7 @@
 
     inst = this;
     attach_rx(false);
-    state.cmd_mode = false;
+    setCmdMode(false);
     wiflyVersionString = NULL;
 }
 
@@ -357,12 +357,14 @@
 {
     int tries = 1;
 
+    INFO("sendCommand %s", cmd);
     while (tries <= 2) {
         cmdMode();      // some influences to the wifi module sometimes kick it out
         if (send(cmd, strlen(cmd), ack, res, timeout) >= 0) {
             return true;
         }
-        state.cmd_mode = false;     // must not really be in cmd mode
+        setCmdMode(false);     // must not really be in cmd mode
+        INFO("  cmdMode = false");
         ERR("sendCommand: failure %d when sending: %s", tries, cmd);
         tries++;
     }
@@ -377,18 +379,17 @@
         // Quick verify to ensure we really are in cmd mode
         flushIn(0);
         if (send("\r", 1, ">") == 1) {
-            INFO("  cmdMode = true\r\n");
             return true;
-        } else
-            state.cmd_mode = false;
+        } else {
+            setCmdMode(false);
+        }
     }
     wait_ms(260);   // manual 1.2.1 (250 msec before and after)
     if (send("$$$", 3, "CMD") == -1) {
-        ERR("cannot enter in cmd mode\r\n");
+        ERR("cannot enter in cmd mode");
         return false;
     }
-    state.cmd_mode = true;
-    INFO("  cmdMode set to true\r\n");
+    setCmdMode(true);
     return true;
 }
 
@@ -427,7 +428,8 @@
 bool Wifly::reboot()
 {
     if (sendCommand("reboot\r", "Reboot")) {
-        state.cmd_mode = false;
+        setCmdMode(false);
+        INFO("  cmdMode = false");
         wait_ms(500);
         wifi.baud(9600);
         baud(baudrate);
@@ -441,14 +443,23 @@
 
 bool Wifly::close()
 {
-    //wait_ms(100);       // we don't know how long to wait, but not waiting long enough truncates outbound data
     if (!state.tcp)
-        return true;
-    if (!sendCommand("close\r", "*CLOS*", NULL, 1000))
-        return false;
-    //exit();
+        return true;    // already closed
+    if (!sendCommand("close\r", "*CLOS*"))
+        return false;   // failed to close
+    #if 1
+    // It appears that the close exits cmd mode
+    // so we won't both trying to close which
+    // could cause it to open command mode to
+    // send the close (which add more 0.25s
+    // delays).
+    setCmdMode(false);
+    #else
+    flushIn();
+    exit();
+    #endif
     state.tcp = false;
-    return true;
+    return true;        // succeeded to close
 }
 
 
@@ -462,10 +473,11 @@
 
 bool Wifly::exit()
 {
-    if (!sendCommand("exit\r", "EXIT"))
+    if (!sendCommand("exit\r", "EXIT")) {
+        ERR("  failed to exit.");
         return false;
-    state.cmd_mode = false;
-    DBG("exit()\r\n");
+    }
+    setCmdMode(false);
     return true;
 }
 
@@ -512,14 +524,15 @@
 int Wifly::send(const char * str, int len, const char * ACK, char * res, int timeout)
 {
     char read;
-    size_t found = string::npos;
-    string checking;
+    //size_t found = string::npos;
+    //string checking;
+    int ackIndex = 0;
     Timer tmr;
     int result = 0;
 
-    //DBG("send w/timeout %d ms this: %s", timeout, str);
+    //DBG("send: %s", str);
     attach_rx(false);
-    flushIn(0);
+//    flushIn(0);
     tmr.start();
     if (!ACK || !strcmp(ACK, "NO")) {
         for (int i = 0; i < len; i++)
@@ -531,22 +544,33 @@
         while (1) {
             if (tmr.read_ms() > timeout) {
                 flushIn();
-                WARN("Can't find [%s] in [%s]", ACK, checking.c_str());
+                WARN("Can't find [%s] from [%s]", ACK, str);
                 attach_rx(true);
                 return -1;
             } else if (wifi.readable()) {
                 read = wifi.getc();
+                #if 1
+                if (read == ACK[ackIndex]) {
+                    ackIndex++;
+                    if (ackIndex == strlen(ACK))
+                        //flushIn(5);
+                        break;
+                } else {
+                    ackIndex = 0;
+                }
+                #else
                 if ( read != '\r' && read != '\n') {
                     checking += read;
                     found = checking.find(ACK);
                     if (found != string::npos) {
-                        flushIn(5);
+                        flushIn(6);
                         break;
                     }
                 }
+                #endif
             }
         }
-        DBG(" found: {%s}", checking.c_str());
+        DBG(" found %s.", ACK);
         attach_rx(true);
         return result;
     }
@@ -590,17 +614,18 @@
     int c;
 #endif
 
-    if (timeout_ms < 0) {
-        timeout_ms = 2 * 10000 / baudrate;  // compute minimal timeout
-        if (timeout_ms < 5)
-            timeout_ms = 5;
+    if (timeout_ms <= 0) {
+        timeout_ms = 1; // 2 * 10000 / baudrate;  // compute minimal timeout
+        //if (timeout_ms < 5)
+        //    timeout_ms = 5;
     }
     tmr.start();
     while (wifi.readable() || (tmr.read_ms() < timeout_ms)) {
         if (wifi.readable()) {
 #ifdef DEBUG
             c = wifi.getc();
-            chatter[count++] = c;
+            if (count < sizeof(chatter)-1)  // guard overflow
+                chatter[count++] = c;
 #else
             wifi.getc();
 #endif
@@ -643,7 +668,7 @@
             while (tryIndex <= BRCOUNT) {
                 DBG("baud() try: %d", tryIndex);
                 sendCommand(cmd); // shift Wifly to desired speed [it may not respond (see 2.3.64)]
-                // state.cmd_mode = false;  // see note above why this is disabled
+                // setCmdMode(false);  // see note above why this is disabled
                 wifi.baud(_targetBaud);     // shift the ARM uart to match
                 if (sendCommand("ver\r", "wifly", NULL, timeToRespond(4))) {  // use this to verify communications
                     baudrate = _targetBaud;
@@ -738,3 +763,8 @@
     state.tcp = value;
 }
 
+void Wifly::setCmdMode(bool newState)
+{
+    //INFO("setCmdMode(%s)", state ? "true" : "false");
+    state.cmd_mode = newState;
+}
\ No newline at end of file
--- a/Wifly/Wifly.h	Sun Sep 01 19:17:15 2013 +0000
+++ b/Wifly/Wifly.h	Thu Sep 05 22:56:33 2013 +0000
@@ -173,7 +173,7 @@
     bool exit();
 
     /**
-    * Close a tcp connection
+    * Close a tcp connection, and exit command mode.
     *
     * @ returns true if successful
     */
@@ -322,6 +322,8 @@
     State state;
     char * getStringSecurity();
     
+    void setCmdMode(bool newState);
+    
     /**
     * Estimates the time needed for the Wifly module to respond
     * to some of the simple commands.