tzapu / WiFiManager

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

How to know if credentials is reconfigured or how to get the last saved AP(ssid) name? #1239

Closed shariq-azim closed 3 years ago

shariq-azim commented 3 years ago

Basic Infos

I am trying to reconnect to the last known configurations or saved credentials(ssid, password) after the connection is lost temporarily for a while. In case it was reconfigured or had no wifi present before timeout ,it will return no proper/empty values. Thus, If I somehow know if there was a change of ssid somehow I can force restart on it to work properly.

Hardware

WiFimanager Branch/Release: Master- Developement 2.0.1 alpha

Esp32

Core Version: Not sure :/

Description

Now, with the code that i have compiled so far. I am facing two issues

  1. In case there was recent successful reconfiguration and >network gets disconnected for a while.. It will not auto reconnect ,and will stay disconnected.. This will although work if i manually hard reboot.
  2. In case there was no wifi available during bootup and the config page has timeout ..Then it will never connect to the wifi anymore.

Unfortunately, since my program is meant to run both online and offline, I cannot keep it struck in the blocking while(WiFi.status() != WL_CONNECTED) loop..

Settings in IDE

Module: Esp32 dev module

Additional libraries:

Sketch

#BEGIN
#include <WiFi.h>
#include <WiFiClient.h>
#include <WebServer.h> //copiedota
#include <ESPmDNS.h> //copiedota
#include <Update.h> //copiedota

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

//needed for library
//#include <DNSServer.h>
//#if defined(ESP8266)
//#include <ESP8266WebServer.h>
//#else
//#include <WebServer.h>
//#endif
#include <WiFiManager.h>   
//#include <ArduinoJson.h>          // https://github.com/bblanchon/ArduinoJson
//wifimanager

#include <BlynkSimpleEsp32.h>
BlynkTimer timer;

#define DEBUG_SW 1

// Pins of Switches
#define S5 32
#define S6 35
#define S7 34
#define S8 39

// Pins of Relay (Appliances Control)
#define R5 15
#define R6 2
#define R7 4
#define R8 22

// By default the mode is with_internet
int MODE = 0;
bool connected_once = false;

// You should get Auth Token in the Blynk App.
// Go to the Project Settings (nut icon).
char auth[] = "xxxx";

// Your WiFi credentials.
const char* host = "shariqESP"; //copiedota
// Set password to "" for open networks.
//char ssid[] = "Wifi aye bahaar aya20";//router
//char ssid[] = "rm7pro";//hotspot
char ssid[] = "";
char pass[] = "passme";

WebServer server(80); //copiedota

void setup()
{
  // put your setup code here, to run once:
 Serial.begin(9600);

  //WiFiManager
  //Local intialization. Once its business is done, there is no need to keep it around
  WiFiManager wm;
  //reset settings - for testing
  //wifiManager.resetSettings();

  //sets timeout until configuration portal gets turned off
  //useful to make it all retry or go to sleep
  //in seconds
  wm.setConfigPortalTimeout(30);

  //fetches ssid and pass and tries to connect
  //if it does not connect it starts an access point with the specified name
  //here  "AutoConnectAP"
  //and goes into a blocking loop awaiting configuration
  //wm.setDebugOutput(true);

  //set custom ip for portal
  //wifiManager.setAPStaticIPConfig(IPAddress(10,0,1,1), IPAddress(10,0,1,1), IPAddress(255,255,255,0));

//  Serial.println( wifiManager.getSSID());
//    Serial.println( WiFi.getSSID());
//Serial.println( wifiManager.getSSID() );

Serial.printf("SSID0: %s\n", wm.getWiFiSSID().c_str());
String saved_ssid_old =wm.getWiFiSSID().c_str();

  if(!wm.autoConnect("AutoConnectAP")) {
    Serial.println("failed to connect and hit timeout");
    delay(3000);
    //reset and try again, or maybe put it to deep sleep
    //ESP.restart();
    //delay(5000);
  } 
   Serial.printf("SSID1: %s\n", WiFi.SSID().c_str());
   Serial.println("SSID00: " + (String)wm.getWiFiSSID());
   Serial.println( wm.getWiFiIsSaved() );

if(WiFi.SSID().c_str() == ""){

int str_len = saved_ssid_old.length() + 1; 
char char_array[str_len];
// Copy it over 
saved_ssid_old.toCharArray(char_array, str_len);
Serial.println( ssid);

strcpy(ssid , char_array);

}

if(WiFi.SSID().c_str() != ""){
    Serial.println("not blank");

  String saved_ssid =WiFi.SSID().c_str();
  String saved_ssid_old =wm.getWiFiSSID().c_str();
  Serial.println(saved_ssid);
  Serial.println( saved_ssid_old );

    if( !saved_ssid_old.equals(saved_ssid)  ){
      // Length (with one extra character for the null terminator)
      int str_len = saved_ssid.length() + 1; 
  // Prepare the character array (the buffer)
  char char_array[str_len];

  // Copy it over 
  saved_ssid.toCharArray(char_array, str_len);
  Serial.println( ssid);
  Serial.println( "different ssid");

  strcpy(ssid , char_array);

    }

}
  Serial.println( ssid);

   WiFi.begin(ssid, pass);
   if (WiFi.status() == WL_CONNECTED)
  {
     Serial.println( "connected once");
   connected_once = true;
  }

  setOTA(); //custom

 timer.setInterval(3000L, checkBlynk); // check if connected to Blynk server every 3 seconds

  Blynk.config(auth);//, ssid, pass);
}

