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:
Sat Mar 01 17:16:55 2014 +0000
Parent:
57:5259cf47106a
Child:
59:8e15d2ca7bd5
Commit message:
Update to support long SSIDs.; Add Wifly module software update API.; Increase time-out to 2500 ms to accommodate Wifly module behavior.; Update documentation.; Clean up dead code.; Revise the debug interface.

Changed in this revision

Socket/TCPSocketServer.cpp 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/TCPSocketServer.cpp	Sat Jan 04 20:56:56 2014 +0000
+++ b/Socket/TCPSocketServer.cpp	Sat Mar 01 17:16:55 2014 +0000
@@ -29,15 +29,22 @@
 {
     char cmd[20];
 
-    wifi->setProtocol(TCP);                 // set TCP protocol
-    sprintf(cmd, "set i l %d\r", port);     // set ip localport #
+    // set TCP protocol
+    wifi->setProtocol(TCP);
+
+    // set ip 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;
-    wifi->reboot();                         // port setting only takes effect after reboot
 
-    // connect to the network
+    // reboot
+    wifi->reboot();
+
+    // connect the network
     if (wifi->isDHCP()) {
         if (!wifi->sendCommand("join\r", "DHCP=ON", NULL, 10000))
             return -1;
@@ -45,7 +52,10 @@
         if (!wifi->sendCommand("join\r", "Associated", NULL, 10000))
             return -1;
     }
+
+    // exit
     wifi->exit();
+
     wait(0.2);
     wifi->flush();
     return 0;
--- a/Wifly/Wifly.cpp	Sat Jan 04 20:56:56 2014 +0000
+++ b/Wifly/Wifly.cpp	Sat Mar 01 17:16:55 2014 +0000
@@ -22,24 +22,33 @@
 #include <algorithm>
 #include <ctype.h>
 
-// Defined to disable remote configuration via telnet which increases security of this device,
-// for Wifly module SW 2.27 and higher.
+// Defined to disable remote configuration via telnet which increases security of this device.
+// Available in Wifly module SW 2.27 and higher. If you want to retain remote telnet, undefine
+// or comment this.
 #define INCREASE_SECURITY
 
-//#define DEBUG       //Debug is disabled by default
+
+#define DEBUG "WiFi"      //Debug is disabled by default
 
+// How to use this debug macro
+//
+// #define DEBUG "myfile"
+// #include "Utility.h"
+// ...
+// INFO("Stuff to show %d", var); // new-line is automatically appended
+// [I myfile  23] Stuff to show 23\r\n
+//
 #if (defined(DEBUG) && !defined(TARGET_LPC11U24))
-#define DBG(x, ...)  std::printf("[DBG Wifly%3d] "x"\r\n", __LINE__, ##__VA_ARGS__);
-#define WARN(x, ...) std::printf("[WRN Wifly%3d] "x"\r\n", __LINE__, ##__VA_ARGS__);
-#define ERR(x, ...)  std::printf("[ERR Wifly%3d] "x"\r\n", __LINE__, ##__VA_ARGS__);
-#define INFO(x, ...) std::printf("[INF Wifly%3d] "x"\r\n", __LINE__, ##__VA_ARGS__);
+#define INFO(x, ...) std::printf("[INF %s %3d] "x"\r\n", DEBUG, __LINE__, ##__VA_ARGS__);
+#define WARN(x, ...) std::printf("[WRN %s %3d] "x"\r\n", DEBUG, __LINE__, ##__VA_ARGS__);
+#define ERR(x, ...)  std::printf("[ERR %s %3d] "x"\r\n", DEBUG, __LINE__, ##__VA_ARGS__);
 #else
-#define DBG(x, ...)
+#define INFO(x, ...)
 #define WARN(x, ...)
 #define ERR(x, ...)
-#define INFO(x, ...)
 #endif
 
+
 #define MAX_TRY_JOIN 3
 
 Wifly * Wifly::inst;
@@ -47,6 +56,7 @@
 Wifly::Wifly(   PinName tx, PinName rx, PinName _reset, PinName tcp_status, const char * ssid, const char * phrase, Security sec):
     wifi(tx, rx), reset_pin(_reset), tcp_status(tcp_status), baudrate(9600), buf_wifly(256)
 {
+    INFO("Wifly constructor");
     memset(&state, 0, sizeof(state));
     state.sec = sec;
 
@@ -55,12 +65,14 @@
 
     inst = this;
     attach_rx(false);
-    setCmdMode(false);
+    state.cmd_mode = false;
     wiflyVersionString = NULL;
+    INFO("  const. exit");
 }
 
 Wifly::~Wifly()
 {
+    INFO("~Wifly()");
     if (ssid) {
         free(ssid);
         ssid = NULL;
@@ -86,7 +98,7 @@
 
 bool Wifly::join()
 {
-    char cmd[20];
+    char cmd[80];   // room for command with maximum ssid or passphrase
 
     INFO("join");
     for (int i= 0; i < MAX_TRY_JOIN; i++) {
@@ -155,8 +167,7 @@
 
         // if no dhcp, set ip, netmask and gateway
         if (!state.dhcp) {
-            DBG("not dhcp");
-
+            INFO("not dhcp");
             sprintf(cmd, "set i a %s\r\n", ip);
             if (!sendCommand(cmd, "AOK"))
                 continue;
@@ -370,13 +381,15 @@
     while (tries <= 2) {
         if (cmdMode()) {      // some influences to the wifi module sometimes kick it out
             if (send(cmd, strlen(cmd), ack, res, timeout) >= 0) {
+                INFO("  sendCommand exit true");
                 return true;
             }
         }
-        setCmdMode(false);     // must not really be in cmd mode
+        state.cmd_mode = false;     // must not really be in cmd mode
         ERR("sendCommand: failure %d when sending: %s", tries, cmd);
         tries++;
     }
+    INFO("  sendCommand exit false");
     return false;
 }
 
@@ -385,6 +398,9 @@
 {
     // if already in cmd mode, return
     if (state.cmd_mode) {
+        #if 1
+        return true;
+        #else  // for deeper debugging
         // Quick verify to ensure we really are in cmd mode
         flushIn(0);
         //INFO("  send \\r to test for cmdMode");
@@ -392,16 +408,18 @@
             //INFO("  is cmdMode");
             return true;
         } else {
-            INFO(" failed to detect command mode");
-            setCmdMode(false);
+            ERR(" failed to detect command mode");
+            state.cmd_mode = false;
         }
+        #endif
+    } else {
+        wait_ms(260);   // manual 1.2.1 (250 msec before and after)
+        if (send("$$$", 3, "CMD") == -1) {  // the module controls the 'after' delay
+            ERR("cannot enter in cmd mode");
+            return false;
+        }
+        state.cmd_mode = true;
     }
-    wait_ms(260);   // manual 1.2.1 (250 msec before and after)
-    if (send("$$$", 3, "CMD") == -1) {  // the module controls the 'after' delay
-        ERR("cannot enter in cmd mode");
-        return false;
-    }
-    setCmdMode(true);
     return true;
 }
 
@@ -434,14 +452,14 @@
     wait_ms(400);
     reset_pin = 1;
     GatherLogonInfo();
+    INFO("swver %3.2f, {%s}", getWiflyVersion(), getWiflyVersionString());
 }
 
 
 bool Wifly::reboot()
 {
     if (sendCommand("reboot\r", "Reboot")) {
-        setCmdMode(false);
-        //INFO("  cmdMode = false");
+        state.cmd_mode = false;
         wait_ms(500);
         wifi.baud(9600);
         baud(baudrate);
@@ -466,7 +484,7 @@
     // so we won't bother trying to close which
     // could cause it to open command mode to
     // send the close (which add more 0.5s delays).
-    setCmdMode(false);
+    state.cmd_mode = false;
 #else
     flushIn();
     exit();
@@ -490,7 +508,7 @@
         ERR("  failed to exit.");
         return false;
     }
-    setCmdMode(false);
+    state.cmd_mode = false;
     return true;
 }
 
@@ -509,7 +527,8 @@
 
 char Wifly::getc()
 {
-    char c = 0;
+    char c = 0xCC;  // avoid compiler warning of uninitialized var.
+
     while (!buf_wifly.available())
         ;
     buf_wifly.dequeue(&c);
@@ -549,6 +568,7 @@
     if (!ACK || !strcmp(ACK, "NO")) {
         ;
     } else {
+        //INFO("  .");
         while (1) {
             if (tmr.read_ms() > timeout) {
                 flushIn();
@@ -569,27 +589,29 @@
                 ; // INFO("  waiting %d", tmr.read_ms());
             }
         }
-        //INFO(" found %s.", ACK);
+        INFO(" found %s.", ACK);
         attach_rx(true);
         return result;
     }
 
     //the user wants the result from the command (ACK == NULL, res != NULL)
-    if ( res != NULL) {
+    if (res != NULL) {
         int i = 0;
+        INFO("  get result");
         while (1) {
             if (tmr.read_ms() > timeout) {
                 res[i] = '\0';
                 if (i == 0) {
                     res = NULL;
                 }
-                //INFO("timeout awaiting response to %s", str);
+                INFO("timeout awaiting response to %s", str);
                 //wait_ms(100);
                 break;
             } else {
                 if (wifi.readable()) {
                     read = wifi.getc();
-                    // we drop \r and \n, but should we since it is for user code...
+                    // this used to drop \r and \n, but should we since 
+                    // it is for user code, it should not.
                     //if ( read != '\r' && read != '\n') {
                     res[i++] = read;
                     //}
@@ -599,6 +621,7 @@
     }
     flushIn();
     attach_rx(true);
+    //INFO("  send exit %d", result);
     return result;
 }
 
@@ -665,7 +688,7 @@
                 //INFO("baud() try: %d: %d", tryIndex, _targetBaud);
                 sendCommand(cmd); // shift Wifly to desired speed [it may not respond (see 2.3.64)]
                 flushIn(10);
-                //setCmdMode(false);  // see note above why this is disabled
+                //state.cmd_mode = false;  // see note above why this is disabled
                 wifi.baud(_targetBaud);     // shift the ARM uart to match
                 if (sendCommand("ver\r", "wifly", NULL, 125)) {  // use this to verify communications
                     baudrate = _targetBaud;
@@ -687,12 +710,6 @@
 }
 
 
-int Wifly::timeToRespond(int stringLen)
-{
-    return 150 + (1 | 10000/baudrate) * stringLen;
-}
-
-
 void Wifly::FixPhrase(char ** dst, const char * src)
 {
     *dst = (char *)malloc(strlen(src)+1);
@@ -742,28 +759,49 @@
             p++;
         swVersion = atof(p);
     }
-    INFO("swVersion: %3.2f,\r\nverString: {%s}", swVersion, wiflyVersionString);
+    WARN("swVersion: %3.2f,\r\nverString: {%s}", swVersion, wiflyVersionString);
 }
 
 
 float Wifly::getWiflyVersion()
 {
+    INFO("swVersion: %3.2f", swVersion);
     return swVersion;
 }
 
 
 char * Wifly::getWiflyVersionString()
 {
+    INFO("version string: %s", wiflyVersionString);
     return wiflyVersionString;
 }
 
+bool Wifly::SWUpdateWifly()
+{
+    bool success = false;
+    
+    if (is_connected()) {
+        // once connected, send command to update firmware
+        if (sendCommand("set ftp address 0\r", "AOK")) {
+            if (sendCommand("set dns name rn.microchip.com\r", "AOK")) {
+                if (sendCommand("save\r", "Stor")) {
+                    if (sendCommand("ftp update\r", "FTP OK", NULL, 30000)) {
+                        if (sendCommand("factory RESET\r")) {
+                            if (reboot()) {
+                                success = true;
+                            }
+                        }
+                    }
+                }
+            }
+        }
+    }
+    return success;
+}
+
 
 void Wifly::setConnectionState(bool value)
 {
     state.tcp = value;
 }
 
-void Wifly::setCmdMode(bool newState)
-{
-    state.cmd_mode = newState;
-}
--- a/Wifly/Wifly.h	Sat Jan 04 20:56:56 2014 +0000
+++ b/Wifly/Wifly.h	Sat Mar 01 17:16:55 2014 +0000
@@ -31,7 +31,7 @@
 #include "RawSerial.h"
 #include "CBuffer.h"
 
-#define DEFAULT_WAIT_RESP_TIMEOUT 1000
+#define DEFAULT_WAIT_RESP_TIMEOUT 2500
 
 enum Security {     // See Wifly user manual Table 2-13.
     NONE        = 0,
@@ -210,11 +210,7 @@
     int send(const char * str, int len, const char * ACK = NULL, char * res = NULL, int timeout = DEFAULT_WAIT_RESP_TIMEOUT);
 
     /**
-    * Send a command to the wify module. 
-    *
-    * This will send a command to the module. If the module is not in command mode, this will enter in command mode.
-    * It will not exit command mode automatically (@see exit), however some commands listed in the WiFly User manual,
-    * in different versions of the firmware, will exit command mode.
+    * Send a command to the wify module. Check if the module is in command mode. If not enter in command mode
     *
     * @param str string to be sent
     * @param ACK string which must be acknowledge by the wifi module. If ACK == NULL, no string has to be acknoledged. (default: "NO")
@@ -294,7 +290,18 @@
     */
     float getWiflyVersion();
 
-
+    /**
+    * Update the software in the Wifly module.
+    *
+    * This attempts to connect to the microchip site, download
+    * a software update, install it as the primary image, and 
+    * reboot to activate that image. It is compile-time defined
+    * to try for 30 seconds.
+    *
+    * @return true if success or false for failure.
+    */
+    bool SWUpdateWifly();
+    
     /**
     * determine if the module is in command mode
     *
@@ -304,17 +311,12 @@
         return state.cmd_mode;
     }
 
-
     static Wifly * getInstance() {
         return inst;
     };
 
 protected:
-    #ifdef MODSERIAL_H
-    MODSERIAL wifi;
-    #else
     RawSerial wifi;
-    #endif
     DigitalOut reset_pin;
     DigitalIn tcp_status;
     int baudrate;
@@ -345,21 +347,6 @@
     State state;
     char * getStringSecurity();
     
-    void setCmdMode(bool newState);
-    
-    /**
-    * Estimates the time needed for the Wifly module to respond
-    * to some of the simple commands.
-    *
-    * This should only be used for simple commands, where the module should
-    * be able to respond almost immediately.
-    *
-    * @param stringLen of the command to be sent, in characters.
-    *
-    * @return integer number of milliseconds (always rounded up a little)
-    */
-    int timeToRespond(int stringLen);
-
     /**
     * Allocate space for the parameter (ssid or passphrase)
     * and then fix it (change ' ' to '$').