#include <SoftwareSerial.h>
#include <avr/wdt.h>
#define DEBUG true
#define REQUEST_FASTTIME 150
#define CIPMUX 1// configure for multiple connections
#define CWMODE 2// режим configure as access point (1=Station, 2=AP, 3=All)
#define CIPSERVER_PORT 80
#define CIPSTO_TIMEOUT 5
#define BOUDFirst 57600 // скорость обмена по умолчанию 9600 или 38400 или 57600 или макс 921600
#define BOUD 57600 // моя максимальная скорость ESP with Arduino 57600
#define REQUEST_START "ARDUINO UNO"
#define REQUEST_END "9may"
#define CONNECTION ""
//#define CONNECTION "Connection: close\r\n"
//#define CONNECTION "Connection: keep-alive\r\n"
#define TEG_SERVER "";
//#define TEG_SERVER "Server: WebSevice\r\n";
#define TEG_REFRESH ""
//#define TEG_REFRESH "Refresh: 1\r\n"
long int time = millis(), time_1, time_2, time_3;
int loopIterat = 3;
boolean firstStop = false;
SoftwareSerial esp8266(2, 3);
void setup()
{
Serial.begin(57600);
Serial.println("_SS_MAX_RX_BUFF="+String(_SS_MAX_RX_BUFF,DEC));
if (BOUDFirst != BOUD){
long b= BOUDFirst;
String s = "AT+CIOBAUD=" + String(BOUD, DEC);
String r = "";
while(true){
esp8266.begin(b);
Serial.print("esp8266.begin = ");
Serial.println(b, DEC);
while(true){
Serial.println(s);
esp8266.println(s);
Serial.println(esp8266.readString());
if(b!=BOUDFirst)break;
}
esp8266.end();
}
}
esp8266.begin(BOUD);
pinMode(11, OUTPUT);
digitalWrite(11, LOW);
pinMode(12, OUTPUT);
digitalWrite(12, LOW);
pinMode(13, OUTPUT);
digitalWrite(13, LOW);
sendData("AT+RST", "reset module", 0);
sendData("AT", "test esp8266", REQUEST_FASTTIME);
sendData("AT+CIOBAUD=?", "speed baud", REQUEST_FASTTIME);
if (DEBUG)sendData("AT", "test esp8266", REQUEST_FASTTIME);
sendData("AT+CIPMUX=" + String(CIPMUX), "configure for multiple connections " + String(CIPMUX), REQUEST_FASTTIME);
sendData("AT+CWMODE=" + String(CWMODE), "configure as access point to " + String(CWMODE) + "(1=Station, 2=AP, 3=All)", REQUEST_FASTTIME);
sendData("AT+CIPSERVER=1," + String(CIPSERVER_PORT), "turn on server on port " + String(CIPSERVER_PORT), REQUEST_FASTTIME);
sendData("AT+GMR", "version flash", REQUEST_FASTTIME);
sendData("AT+CIFSR", "get ip address", REQUEST_FASTTIME);
sendData("AT+CIPSTO=" + String(CIPSTO_TIMEOUT), "timeout " + String(CIPSTO_TIMEOUT), REQUEST_FASTTIME);
if (DEBUG)sendData("AT", "AT esp8266", REQUEST_FASTTIME);
//if(DEBUG)sendData("AT+CWLAP","View access point", 5000); //1 раз сработало
//Serial.println("# delay(2000)");delay(2000);
sendData("AT", "AT esp8266", REQUEST_FASTTIME);
Serial.println(""); printTime();
Serial.println("# flush()"); esp8266.flush();
Serial.println("# init end -----"+String(REQUEST_FASTTIME,DEC)+"-------------------------------------");
time_1 = millis(); time_2 = millis();
}
// Основной цикл- Ждем +IPD и выталкиваем буфер
void loop()
{
Serial.println("# main loop ---------------------------------\n");
//while(!esp8266.overflow()){
while (true) {
if (DEBUG) if (millis() - time_1 > 1000)Serial.println(printTime(time_1) + "second 1"); time_1 = millis();
time = millis();
char c = 0; long conId = 0;
while (esp8266.available()) {
time = millis();
if ( ( c = esp8266.read() ) == '+' ) {
while (esp8266.available()<64)delay(1);
//if (!DEBUG) delay(10);
//if(millis()-time_2>2000) Serial.println(printTime(time_2)+"available------second 2---------");time_2 = millis();
if ( (c = esp8266.read()) == 'I' && (c = esp8266.read()) == 'P' && (c = esp8266.read()) == 'D' && (c = esp8266.read()) == ',')
//if(esp8266.find("IPD,"))
{
//while(!esp8266.overflow()) delay(1);
printTime();Serial.println("..");
if (!firstStop) {
Serial.println("Start loop [" + String(loopIterat++) + "]");
firstStop = true;
} else Serial.println("loop [" + String(loopIterat++) + "]");
if (CIPMUX == 1)conId = esp8266.parseInt();
if (DEBUG) {
Serial.print(printTime() + "++++++++++++++++++++++++");
Serial.print(" +IPD");
Serial.println(conId);
}
//printTime();Serial.println(">");
retriveOk(conId);
//printTime();Serial.println(">>\n");
if (DEBUG)Serial.println(printTime() + "loop iteration end");
}
} else if (DEBUG)if (c != 0)
{
if (millis() - time_3 > 10) {
Serial.println("");
printTime(time_3);
Serial.print(c);
}
else Serial.print(c);
time_3 = millis();
}
}
//delay(50);
}
}
void retriveOk(long connId)
{
if (DEBUG)Serial.println(printTime() + "retriveOk");
// ищем команду /set и номер pin=
if ( esp8266.find(" /") && esp8266.read() == 's' && esp8266.find("pin=") )
{
int pin = esp8266.parseInt();
if (DEBUG)Serial.print(printTime() + "Setup pin=");
if (DEBUG)Serial.println(pin);
digitalWrite(pin, digitalRead(pin) == LOW ? HIGH : LOW);
}
// чистим буфер
if (DEBUG)printTime(); while (esp8266.available()) esp8266.read();
if (DEBUG)Serial.print("ClearBuffer");
if (DEBUG)Serial.println(printTime());
String requestText = REQUEST_START;
// собираем инфо для ответа
for (int pin = 11; pin <= 13; pin++) {
requestText += "\npin" + String(pin, DEC) + "=";
requestText += digitalRead(pin) == HIGH;
}
requestText += "\ntime=" + String(millis() - time, DEC) + "\n";
requestText += REQUEST_END;
String request = "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nAccess-Control-Allow-Origin: *\r\n";
request += TEG_SERVER;
request += CONNECTION;
request += TEG_REFRESH;
request += "Content-Length: "; request += String(requestText.length(), DEC) + "\r\n";
request += "\r\n" + requestText;
// стартуем обмен данными
String sSend = "AT+CIPSEND";
if (CIPMUX == 1)sSend += "=" + String(connId, DEC) + ",";
sSend += request.length();
if (DEBUG)Serial.print(printTime() + "send.>");
if (DEBUG)Serial.println(sSend+"\r\n"+request);
esp8266.print(sSend+"\r\n"+request);
if (DEBUG)Serial.println(printTime() + "send..");
// Очиста буфера произойдет в основном цикле
if (DEBUG)Serial.println(printTime() + "++++++++++++++++++++++++");
}
// Отправка команды
void sendData(String command, String comment, long int delayTime)
{
Serial.print("\n# " + comment);
if(delayTime == 0)Serial.print("> ");
esp8266.println(command);
String response = delayTime != 0 ? esp8266readString(delayTime) : esp8266.readString();
{
String ss = response; ss.trim();
if (response.indexOf(command) < 0) Serial.println(command+">");
else {
ss.replace("\r\n\r\n", "\n");
String sss=command+"\r\nOK";
if( sss.equals(ss)){
Serial.print(command+" OK");
return;
}
Serial.println("");
}
printTime();
if (response.length() > 0)Serial.println(ss); else Serial.println("response = >null");
}
return;
}
String printTime() {
return printTime(time);
}
String printTime(long int time) {
Serial.print("#");
Serial.print(LeftPad(String(millis() - time, DEC), 4, " "));
Serial.print(LeftPad(String(esp8266.available(), DEC), 4, " "));
Serial.print("\\");
Serial.print(esp8266.overflow());
Serial.print(":");
return "";
}
String LeftPad(String st, int n, String s) {
if(st.length()>=n)return st;
String ss = ""; for (int i = 0; i < n - st.length(); i++)ss += s; return ss + st;
}
String RightPad(String st, int n, String s) {
if(st.length()>=n)return st;
String ss = ""; for (int i = 0; i < n - st.length(); i++)ss += s; return st + ss;
}
// примеры рестарта Arduino
void(* resetFunc) (void) = 0;
void reboot() {
wdt_disable();
wdt_enable(WDTO_15MS);
while (1) {}
}
void restart(String meesage) {
Serial.println(printTime() + "Error!!!!Error!!!!Error!!!!Error!!!!");
Serial.println(meesage);
Serial.println(esp8266.readString());
return;
while (true) {
String s = esp8266.readString();
if (s.length() > 0)Serial.println(s);
}
reboot();
}
String esp8266readString(long int delayTime) {
//Serial.print(", fast(" + String(delayTime) + ")>");
Serial.print(">");
String result = "";
long int delayT = delayTime + millis();
while (result.length()==0 || millis() <= delayT)
while (esp8266.available()) {
char c = esp8266.read();
result += c;
}
return result;
}
String esp8266readString() {
return esp8266readString(0);
}
void loop1() {
if (esp8266.available()) Serial.print(esp8266.readString());
}