void loop()
{
 Serial.println("Loop started");
  Serial.print("Wifi status: ");
  Serial.println(WiFi.status());
  if (WiFi.status() != WL_CONNECTED)
  {
    if (DEBUG_SW) Serial.println("Not Connected");

    if( connected_once == true){
      Serial.println("Reconnecting");
    WiFi.reconnect();
    }
    else{
      Serial.println("Re-attempting to connect");
      WiFi.begin(ssid, pass);
      }
  }
  else
  {
    if (DEBUG_SW) Serial.println(" Connected");
    Blynk.run();
  }

  timer.run(); // Initiates SimpleTimer

  server.handleClient(); //custom
  delay(400); //custom

  if (MODE == 0)
    with_internet();
  else
    without_internet();
  // put your main code here, to run repeatedly:
}

void with_internet()
{
//removed redundancy
}
void without_internet
{
//removed redundancy
}

#END

Debug Messages

In case **timeout happens without any configuration change**

*WM: [1] AutoConnect 
*WM: [2] ESP32 event handler enabled 
*WM: [2] Connecting as wifi client... 
*WM: [3] STA static IP:
*WM: [2] setSTAConfig static ip not set, skipping 
*WM: [1] Connecting to SAVED AP: rm7pro   **//how to get this??**
*WM: [3] Using Password: <*******>
*WM: [3] WiFi station enable 
*WM: [1] connectTimeout not set, ESP waitForConnectResult... 
*WM: [2] [EVENT] WIFI_REASON: 201
*WM: [2] [EVENT] WIFI_REASON: NO_AP_FOUND 
*WM: [2] Connection result: WL_NO_SSID_AVAIL
*WM: [3] lastconxresult: WL_NO_SSID_AVAIL
*WM: [1] AutoConnect: FAILED 
*WM: [2] Starting Config Portal 
*WM: [3] WIFI station disconnect 
*WM: [3] WiFi station enable 
*WM: [2] Disabling STA 
*WM: [2] Enabling AP 
*WM: [1] StartAP with SSID:  AutoConnectAP
*WM: [2] AP has anonymous access! 
*WM: [1] SoftAP Configuration 
*WM: [1] -------------------- 
*WM: [1] ssid:             AutoConnectAP
*WM: [1] password:         
*WM: [1] ssid_len:         13
*WM: [1] channel:          1
*WM: [1] authmode:        
*WM: [1] ssid_hidden:     
*WM: [1] max_connection:   4
*WM: [1] country:          CN 
I⸮?
*WM: [1] beacon_interval:  100(ms)
*WM: [1] -------------------- 
*WM: [1] AP IP address: 192.168.4.1
*WM: [3] setupConfigPortal 
*WM: [1] Starting Web Portal 
*WM: [3] dns server started with ip:  192.168.4.1
*WM: [2] HTTP server started 
*WM: [2] WiFi Scan ASYNC completed in 4704 ms
*WM: [2] WiFi Scan ASYNC found: 1
*WM: [2] WiFi Scan completed in 4704 ms
*WM: [2] Config Portal Running, blocking, waiting for clients... 
*WM: [2] Portal Timeout In 2 seconds
*WM: [1] config portal has timed out 
*WM: [3] configportal abort 
*WM: [2] disconnect configportal 
*WM: [0] [ERROR] disconnect configportal - softAPdisconnect FAILED 
*WM: [2] restoring usermode STA
*WM: [2] wifi status: WL_DISCONNECTED
*WM: [2] wifi mode: STA
*WM: [1] config portal exiting 
failed to connect and hit timeout[ERROR] wm not ready

SSID1: 
SSID00:    **_this is also strange_**
1
not blank

