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
}

Wifly/Wifly.cpp

Committer:
WiredHome
Date:
2013-06-25
Revision:
8:79415e982c32
Parent:
7:b3d740f89f27
Child:
9:86105ba18d96

File content as of revision 8:79415e982c32:

/* 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
 *   It is a lengthy set of small mods, including timeout, refactoring to flush the input
 *   not store after a join, ability to kick up the baud rate, and many more.
 */
#include "mbed.h"
#include "Wifly.h"
#include <string>
#include <algorithm>

//Debug is disabled by default
#if (0 && !defined(TARGET_LPC11U24))
#define DEBUG
#define DBG(x, ...)  std::printf("[DBG Wifly%4d] "x"\r\n", __LINE__, ##__VA_ARGS__);
#define WARN(x, ...) std::printf("[WRN Wifly%4d] "x"\r\n", __LINE__, ##__VA_ARGS__);
#define ERR(x, ...)  std::printf("[ERR Wifly%4d] "x"\r\n", __LINE__, ##__VA_ARGS__);
#define INFO(x, ...) std::printf("[INF Wifly%4d] "x"\r\n", __LINE__, ##__VA_ARGS__);
#else
#define DBG(x, ...)
#define WARN(x, ...)
#define ERR(x, ...)
#define INFO(x, ...)
#endif

#define MAX_TRY_JOIN 3

Wifly * Wifly::inst;

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), buf_wifly(256)
{
    memset(&state, 0, sizeof(state));
    state.sec = sec;

    // change all ' ' in '$' in the ssid and the passphrase
    strcpy(this->ssid, ssid);
    for (int i = 0; i < strlen(ssid); i++) {
        if (this->ssid[i] == ' ')
            this->ssid[i] = '$';
    }
    strcpy(this->phrase, phrase);
    for (int i = 0; i < strlen(phrase); i++) {
        if (this->phrase[i] == ' ')
            this->phrase[i] = '$';
    }

    inst = this;
    attach_rx(false);
    state.cmd_mode = false;
    reset();
    baudrate = 9600;
}


void Wifly::flushIn(int timeout_ms)
{
    Timer tmr;
    tmr.start();
    if (timeout_ms == 0) {
        timeout_ms = 2 * 10000 / baudrate;
        if (timeout_ms == 0)
            timeout_ms = 2;
    }
    while (wifi.readable() || (tmr.read_ms() < timeout_ms)) {
        if (wifi.readable()) {
            tmr.reset();
            tmr.start(); // start should not be necessary
#if defined(DEBUG)
            std::putchar(wifi.getc());
#else
            wifi.getc();
#endif
        }
    }
}


void Wifly::baud(int _baudrate)
{
    char cmd[20];

    baudrate = _baudrate;
    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)) {
        // state.cmd_mode = false;  // see note above why this is disabled
        wifi.baud(baudrate);
    }
}

bool Wifly::join()
{
    char cmd[20];

    for (int i= 0; i < MAX_TRY_JOIN; i++) {
        // no auto join
        if (!sendCommand("set w j 0\r", "AOK"))
            continue;

        //no echo
        if (!sendCommand("set u m 1\r", "AOK"))
            continue;

        // set time
        if (!sendCommand("set c t 30\r", "AOK"))
            continue;

        // set size
        if (!sendCommand("set c s 1420\r", "AOK"))
            continue;

        // red led on when tcp connection active
        if (!sendCommand("set s i 0x40\r", "AOK"))
            continue;

        // no string sent to the tcp client
        if (!sendCommand("set c r 0\r", "AOK"))
            continue;

        // tcp protocol
        if (!sendCommand("set i p 2\r", "AOK"))
            continue;

        // tcp retry
        if (!sendCommand("set i f 0x7\r", "AOK"))
            continue;

        // set dns server
        if (!sendCommand("set d n rn.microchip.com\r", "AOK"))
            continue;

        //dhcp
        sprintf(cmd, "set i d %d\r", (state.dhcp) ? 1 : 0);
        if (!sendCommand(cmd, "AOK"))
            continue;

        // ssid
        sprintf(cmd, "set w s %s\r", ssid);
        if (!sendCommand(cmd, "AOK"))
            continue;

        //auth
        sprintf(cmd, "set w a %d\r", state.sec);
        if (!sendCommand(cmd, "AOK"))
            continue;

        // if no dhcp, set ip, netmask and gateway
        if (!state.dhcp) {
            DBG("not dhcp");

            sprintf(cmd, "set i a %s\r\n", ip);
            if (!sendCommand(cmd, "AOK"))
                continue;

            sprintf(cmd, "set i n %s\r", netmask);
            if (!sendCommand(cmd, "AOK"))
                continue;

            sprintf(cmd, "set i g %s\r", gateway);
            if (!sendCommand(cmd, "AOK"))
                continue;
        }

        //key step
        if (state.sec != NONE) {
            if (state.sec == WPA)
                sprintf(cmd, "set w p %s\r", phrase);
            else if (state.sec == WEP_128)
                sprintf(cmd, "set w k %s\r", phrase);

            if (!sendCommand(cmd, "AOK"))
                continue;
        }

        //join the network (10s timeout)
        if (state.dhcp) {
            if (!sendCommand("join\r", "DHCP=ON", NULL, 0, 10000))
                continue;
        } else {
            if (!sendCommand("join\r", "Associated", NULL, 0, 10000))
                continue;
        }

        //do not store, so it is default on every start
        //if (!sendCommand("save\r", "Stor"))
        //    continue;
        exit();     // exit command mode

        state.associated = true;
        //INFO("\r\nssid: %s\r\nphrase: %s\r\nsecurity: %s\r\n\r\n", this->ssid, this->phrase, getStringSecurity());
        return true;
    }
    return false;
}


