tzapu / WiFiManager

ESP8266 WiFi Connection manager with web captive portal
http://tzapu.com/esp8266-wifi-connection-manager-library-arduino-ide/
MIT License
6.46k stars 1.94k forks source link

ESP 8266 using deep Sleep and Autoconnect #943

Open rafaelpascale opened 4 years ago

rafaelpascale commented 4 years ago

ESP 8266 using deep Sleep and Autoconnect

WiFimanager Branch/Release:

Esp8266/Esp32:

Hardware: ESP-12e, esp01, esp25

Hello

After using deep sleep to save power, the program goes back to the beginning and it is necessary to login again and enter the password. Would it have any way that after entering deep sleep mode the autoconnection is automatic?

De Problem description

Settings in IDE

Module: NodeMcu, Wemos D1

Additional libraries:

Sketch

#if defined(ESP8266)
#include <ESP8266WiFi.h>  //ESP8266 Core WiFi Library         
#else
#include <WiFi.h>      //ESP32 Core WiFi Library    
#endif

#include <FirebaseArduino.h>                                                // firebase library
#include <DHT.h>                                                            // dht11 temperature and humidity sensor library

#include <NTPClient.h>
#include <WiFiUdp.h>

#include <Wire.h> //INCLUSÃO DA BIBLIOTECA
#include <WiFiManager.h>    
#include <SoftwareSerial.h>

//needed for library
#include <DNSServer.h> //Local DNS Server used for redirecting all requests to the configuration portal ( https://github.com/zhouhan0126/DNSServer---esp32 )
#if defined(ESP8266)
#include <ESP8266WebServer.h> //Local WebServer used to serve the configuration portal
#else
#include <WebServer.h> //Local WebServer used to serve the configuration portal ( https://github.com/zhouhan0126/WebServer-esp32 )
#endif
#include <WiFiManager.h>   // WiFi Configuration Magic ( https://github.com/zhouhan0126/WIFIMANAGER-ESP32 ) >> https://github.com/tzapu/WiFiManager (ORIGINAL)

#define DHTPIN D5                                                           // what digital pin we're connected to

#define FIREBASE_HOST "_____"                          // the project name address from firebase id
#define FIREBASE_AUTH "_______"            // the secret key generated from firebase

float Temperature = 0;

float Humididty = 0;

DHT dht(DHTPIN, DHT22);  
WiFiUDP ntpUDP;
NTPClient timeClient(ntpUDP);

//flag para indicar se foi salva uma nova configuração de rede
bool shouldSaveConfig = false;

//pino do botão
const int PIN_AP = 2;

String formattedDate;
String dayStamp;
String timeStamp;
float ip;

