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:
Sun Aug 04 21:30:51 2013 +0000
Parent:
28:b7c1182aed28
Child:
30:f500260463b7
Commit message:
Changes focused on connection reliability. A number of small changes to debug macros, while discovering that something kicks wifly out of command mode. So, the cmdMode() API forces a check. This seems to be a huge improvement.

Changed in this revision

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/Wifly/Wifly.cpp	Sat Jul 27 23:44:05 2013 +0000
+++ b/Wifly/Wifly.cpp	Sun Aug 04 21:30:51 2013 +0000
@@ -97,6 +97,10 @@
         if (!sendCommand("set c s 1420\r", "AOK"))
             continue;
 
+        // set comm idle time to auto-close (sec)
+        //if (!sendCommand("set c i 5\r", "AOK"))
+        //    continue;
+
         // red led on when tcp connection active
         if (!sendCommand("set s i 0x40\r", "AOK"))
             continue;
@@ -294,17 +298,17 @@
         char * begin = strstr(rcv, "=") + 1;
         for (int i = 0; i < 3; i++) {
             point = strstr(begin + l, ".");
-            DBG("str: %s", begin + l);
+            INFO("str: %s", begin + l);
             l += point - (begin + l) + 1;
         }
-        DBG("str: %s", begin + l);
+        INFO("str: %s", begin + l);
         while(*(begin + l + nb_digits) >= '0' && *(begin + l + nb_digits) <= '9') {
-            DBG("digit: %c", *(begin + l + nb_digits));
+            INFO("digit: %c", *(begin + l + nb_digits));
             nb_digits++;
         }
         memcpy(ip, begin, l + nb_digits);
         ip[l+nb_digits] = 0;
-        DBG("ip from dns: %s", ip);
+        INFO("ip from dns: %s", ip);
     }
     return true;
 }
@@ -312,6 +316,19 @@
 
 void Wifly::flush()
 {
+#ifdef DEBUG
+    char chatter[500];
+    int count = 0;
+    char c;
+
+    while (buf_wifly.available()) {
+        buf_wifly.dequeue(&c);
+        chatter[count++] = c;
+    }
+    chatter[count] = '\0';
+    if (count)
+        DBG("Wifly::flush {%s}", chatter);
+#endif
     buf_wifly.flush();
 }
 
@@ -319,18 +336,16 @@
 bool Wifly::sendCommand(const char * cmd, const char * ack, char * res, int timeout)
 {
     int tries = 1;
-    
-    if (!state.cmd_mode) {
-        cmdMode();
-    }
+
     while (tries <= 2) {
-        DBG("sendCommand() try: %d, this: %s", tries, cmd);
+        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
+        ERR("sendCommand: failure %d when sending: %s", tries, cmd);
         tries++;
     }
-    ERR("sendCommand: failed: %s", cmd);
     return false;
 }
 
@@ -338,16 +353,22 @@
 bool Wifly::cmdMode()
 {
     // if already in cmd mode, return
-    if (state.cmd_mode)
-        return true;
-
-    wait_ms(250);   // manual 1.2.1 (250 msec before and after)
+    if (state.cmd_mode) {
+        // 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;
+    }
+    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");
-        exit();
         return false;
     }
     state.cmd_mode = true;
+    INFO("  cmdMode set to true\r\n");
     return true;
 }
 
@@ -400,12 +421,12 @@
 
 bool Wifly::close()
 {
-    wait_ms(100);       // we don't know how long to wait, but not waiting long enough truncates outbound data
+    //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"))
+    if (!sendCommand("close\r", "*CLOS*", NULL, 1000))
         return false;
-    exit();
+    //exit();
     state.tcp = false;
     return true;
 }
@@ -424,6 +445,7 @@
     if (!sendCommand("exit\r", "EXIT"))
         return false;
     state.cmd_mode = false;
+    DBG("exit()\r\n");
     return true;
 }
 
@@ -475,9 +497,9 @@
     Timer tmr;
     int result = 0;
 
