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
Resources
- SmartBoard - Wifly is a small adapter I created to plug in (another) adapter to my baseboard.
- SmartBoard - Baseboard is a baseboard I designed for a variety of small projects.
- Cookbook - WiflyInterface, especially the "More Details" section.
- Components - WiFly
- Search - WiflyInterface
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 Boots | Watchdog Events | Notes |
100's | 30 | An early version of my derivative WiflyInterface, including my derivative of "send( )" API. Let's call this version 0.1. |
2668 | 4 | My derivative WiflyInterface, but with the mbed official "send( )" API. Much improved. This was over the course of about 12 hours. |
2400 | 3 | Most 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-08-12
- Revision:
- 31:e4422f192d25
- Parent:
- 30:f500260463b7
- Child:
- 32:4543e91ab4bf
File content as of revision 31:e4422f192d25:
/* 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. */ #include "mbed.h" #include "Wifly.h" #include <string> #include <algorithm> // Defined to disable remote configuration via telnet which increases security of this device. #define INCREASE_SECURITY #define DEBUG //Debug is disabled by default #if (defined(DEBUG) && !defined(TARGET_LPC11U24)) #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), baudrate(9600), buf_wifly(256) { memset(&state, 0, sizeof(state)); state.sec = sec; FixPhrase(&this->ssid, ssid); FixPhrase(&this->phrase, phrase); inst = this; attach_rx(false); state.cmd_mode = false; wiflyVersionString = NULL; } Wifly::~Wifly() { if (ssid) { free(ssid); ssid = NULL; } if (phrase) { free(phrase); phrase = NULL; } if (wiflyVersionString) { free(wiflyVersionString); wiflyVersionString = NULL; } } bool Wifly::join() { char cmd[20]; INFO("join"); 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 comm time to flush (ms) if (!sendCommand("set c t 30\r", "AOK")) continue; // set comm size to auto-send 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; // no hello 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 (retry enabled, Nagle alg, retain link) if (!sendCommand("set i f 0x7\r", "AOK")) continue; #ifdef INCREASE_SECURITY // tcp-mode 0x10 = disable remote configuration // only in SW 2.27 and higher (see 2.3.39) if ((swVersion >= 2.27) && (!sendCommand("set i t 0x10\r", "AOK"))) continue; #endif // 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 cmd[0] = '\0'; switch (state.sec) { case WPE_64: // google searching suggests this is a typo and should be WEP_64 case WEP_128: sprintf(cmd, "set w k %s\r", phrase); break; case WPA1: case WPA_MIXED: // alias WPA case WPA2_PSK: sprintf(cmd, "set w p %s\r", phrase); break; case ADHOC: case NONE: default: break; } if (cmd[0] && !sendCommand(cmd, "AOK")) continue; //join the network (10s timeout) if (state.dhcp) { if (!sendCommand("join\r", "DHCP=ON", NULL, 10000)) continue; } else { if (!sendCommand("join\r", "Associated", NULL, 10000)) continue; } if (!sendCommand("save\r", "Stor")) continue; exit(); state.associated = true; // Don't advertise this info //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: // 0 return "NONE"; case WEP_128: // 1 return "WEP_128"; case WPA1: // 2 return "WPA1"; case WPA: // 3 return "WPA"; case WPA2_PSK: // 4 return "WPA2_PSK"; case ADHOC: // 6 return "ADHOC"; case WPE_64: // 8 return "WPE_64"; default: // ? return "UNKNOWN"; } } bool Wifly::connect(const char * host, int port) { char rcv[20]; char cmd[20]; // try to open sprintf(cmd, "open %s %d\r", host, port); if (sendCommand(cmd, "OPEN", NULL, 10000)) { state.tcp = true; exit(); return true; } // if failed, retry and parse the response if (sendCommand(cmd, NULL, rcv, 5000)) { if (strstr(rcv, "OPEN") == NULL) { if (strstr(rcv, "Connected") != NULL) { if (!sendCommand("close\r", "CLOS")) return false; if (!sendCommand(cmd, "OPEN", NULL, 10000)) return false; } else { return false; } } } else { return false; } state.tcp = true; exit(); return true; } bool Wifly::gethostbyname(const char * host, char * 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)) return false; // look for the ip address char * begin = strstr(rcv, "=") + 1; for (int i = 0; i < 3; i++) { point = strstr(begin + l, "."); INFO("str: %s", begin + l); l += point - (begin + l) + 1; } INFO("str: %s", begin + l); while(*(begin + l + nb_digits) >= '0' && *(begin + l + nb_digits) <= '9') { INFO("digit: %c", *(begin + l + nb_digits)); nb_digits++; } memcpy(ip, begin, l + nb_digits); ip[l+nb_digits] = 0; INFO("ip from dns: %s", ip); } return true; } 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(); } bool Wifly::sendCommand(const char * cmd, const char * ack, char * res, int timeout) { int tries = 1; while (tries <= 2) { 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++; } return false; } bool Wifly::cmdMode() { // if already in cmd mode, return 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"); return false; } state.cmd_mode = true; INFO(" cmdMode set to true\r\n"); 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; wifi.baud(9600); wait_ms(200); reset_pin = 1; GatherLogonInfo(); } bool Wifly::reboot() { if (sendCommand("reboot\r", "Reboot")) { state.cmd_mode = false; wait_ms(500); wifi.baud(9600); baud(baudrate); exit(); return true; } else { return false; } } bool Wifly::close() { //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*", NULL, 1000)) return false; //exit(); state.tcp = false; return true; } int Wifly::putc(char c) { while (!wifi.writeable()) ; return wifi.putc(c); } bool Wifly::exit() { if (!sendCommand("exit\r", "EXIT")) return false; state.cmd_mode = false; DBG("exit()\r\n"); 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 timeout) { char read; size_t found = string::npos; string checking; Timer tmr; int result = 0; //DBG("send w/timeout %d ms this: %s", timeout, str); attach_rx(false); flushIn(0); tmr.start(); if (!ACK || !strcmp(ACK, "NO")) { for (int i = 0; i < len; i++) result = (putc(str[i]) == str[i]) ? result + 1 : result; } else { for (int i = 0; i < len; i++) result = (putc(str[i]) == str[i]) ? result + 1 : result; while (1) { if (tmr.read_ms() > timeout) { flushIn(); WARN("Can't find [%s] in [%s]", ACK, checking.c_str()); attach_rx(true); return -1; } else if (wifi.readable()) { read = wifi.getc(); if ( read != '\r' && read != '\n') { checking += read; found = checking.find(ACK); if (found != string::npos) { flushIn(5); break; } } } } DBG(" found: {%s}", checking.c_str()); attach_rx(true); return result; } //the user wants the result from the command (ACK == NULL, res != NULL) if ( res != NULL) { int i = 0; while (1) { if (tmr.read_ms() > timeout) { res[i] = '\0'; if (i == 0) { res = NULL; } INFO("timeout awaiting response to %s", str); break; } else { if (wifi.readable()) { read = wifi.getc(); // we drop \r and \n, but should we since it is for user code... if ( read != '\r' && read != '\n') { res[i++] = read; } } } } DBG("user str: {%s}", res); } flushIn(); attach_rx(true); return result; } void Wifly::flushIn(int timeout_ms) { Timer tmr; #ifdef DEBUG char chatter[500]; int count = 0; int c; #endif if (timeout_ms < 0) { timeout_ms = 2 * 10000 / baudrate; // compute minimal timeout if (timeout_ms < 5) timeout_ms = 5; } tmr.start(); while (wifi.readable() || (tmr.read_ms() < timeout_ms)) { if (wifi.readable()) { #ifdef DEBUG c = wifi.getc(); chatter[count++] = c; #else wifi.getc(); #endif tmr.reset(); tmr.start(); // start should not be necessary } } #ifdef DEBUG chatter[count] = '\0'; if (count) DBG("Wifly::flushIn(%d) {%s}", timeout_ms, chatter); #endif } // The ARM uart and the Wifly uart have to be in sync or we get // no meaningful response, so then have to try the possibilities. // // First try is at the currently configured ARM uart baud, if // that fails then it shifts the ARM uart baud through the probable // speeds, trying to establish contact with the Wifly module. // Once contact is demonstrated (response to the 'ver' command), // then it sets the Wifly module and then the ARM uart. bool Wifly::baud(int _targetBaud) { // in testing, 460800 and 921600 may change the Wifly module where you can't // change it back w/o a reset. So, we won't even permit those speeds. const int baudrates[] = {2400, 4800, 9600, 19200, 38400, 57600, 115200, 230400}; //, 460800, 921600}; #define BRCOUNT (sizeof(baudrates)/sizeof(baudrates[0])) char cmd[20]; // sized for "set u i 460800\r" [15+1], plus margin [4] int tryIndex = 0; bool res = false; int userIndex; sprintf(cmd, "set u i %d\r", _targetBaud); // set u i # should cause it to exit command mode (manual 2.3.64), // but testing indicates that it does not. for (userIndex=0; userIndex < BRCOUNT; userIndex++) { if (_targetBaud == baudrates[userIndex]) { while (tryIndex <= BRCOUNT) { DBG("baud() try: %d", tryIndex); sendCommand(cmd); // shift Wifly to desired speed [it may not respond (see 2.3.64)] // 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, timeToRespond(4))) { // use this to verify communications baudrate = _targetBaud; res = true; break; // success } // keep trying baudrates between ARM and WiFly if (tryIndex < BRCOUNT) { WARN(" baud() set to %d", baudrates[tryIndex]); wifi.baud(baudrates[tryIndex]); } tryIndex++; } break; // if they selected a legitimate baud, try no others } } DBG(" baud() result: %d", res); return res; } int Wifly::timeToRespond(int stringLen) { return 150 + (1 | 10000/baudrate) * stringLen; } void Wifly::FixPhrase(char ** dst, const char * src) { // change all ' ' in '$' in the ssid and the passphrase *dst = (char *)malloc(strlen(src)+1); if (*dst) { strcpy(*dst, src); for (int i = 0; i < strlen(*dst); i++) { if ((*dst)[i] == ' ') (*dst)[i] = '$'; } } else { *dst = NULL; } } void Wifly::GatherLogonInfo() { Timer timer; char logonText[200]; int i = 0; char *p; timer.start(); if (wiflyVersionString) { free(wiflyVersionString); wiflyVersionString = NULL; } logonText[i] = '\0'; while (timer.read_ms() < 500) { while (wifi.readable()) { logonText[i++] = wifi.getc(); } } logonText[i] = '\0'; p = strchr(logonText, '\r'); if (p) *p = '\0'; wiflyVersionString = (char *)malloc(strlen(logonText)+1); if (wiflyVersionString) strcpy(wiflyVersionString, logonText); p = strstr(logonText, "Ver "); if (p) { p += 4; swVersion = atof(p); } INFO("swVersion: %3.2f, versionString: {%s}", swVersion, wiflyVersionString); } float Wifly::getWiflyVersion() { return swVersion; } char * Wifly::getWiflyVersionString() { return wiflyVersionString; } void Wifly::setConnectionState(bool value) { state.tcp = value; }