Advertisement
RuiViana

ESP8266_VersaoJC

Aug 7th, 2018
261
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 13.83 KB | None | 0 0
  1. // Extarido e modificado do AutoConnectWithFSParametersAndCustomIP da biblioteca WiFiManager
  2. // Era AutoConnectWithFSParametersAndCustomIP_V03
  3. // Versao V03
  4. // Versao V04  Usar interruptor para detectar reset
  5. /*
  6.   Nesta versao, ao ligar o modulo, se o interruptor estiver ligado,
  7.   isto pode ser verificado porque a lampada esta acessa ao ligar,
  8.   e antes de 5 segundos for desligado o interruptor, o modulo entra em AP mode.
  9.   Em AP mode ele cria uma rede chamada "AP_Configure", com IP 192.168.1.4.
  10.   Acessando este IP configura-se a rede com os novos parametros de:
  11.   SSID. Password, IP, Gateway, e SubNet.
  12.   Mas ao ligar o modulo, se o interruptor estiver desligado,
  13.   isto pode ser verificado porque a lampada esta apagada ao ligar,
  14.   e antes de 5 segundos for ligado o interruptor, o modulo bypass
  15.   o wifi mode indo direto para o loop com  controle normal da lampada
  16.   pelo interruptor.
  17. */
  18. #include <FS.h>                           // This needs to be first, or it all crashes and burns...
  19. #include <ESP8266WiFi.h>                  // https://github.com/esp8266/Arduino
  20. #include <ESP8266WebServer.h>
  21. #include <WiFiManager.h>                  // https://github.com/tzapu/WiFiManager
  22. #include <ArduinoJson.h>                  // https://github.com/bblanchon/ArduinoJson
  23.  
  24. char static_ip[16] = "10.0.1.56";         // Default custom static IP
  25. char static_gw[16] = "10.0.1.1";
  26. char static_sn[16] = "255.255.255.0";
  27. bool shouldSaveConfig = false;            // Flag for saving data
  28.  
  29. // Port em uso
  30. // 0 15   SHT 2 MOC 4 SW 5 LED 13 Rst
  31. #include <SHT1x.h>                                          // https://github.com/practicalarduino/SHT1x
  32. #define dataPin  0                                          // GPIO 0  D3  Port para o Data do SHT10
  33. #define clockPin 15                                         // GPIO 15 D8  Port para o Clock do SHT10
  34. SHT1x sht1x(dataPin, clockPin);                             // Instancia shtx1
  35.  
  36. ESP8266WebServer server(80);                                // Instancia server
  37. //  Strings com HTML
  38. String Q_1 = "<!DOCTYPE HTML><html><head><meta http-equiv='refresh' content='1;URL=/Controle'/></head><h1><center>Controle de luz, Temperatura e Umidade</center>";
  39. String Q_2 = "</p></center><h3><BR></h3><html>\r\n";
  40. String Ql = "";                                             // Quarto ligado
  41. String Qd = "";                                             // Quarto desligado
  42. String Qil = "";                                            // Quarto intermediario ligado
  43. String Qid = "";                                            // Quarto intermediario desligado
  44. String LuzQuarto;                                           // String para controle
  45. float temp_c;                                               // Variavel para temperatura
  46. int humidity;                                               // Variavel para umidade
  47. #define Led_Ap_Mode 5                                       // Led indicativo de AP mode
  48. #define Saida1 2                                            // GPIO2 Port para ligar Controle do triac (Pino 2 do MOC3023)
  49. #define Switch1 4                                           // GPIO4 Port para ligar o interruptor
  50. byte Switch1_atual = 0;                                     // Variavel para staus de GPIO5 (Status do interruptor)
  51. unsigned long previousMillis = 0;                           // Variavel para medir periodos
  52. const long interval = 2000;                                 // Periodo de leitura da temperatura e umidade
  53. bool flagRst = 0;                                           // Flag para permitir reset dos parametros SSID e PW
  54. bool bypass = LOW;                                          // Controle do automatico
  55. //---------------------------------------
  56. void gettemperature()                                       // Funcoa para ler temperatura e umidade
  57. {
  58.   if (millis() - previousMillis >= interval)                // Se passou o intervalo
  59.   {
  60.     previousMillis = millis();                              // Restaura valor de previousMillis
  61.     humidity = sht1x.readHumidity();                        // Le umidade em SHT10
  62.     temp_c = sht1x.readTemperatureC();                      // Le temperatura em SHT10
  63.   }
  64. }
  65. //-------------------------------
  66. void saveConfigCallback ()                                  // Callback notifying us of the need to save config
  67. {
  68.   Serial.println("Should save config");
  69.   shouldSaveConfig = true;
  70. }
  71. //-------------------------------
  72. void setup()
  73. {
  74.   Ql += Q_1;                                                // Monta tela pra informar que a luz
  75.   Ql += "<p><center>Luz</p><p><a href=\"/Controle?LuzQuarto=off \"><button style=\"background-color: rgb(255, 0,   0);height: 100px; width: 200px;\"><h1> Acesa</h1></button></a>";
  76.   Qd += Q_1;                                                // Monta tela pra informar que a luz
  77.   Qd += "<p><center>Luz</p><p><a href=\"/Controle?LuzQuarto=on \"><button style=\"background-color: rgb(0, 255,   0);height: 100px; width: 200px;\"><h1> Apagada</h1></button></a>";
  78.  
  79.   Serial.begin(115200);                                       // Inicializa Serial
  80.   Serial.println();                                           // Pint
  81.   pinMode(Led_Ap_Mode, OUTPUT);                               // Led_Ap_Mode como saida
  82.   digitalWrite(Led_Ap_Mode, HIGH);                            // Apaga o Led indicativo de AP
  83.   pinMode(Switch1, INPUT_PULLUP);                             // Switch1 como entrada e liga o resistor de pullup
  84.   delay(20);                                                  // Delay para estabilizar o port
  85.   Switch1_atual = digitalRead(Switch1);                       // Atualiza status de Switch1_atual
  86.   pinMode(Saida1, OUTPUT);                                    // Saida1 como saida
  87.   digitalWrite(Saida1, LOW);                                  // Liga saída
  88.  
  89.   // Reset da rede wifi
  90.   if (digitalRead(Switch1) == LOW)                            // Se interruptor esta pressionado
  91.   {
  92.     digitalWrite(Saida1, HIGH);                               // Liga saída1
  93.     delay(5000);                                              // Aguarda 5 segundos
  94.     digitalWrite(Saida1, LOW);                                // Desliga saída1
  95.     if (digitalRead(Switch1) == HIGH)                         // Se interruptor esta liberado
  96.     {
  97.       flagRst = HIGH;                                         // Indica reset de parametros
  98.     }
  99.   }
  100.   // Bypass da rede wifi
  101.   if (fagRst == LOW)                                          // Se não foi reseted
  102.   {
  103.     if (digitalRead(Switch1) == HIGH)                         // Se interruptor está liberado
  104.     {
  105.       digitalWrite(Saida1, LOW);                              // desliga saída1
  106.       delay(5000);                                            // Aguarda 5 segundos
  107.       digitalWrite(Saida1, HIGH);                             // Liga saída1
  108.       if (digitalRead(Switch1) == LOW)                        // Se interruptor esta pressionado
  109.       {
  110.         bypass = HIGH;                                        // Desabilita o sistema de wifi
  111.       }
  112.     }
  113.   }
  114.   if (bypass == LOW)                                          // Se bypass esta desabilitado
  115.   {
  116.     digitalWrite(Saida1, LOW);                                // Se não deliga saida1
  117.  
  118.     //SPIFFS.format();                                        // Clean FS, for testing
  119.     Serial.println("mounting FS...");                         // Read configuration from FS json
  120.     if (SPIFFS.begin())
  121.     {
  122.       Serial.println("mounted file system");
  123.       if (SPIFFS.exists("/config.json"))                      // If file exists, reading and loading
  124.       {
  125.         Serial.println("reading config file");
  126.         File configFile = SPIFFS.open("/config.json", "r");
  127.         if (configFile) {
  128.           Serial.println("opened config file");
  129.           size_t size = configFile.size();
  130.           std::unique_ptr<char[]> buf(new char[size]);        // Allocate a buffer to store contents of the file.
  131.           configFile.readBytes(buf.get(), size);
  132.           DynamicJsonBuffer jsonBuffer;
  133.           JsonObject& json = jsonBuffer.parseObject(buf.get());
  134.           json.printTo(Serial);
  135.           if (json.success())
  136.           {
  137.             Serial.println("\nparsed json");
  138.             if (json["ip"])
  139.             {
  140.               Serial.println("setting custom ip from config");
  141.               strcpy(static_ip, json["ip"]);
  142.               strcpy(static_gw, json["gateway"]);
  143.               strcpy(static_sn, json["subnet"]);
  144.               Serial.println(static_ip);
  145.             }
  146.             else
  147.             {
  148.               Serial.println("no custom ip in config");
  149.             }
  150.           }
  151.           else
  152.           {
  153.             Serial.println("failed to load json config");
  154.           }
  155.         }
  156.       }
  157.     }
  158.     else
  159.     {
  160.       Serial.println("failed to mount FS");
  161.     }
  162.     Serial.println(static_ip);                                  // end read
  163.     WiFiManager wifiManager;
  164.  
  165.     if (flagRst == HIGH)                                        // Se reset foi habilitado
  166.     {
  167.       flagRst = LOW;                                            // Desabilita reset
  168.       wifiManager.resetSettings();                              // Reseta SSID e PW
  169.     }
  170.     digitalWrite(Led_Ap_Mode, HIGH);                            // Acende o Led indicativo de AP
  171.  
  172.     wifiManager.setSaveConfigCallback(saveConfigCallback);      // Set config save notify callback
  173.     IPAddress _ip, _gw, _sn;                                    // Set static ip
  174.     _ip.fromString(static_ip);
  175.     _gw.fromString(static_gw);
  176.     _sn.fromString(static_sn);
  177.     wifiManager.setSTAStaticIPConfig(_ip, _gw, _sn);
  178.  
  179.     // wifiManager.resetSettings();                               // Reset settings - for testing
  180.  
  181.     wifiManager.setMinimumSignalQuality();                        // Set minimu quality of signal so it ignores AP's under that quality    //defaults to 8%
  182.     if (!wifiManager.autoConnect("AP_Configure", "password"))
  183.     {
  184.       Serial.println("failed to connect and hit timeout");
  185.       delay(3000);
  186.  
  187.       ESP.reset();                                                // Reset and try again, or maybe put it to deep sleep
  188.       delay(5000);
  189.     }
  190.     //  Serial.println("connected...yeey :)");                    // If you get here you have connected to the WiFi
  191.     digitalWrite(Led_Ap_Mode, LOW);                               // Apaga o Led indicativo de AP
  192.     if (shouldSaveConfig)                                         // Save the custom parameters to FS
  193.     {
  194.       Serial.println("saving config");
  195.       DynamicJsonBuffer jsonBuffer;
  196.       JsonObject& json = jsonBuffer.createObject();
  197.       json["ip"] = WiFi.localIP().toString();
  198.       json["gateway"] = WiFi.gatewayIP().toString();
  199.       json["subnet"] = WiFi.subnetMask().toString();
  200.       File configFile = SPIFFS.open("/config.json", "w");
  201.       if (!configFile)
  202.       {
  203.         Serial.println("failed to open config file for writing");
  204.       }
  205.       json.prettyPrintTo(Serial);
  206.       json.printTo(configFile);
  207.       configFile.close();    //end save
  208.     }
  209.     Serial.println("local ip");
  210.     Serial.println(WiFi.localIP());
  211.     Serial.println(WiFi.gatewayIP());
  212.     Serial.println(WiFi.subnetMask());
  213.  
  214.     server.on("/", []()                                       // Ao request
  215.     {
  216.       server.send(200, "text/html", Ql);                      // Executa o HTML Ql (Quarto ligado)
  217.     });
  218.     server.on("/Controle", []()                               // Ao requeste
  219.     {
  220.       //    gettemperature();                                       // Le temperatura e umidade. Comentar se tiver sem sensor pois fica lento
  221.       LuzQuarto = server.arg("LuzQuarto");                    // Recupera o valor do parametro luz enviado
  222.       if (LuzQuarto == "off") digitalWrite(Saida1, LOW);      // Se o valor de luz e off desliga a saida
  223.       if (LuzQuarto == "on") digitalWrite(Saida1, HIGH);      // Se o valor de luz e on liga a saida
  224.  
  225.       if (digitalRead(Saida1) == HIGH)                        // Se a saida esta ligada, carrega a pagina "ligada"
  226.       {
  227.         Qil += Ql;                                            // Monta tela nova quarto ligado
  228.         Qil +=  "<p><center>Temperatura: " + String((float)temp_c) + "C </p>";
  229.         Qil +=  "<p><center>Umidade: " + String((int)humidity) + "% </p>";
  230.         Qil += Q_2;
  231.         server.send(200, "text/html", Qil);                   // Mostra Quarto ligado
  232.         Qil = "";                                             // Limpa valor de temperatura e umidade
  233.       }
  234.       if (digitalRead(Saida1) == LOW)                         // Se a saida esta desligada, carrega a pagina "desligada"
  235.       {
  236.         Qid += Qd;                                            // Monta tela nova quarto desligado
  237.         Qid += "<p><center>Temperatura: " + String((float)temp_c) + "C </p>";
  238.         Qid += "<p><center>Umidade: " + String((int)humidity) + "% </p>";
  239.         Qid += Q_2;
  240.         server.send(200, "text/html", Qid);                   // Mostra Quarto desligado
  241.         Qid = "";                                             // Limpa valor de temperatura e umidade
  242.       }
  243.       delay(100);                                             // Delay
  244.     });
  245.     server.begin();                                           // Inicaliza servidor
  246.     Serial.println("HTTP server started");                    // Imprime
  247.   }
  248. }
  249. //-------------------------------
  250. void loop()
  251. {
  252.   server.handleClient();                                    // Executa instancia
  253.  
  254.   if (digitalRead(Switch1) !=  Switch1_atual)               // Se o valor do SW alterou
  255.   {
  256.     delay(40);                                              // Delay
  257.     if (digitalRead(Switch1) !=  Switch1_atual)             // Se o valor do SW alterou
  258.     {
  259.       digitalWrite(Saida1, !digitalRead(Saida1));           // Inverte a saida lamp1
  260.       Switch1_atual = digitalRead(Switch1);                 // Atualisa o Gpio5 atual
  261.     }
  262.   }
  263. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement