ESP8266 ESP-01 moduel WiFi client demo with LPC1768

Dependencies:   BreathLed BufferedSerial ESP8266 mbed

main.cpp

Committer:
steeven
Date:
2015-05-03
Revision:
0:1e99d872e742

File content as of revision 0:1e99d872e742:

#include "mbed.h"
#include "BreathLed/BreathLed.h"
#include "ESP8266/Esp8266.h"
#include "BufferedSerial/BufferedSerial.h"

using namespace steeven;

/*
 * ESP8266 demo that:
 * 1. accept host name from console, print http request result
 * 2. print AT command result from console
 * Press user button on LPC1768 to switch mode and debug level, see console prompt
 */

BreathLed led4(LED4);
DigitalOut led1(LED1); //0:no log, 1:log
DigitalOut led2(LED2); //2:dbg 1, 3:dbg 2
DigitalOut led3(LED3); //input host or cmd
InterruptIn btn(P2_8); //UBTN

BufferedSerial pc(USBTX, USBRX, 256, 20);
Esp8266 wifi(p28, p27, p29, p26);

void on_btn(void) {

    int n = (led3 << 2) + (led2 << 1) + led1;
    n++;
    led3 = (n >> 2) & 1;
    led2 = (n >> 1) & 1;
    led1 = (n >> 0) & 1;
    wifi.set_log((n & 7) > 0 ? &pc : NULL, (n & 3) - 1);
    if (wifi._dbg == -1)
        wifi.set_log(wifi._logger, 0);
    pc.printf("log:%d dbg:%d mode:%s\n", wifi._logger == NULL ? 0 : 1,
            wifi._dbg, led3 > 0 ? "host" : "cmd");

}

char *trim(char *buf) {
    int len = strlen(buf);
    int i;
    for (i = len - 1; i >= 0; i--) {
        if (buf[i] == '\r' || buf[i] == '\n' || buf[i] == '\t' || buf[i] == ' ')
            buf[i] = 0;
        else
            break;
    }
    return buf;
}

void ipd_cb(char *buf, int len) {
    if (buf != NULL) {
         pc.printf("\n-----------HTTP data len: %d----------\n", len);
        /* WARNNING: print data to console will cause data lost for big pages */
        buf[len] = 0;
        pc.puts(buf);
    } else {
        pc.puts("===================END====================\n");
    }
}

int main() {
    char buf[256];
    char tx[256];
    int r;
    char *cmd;

    pc.baud(115200);
    pc.printf("starting...\n");

    led4.loop(0.5, 0.2);
    btn.fall(on_btn);

//  wifi.set_log(&pc, 0);

    wifi.init();
    wifi.switchClientMode(1);

    wifi.cmd_data("AT+CWLAP"); //list Routers

    wifi.connect("steeven@qp", "xxxxxx");

    // http://releases.ubuntu.com/14.10/MD5SUMS
    wifi.send("releases.ubuntu.com", 80, "GET /14.10/MD5SUMS HTTP/1.1\r\nHOST: releases.ubuntu.com\r\n\r\n", ipd_cb);

//  wifi.send("g.cn", 80, "GET / HTTP/1.1\r\nHOST: g.cn\r\n\r\n", ipd_cb);

    while (1) {
        pc.readl(buf, sizeof(buf));
        cmd = trim(buf);
        if (led3.read() == 1)
            wifi.cmd_data(cmd);
        else {
            sprintf(tx, "GET / HTTP/1.1\r\nHOST: %s\r\n\r\n", cmd);
            if ((r = wifi.send(cmd, 80, tx,
                    (led1 == 0 && led2 == 0) ? ipd_cb : NULL)) <= 0)
                pc.printf("========== Error: %d ==========\n", r);
        }
    }
}