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:
Tue Jun 25 16:35:56 2013 +0000
Parent:
7:b3d740f89f27
Child:
9:86105ba18d96
Commit message:
When a pointer to a buffer is passed in to the APIs that can modify that buffer, good practices will also pass the size of that buffer to avoid buffer overrun.

Changed in this revision

Socket/TCPSocketServer.cpp Show annotated file Show diff for this revision Revisions of this file
Socket/UDPSocket.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
WiflyInterface.cpp Show annotated file Show diff for this revision Revisions of this file
--- a/Socket/TCPSocketServer.cpp	Mon Jun 24 19:52:51 2013 +0000
+++ b/Socket/TCPSocketServer.cpp	Tue Jun 25 16:35:56 2013 +0000
@@ -1,102 +1,103 @@
-/* Copyright (C) 2012 mbed.org, MIT License
- *
- * Permission is hereby granted, free of charge, to any person obtaining a copy of this software
- * and associated documentation files (the "Software"), to deal in the Software without restriction,
- * including without limitation the rights to use, copy, modify, merge, publish, distribute,
- * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
- * furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in all copies or
- * substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
- * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
- * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
- * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
- */
-
-/* Modifications by David Smart
- *  bind - don't save and don't reboot, eliminate unecessary delay
- *  accept - change to non-blocking, change the connection state so the close works properly
- */
-
-#include "TCPSocketServer.h"
-#include <string>
-
-TCPSocketServer::TCPSocketServer() {
-}
-
-// Server initialization
-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
-//DS    if (!wifi->sendCommand("save\r", "Stor"))
-//        return -1;
-    
-    // reboot
-//DS    wifi->reboot();
-    
-    // connect the network
-    if (wifi->isDHCP()) {
-        if (!wifi->sendCommand("join\r", "DHCP=ON", NULL, 10000))
-            return -1;
-    } else {
-        if (!wifi->sendCommand("join\r", "Associated", NULL, 10000))
-            return -1;
-    }
-        
-    // exit
-    wifi->exit();
-    
-    //wait(0.2);        //DS Should not be necessary
-    wifi->flush();
-    return 0;
-}
-
-int TCPSocketServer::listen(int backlog) {
-    if (backlog != 1)
-        return -1;
-    return 0;
-}
-
-
-int TCPSocketServer::accept(TCPSocketConnection& connection) {
-    int nb_available = 0, pos = 0;
-    char c;
-    string str;
-    bool o_find = false;
-
-    while (1) {
-        //while(!wifi->readable()); //DS
-        nb_available = wifi->readable();
-        if (nb_available == 0 && !_blocking)      //DS
-            return -1;              //DS
-        for (int i = 0; i < nb_available; i++) {
-            c = wifi->getc();
-            //printf("accept %c\r\n", c);
-            if (c == '*') {
-                o_find = true;
-            }
-            if (o_find && c != '\r' && c != '\n') {
-                str += c;
-                pos = str.find("*OPEN*");
-                if (pos != string::npos) {
-                    //wifi->flush();        //DS this might be damaging inbound content
-                    wifi->setConnectionState(true);
-                    //printf("accept *OPEN*\r\n");
-                    return 0;
-                }
-            }
-        }
-    }
+/* Copyright (C) 2012 mbed.org, MIT License
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy of this software
+ * and associated documentation files (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge, publish, distribute,
+ * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in all copies or
+ * substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+ * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
+ * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+/* Modifications by David Smart
+ *  bind - don't save and don't reboot, eliminate unecessary delay
+ *  accept - change to non-blocking, change the connection state so the close works properly
+ */
+
+#include "TCPSocketServer.h"
+#include <string>
+
+TCPSocketServer::TCPSocketServer() {
 }
+
+// Server initialization
+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
+//DS    if (!wifi->sendCommand("save\r", "Stor"))
+//        return -1;
+    
+    // reboot
+//DS    wifi->reboot();
+    
+    // connect the network
+    if (wifi->isDHCP()) {
+        if (!wifi->sendCommand("join\r", "DHCP=ON", NULL, 0, 10000))
+            return -1;
+    } else {
+        if (!wifi->sendCommand("join\r", "Associated", NULL, 0, 10000))
+            return -1;
+    }
+        
+    // exit
+    wifi->exit();
+    
+    //wait(0.2);        //DS Should not be necessary
+    wifi->flush();
+    return 0;
+}
+
+int TCPSocketServer::listen(int backlog) {
+    if (backlog != 1)
+        return -1;
+    return 0;
+}
+
+
+int TCPSocketServer::accept(TCPSocketConnection& connection) {
+    int nb_available = 0, pos = 0;
+    char c;
+    string str;
+    bool o_find = false;
+
+    while (1) {
+        //while(!wifi->readable()); //DS
+        nb_available = wifi->readable();
+        if (nb_available == 0 && !_blocking)      //DS
+            return -1;              //DS
+        for (int i = 0; i < nb_available; i++) {
+            c = wifi->getc();
+            //printf("accept %c\r\n", c);
+            if (c == '*') {
+                o_find = true;
+            }
+            if (o_find && c != '\r' && c != '\n') {
+                str += c;
+                pos = str.find("*OPEN*");
+                if (pos != string::npos) {
+                    //wifi->flush();        //DS this might be damaging inbound content
+                    wifi->setConnectionState(true);
+                    //printf("accept *OPEN*\r\n");
+                    return 0;
+                }
+            }
+        }
+    }
+}
+
--- a/Socket/UDPSocket.cpp	Mon Jun 24 19:52:51 2013 +0000
+++ b/Socket/UDPSocket.cpp	Tue Jun 25 16:35:56 2013 +0000
@@ -56,10 +56,10 @@
     
     // connect the network
     if (wifi->isDHCP()) {
-        if (!wifi->sendCommand("join\r", "DHCP=ON", NULL, 10000))
+        if (!wifi->sendCommand("join\r", "DHCP=ON", NULL, 0, 10000))
             return -1;
     } else {
-        if (!wifi->sendCommand("join\r", "Associated", NULL, 10000))
+        if (!wifi->sendCommand("join\r", "Associated", NULL, 0, 10000))
             return -1;
     }
         
