SHARE
TWEET

Webserver eeprom wemos

tbatista Nov 3rd, 2016 (edited) 231 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <ESP8266WiFi.h>  //https://github.com/ekstrand/ESP8266wifi
  2. #include <WiFiUdp.h>
  3. #include <WiFiManager.h>  //https://github.com/tzapu/WiFiManager
  4. #include <TimeLib.h>      //https://github.com/PaulStoffregen/Time
  5. #include <Ticker.h>
  6.  
  7. //***eeprom***
  8. #include <EEPROM.h>
  9. // endereço de escrita na memória
  10. uint8_t addr = 0;   // horaliga
  11. uint8_t addr1 = 1;  // minutoLiga
  12. uint8_t addr2 = 2;  // horaDesl
  13. uint8_t addr3 = 3;  // minutoDesl
  14. uint8_t addr4 = 4;  // stateRelay
  15.  
  16. //***OTA***
  17. #include <ESP8266mDNS.h>
  18. #include <ArduinoOTA.h>
  19.  
  20. WiFiManager wifiManager;
  21. WiFiServer server(80);
  22. Ticker secondtick;
  23. volatile int watchdogCount = 0;
  24.  
  25. /*
  26.     void reset_config(void) { // apaga rom do esp
  27.     wifiManager.resetSettings();
  28.     delay(1500);
  29.     ESP.reset();
  30.   }
  31. */
  32.  
  33. //************* Função temporizada *************//
  34. int  horaLiga = 00;
  35. int  minutoLiga = 00;
  36. int  horaDesl = 00;
  37. int  minutoDesl = 00;
  38.  
  39. char hora[30];
  40. char horaLigar[10];
  41. char horaDesligar[10];
  42.  
  43. int Relay = 5;                // Pino Utilizado
  44. uint8_t status_gpio = 0;      // define condição para gpio
  45. uint8_t status_auto = false;  // define status do botão auto
  46. boolean stateRelay;           //estado do pino Relay = 0
  47.  
  48. void TimedAction() {//executa
  49.   if (status_auto) {
  50.     digitalWrite(Relay, stateRelay);
  51.     if (int(hour()) == (int)horaLiga && int(minute()) == (int)minutoLiga) {
  52.       //      digitalWrite(Relay, !stateRelay);
  53.       stateRelay = true;
  54.       status_gpio = 1;
  55.     } else if (int(hour()) == (int)horaDesl && int(minute()) == (int)minutoDesl) {
  56.       //      digitalWrite(Relay, stateRelay);
  57.       stateRelay = false;
  58.       status_gpio = 0;
  59.     }
  60.   }
  61. }
  62.  
  63. void ISRWatchdog() {
  64.   watchdogCount++;
  65.   if (watchdogCount > 30) {
  66.     Serial.println("Watchdog bite!");
  67.     ESP.reset();
  68.   }
  69. }
  70.  
  71. //******************** NTP *******************//
  72. static const char ntpServerName[] = "a.ntp.br"; //Servidor (pode ser a.ntp.br / b.ntp.br / c.ntp.br )
  73. const int timeZone = -3; // Fuso horario (-3 Padrão / -2 Horário de Verão)
  74.  
  75. WiFiUDP Udp;
  76. unsigned int localPort = 8888;
  77. time_t getNtpTime();
  78. void sendNTPpacket(IPAddress &address);
  79. const int NTP_PACKET_SIZE = 48;
  80. byte packetBuffer[NTP_PACKET_SIZE];
  81.  
  82. time_t getNtpTime()
  83. {
  84.   IPAddress ntpServerIP;
  85.   while (Udp.parsePacket() > 0) ;
  86.   Serial.println(F("Transmitindo NTP Request"));
  87.   WiFi.hostByName(ntpServerName, ntpServerIP);
  88.   Serial.print(ntpServerName);
  89.   Serial.print(": ");
  90.   Serial.println(ntpServerIP);
  91.   sendNTPpacket(ntpServerIP);
  92.   uint32_t beginWait = millis();
  93.   while (millis() - beginWait < 3000) {
  94.     int size = Udp.parsePacket();
  95.     if (size >= NTP_PACKET_SIZE) {
  96.       Serial.println(F("Resposta recebida do NTP"));
  97.       Udp.read(packetBuffer, NTP_PACKET_SIZE);
  98.       unsigned long secsSince1900;
  99.       secsSince1900 =  (unsigned long)packetBuffer[40] << 24;
  100.       secsSince1900 |= (unsigned long)packetBuffer[41] << 16;
  101.       secsSince1900 |= (unsigned long)packetBuffer[42] << 8;
  102.       secsSince1900 |= (unsigned long)packetBuffer[43];
  103.       return secsSince1900 - 2208988800UL + timeZone * SECS_PER_HOUR;
  104.     }
  105.   }
  106.   Serial.println("Sem resposta do NTP");
  107.   return 0;
  108. }
  109.  
  110. void sendNTPpacket(IPAddress &address)
  111. {
  112.   memset(packetBuffer, 0, NTP_PACKET_SIZE);
  113.   packetBuffer[0] = 0b11100011;
  114.   packetBuffer[1] = 0;
  115.   packetBuffer[2] = 6;
  116.   packetBuffer[3] = 0xEC;
  117.   packetBuffer[12] = 49;
  118.   packetBuffer[13] = 0x4E;
  119.   packetBuffer[14] = 49;
  120.   packetBuffer[15] = 52;
  121.   Udp.beginPacket(address, 123);
  122.   Udp.write(packetBuffer, NTP_PACKET_SIZE);
  123.   Udp.endPacket();
  124. }
  125. time_t prevDisplay = 0;
  126.  
  127. void RTCSoft() {
  128.   if (timeStatus() != timeNotSet) {
  129.     if (now() != prevDisplay) {
  130.       prevDisplay = now();
  131.       TimedAction();
  132.     }
  133.   }
  134. }
  135.  
  136. void VerifyTimeNow() {//concatena a leitura da hora
  137.   sprintf( hora, "%02d:%02d:%02d", hour(), minute(), second());
  138.   sprintf( horaLigar, "%02d:%02d", horaLiga, minutoLiga);
  139.   sprintf( horaDesligar, "%02d:%02d", horaDesl, minutoDesl);
  140. }
  141.  
  142. ///******************************************
  143. void webpage() {
  144.  
  145.  
  146.   WiFiClient client = server.available();
  147.   if (!client) {
  148.     return;
  149.   }
  150.   Serial.println(F("Nova conexao requisitada..."));
  151.   while (!client.available()) {
  152.     delay(1);
  153.   }
  154.   Serial.println (F("Nova conexao OK..."));
  155.   String req = client.readStringUntil('\r'); //Le a string enviada pelo cliente
  156.   Serial.println(req);  //Mostra a string enviada
  157.   client.flush();       //Limpa dados/buffer
  158.  
  159.   digitalWrite(Relay, stateRelay);
  160.   if (req.indexOf(F("Auto_on")) != -1) {
  161.     status_auto = true;
  162.   } else if (req.indexOf(F("Auto_off")) != -1) {
  163.     status_auto = false;
  164.   } else if (req.indexOf(F("setHLu")) != -1) {
  165.     horaLiga++; if (horaLiga > 23) {
  166.       horaLiga = 00;
  167.     }
  168.   } else if (req.indexOf(F("setHLd")) != -1) {
  169.     horaLiga--; if (horaLiga < 00) {
  170.       horaLiga = 23;
  171.     }
  172.   } else if (req.indexOf(F("setMLu")) != -1) {
  173.     minutoLiga = minutoLiga + 5;
  174.     if (minutoLiga > 59) {
  175.       minutoLiga = 00;
  176.     }
  177.   } else if (req.indexOf(F("setMLd")) != -1) {
  178.     minutoLiga = minutoLiga - 5;
  179.     if (minutoLiga < 0) {
  180.       minutoLiga = 55;
  181.     }
  182.   } else if (req.indexOf(F("setHDu")) != -1) {
  183.     horaDesl++;
  184.     if (horaDesl > 23) {
  185.       horaDesl = 00;
  186.     }
  187.   } else if (req.indexOf(F("setHDd")) != -1) {
  188.     horaDesl--;
  189.     if (horaDesl < 00) {
  190.       horaDesl = 23;
  191.     }
  192.   } else if (req.indexOf(F("setMDu")) != -1) {
  193.     minutoDesl = minutoDesl + 5;
  194.     if (minutoDesl > 59) {
  195.       minutoDesl = 00;
  196.     }
  197.   } else if (req.indexOf(F("setMDd")) != -1) {
  198.     minutoDesl = minutoDesl - 5;
  199.     if (minutoDesl < 00) {
  200.       minutoDesl = 55;
  201.     }
  202.   } else if (req.indexOf(F("rele_on")) != -1) {
  203.     //    digitalWrite(Relay, !stateRelay);
  204.     stateRelay = true;
  205.     status_gpio = 1;
  206.   } else if (req.indexOf(F("rele_off")) != -1) {
  207.     //    digitalWrite(Relay, stateRelay);
  208.     stateRelay = false;
  209.     status_gpio = 0;
  210.   } else {
  211.     Serial.println(F("Requisicao invalida"));
  212.   }
  213.  
  214.   //***eeprom write
  215.   EEPROM.write(addr,(byte) horaLiga);
  216.   EEPROM.write(addr1,(byte) minutoLiga);
  217.   EEPROM.write(addr2,(byte) horaDesl);
  218.   EEPROM.write(addr3,(byte) minutoDesl);
  219.   EEPROM.write(addr4,(byte) stateRelay);
  220.   EEPROM.commit();
  221.   //
  222.   VerifyTimeNow();
  223.   //Prepara a resposta para o cliente e carrega a pagina
  224.   String buf = "";
  225.   buf += "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n<!DOCTYPE HTML>\r\n";
  226.   buf += "<html lang=\"en\">";
  227.   buf += "<head><meta name=\"viewport\" content=\"width=device-width, initial-scale=1, user-scalable=no\"/>\r\n";
  228.   buf += "<link href='https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css' rel='stylesheet'></link>";
  229.   buf += "<link rel=\"stylesheet\" href=\"http://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.6.3/css/font-awesome.min.css\">";
  230.   buf += "<script src='https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js'></script>";
  231.   buf += "<script src='http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js'></script>";
  232.   buf += "<script src=\"https://labs.zonamaker.com.br/js/hora.js\"></script>";
  233.   buf += "<title>WebServer ESP8266</title>";
  234.   buf += "<style>.c{text-align: center;} div,input{padding:5px;font-size:1em;} input{width:80%;} body{text-align: center;font-family:verdana;}</style>";
  235.   buf += "</head>";
  236.   buf += "<body onload='startTime()'><div class=\"panel panel-primary\">";
  237.   buf += "<div class=\"panel-heading\"><h3>ESP8266 Web NTP</h3></div>";
  238.   buf += "<div class=\"panel-body\">";
  239.   buf += "<div id=\"txt\" style=\"font-weight:bold;\"></div>";
  240.   //********botão lampada varanda**************
  241.   buf += "</p><div class='container'>";
  242.   buf += "<h4>Lampada</h4>";
  243.   buf += "<div class='btn-group'>";
  244.   //verificar como deixar automatico envia o comando
  245.   if (status_auto)  // alterna botões on off
  246.     buf += "<a href=\"?function=Auto_off\" class='btn btn-success'>Auto <i class=\"fa fa-toggle-on\" aria-hidden=\"true\"></i></a>";
  247.   else
  248.     buf += "<a href=\"?function=Auto_on\" class='btn btn-primary'>Auto <i class=\"fa fa-toggle-off\" aria-hidden=\"true\"></i></a>";
  249.   //De acordo com o status da GPIO
  250.   if (status_gpio)
  251.     buf += "<a href=\"?function=rele_off\" class='btn btn-danger'><i class=\"fa fa-power-off\" aria-hidden=\"true\"></i> Desligar</a>";
  252.   else
  253.     buf += "<a href=\"?function=rele_on\" class='btn btn-success'><i class=\"fa fa-power-off\" aria-hidden=\"true\"></i> Ligar</a>";
  254.   buf += "</div>";//btn group
  255.   buf += "<p>Programado para ligar &#224;s <span class=\"label label-success\">";
  256.   buf += String(horaLigar);
  257.   buf += "</span> e desligar &#224;s <span class=\"label label-danger\">";
  258.   buf += String(horaDesligar);
  259.   buf += "</span></p></br>";
  260.   buf += (F("<div class='btn-group'>"));
  261.   buf += (F("<h4>Hora para ligar</h4>"));
  262.   buf += (F("<a href=\"?function=setHLu\"><button type='button' class='btn btn-info' style='margin: 5px'>+1 h</button></a>"));
  263.   buf += (F("<a href=\"?function=setHLd\"><button type='button' class='btn btn-info' style='margin: 5px'>-1 h</button></a>"));
  264.   buf += (F("<a href=\"?function=setMLu\"><button type='button' class='btn btn-info' style='margin: 5px'>+5 min</button></a>"));
  265.   buf += (F("<a href=\"?function=setMLd\"><button type='button' class='btn btn-info' style='margin: 5px'>-5 min</button></a>"));
  266.   buf += (F("<h4>Hora para desligar</h4>"));
  267.   buf += (F("<a href=\"?function=setHDu\"><button type='button' class='btn btn-info' style='margin: 5px'>+1 h</button></a>"));
  268.   buf += (F("<a href=\"?function=setHDd\"><button type='button' class='btn btn-info' style='margin: 5px'>-1 h</button></a>"));
  269.   buf += (F("<a href=\"?function=setMDu\"><button type='button' class='btn btn-info' style='margin: 5px'>+5 min</button></a>"));
  270.   buf += (F("<a href=\"?function=setMDd\"><button type='button' class='btn btn-info' style='margin: 5px'>-5 min</button></a>"));
  271.   buf += (F("</div> "));
  272.   buf += "</div></div> ";//container
  273.   //************************************
  274.   buf += "<p>Pagina atualizada as "; // DIV para hora
  275.   buf += String(hora);
  276.   buf += "</body>";
  277.   buf += "</html>\n";
  278.   VerifyTimeNow();
  279.   client.print(buf);
  280.   VerifyTimeNow();
  281.   client.flush();
  282.   client.stop();
  283.   Serial.println(F("Cliente desconectado!"));
  284.  
  285. //  //***eeprom***
  286. //  EEPROM.end();
  287. //  //
  288. }
  289.  
  290. void OTA() {
  291.   ArduinoOTA.setHostname("esp8266");
  292.   // No authentication by default
  293.   ArduinoOTA.setPassword("admin");
  294.  
  295.   ArduinoOTA.onStart([]() {
  296.     String type;
  297.     if (ArduinoOTA.getCommand() == U_FLASH)
  298.       type = "sketch";
  299.     else // U_SPIFFS
  300.       type = "filesystem";
  301.  
  302.     // NOTE: if updating SPIFFS this would be the place to unmount SPIFFS using SPIFFS.end()
  303.     Serial.println("Start updating " + type);
  304.   });
  305.   ArduinoOTA.onEnd([]() {
  306.     Serial.println("\nEnd");
  307.   });
  308.   ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) {
  309.     Serial.printf("Progress: %u%%\r", (progress / (total / 100)));
  310.   });
  311.   ArduinoOTA.onError([](ota_error_t error) {
  312.     Serial.printf("Error[%u]: ", error);
  313.     if (error == OTA_AUTH_ERROR) Serial.println("Auth Failed");
  314.     else if (error == OTA_BEGIN_ERROR) Serial.println("Begin Failed");
  315.     else if (error == OTA_CONNECT_ERROR) Serial.println("Connect Failed");
  316.     else if (error == OTA_RECEIVE_ERROR) Serial.println("Receive Failed");
  317.     else if (error == OTA_END_ERROR) Serial.println("End Failed");
  318.   });
  319.   ArduinoOTA.begin();
  320.   Serial.println(F("Ready OTA ESP8266"));
  321.   Serial.print(F("IP address: "));
  322.   Serial.println(WiFi.localIP());
  323. }
  324.  
  325.  
  326. void setup() {
  327.   WiFi.persistent(false);
  328.   Serial.begin(115200);
  329.  
  330.   //***eeprom***
  331.   EEPROM.begin(256);
  332.   //***eeprom*** lê o byte no endereço atual da EEPROM
  333.   horaLiga = EEPROM.read(addr);
  334.   minutoLiga = EEPROM.read(addr1);
  335.   horaDesl = EEPROM.read(addr2);
  336.   minutoDesl = EEPROM.read(addr3);
  337.   stateRelay = EEPROM.read(addr4);
  338.   //
  339.   delay(250);
  340.   pinMode(Relay, OUTPUT);
  341.   digitalWrite(Relay, stateRelay);
  342.   secondtick.attach(1, ISRWatchdog);
  343.  
  344.   //Define o auto connect e o SSID do modo AP
  345.   wifiManager.setConfigPortalTimeout(180);
  346.   wifiManager.autoConnect("ESPWebServer");
  347.  
  348.   while (WiFi.status() != WL_CONNECTED) {
  349.     delay(500);
  350.     Serial.print(".");
  351.   }
  352.  
  353.   while (WiFi.waitForConnectResult() != WL_CONNECTED) {
  354.     Serial.println(F("Connection Failed! Rebooting..."));
  355.     delay(5000);
  356.     ESP.restart();
  357.   }
  358.  
  359.   OTA();//inicia interface OTA
  360.  
  361.   Serial.println(F("Conectado"));
  362.   server.begin();
  363.  
  364.   Serial.print("IP: ");
  365.   Serial.println(WiFi.localIP());
  366.   Serial.println(F("Iniciando UDP"));
  367.   Udp.begin(localPort);
  368.   Serial.print(F("Porta local: "));
  369.   Serial.println(Udp.localPort());
  370.   Serial.println(F("Aguardando sincronia do NTP"));
  371.   setSyncProvider(getNtpTime);
  372.   setSyncInterval(300);
  373. }
  374.  
  375. void loop() {
  376.   ArduinoOTA.handle();//inicia OTA
  377.   watchdogCount = 0;
  378.   RTCSoft();  //sincroniza o relógio
  379.   webpage();  //carrega o webserver
  380. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top