IP address is : 0.0.0.0
*WM: [3] unloading 
Loop started
Wifi status: 6
Not Connected
Re-attempting to connect
Loop started
Wifi status: 6
Not Connected
Re-attempting to connect
Loop started
Wifi status: 6     **wifi is on by now**
Not Connected
Re-attempting to connect
...

////////////////////////////////////////////////////////////////////////

In case **new wifi is configured**
SSID0: 
*WM: [1] AutoConnect 
*WM: [2] ESP32 event handler enabled 
*WM: [2] Connecting as wifi client... 
*WM: [3] STA static IP:
*WM: [2] setSTAConfig static ip not set, skipping 
*WM: [1] Connecting to SAVED AP: rm7pro      **//how to get this??**
*WM: [3] Using Password: <******>
*WM: [3] WiFi station enable 
*WM: [1] connectTimeout not set, ESP waitForConnectResult... 
*WM: [2] [EVENT] WIFI_REASON: 201
*WM: [2] [EVENT] WIFI_REASON: NO_AP_FOUND 
*WM: [2] Connection result: WL_NO_SSID_AVAIL
*WM: [3] lastconxresult: WL_NO_SSID_AVAIL
*WM: [1] AutoConnect: FAILED 
*WM: [2] Starting Config Portal 
*WM: [3] WIFI station disconnect 
*WM: [3] WiFi station enable 
*WM: [2] Disabling STA 
*WM: [2] Enabling AP 
*WM: [1] StartAP with SSID:  AutoConnectAP
*WM: [2] AP has anonymous access! 
*WM: [1] SoftAP Configuration 
*WM: [1] -------------------- 
*WM: [1] ssid:             AutoConnectAP
*WM: [1] password:         
*WM: [1] ssid_len:         13
*WM: [1] channel:          1
*WM: [1] authmode:        
*WM: [1] ssid_hidden:     
*WM: [1] max_connection:   4
*WM: [1] country:          CN 
I⸮?
*WM: [1] beacon_interval:  100(ms)
*WM: [1] -------------------- 
*WM: [1] AP IP address: 192.168.4.1
*WM: [3] setupConfigPortal 
*WM: [1] Starting Web Portal 
*WM: [3] dns server started with ip:  192.168.4.1
*WM: [2] HTTP server started 
*WM: [2] WiFi Scan ASYNC completed in 4904 ms
*WM: [2] WiFi Scan ASYNC found: 3
*WM: [2] WiFi Scan completed in 4904 ms
*WM: [2] Config Portal Running, blocking, waiting for clients... 
*WM: [3] -> 192.168.4.1 
*WM: [2] Portal Timeout In 21 seconds
*WM: [2] <- HTTP WiFi save  
*WM: [3] Method: POST
*WM: [3] Sent wifi save page 
*WM: [2] processing save 
*WM: [2] Connecting as wifi client... 
*WM: [3] STA static IP:
*WM: [2] setSTAConfig static ip not set, skipping 
*WM: [1] CONNECTED:
*WM: [1] Connecting to NEW AP: Wifi aye bahaar aya
*WM: [3] Using Password: <*****>
*WM: [3] WiFi station enable 
*WM: [1] connectTimeout not set, ESP waitForConnectResult... 
*WM: [2] Connection result: WL_CONNECTED
*WM: [3] lastconxresult: WL_CONNECTED
*WM: [1] Connect to new AP [SUCCESS] 
*WM: [1] Got IP Address: 
*WM: [1] 192.168.0.9 
*WM: [2] disconnect configportal 
*WM: [0] [ERROR] disconnect configportal - softAPdisconnect FAILED 
*WM: [2] restoring usermode STA
*WM: [2] wifi status: WL_CONNECTED
*WM: [2] wifi mode: STA
*WM: [1] config portal exiting 
SSID1: Wifi aye bahaar aya
[ERROR] wm not ready
SSID00: Wifi aye bahaar aya
1
not blank
Wifi aye bahaar aya
Wifi aye bahaar aya

connected once
IP address is : 192.168.0.9
*WM: [3] unloading 
Loop started
Wifi status: 3
 Connected
Loop started
Wifi status: 3
 Connected
Loop started                                        **intentionally switched off and on**
Wifi status: 5                                        **intentionally switched off and on**
Not Connected                                    **intentionally switched off and on**
Reconnecting
Loop started
Wifi status: 5
Not Connected
Reconnecting
Loop started
_**(after few attempts, skipped between lines)**_
Wifi status: 0
Not Connected
Reconnecting

succesful case if manally rebooted and wifi available


