David Smart / WiflyInterface Featured

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
}
Revision:
58:f49aab8072ec
Parent:
56:eba4aabaad3e
Child:
59:8e15d2ca7bd5
diff -r 5259cf47106a -r f49aab8072ec Wifly/Wifly.cpp
--- 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;
-}