-    DBG("send w/timeout %d ms this: %s", timeout, str);
+    //DBG("send w/timeout %d ms this: %s", timeout, str);
     attach_rx(false);
-    flushIn();
+    flushIn(0);
     tmr.start();
     if (!ACK || !strcmp(ACK, "NO")) {
         for (int i = 0; i < len; i++)
@@ -489,7 +511,7 @@
         while (1) {
             if (tmr.read_ms() > timeout) {
                 flushIn();
-                DBG("check: %s", checking.c_str());
+                WARN("Can't find [%s] in [%s]", ACK, checking.c_str());
                 attach_rx(true);
                 return -1;
             } else if (wifi.readable()) {
@@ -498,13 +520,13 @@
                     checking += read;
                     found = checking.find(ACK);
                     if (found != string::npos) {
-                        flushIn(10);
+                        flushIn(5);
                         break;
                     }
                 }
             }
         }
-        DBG("check: {%s}", checking.c_str());
+        DBG(" found: {%s}", checking.c_str());
         attach_rx(true);
         return result;
     }
@@ -518,7 +540,7 @@
                 if (i == 0) {
                     res = NULL;
                 }
-                DBG("timed out");
+                ERR("timeout w/o response to %s", str);
                 break;
             } else {
                 if (wifi.readable()) {
@@ -535,7 +557,6 @@
 
     flushIn();
     attach_rx(true);
-    DBG("result: %d", result)
     return result;
 }
 
@@ -549,20 +570,19 @@
     int c;
 #endif
 
-    if (timeout_ms == 0) {
+    if (timeout_ms < 0) {
         timeout_ms = 2 * 10000 / baudrate;  // compute minimal timeout
-        if (timeout_ms < 2)
-            timeout_ms = 2;
+        if (timeout_ms < 5)
+            timeout_ms = 5;
     }
     tmr.start();
     while (wifi.readable() || (tmr.read_ms() < timeout_ms)) {
         if (wifi.readable()) {
-#ifndef DEBUG
-            wifi.getc();
+#ifdef DEBUG
+            c = wifi.getc();
+            chatter[count++] = c;
 #else
-            c = wifi.getc();
-            if (c != '\r' && c != '\n')
-                chatter[count++] = c;
+            wifi.getc();
 #endif
             tmr.reset();
             tmr.start(); // start should not be necessary
@@ -570,7 +590,8 @@
     }
 #ifdef DEBUG
     chatter[count] = '\0';
-    DBG("Wifly::flushIn(%d) {%s}", timeout_ms, chatter);
+    if (count)
+        DBG("Wifly::flushIn(%d) {%s}", timeout_ms, chatter);
 #endif
 }
 
@@ -611,7 +632,7 @@
                 }
                 // keep trying baudrates between ARM and WiFly
                 if (tryIndex < BRCOUNT) {
-                    DBG(" baud() set to %d", baudrates[tryIndex]);
+                    WARN(" baud() set to %d", baudrates[tryIndex]);
                     wifi.baud(baudrates[tryIndex]);
                 }
                 tryIndex++;
@@ -624,7 +645,7 @@
 }
 
 
-int Wifly::timeToRespond(int stringLen) 
+int Wifly::timeToRespond(int stringLen)
 {
     return 150 + (1 | 10000/baudrate) * stringLen;
 }
@@ -676,7 +697,7 @@
         p += 4;
         swVersion = atof(p);
     }
-    DBG("swVersion: %3.2f, versionString: {%s}", swVersion, wiflyVersionString);
+    INFO("swVersion: %3.2f, versionString: {%s}", swVersion, wiflyVersionString);
 }
 
 
--- a/Wifly/Wifly.h	Sat Jul 27 23:44:05 2013 +0000
+++ b/Wifly/Wifly.h	Sun Aug 04 21:30:51 2013 +0000
@@ -302,7 +302,7 @@
 
     void attach_rx(bool null);
     void handler_rx(void);
-    void flushIn(int timeout_ms = 0);
+    void flushIn(int timeout_ms = -1);
 
     typedef struct STATE {
         bool associated;