bool Wifly::setProtocol(Protocol p)
{
    // use udp auto pairing
    char cmd[20];
    sprintf(cmd, "set i p %d\r", p);
    if (!sendCommand(cmd, "AOK"))
        return false;

    switch(p) {
        case TCP:
            // set ip flags: tcp retry enabled
            if (!sendCommand("set i f 0x07\r", "AOK"))
                return false;
            break;
        case UDP:
            // set ip flags: udp auto pairing enabled
            if (!sendCommand("set i h 0.0.0.0\r", "AOK"))
                return false;
            if (!sendCommand("set i f 0x40\r", "AOK"))
                return false;
            break;
    }
    state.proto = p;
    return true;
}

char * Wifly::getStringSecurity()
{
    switch(state.sec) {
        case NONE:
            return "NONE";
        case WEP_128:
            return "WEP_128";
        case WPA:
            return "WPA";
    }
    return "UNKNOWN";
}

bool Wifly::connect(const char * host, int port)
{
    char rcv[20];
    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, 0, 10000)) {
        state.tcp = true;
        state.cmd_mode = false;
        return true;
    }

    // if failed, retry and parse the response
    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, 0, 10000))
                    return false;
            } else {
                return false;
            }
        }
    } else {
        return false;
    }

    state.tcp = true;
    state.cmd_mode = false;

    return true;
}

void Wifly::setConnectionState(bool value) {
    state.tcp = value;
}



bool Wifly::gethostbyname(const char * host, char * ip, int sizeof_ip)
{
    string h = host;
    char cmd[30], rcv[100];
    int l = 0;
    char * point;
    int nb_digits = 0;

    // no dns needed
    int pos = h.find(".");
    if (pos != string::npos) {
        string sub = h.substr(0, h.find("."));
        nb_digits = atoi(sub.c_str());
    }
    //printf("substrL %s\r\n", sub.c_str());
    if (count(h.begin(), h.end(), '.') == 3 && nb_digits > 0) {
        strcpy(ip, host);
    }
    // dns needed
    else {
        nb_digits = 0;
        sprintf(cmd, "lookup %s\r", host);
        if (!sendCommand(cmd, NULL, rcv, sizeof(rcv)))
            return false;

        // look for the ip address
        char * begin = strstr(rcv, "=") + 1;
        for (int i = 0; i < 3; i++) {
            point = strstr(begin + l, ".");
            DBG("str: %s", begin + l);
            l += point - (begin + l) + 1;
        }
        DBG("str: %s", begin + l);
        while(*(begin + l + nb_digits) >= '0' && *(begin + l + nb_digits) <= '9') {
            DBG("digit: %c", *(begin + l + nb_digits));
            nb_digits++;
        }
        if (l + nb_digits <= sizeof_ip) {
            memcpy(ip, begin, l + nb_digits);
            ip[l+nb_digits] = 0;
            DBG("ip from dns: %s", ip);
        } else {
            return false;
        }
    }
    return true;
}


void Wifly::flush()
{
    buf_wifly.flush();
}

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, resSize, timeout) == -1) {
        ERR("sendCommand: cannot %s\r\n", cmd);
        exit();
        return false;
    }
    return true;
}

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 (send("$$$", 3, "CMD") == -1) {
        ERR("cannot enter in cmd mode\r\n");
        exit();
        return false;
    }
    state.cmd_mode = true;
    return true;
}

