It is the project that wifi run on the rtos

Fork of WiflyInterface by Mbed

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers Wifly.cpp Source File

Wifly.cpp

00001 /* Copyright (C) 2012 mbed.org, MIT License
00002  *
00003  * Permission is hereby granted, free of charge, to any person obtaining a copy of this software
00004  * and associated documentation files (the "Software"), to deal in the Software without restriction,
00005  * including without limitation the rights to use, copy, modify, merge, publish, distribute,
00006  * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
00007  * furnished to do so, subject to the following conditions:
00008  *
00009  * The above copyright notice and this permission notice shall be included in all copies or
00010  * substantial portions of the Software.
00011  *
00012  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
00013  * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
00014  * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
00015  * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
00016  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
00017  */
00018 
00019 #include "mbed.h"
00020 #include "Wifly.h"
00021 #include <string>
00022 #include <algorithm>
00023 
00024 //Debug is disabled by default
00025 #if (0 && !defined(TARGET_LPC11U24))
00026 #define DBG(x, ...) std::printf("[Wifly : DBG]"x"\r\n", ##__VA_ARGS__);
00027 #define WARN(x, ...) std::printf("[Wifly : WARN]"x"\r\n", ##__VA_ARGS__);
00028 #define ERR(x, ...) std::printf("[Wifly : ERR]"x"\r\n", ##__VA_ARGS__);
00029 #else
00030 #define DBG(x, ...)
00031 #define WARN(x, ...)
00032 #define ERR(x, ...)
00033 #endif
00034 
00035 #if !defined(TARGET_LPC11U24)
00036 #define INFO(x, ...) printf("[Wifly : INFO]"x"\r\n", ##__VA_ARGS__);
00037 #else
00038 #define INFO(x, ...)
00039 #endif
00040 
00041 #define MAX_TRY_JOIN 3
00042 
00043 Wifly * Wifly::inst;
00044 
00045 Wifly::Wifly(   PinName tx, PinName rx, PinName _reset, PinName tcp_status, const char * ssid, const char * phrase, Security sec):
00046     wifi(tx, rx), reset_pin(_reset), tcp_status(tcp_status), buf_wifly(256)
00047 {
00048     memset(&state, 0, sizeof(state));
00049     state.sec = sec;
00050 
00051     // change all ' ' in '$' in the ssid and the passphrase
00052     strcpy(this->ssid, ssid);
00053     for (int i = 0; i < strlen(ssid); i++) {
00054         if (this->ssid[i] == ' ')
00055             this->ssid[i] = '$';
00056     }
00057     strcpy(this->phrase, phrase);
00058     for (int i = 0; i < strlen(phrase); i++) {
00059         if (this->phrase[i] == ' ')
00060             this->phrase[i] = '$';
00061     }
00062 
00063     inst = this;
00064     attach_rx(false);
00065     state.cmd_mode = false;
00066 }
00067 
00068 bool Wifly::join()
00069 {
00070     char cmd[75];
00071 
00072     for (int i= 0; i < MAX_TRY_JOIN; i++) {
00073 
00074         // no auto join
00075         if (!sendCommand("set w j 0\r", "AOK"))
00076             continue;
00077 
00078         //no echo
00079         if (!sendCommand("set u m 1\r", "AOK"))
00080             continue;
00081 
00082         // set time
00083         if (!sendCommand("set c t 30\r", "AOK"))
00084             continue;
00085 
00086         // set size
00087         if (!sendCommand("set c s 1024\r", "AOK"))
00088             continue;
00089 
00090         // red led on when tcp connection active
00091         if (!sendCommand("set s i 0x40\r", "AOK"))
00092             continue;
00093 
00094         // no string sent to the tcp client
00095         if (!sendCommand("set c r 0\r", "AOK"))
00096             continue;
00097 
00098         // tcp protocol
00099         if (!sendCommand("set i p 2\r", "AOK"))
00100             continue;
00101 
00102         // tcp retry
00103         if (!sendCommand("set i f 0x7\r", "AOK"))
00104             continue;
00105             
00106         // set dns server
00107         if (!sendCommand("set d n rn.microchip.com\r", "AOK"))
00108             continue;
00109 
00110         //dhcp
00111         sprintf(cmd, "set i d %d\r", (state.dhcp) ? 1 : 0);
00112         if (!sendCommand(cmd, "AOK"))
00113             continue;
00114 
00115         // ssid
00116         sprintf(cmd, "set w s %s\r", ssid);
00117         if (!sendCommand(cmd, "AOK"))
00118             continue;
00119 
00120         //auth
00121         sprintf(cmd, "set w a %d\r", state.sec);
00122         if (!sendCommand(cmd, "AOK"))
00123             continue;
00124 
00125         // if no dhcp, set ip, netmask and gateway
00126         if (!state.dhcp) {
00127             DBG("not dhcp\r");
00128 
00129             sprintf(cmd, "set i a %s\r\n", ip);
00130             if (!sendCommand(cmd, "AOK"))
00131                 continue;
00132 
00133             sprintf(cmd, "set i n %s\r", netmask);
00134             if (!sendCommand(cmd, "AOK"))
00135                 continue;
00136 
00137             sprintf(cmd, "set i g %s\r", gateway);
00138             if (!sendCommand(cmd, "AOK"))
00139                 continue;
00140         }
00141 
00142         //key step
00143         if (state.sec != NONE) {
00144             if (state.sec == WPA)
00145                 sprintf(cmd, "set w p %s\r", phrase);
00146             else if (state.sec == WEP_128)
00147                 sprintf(cmd, "set w k %s\r", phrase);
00148 
00149             if (!sendCommand(cmd, "AOK"))
00150                 continue;
00151         }
00152 
00153         //join the network (10s timeout)
00154         if (state.dhcp) {
00155             if (!sendCommand("join\r", "DHCP=ON", NULL, 10000))
00156                 continue;
00157         } else {
00158             if (!sendCommand("join\r", "Associated", NULL, 10000))
00159                 continue;
00160         }
00161 
00162         if (!sendCommand("save\r", "Stor"))
00163             continue;
00164 
00165         exit();
00166 
00167         state.associated = true;
00168         INFO("\r\nssid: %s\r\nphrase: %s\r\nsecurity: %s\r\n\r\n", this->ssid, this->phrase, getStringSecurity());
00169         return true;
00170     }
00171     return false;
00172 }
00173 
00174 
00175 bool Wifly::setProtocol(Protocol p)
00176 {
00177     // use udp auto pairing
00178     char cmd[20];
00179     sprintf(cmd, "set i p %d\r", p);
00180     if (!sendCommand(cmd, "AOK"))
00181         return false;
00182 
00183     switch(p) {
00184         case TCP:
00185             // set ip flags: tcp retry enabled
00186             if (!sendCommand("set i f 0x07\r", "AOK"))
00187                 return false;
00188             break;
00189         case UDP:
00190             // set ip flags: udp auto pairing enabled
00191             if (!sendCommand("set i h 0.0.0.0\r", "AOK"))
00192                 return false;
00193             if (!sendCommand("set i f 0x40\r", "AOK"))
00194                 return false;
00195             break;
00196     }
00197     state.proto = p;
00198     return true;
00199 }
00200 
00201 char * Wifly::getStringSecurity()
00202 {
00203     switch(state.sec) {
00204         case NONE:
00205             return "NONE";
00206         case WEP_128:
00207             return "WEP_128";
00208         case WPA:
00209             return "WPA";
00210     }
00211     return "UNKNOWN";
00212 }
00213 
00214 bool Wifly::connect(const char * host, int port)
00215 {
00216     char rcv[20];
00217     char cmd[20];
00218 
00219     // try to open
00220     sprintf(cmd, "open %s %d\r", host, port);
00221     if (sendCommand(cmd, "OPEN", NULL, 10000)) {
00222         state.tcp = true;
00223         state.cmd_mode = false;
00224         return true;
00225     }
00226 
00227     // if failed, retry and parse the response
00228     if (sendCommand(cmd, NULL, rcv, 5000)) {
00229         if (strstr(rcv, "OPEN") == NULL) {
00230             if (strstr(rcv, "Connected") != NULL) {
00231                 wait(0.25);
00232                 if (!sendCommand("close\r", "CLOS"))
00233                     return false;
00234                 wait(0.25);
00235                 if (!sendCommand(cmd, "OPEN", NULL, 10000))
00236                     return false;
00237             } else {
00238                 return false;
00239             }
00240         }
00241     } else {
00242         return false;
00243     }
00244 
00245     state.tcp = true;
00246     state.cmd_mode = false;
00247 
00248     return true;
00249 }
00250 
00251 
00252 bool Wifly::gethostbyname(const char * host, char * ip)
00253 {
00254     string h = host;
00255     char cmd[30], rcv[100];
00256     int l = 0;
00257     char * point;
00258     int nb_digits = 0;
00259 
00260     // no dns needed
00261     int pos = h.find(".");
00262     if (pos != string::npos) {
00263         string sub = h.substr(0, h.find("."));
00264         nb_digits = atoi(sub.c_str());
00265     }
00266     //printf("substrL %s\r\n", sub.c_str());
00267     if (count(h.begin(), h.end(), '.') == 3 && nb_digits > 0) {
00268         strcpy(ip, host);
00269     }
00270     // dns needed
00271     else {
00272         nb_digits = 0;
00273         sprintf(cmd, "lookup %s\r", host);
00274         if (!sendCommand(cmd, NULL, rcv))
00275             return false;
00276 
00277         // look for the ip address
00278         char * begin = strstr(rcv, "=") + 1;
00279         for (int i = 0; i < 3; i++) {
00280             point = strstr(begin + l, ".");
00281             DBG("str: %s", begin + l);
00282             l += point - (begin + l) + 1;
00283         }
00284         DBG("str: %s", begin + l);
00285         while(*(begin + l + nb_digits) >= '0' && *(begin + l + nb_digits) <= '9') {
00286             DBG("digit: %c", *(begin + l + nb_digits));
00287             nb_digits++;
00288         }
00289         memcpy(ip, begin, l + nb_digits);
00290         ip[l+nb_digits] = 0;
00291         DBG("ip from dns: %s", ip);
00292     }
00293     return true;
00294 }
00295 
00296 
00297 void Wifly::flush()
00298 {
00299     buf_wifly.flush();
00300 }
00301 
00302 bool Wifly::sendCommand(const char * cmd, const char * ack, char * res, int timeout)
00303 {
00304     if (!state.cmd_mode) {
00305         if (!cmdMode()) {
00306             return false;
00307         }
00308     }
00309     if (send(cmd, strlen(cmd), ack, res, timeout) == -1) {
00310         ERR("sendCommand: cannot %s\r\n", cmd);
00311         exit();
00312         return false;
00313     }
00314     return true;
00315 }
00316 
00317 bool Wifly::cmdMode()
00318 {
00319     // if already in cmd mode, return
00320     if (state.cmd_mode) {
00321         return true;
00322     }
00323     if (send("$$$", 3, "CMD") == -1) {
00324         if (send("\r\n", 3, ">") == -1) {
00325             ERR("cannot enter in cmd mode\r\n");
00326             exit();
00327             return false;
00328         }
00329     }
00330     state.cmd_mode = true;
00331     return true;
00332 }
00333 
00334 bool Wifly::disconnect()
00335 {
00336     // if already disconnected, return
00337     if (!state.associated)
00338         return true;
00339 
00340     if (!sendCommand("leave\r", "DeAuth"))
00341         return false;
00342     exit();
00343 
00344     state.associated = false;
00345     return true;
00346 
00347 }
00348 
00349 bool Wifly::is_connected()
00350 {
00351     return (tcp_status.read() ==  1) ? true : false;
00352 }
00353 
00354 
00355 void Wifly::reset()
00356 {
00357     reset_pin = 0;
00358     wait(0.2);
00359     reset_pin = 1;
00360     wait(0.2);
00361 }
00362 
00363 bool Wifly::reboot()
00364 {
00365     // if already in cmd mode, return
00366     if (!sendCommand("reboot\r"))
00367         return false;
00368     
00369     wait(0.3);
00370 
00371     state.cmd_mode = false;
00372     return true;
00373 }
00374 
00375 bool Wifly::close()
00376 {
00377     // if not connected, return
00378     if (!state.tcp)
00379         return true;
00380 
00381     wait(0.25);
00382     if (!sendCommand("close\r", "CLOS"))
00383         return false;
00384     exit();
00385 
00386     state.tcp = false;
00387     return true;
00388 }
00389 
00390 
00391 int Wifly::putc(char c)
00392 {
00393     while (!wifi.writeable());
00394     return wifi.putc(c);
00395 }
00396 
00397 
00398 bool Wifly::exit()
00399 {
00400     flush();
00401     if (!state.cmd_mode)
00402         return true;
00403     if (!sendCommand("exit\r", "EXIT"))
00404         return false;
00405     state.cmd_mode = false;
00406     flush();
00407     return true;
00408 }
00409 
00410 
00411 int Wifly::readable()
00412 {
00413     return buf_wifly.available();
00414 }
00415 
00416 int Wifly::writeable()
00417 {
00418     return wifi.writeable();
00419 }
00420 
00421 char Wifly::getc()
00422 {
00423     char c = 0xcc;
00424     while (!buf_wifly.available());
00425     buf_wifly.dequeue(&c);
00426     return c;
00427 }
00428 
00429 void Wifly::handler_rx(void)
00430 {
00431     //read characters
00432     while (wifi.readable())
00433         buf_wifly.queue(wifi.getc());
00434 }
00435 
00436 void Wifly::attach_rx(bool callback)
00437 {
00438     if (!callback)
00439         wifi.attach(NULL);
00440     else
00441         wifi.attach(this, &Wifly::handler_rx);
00442 }
00443 
00444 
00445 int Wifly::send(const char * str, int len, const char * ACK, char * res, int timeout)
00446 {
00447     char read;
00448     size_t found = string::npos;
00449     string checking;
00450     Timer tmr;
00451     int result = 0;
00452 
00453     DBG("will send: %s\r\n",str);
00454 
00455     attach_rx(false);
00456 
00457     //We flush the buffer
00458     while (wifi.readable())
00459         wifi.getc();
00460 
00461     if (!ACK || !strcmp(ACK, "NO")) {
00462         for (int i = 0; i < len; i++)
00463             result = (putc(str[i]) == str[i]) ? result + 1 : result;
00464     } else {
00465         //We flush the buffer
00466         while (wifi.readable())
00467             wifi.getc();
00468 
00469         tmr.start();
00470         for (int i = 0; i < len; i++)
00471             result = (putc(str[i]) == str[i]) ? result + 1 : result;
00472 
00473         while (1) {
00474             if (tmr.read_ms() > timeout) {
00475                 //We flush the buffer
00476                 while (wifi.readable())
00477                     wifi.getc();
00478 
00479                 DBG("check: %s\r\n", checking.c_str());
00480 
00481                 attach_rx(true);
00482                 return -1;
00483             } else if (wifi.readable()) {
00484                 read = wifi.getc();
00485                 if ( read != '\r' && read != '\n') {
00486                     checking += read;
00487                     found = checking.find(ACK);
00488                     if (found != string::npos) {
00489                         wait(0.01);
00490 
00491                         //We flush the buffer
00492                         while (wifi.readable())
00493                             wifi.getc();
00494 
00495                         break;
00496                     }
00497                 }
00498             }
00499         }
00500         DBG("check: %s\r\n", checking.c_str());
00501 
00502         attach_rx(true);
00503         return result;
00504     }
00505 
00506     //the user wants the result from the command (ACK == NULL, res != NULL)
00507     if ( res != NULL) {
00508         int i = 0;
00509         Timer timeout;
00510         timeout.start();
00511         tmr.reset();
00512         while (1) {
00513             if (timeout.read() > 2) {
00514                 if (i == 0) {
00515                     res = NULL;
00516                     break;
00517                 }
00518                 res[i] = '\0';
00519                 DBG("user str 1: %s\r\n", res);
00520 
00521                 break;
00522             } else {
00523                 if (tmr.read_ms() > 300) {
00524                     res[i] = '\0';
00525                     DBG("user str: %s\r\n", res);
00526 
00527                     break;
00528                 }
00529                 if (wifi.readable()) {
00530                     tmr.start();
00531                     read = wifi.getc();
00532 
00533                     // we drop \r and \n
00534                     if ( read != '\r' && read != '\n') {
00535                         res[i++] = read;
00536                     }
00537                 }
00538             }
00539         }
00540         DBG("user str: %s\r\n", res);
00541     }
00542 
00543     //We flush the buffer
00544     while (wifi.readable())
00545         wifi.getc();
00546 
00547     attach_rx(true);
00548     DBG("result: %d\r\n", result)
00549     return result;
00550 }