Added monitoring feature of ESP8266's UART

Dependents:   ESP8266_W7500_Example DualNetworkInterface-Basic

Fork of ESP8266Interface by ESP8266

ESP8266/ESP8266.cpp

Committer:
michaeljkoster
Date:
2014-12-01
Revision:
16:3f0efaa57a12
Parent:
15:37a7a56a424f
Child:
17:d11fa4c3ac65

File content as of revision 16:3f0efaa57a12:

/* 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 "ESP8266.h"
#include "Endpoint.h"
#include <string>
#include <algorithm>

//Debug is disabled by default
#if (defined(DEBUG))
#define DBG(x, ...) std::printf("[ESP8266 : DBG]"x"\r\n", ##__VA_ARGS__);
#define WARN(x, ...) std::printf("[ESP8266 : WARN]"x"\r\n", ##__VA_ARGS__);
#define ERR(x, ...) std::printf("[ESP8266 : ERR]"x"\r\n", ##__VA_ARGS__);
#else
#define DBG(x, ...)
#define WARN(x, ...)
#define ERR(x, ...)
#endif

#if defined(DEBUG)
#define INFO(x, ...) printf("[ESP8266 : INFO]"x"\r\n", ##__VA_ARGS__);
#else
#define INFO(x, ...)
#endif

#define MAX_TRY_JOIN 3

extern Serial pc;

ESP8266 * ESP8266::inst;

ESP8266::ESP8266(   PinName tx, PinName rx, PinName _reset, const char * ssid, const char * phrase ):
    wifi(tx, rx), reset_pin(_reset), buf_ESP8266(256)
{
    memset(&state, 0, sizeof(state));

    // 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);
    
    wifi.baud(9600); // initial baud rate of the ESP8266 
    pc.printf("ESP8266 test\r\n");
}

bool ESP8266::join()
{
    string cmd="AT+CWJAP=\""+(string)this->ssid+"\",\""+(string)this->phrase+"\"";
    if( sendCommand( cmd.c_str(), "OK", NULL, 10000) ){
        // successfully joined the network
        state.associated = true;
        INFO("\r\nssid: %s\r\nphrase: %s\r\nsecurity: %s\r\n\r\n", this->ssid, this->phrase);
        return true;
    }
    return false;
}

bool ESP8266::connect()
{
    return true;
}

bool ESP8266::is_connected()
{
    return true;
}

bool ESP8266::startUDP(char* ip, int port){
    char* portstr = "";
    sprintf(portstr, "%d", port);
    
    sendCommand(( "AT+CIPSTART=\"UDP\",\"" + (string) ip + "\"" + (string) portstr + "\"").c_str(), "OK", NULL, 10000);
    
    sendCommand("AT+CIPSEND", "OK", NULL, 1000);// go into transparent mode 

    return true;
}

bool ESP8266::close()
{
    sendCommand("AT+CIPCLOSE","OK", NULL, 10000);
    return true;
}

bool ESP8266::disconnect()
{
    // if already disconnected, return
    if (!state.associated)
        return true;
    // send command to quit AP
    sendCommand("AT+CWQAP", "OK", NULL, 10000); 
    state.associated = false;
    return true;
}

char* ESP8266::getIPAddress()
{
    sendCommand("AT+CWLIF", "OK", NULL, 10000);
    return ipString;
}

bool ESP8266::gethostbyname(const char * host, char * ip)
{
    string h = host;
    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);
        return true;
    }
    else {
        // dns needed, not currently available
        return false;
    }
}

void ESP8266::reset()
{
    sendCommand("AT+RST", "ready", NULL, 10000);
    /*
    reset_pin = 0;
    wait(0.2);
    reset_pin = 1;
    wait(0.2);
    */
}

bool ESP8266::reboot()
{
    reset();
    return true;
}

void ESP8266::handler_rx(void)
{
    //read characters
    char c;
    while (wifi.readable()){
        c=wifi.getc();
        buf_ESP8266.queue(c);
        //pc.printf("%c",c);
    }
}

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

int ESP8266::readable()
{
    return buf_ESP8266.available();
}

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

char ESP8266::getc()
{
    char c=0;
    while (!buf_ESP8266.available());
    buf_ESP8266.dequeue(&c);
    return c;
}

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

void ESP8266::flush()
{
    buf_ESP8266.flush();
}

int ESP8266::send(const char * buf, int len)
{
    const char* bufptr=buf;
    while(!wifi.writeable()){}
    for(int i=0; i<len; i++){
        wifi.putc((int)*bufptr++);
        while(!wifi.writeable()){}
    }return true;
}

bool ESP8266::sendCommand(const char * cmd, const char * ACK, char * res, int timeout)
{
    char read;
    size_t found = string::npos;
    string checking;
    Timer tmr;
    int result = 0;

    DBG("will send: %s\r\n",cmd);

    attach_rx(false);

    //We flush the buffer
    while (wifi.readable())
        wifi.getc();
    
    while(!wifi.writeable()){};

    if (!ACK || !strcmp(ACK, "NO")) {
        for (int i = 0; i < sizeof(cmd); i++){
            result = (putc(cmd[i]) == cmd[i]) ? result + 1 : result;
            while(!wifi.writeable()){};
        }
        putc(13); //CR
        while(!wifi.writeable()){};
        putc(10); //LF

    } else {
        //We flush the buffer
        while (wifi.readable())
            wifi.getc();

        tmr.start();
        for (int i = 0; i < sizeof(cmd); i++){
            result = (putc(cmd[i]) == cmd[i]) ? result + 1 : result;
            while(!wifi.writeable()){};
        }
        putc(13); //CR
        while(!wifi.writeable()){};
        putc(10); //LF

        while (1) {
            if (tmr.read_ms() > timeout) {
                //We flush the buffer
                while (wifi.readable())
                    wifi.getc();

                DBG("check: %s\r\n", checking.c_str());

                attach_rx(true);
                return -1;
            } else if (wifi.readable()) {
                read = wifi.getc();
                pc.putc(read);//debug
                if ( read != '\r' && read != '\n') {
                    checking += read;
                    found = checking.find(ACK);
                    if (found != string::npos) {
                        wait(0.01);

                        //We flush the buffer
                        while (wifi.readable())
                            wifi.getc();

                        break;
                    }
                }
            }
        }
        DBG("check: %s\r\n", 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;
        Timer timeout;
        timeout.start();
        tmr.reset();
        while (1) {
            if (timeout.read() > 2) {
                if (i == 0) {
                    res = NULL;
                    break;
                }
                res[i] = '\0';
                DBG("user str 1: %s\r\n", res);

                break;
            } else {
                if (tmr.read_ms() > 300) {
                    res[i] = '\0';
                    DBG("user str: %s\r\n", res);

                    break;
                }
                if (wifi.readable()) {
                    tmr.start();
                    read = wifi.getc();

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

    //We flush the buffer
    while (wifi.readable())
        wifi.getc();

    attach_rx(true);
    DBG("result: %d\r\n", result)
    return result;
}

void ESP8266::ATcommand(char* command){
    char* cmd=command;
    while(!wifi.writeable() || wifi.readable()){}
    while(*cmd){
        wifi.putc((int)*cmd++);
        wait(.005); // wait for the echo
        while(!wifi.writeable() || wifi.readable()){}
    }
    wifi.putc(13); //CR
    while(!wifi.writeable() || wifi.readable()){}
    wifi.putc(10); //LF
}