Master Program

Dependencies:   BSP_DISCO_F746NG LCD_DISCO_F746NG TS_DISCO_F746NG mbed

main.cpp

Committer:
GabDiSi
Date:
2015-10-31
Revision:
0:beeeb5671c2a
Child:
1:b6e184239fba

File content as of revision 0:beeeb5671c2a:

#include <string.h>
#include "mbed.h"
 
Serial pc(USBTX, USBRX); // tx, rx
Serial serial6(D1, D0); // tx, rx
DigitalOut led1(LED1);

int ESP8266limitResponse = 999999;

char ESP8266okStr[] = "OK\r\n";
char ESP8266getStr[] = "OK\r\n> ";
char ESP8266readyStr[] = "ready\r\n";
char ESP8266sendStr[] = "SEND OK\r\n\r\n";
char ESP8266closedStr[] = "CLOSED\r\n";

bool ESP8266readResponse(char* delimiter, char* response) {
    int i = 0, j = 0;
    char c;
    
    while(j<ESP8266limitResponse) {
        c = serial6.getc();
        response[j++] = c;
        
        if(c == delimiter[i]) {
            i++;
            
            if(delimiter[i] == '\0') {
                response[j] = '\0';
                return true;
            };
        } else {
            i = 0;
        };
    };
    
    response[j] = '\0';
    return false;
};

void ESP8266init(char* ssid, char* password) {
    led1 = 0;
    
    pc.baud(115200);
    serial6.baud(115200);
    
    pc.printf("Hello!\r\n");
    
    pc.printf("ESP8266... ");
    serial6.printf("AT+RST\r\n");
    ESP8266readResponse(ESP8266okStr, NULL);
    ESP8266readResponse(ESP8266readyStr, NULL);
    pc.printf("ready!\r\n");
    
    pc.printf("Client mode... ");
    serial6.printf("AT+CWMODE=1\r\n");
    ESP8266readResponse(ESP8266okStr, NULL);
    pc.printf("done!\r\n");
    
    pc.printf("Wi-Fi connection... ");
    serial6.printf("AT+CWJAP=\"%s\",\"%s\"\r\n", ssid, password);
    ESP8266readResponse(ESP8266okStr, NULL);
    pc.printf("done!\r\n");
    
    led1 = 1;
};

void ESP8266get(char* domain, char* url, char* response) {
    int n1, n2;
    
    n1 = strlen(domain);
    n2 = strlen(url);
    
    pc.printf("Connection at server... ");
    serial6.printf("AT+CIPSTART=\"TCP\",\"%s\",80\r\n", domain);
    ESP8266readResponse(ESP8266okStr, NULL);
    pc.printf("done!\r\n");
    
    pc.printf("Sending # chars... ");
    serial6.printf("AT+CIPSEND=%d\r\n", 11+n1+1+n2+13);
    ESP8266readResponse(ESP8266getStr, NULL);
    pc.printf("done!\r\n");
    
    pc.printf("Sending request... ");
    serial6.printf("GET http://%s/%s HTTP/1.0\r\n\r\n", domain, url);
    ESP8266readResponse(ESP8266sendStr, NULL);
    ESP8266readResponse(ESP8266closedStr, response);
    pc.printf("done!\r\n");
};

int main() {
    char response[ESP8266limitResponse];
    char domain[] = "gabrieledisimone.it";
    char url[] = "";
    
    ESP8266init("Telecom-47520601", "famigliaquino2000router10");
    
    ESP8266get(domain, url, response);
    
    pc.printf("response:\r\n%s", response);
    while(1) {
        pc.putc(serial6.getc());
    };
};