void setup() {
  Serial.begin(9600);
    dht.begin();
  pinMode(PIN_AP, INPUT);
  //declaração do objeto wifiManager
  WiFiManager wifiManager;

  //utilizando esse comando, as configurações são apagadas da memória
  //caso tiver salvo alguma rede para conectar automaticamente, ela é apagada.
//  wifiManager.resetSettings();

//por padrão as mensagens de Debug vão aparecer no monitor serial, caso queira desabilitá-la
//utilize o comando setDebugOutput(false);
//  wifiManager.setDebugOutput(false);

//caso queira iniciar o Portal para se conectar a uma rede toda vez, sem tentar conectar 
//a uma rede salva anteriormente, use o startConfigPortal em vez do autoConnect
//  wifiManager.startConfigPortal(char const *apName, char const *apPassword = NULL);

  //setar IP fixo para o ESP (deve-se setar antes do autoConnect)
//  setAPStaticIPConfig(ip, gateway, subnet);
//  wifiManager.setAPStaticIPConfig(IPAddress(192,168,16,2), IPAddress(192,168,16,1), IPAddress(255,255,255,0)); //modo AP

//  setSTAStaticIPConfig(ip, gateway, subnet);
//  wifiManager.setSTAStaticIPConfig(IPAddress(192,168,0,99), IPAddress(192,168,0,1), IPAddress(255,255,255,0)); //modo estação

//callback para quando entra em modo de configuração AP
  wifiManager.setAPCallback(configModeCallback); 
//callback para quando se conecta em uma rede, ou seja, quando passa a trabalhar em modo estação
  wifiManager.setSaveConfigCallback(saveConfigCallback); 

  wifiManager.autoConnect("MINIPA_TAM","12345678"); //cria uma rede sem senha
//wifiManager.autoConnect(); //gera automaticamente o SSID com o chip ID do ESP e sem senha

//  wifiManager.setMinimumSignalQuality(10); // % minima para ele mostrar no SCAN

//wifiManager.setRemoveDuplicateAPs(false); //remover redes duplicadas (SSID iguais)

//wifiManager.setConfigPortalTimeout(10); //timeout para o ESP nao ficar esperando para ser configurado para sempre
  Firebase.begin(FIREBASE_HOST, FIREBASE_AUTH);                              // connect to firebase
    timeClient.begin();  // GMT -3 = - 10800
  timeClient.setTimeOffset(-10800);
   if ( digitalRead(PIN_AP) == HIGH ) {
      Serial.println("resetar"); //tenta abrir o portal
      if(!wifiManager.startConfigPortal("MINIPA_TAM", "12345678") ){
        Serial.println("Falha ao conectar");
        delay(2000);
        ESP.restart();
        delay(1000);
      }
      Serial.println("Conectou a internet!!!");
   }

  while(!timeClient.update()) {
    timeClient.forceUpdate();
  }
  // The formattedDate comes with the following format:
  // 2018-05-28T16:00:13Z
  // We need to extract date and time
  formattedDate = timeClient.getFormattedDate();
  //Serial.println(formattedDate);

  // Extract date
  int splitT = formattedDate.indexOf("T");

  dayStamp = formattedDate.substring(0, splitT);
  Serial.print("DIA: ");
  Serial.println(dayStamp); // Extract time

  timeStamp = formattedDate.substring(splitT+1, formattedDate.length()-1);
  Serial.print("HORA: ");
  Serial.println(timeStamp);

  float h = dht.readHumidity();                                              // Reading temperature or humidity takes about 250 milliseconds!
  float t = dht.readTemperature();                                           // Read temperature as Celsius (the default)

  if (isnan(h) || isnan(t)) {                                                // Check if any reads failed and exit early (to try again).
    Serial.println(F("Aguardando dados do sensor!"));
    return;
  }

  Serial.print("Humidity: ");  Serial.print(h);
  String fireHumid = String(h) + String("%");                                         //convert integer humidity to string humidity 
  Serial.print("%  Temperature: ");  Serial.print(t);  Serial.println("°C ");
  String fireTemp = String(t) + String("°C");                                                     //convert integer temperature to string temperature
  delay(500);

   String dia = String(dayStamp);
 String hora = String(timeStamp); 

  Serial.print("\n");
  delay(500);

  Firebase.pushString("Dia", dia);                                  //setup path and send readings
  Firebase.pushString("Hora", hora);                                  //setup path and send readings
   Firebase.pushString(dia, hora);                                  //setup path and send readings

  Firebase.pushString("Umidade", fireHumid);                                  //setup path and send readings
  Firebase.pushString("Temperatura", fireTemp);                                //setup path and send readings

}

//callback que indica que o ESP entrou no modo AP
void configModeCallback (WiFiManager *myWiFiManager) {  
//  Serial.println("Entered config mode");
  Serial.println("Entrou no modo de configuração");
  Serial.println(WiFi.softAPIP()); //imprime o IP do AP
  Serial.println(myWiFiManager->getConfigPortalSSID()); //imprime o SSID criado da rede

  Serial.println("deep sleep for 10 seconds");
  ESP.deepSleep(10e6); 
}

//callback que indica que salvamos uma nova rede para se conectar (modo estação)
void saveConfigCallback () {
//  Serial.println("Should save config");
  Serial.println("Configuração salva");
  Serial.println(WiFi.softAPIP()); //imprime o IP do AP
}

void loop() {

  }
dontsovcmc commented 4 years ago

Look at my project. It works well.

https://github.com/dontsovcmc/waterius/blob/master/ESP8266/src/main.cpp

the difference I see:

Here is initializing Wifi with SSID & pwd I need: https://github.com/dontsovcmc/waterius/blob/master/ESP8266/src/wifi_settings.cpp#L144

Init: WiFi.begin(VALUE(SSID_NAME), VALUE(SSID_PASS), 0, NULL, false); //connect=false, cause we call Wifi.begin() next; Connect in deep sleep loop:

WiFi.begin(); 
uint32_t start = millis();
while (WiFi.status() != WL_CONNECTED && millis() - start < ESP_CONNECT_TIMEOUT) {
     LOG_NOTICE("WIF", "Status: " << WiFi.status());
     delay(200);

      check_voltage(data, cdata);
 }
tablatronix commented 4 years ago

Is autoconnect not working upon wake? This is not a known issue, can you provide some debug enabled logs? This should not have to be done