SSID0: 
*WM: [1] AutoConnect 
*WM: [2] ESP32 event handler enabled 
*WM: [2] Connecting as wifi client... 
*WM: [3] STA static IP:
*WM: [2] setSTAConfig static ip not set, skipping 
*WM: [1] Connecting to SAVED AP: Wifi aye bahaar aya                  **how to get this??**
*WM: [3] Using Password: <****>
*WM: [3] WiFi station enable 
*WM: [1] connectTimeout not set, ESP waitForConnectResult... 
*WM: [2] Connection result: WL_CONNECTED
*WM: [3] lastconxresult: WL_CONNECTED
*WM: [1] AutoConnect: SUCCESS 
*WM: [1] STA IP Address: 192.168.0.9
SSID1: Wifi aye bahaar aya
SSID00: Wifi aye bahaar aya
1
not blank
Wifi aye bahaar aya
Wifi aye bahaar aya

connected once
IP address is : 192.168.0.9
*WM: [3] unloading 
Loop started
Wifi status: 3
 Connected
Loop started
Wifi status: 3
 Connected
Loop started                     ```**intentionally switched off and on**```
Wifi status: 1                     **intentionally switched off and on**
Not Connected                 **intentionally switched off and on**
Reconnecting
Loop started
Wifi status: 1
Not Connected
Reconnecting
Loop started
Wifi status: 0
Not Connected
Reconnecting
Loop started
Wifi status: 3  
 Connected
```**succesfully gets connected**```
tablatronix commented 3 years ago

esp32 has no autoconnect you will have to use the event hooks and add your own or add some timed loop check and reconnect with standard esp methods begin() or reconnect()

esp32 should reconnect though, maybe it broke

shariq-azim commented 3 years ago

@tablatronix hey that's what I am doing right in loop function? ` void loop() { Serial.println("Loop started"); Serial.print("Wifi status: "); Serial.println(WiFi.status()); if (WiFi.status() != WL_CONNECTED) { if (DEBUG_SW) Serial.println("Not Connected");

if( connected_once == true){
  Serial.println("Reconnecting");
WiFi.reconnect();

//even tried // WiFi.disconnect(); // delay(1100); //custom // WiFi.begin(ssid, pass); } else{ Serial.println("Re-attempting to connect"); WiFi.begin(ssid, pass); } } else { if (DEBUG_SW) Serial.println(" Connected"); Blynk.run(); }

timer.run(); // Initiates SimpleTimer

server.handleClient(); //custom delay(400); //custom

if (MODE == 0) with_internet(); else without_internet(); // put your main code here, to run repeatedly: } `

btw, are you aware if wifi manager library updates ssid chars, during its operation in loop function? i put some logs, and saw "rm7pro" getting updated to either "rm7p " or "r 7pro".. it is even strangely updating the last saved ap ssid?

tablatronix commented 3 years ago

It does not , sounds like a memory issue something is clobbering that memory

tablatronix commented 3 years ago

Just do begin()

shariq-azim commented 3 years ago

Hi there, It definitely looks like memory issue.. But I was able to reconnect removing if (WiFi.status() == WL_CONNECTED) { Serial.println( "connected once"); connected_once = true; } in main function..

And adding a while loop in loop function.

` if (WiFi.status() != WL_CONNECTED) { Serial.println("Re-attempting to connect"); WiFi.reconnect();

  int ct =0;
  while(WiFi.status() != WL_CONNECTED){
    delay(1000); //custom
    Serial.print(".");
    ct=ct+1000;
    if(ct>10000){
      break;
      }

} }`

But, my question remains "How to know if the credentials is reconfigured or how can we get the last saved AP(ssid) name"?

tablatronix commented 3 years ago

you will want to add a timer for that probably, or else it will try on every loop when router is down or out of range

tablatronix commented 3 years ago

WiFi.begin(); is all you need you can get the ssid like you normally do for esps only diff with esp32 is it will be blank if wifi is not initialized yet ( remember no esp32 has no autoconnect)

shariq-azim commented 3 years ago

Hello @tablatronix . I am late to properly understand and implement your suggestions. But , yes you are correct. Using Wifi.begin() instead of WiFi.reconnect() solved my issue.. Thanks

shariq-azim commented 1 year ago

Hello @tablatronix , All this were still working well for a while and i also didnt check much to work on it.. Now all of a sudden when i thought to tweak it a little, i see the same issue coming up. the changes now done are just publishing into a new channel thats it.

My library version is 2.0.16-rc.2 now

tablatronix commented 1 year ago

Yeah I had to disable some stuff you have have wifi init on esp32 to read the stored flash config

shariq-azim commented 1 year ago

Yeah I had to disable some stuff you have have wifi init on esp32 to read the stored flash config

Sorry little confused what should i be doing?