WIFI library for WIFI Shield of Seeed Studio

Fork of WiflyInterface by mbed official

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_LPC1768))
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 TARGET_LPC1768
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, const char * ssid, const char * phrase, Security sec):
00046     wifi(tx, rx), 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[20];
00071 
00072     for (int i= 0; i < MAX_TRY_JOIN; i++) {
00073         // set time
00074         if (!sendCommand("set c t 20\r", "AOK"))
00075             continue;
00076 
00077         // set size
00078         if (!sendCommand("set c s 128\r", "AOK"))
00079             continue;
00080 
00081         // red led on when tcp connection active
00082         if (!sendCommand("set s i 0x40\r", "AOK"))
00083             continue;
00084 
00085         // no string sent to the tcp client
00086         if (!sendCommand("set c r 0\r", "AOK"))
00087             continue;
00088 
00089         // tcp protocol
00090         if (!sendCommand("set i p 2\r", "AOK"))
00091             continue;
00092 
00093         // tcp retry
00094         if (!sendCommand("set i f 0x7\r", "AOK"))
00095             continue;
00096 
00097         //no echo
00098         if (!sendCommand("set u m 1\r", "AOK"))
00099             continue;
00100 
00101         // no auto join
00102         if (!sendCommand("set w j 0\r", "AOK"))
00103             continue;
00104 
00105         //dhcp
00106         sprintf(cmd, "set i d %d\r", (state.dhcp) ? 1 : 0);
00107         if (!sendCommand(cmd, "AOK"))
00108             continue;
00109 
00110         // ssid
00111         sprintf(cmd, "set w s %s\r", ssid);
00112         if (!sendCommand(cmd, "AOK"))
00113             continue;
00114 
00115         //auth
00116         sprintf(cmd, "set w a %d\r", state.sec);
00117         if (!sendCommand(cmd, "AOK"))
00118             continue;
00119 
00120         // if no dhcp, set ip, netmask and gateway
00121         if (!state.dhcp) {
00122             DBG("not dhcp\r");
00123 
00124             sprintf(cmd, "set i a %s\r\n", ip);
00125             if (!sendCommand(cmd, "AOK"))
00126                 continue;
00127 
00128             sprintf(cmd, "set i n %s\r", netmask);
00129             if (!sendCommand(cmd, "AOK"))
00130                 continue;
00131 
00132             sprintf(cmd, "set i g %s\r", gateway);
00133             if (!sendCommand(cmd, "AOK"))
00134                 continue;
00135         }
00136 
00137         //key step
00138         if (state.sec != NONE) {
00139             if (state.sec == WPA)
00140                 sprintf(cmd, "set w p %s\r", phrase);
00141             else if (state.sec == WEP_128)
00142                 sprintf(cmd, "set w k %s\r", phrase);
00143 
00144             if (!sendCommand(cmd, "AOK"))
00145                 continue;
00146         }
00147 
00148         //join the network
00149         sprintf(cmd, "join\r");
00150         if (!sendCommand(cmd, "Associated", NULL, 3000))
00151             continue;
00152 
00153         if (state.dhcp) {
00154             if (!sendCommand("", "DHCP=ON", NULL, 3000))
00155                 continue;
00156         }
00157 
00158         exit();
00159 
00160         state.associated = true;
00161         INFO("\r\nssid: %s\r\nphrase: %s\r\nsecurity: %s\r\n\r\n", this->ssid, this->phrase, getStringSecurity());
00162         return true;
00163     }
00164     return false;
00165 }
00166 
00167 
00168 bool Wifly::setProtocol(Protocol p)
00169 {
00170     // use udp auto pairing
00171     char cmd[20];
00172     sprintf(cmd, "set i p %d\r", p);
00173     if (!sendCommand(cmd, "AOK"))
00174         return false;
00175 
00176     switch(p) {
00177         case TCP:
00178             // set ip flags: tcp retry enabled
00179             if (!sendCommand("set i f 0x07\r", "AOK"))
00180                 return false;
00181             break;
00182         case UDP:
00183             // set ip flags: udp auto pairing enabled
00184             if (!sendCommand("set i f 0x40\r", "AOK"))
00185                 return false;
00186             if (!sendCommand("set i h 0.0.0.0\r", "AOK"))
00187                 return false;
00188             if (!sendCommand("set i r 0\r", "AOK"))
00189                 return false;
00190             break;
00191     }
00192     state.proto = p;
00193     return true;
00194 }
00195 
00196 char * Wifly::getStringSecurity()
00197 {
00198     switch(state.sec) {
00199         case NONE:
00200             return "NONE";
00201         case WEP_128:
00202             return "WEP_128";
00203         case WPA:
00204             return "WPA";
00205     }
00206     return "UNKNOWN";
00207 }
00208 
00209 bool Wifly::connect(const char * host, int port)
00210 {
00211     char rcv[20];
00212     char cmd[20];
00213 
00214     // get ip from host and set host
00215     if (gethostbyname(host, rcv)) {
00216         sprintf(cmd, "set i h %s\r", rcv);
00217         if (!sendCommand(cmd, "AOK"))
00218             return false;
00219     } else {
00220         return false;
00221     }
00222 
00223     // set port
00224     sprintf(cmd, "set i r %d\r", port);
00225     if (!sendCommand(cmd, "AOK"))
00226         return false;
00227 
00228     // open
00229     if (sendCommand("open\r", NULL, rcv)) {
00230         if (strstr(rcv, "OPEN") == NULL) {
00231             if (strstr(rcv, "Connected") != NULL) {
00232                 if (!sendCommand("close\r", "CLOS"))
00233                     return false;
00234                 if (!sendCommand("open\r", "OPEN"))
00235                     return false;
00236             } else {
00237                 return false;
00238             }
00239         }
00240     } else {
00241         return false;
00242     }
00243     
00244     state.tcp = true;
00245     state.cmd_mode = false;
00246 
00247     return true;
00248 }
00249 
00250 
00251 bool Wifly::gethostbyname(const char * host, char * ip)
00252 {
00253     string h = host;
00254     char cmd[30], rcv[100];
00255     int l = 0;
00256     char * point;
00257     int nb_digits = 0;
00258 
00259     // no dns needed
00260     int pos = h.find(".");
00261     if (pos != string::npos) {
00262         string sub = h.substr(0, h.find("."));
00263         nb_digits = atoi(sub.c_str());
00264     }
00265     //printf("substrL %s\r\n", sub.c_str());
00266     if (count(h.begin(), h.end(), '.') == 3 && nb_digits > 0) {
00267         strcpy(ip, host);
00268     }
00269     // dns needed
00270     else {
00271         nb_digits = 0;
00272         sprintf(cmd, "lookup %s\r", host);
00273         if (!sendCommand(cmd, NULL, rcv))
00274             return false;
00275 
00276         // look for the ip address
00277         char * begin = strstr(rcv, "=") + 1;
00278         for (int i = 0; i < 3; i++) {
00279             point = strstr(begin + l, ".");
00280             DBG("str: %s", begin + l);
00281             l += point - (begin + l) + 1;
00282         }
00283         DBG("str: %s", begin + l);
00284         while(*(begin + l + nb_digits) >= '0' && *(begin + l + nb_digits) <= '9') {
00285             DBG("digit: %c", *(begin + l + nb_digits));
00286             nb_digits++;
00287         }
00288         memcpy(ip, begin, l + nb_digits);
00289         ip[l+nb_digits] = 0;
00290         DBG("ip from dns: %s", ip);
00291     }
00292     return true;
00293 }
00294 
00295 
00296 void Wifly::flush()
00297 {
00298     buf_wifly.flush();
00299 }
00300 
00301 bool Wifly::sendCommand(const char * cmd, const char * ack, char * res, int timeout)
00302 {
00303     if (!state.cmd_mode) {
00304         cmdMode();
00305     }
00306     if (send(cmd, strlen(cmd), ack, res, timeout) == -1) {
00307         ERR("sendCommand: cannot %s\r\n", cmd);
00308         exit();
00309         return false;
00310     }
00311     return true;
00312 }
00313 
00314 bool Wifly::cmdMode()
00315 {
00316     // if already in cmd mode, return
00317     if (state.cmd_mode)
00318         return true;
00319         
00320     if (send("$$$", 3, "CMD") == -1) {
00321         ERR("cannot enter in cmd mode\r\n");
00322         return false;
00323     }
00324     state.cmd_mode = true;
00325     return true;
00326 }
00327 
00328 bool Wifly::disconnect()
00329 {
00330     // if already disconnected, return
00331     if (!state.associated)
00332         return true;
00333         
00334     if (!sendCommand("leave\r", "DeAuth"))
00335         return false;
00336     exit();
00337     
00338     state.associated = false;
00339     return true;
00340 
00341 }
00342 
00343 bool Wifly::is_connected()
00344 {
00345     return state.tcp;
00346 }
00347 
00348 
00349 void Wifly::reset()
00350 {
00351     // Not available
00352 }
00353 
00354 bool Wifly::close()
00355 {
00356     // if not connected, return
00357     if (!state.tcp)
00358         return true;
00359         
00360     wait(0.25);
00361     if (!sendCommand("close\r", "CLOS"))
00362         return false;
00363     exit();
00364     
00365     state.tcp = false;
00366     return true;
00367 }
00368 
00369 
00370 int Wifly::putc(char c)
00371 {
00372     while (!wifi.writeable());
00373     return wifi.putc(c);
00374 }
00375 
00376 
00377 bool Wifly::exit()
00378 {
00379     flush();
00380     if (!state.cmd_mode)
00381         return true;
00382     if (!sendCommand("exit\r", "EXIT"))
00383         return false;
00384     state.cmd_mode = false;
00385     flush();
00386     return true;
00387 }
00388 
00389 
00390 int Wifly::readable()
00391 {
00392     return buf_wifly.available();
00393 }
00394 
00395 int Wifly::writeable()
00396 {
00397     return wifi.writeable();
00398 }
00399 
00400 char Wifly::getc()
00401 {
00402     char c;
00403     while (!buf_wifly.available());
00404     buf_wifly.dequeue(&c);
00405     return c;
00406 }
00407 
00408 void Wifly::handler_rx(void)
00409 {
00410     //read characters
00411     while (wifi.readable())
00412         buf_wifly.queue(wifi.getc());
00413 }
00414 
00415 void Wifly::attach_rx(bool callback)
00416 {
00417     if (!callback)
00418         wifi.attach(NULL);
00419     else
00420         wifi.attach(this, &Wifly::handler_rx);
00421 }
00422 
00423 
00424 int Wifly::send(const char * str, int len, const char * ACK, char * res, int timeout)
00425 {
00426     char read;
00427     size_t found = string::npos;
00428     string checking;
00429     Timer tmr;
00430     int result = 0;
00431 
00432     DBG("will send: %s\r\n",str);
00433 
00434     attach_rx(false);
00435 
00436     //We flush the buffer
00437     while (wifi.readable())
00438         wifi.getc();
00439 
00440     if (!ACK || !strcmp(ACK, "NO")) {
00441         for (int i = 0; i < len; i++)
00442             result = (putc(str[i]) == str[i]) ? result + 1 : result;
00443     } else {
00444         //We flush the buffer
00445         while (wifi.readable())
00446             wifi.getc();
00447 
00448         tmr.start();
00449         for (int i = 0; i < len; i++)
00450             result = (putc(str[i]) == str[i]) ? result + 1 : result;
00451 
00452         while (1) {
00453             if (tmr.read_ms() > timeout) {
00454                 //We flush the buffer
00455                 while (wifi.readable())
00456                     wifi.getc();
00457 
00458                 DBG("check: %s\r\n", checking.c_str());
00459 
00460                 attach_rx(true);
00461                 return -1;
00462             } else if (wifi.readable()) {
00463                 read = wifi.getc();
00464                 if ( read != '\r' && read != '\n') {
00465                     checking += read;
00466                     found = checking.find(ACK);
00467                     if (found != string::npos) {
00468                         wait(0.01);
00469 
00470                         //We flush the buffer
00471                         while (wifi.readable())
00472                             wifi.getc();
00473 
00474                         break;
00475                     }
00476                 }
00477             }
00478         }
00479         DBG("check: %s\r\n", checking.c_str());
00480 
00481         attach_rx(true);
00482         return result;
00483     }
00484 
00485     //the user wants the result from the command (ACK == NULL, res != NULL)
00486     if ( res != NULL) {
00487         int i = 0;
00488         Timer timeout;
00489         timeout.start();
00490         tmr.reset();
00491         while (1) {
00492             if (timeout.read() > 2) {
00493                 if (i == 0) {
00494                     res = NULL;
00495                     break;
00496                 }
00497                 res[i] = '\0';
00498                 DBG("user str 1: %s\r\n", res);
00499 
00500                 break;
00501             } else {
00502                 if (tmr.read_ms() > 300) {
00503                     res[i] = '\0';
00504                     DBG("user str: %s\r\n", res);
00505 
00506                     break;
00507                 }
00508                 if (wifi.readable()) {
00509                     tmr.start();
00510                     read = wifi.getc();
00511 
00512                     // we drop \r and \n
00513                     if ( read != '\r' && read != '\n') {
00514                         res[i++] = read;
00515                     }
00516                 }
00517             }
00518         }
00519         DBG("user str: %s\r\n", res);
00520     }
00521 
00522     //We flush the buffer
00523     while (wifi.readable())
00524         wifi.getc();
00525 
00526     attach_rx(true);
00527     DBG("result: %d\r\n", result)
00528     return result;
00529 }