@@ -157,7 +157,7 @@
     string addr;
     int port;
     if (!endpoint_read) {
-        if (!wifi->sendCommand("get ip\r", NULL, recv))
+        if (!wifi->sendCommand("get ip\r", NULL, recv, sizeof(recv)))
             return false;
         wifi->exit();
         str = recv;
@@ -179,3 +179,4 @@
     }
     return false;
 }
+
--- a/Wifly/Wifly.cpp	Mon Jun 24 19:52:51 2013 +0000
+++ b/Wifly/Wifly.cpp	Tue Jun 25 16:35:56 2013 +0000
@@ -100,7 +100,7 @@
     sprintf(cmd, "set u i %d\r", baudrate);
     // set u i # causes it to exit command mode (manual 2.3.64)
     // but testing indicates that it does not exit command mode.
-    if (sendCommand(cmd, NULL, NULL, 0)) {
+    if (sendCommand(cmd)) {
         // state.cmd_mode = false;  // see note above why this is disabled
         wifi.baud(baudrate);
     }
@@ -192,10 +192,10 @@
 
         //join the network (10s timeout)
         if (state.dhcp) {
-            if (!sendCommand("join\r", "DHCP=ON", NULL, 10000))
+            if (!sendCommand("join\r", "DHCP=ON", NULL, 0, 10000))
                 continue;
         } else {
-            if (!sendCommand("join\r", "Associated", NULL, 10000))
+            if (!sendCommand("join\r", "Associated", NULL, 0, 10000))
                 continue;
         }
 
@@ -257,23 +257,25 @@
     char cmd[20];
 
     // try to open
+    #if defined(DEBUG)
     printf("Wifly::connect(%s,%d)\r\n", host, port);
+    #endif
     sprintf(cmd, "open %s %d\r", host, port);
-    if (sendCommand(cmd, "OPEN", NULL, 10000)) {
+    if (sendCommand(cmd, "OPEN", NULL, 0, 10000)) {
         state.tcp = true;
         state.cmd_mode = false;
         return true;
     }
 
     // if failed, retry and parse the response
-    if (sendCommand(cmd, NULL, rcv, 5000)) {
+    if (sendCommand(cmd, NULL, rcv, sizeof(rcv), 5000)) {
         if (strstr(rcv, "OPEN") == NULL) {
             if (strstr(rcv, "Connected") != NULL) {
                 //wait_ms(250);         //DS This should be unnecessary
                 if (!sendCommand("close\r", "CLOS"))
                     return false;
                 //wait_ms(250);         //DS This should be unnecessary
-                if (!sendCommand(cmd, "OPEN", NULL, 10000))
+                if (!sendCommand(cmd, "OPEN", NULL, 0, 10000))
                     return false;
             } else {
                 return false;
@@ -317,7 +319,7 @@
     else {
         nb_digits = 0;
         sprintf(cmd, "lookup %s\r", host);
-        if (!sendCommand(cmd, NULL, rcv))
+        if (!sendCommand(cmd, NULL, rcv, sizeof(rcv)))
             return false;
 
         // look for the ip address
@@ -349,12 +351,12 @@
     buf_wifly.flush();
 }
 
-bool Wifly::sendCommand(const char * cmd, const char * ack, char * res, int timeout)
+bool Wifly::sendCommand(const char * cmd, const char * ack, char * res, int resSize, int timeout)
 {
     if (!state.cmd_mode) {
         cmdMode();
     }
-    if (send(cmd, strlen(cmd), ack, res, timeout) == -1) {
+    if (send(cmd, strlen(cmd), ack, res, resSize, timeout) == -1) {
         ERR("sendCommand: cannot %s\r\n", cmd);
         exit();
         return false;
@@ -491,7 +493,7 @@
 }
 
 
-int Wifly::send(const char * str, int len, const char * ACK, char * res, int timeout)
+int Wifly::send(const char * str, int len, const char * ACK, char * res, int resSize, int timeout)
 {
     char read;
     size_t found = string::npos;
@@ -556,13 +558,13 @@
         return result;
     }
 
-    //the user wants the result from the command (ACK == NULL, res != NULL)
-    if ( res != NULL) {
+    //the user wants the result from the command (ACK == NULL, res != NULL, resSize > 0)
+    if ( res != NULL && resSize > 0) {
         int i = 0;
         Timer timeout;
         timeout.start();
         tmr.reset();
-        while (1) {
+        while (i < resSize) {
             if (timeout.read() > 2) {
                 if (i == 0) {
                     res = NULL;
@@ -584,6 +586,7 @@
                     // we drop \r and \n
                     if ( read != '\r' && read != '\n') {
                         res[i++] = read;
+                        res[i] = '\0';
                     }
                 }
             }
@@ -597,3 +600,4 @@
     attach_rx(true);
     return result;
 }
+
--- a/Wifly/Wifly.h	Mon Jun 24 19:52:51 2013 +0000
+++ b/Wifly/Wifly.h	Tue Jun 25 16:35:56 2013 +0000
@@ -24,6 +24,9 @@
  * http://dlnmh9ip6v2uc.cloudfront.net/datasheets/Wireless/WiFi/WiFly-RN-UM.pdf
  */
 /* Modifications by David Smart
+ * 25 Jun 2013
+ *  Added other security values
+ * <prior>
  *  baud - added method to crank up the baud rate.
  *  isCmdMode - added a method to find out if it is in command mode
  *  send - documented the timeout parameter
@@ -40,10 +43,15 @@
 
 #define DEFAULT_WAIT_RESP_TIMEOUT 1000
 
-enum Security {
-    NONE = 0,
-    WEP_128 = 1,
-    WPA = 3
+enum Security {     // See Wifly user manual Table 2-13.
+    NONE =      0,
+    WEP_128 =   1,
+    WPA1 =      2,
+    WPA_MIXED = 3,
+    WPA =       3,  // maintained for backward compatibility
+    WPA2_PSK =  4,
+    ADHOC =     6,
+    WPE_64 =    8
 };
 
 enum Protocol {
@@ -204,11 +212,12 @@
     * @param len string length
     * @param ACK string which must be acknowledge by the wifi module. If ACK == NULL, no string has to be acknoledged. (default: "NO")
     * @param res this field will contain the response from the wifi module, result of a command sent. This field is available only if ACK = "NO" AND res != NULL (default: NULL)
+    * @param resSize is the size of the field that res references, to avoid buffer overrun. If res is != NULL resSize is evaluated.
     * @param timeout is the time in msec to wait for the acknowledge
     *
     * @return true if ACK has been found in the response from the wifi module. False otherwise or if there is no response in 5s.
     */
-    int send(const char * str, int len, const char * ACK = NULL, char * res = NULL, int timeout = DEFAULT_WAIT_RESP_TIMEOUT);
+    int send(const char * str, int len, const char * ACK = NULL, char * res = NULL, int resSize = 0, int timeout = DEFAULT_WAIT_RESP_TIMEOUT);
 
     /**
     * Send a command to the wify module. Check if the module is in command mode. If not enter in command mode
@@ -216,11 +225,12 @@
     * @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")
     * @param res this field will contain the response from the wifi module, result of a command sent. This field is available only if ACK = "NO" AND res != NULL (default: NULL)
+    * @param resSize is the size of the field that res references, to avoid buffer overrun. If res is != NULL resSize is evaluated.
     * @param timeout is the time in msec to wait for the acknowledge
     *
     * @returns true if successful
     */
-    bool sendCommand(const char * cmd, const char * ack = NULL, char * res = NULL, int timeout = DEFAULT_WAIT_RESP_TIMEOUT);
+    bool sendCommand(const char * cmd, const char * ack = NULL, char * res = NULL, int resSize = 0, int timeout = DEFAULT_WAIT_RESP_TIMEOUT);
     
     /**
     * Return true if the module is using dhcp
--- a/WiflyInterface.cpp	Mon Jun 24 19:52:51 2013 +0000
+++ b/WiflyInterface.cpp	Tue Jun 25 16:35:56 2013 +0000
@@ -41,7 +41,7 @@
 {
     char * match = 0;
     if (!ip_set) {
-        if (!sendCommand("get ip a\r", NULL, ip_string))
+        if (!sendCommand("get ip a\r", NULL, ip_string, sizeof(ip_string)))
             return NULL;
         exit();
         flush();
@@ -59,4 +59,4 @@
         ip_set = true;
     }
     return ip_string;
-}
\ No newline at end of file
+}