bool Wifly::disconnect()
{
    // if already disconnected, return
    if (!state.associated)
        return true;

    if (!sendCommand("leave\r", "DeAuth"))
        return false;
    exit();

    state.associated = false;
    return true;

}

bool Wifly::is_connected()
{
    return (tcp_status.read() ==  1) ? true : false;
}


void Wifly::reset()
{
    reset_pin = 0;
    wait_ms(200);
    reset_pin = 1;
    wait_ms(200);
    flushIn();          // clear the reset text
}

bool Wifly::reboot()
{
    // if already in cmd mode, return
    if (!sendCommand("reboot\r"))
        return false;

    wait_ms(300);
    wifi.baud(9600);        // After a reboot, it is back at 9600 baud because we don't store
    baud(baudrate);         // shift it up to where you want it
    exit();                 // exit command mode
    return true;
}

bool Wifly::close()
{
    if (!state.tcp)
        return true;

    if (!sendCommand("close\r", "CLOS"))
        return false;
    exit();

    state.tcp = false;
    return true;
}


int Wifly::putc(char c)
{
    while (!wifi.writeable())
        ;
    return wifi.putc(c);
}


bool Wifly::exit()
{
    flush();
    if (!state.cmd_mode)
        return true;
    if (!sendCommand("exit\r", "EXIT"))
        return false;
    state.cmd_mode = false;
    flush();
    return true;
}


int Wifly::readable()
{
    return buf_wifly.available();
}

int Wifly::writeable()
{
    return wifi.writeable();
}

char Wifly::getc()
{
    char c;
    while (!buf_wifly.available())
        ;
    buf_wifly.dequeue(&c);
    return c;
}

void Wifly::handler_rx(void)
{
    //read characters
    while (wifi.readable())
        buf_wifly.queue(wifi.getc());
}

void Wifly::attach_rx(bool callback)
{
    if (!callback)
        wifi.attach(NULL);
    else
        wifi.attach(this, &Wifly::handler_rx);
}


int Wifly::send(const char * str, int len, const char * ACK, char * res, int resSize, int timeout)
{
    char read;
    size_t found = string::npos;
    string checking;
    Timer tmr;
    int result = 0;

    attach_rx(false);

    //We flush the buffer
    flushIn();

#ifdef DEBUG
    char dbuf[100];
    strcpy(dbuf, str);
    char * p = dbuf;
    while (*p && *p >= ' ')
        *p++;
    *p = '\0';
    DBG("send(%s,%d,%s,...,%d)",dbuf,len,ACK,timeout);
#endif

    if (!ACK || !strcmp(ACK, "NO")) {
        for (int i = 0; i < len; i++)
            result = (putc(str[i]) == str[i]) ? result + 1 : result;
    } else {
        tmr.start();
        for (int i = 0; i < len; i++)
            result = (putc(str[i]) == str[i]) ? result + 1 : result;
        while (1) {
            if (tmr.read_ms() > timeout) {
                DBG("  timeout");
                flushIn();

                //DBG("check: %s", checking.c_str());

                result = -1;
                break;
            } else if (wifi.readable()) {
                read = wifi.getc();
                if ( read != '\r' && read != '\n') {
                    checking += read;
                    found = checking.find(ACK);
                    if (found != string::npos) {
                        wait_ms(10);
                        flushIn();
                        break;
                    }
                    // We can "early out" if we got an error response
                    found = checking.find("ERR: ");
                    if (found != string::npos) {
                        wait_ms(10);
                        ERR("  response: %s", checking.c_str());
                        flushIn();
                        result = -1;
                        break;
                    }
                }
            }
        }
        attach_rx(true);
        return result;
    }

    //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 (i < resSize) {
            if (timeout.read() > 2) {
                if (i == 0) {
                    res = NULL;
                    break;
                }
                res[i] = '\0';
                DBG("user str 1: %s", res);
                break;
            } else {
                if (tmr.read_ms() > 300) {
                    res[i] = '\0';
                    DBG("user str: %s", res);
                    break;
                }
                if (wifi.readable()) {
                    tmr.start();
                    read = wifi.getc();

                    // we drop \r and \n
                    if ( read != '\r' && read != '\n') {
                        res[i++] = read;
                        res[i] = '\0';
                    }
                }
            }
        }
        DBG("user str: %s", res);
    }

    //We flush the buffer
    flushIn();

    attach_rx(true);
    return result;
}