[GH-ISSUE #272] Create reconnectIfNecessary() helper method for use in loop #228

Closed
opened 2026-02-28 01:24:12 +03:00 by kerem · 8 comments
Owner

Originally created by @cosmocracy on GitHub (Jan 3, 2017).
Original GitHub issue: https://github.com/tzapu/WiFiManager/issues/272

Because Wifi connections periodically drop, any significant sketch needs to deal with reconnection. This logic isn't trivial: in my investigation related to connection robustness I saw at least a half-dozen variants of how to reconnect, some of which were successful for some (and not others).

This issue suggests the creation of a simple "reconnectIfNecessary" helper method that is to be called at the top of the "loop()" code. In this way consumers of WiFiManager have at their disposal a simple utility for ensuring the ESP8266 is connected--blocking until connected if necessary. Since this helper ideally emits logging via Serial.print(...) methods, there are helpful cues to a sketch programmer when a reconnection is afoot.

Originally created by @cosmocracy on GitHub (Jan 3, 2017). Original GitHub issue: https://github.com/tzapu/WiFiManager/issues/272 Because Wifi connections periodically drop, any significant sketch needs to deal with reconnection. This logic isn't trivial: in my investigation related to connection robustness I saw at least a half-dozen variants of how to reconnect, some of which were successful for some (and not others). This issue suggests the creation of a simple "reconnectIfNecessary" helper method that is to be called at the top of the "loop()" code. In this way consumers of WiFiManager have at their disposal a simple utility for ensuring the ESP8266 is connected--blocking until connected if necessary. Since this helper ideally emits logging via Serial.print(...) methods, there are helpful cues to a sketch programmer when a reconnection is afoot.
kerem closed this issue 2026-02-28 01:24:12 +03:00
Author
Owner

@cosmocracy commented on GitHub (Jan 3, 2017):

I am working on a fork of https://github.com/cosmocracy/LinkNode-R4-Controlled-By-Amazon-Alexa that integrates WiFiManager--specifically this issue: https://github.com/CharlesJGantt/LinkNode-R4-Controlled-By-Amazon-Alexa/issues/2.

Here is the implementation that I am currently using--you are freely welcome to use it...

Inside my setup() method I add a couple of variables to capture the SSID and PSK (saved_ssid and saved_psk)... these may not needed if this is added as a helper to WiFiManager since presumably these are held internally.

And the helper:

/* If disconnected from Wifi, enter a blocking loop that periodically attempts reconnection */
void reconnectIfNecessary() {
  while(WiFi.status() != WL_CONNECTED) {
    Serial.println("Disconnected; Attempting reconnect to " + String(saved_ssid) + "...");
    WiFi.disconnect();
    WiFi.mode(WIFI_AP_STA);
    WiFi.begin(saved_ssid, saved_psk);
    // Output reconnection status info every second over the next 10 sec
    for( int i = 0; i < 10 ; i++ )  {
      delay(1000);
      Serial.print("WiFi status = ");
      if( WiFi.status() == WL_CONNECTED ) {
        Serial.println("Connected");
        break;
      } else {
        Serial.println("Disconnected");
      }
    }
    if(WiFi.status() != WL_CONNECTED) {
      Serial.println("Failure to establish connection after 10 sec. Will reattempt connection in 2 sec");
      delay(2000);
    }
  }
}

All that then remains is to call this helper in loop (at the beginning), for example:

void loop()
{
  // Ensure wifi is connected (won't return until it has connected)
  reconnectIfNecessary();
  // Respond to any Alexa/discovery requests
  upnpBroadcastResponder.serverLoop();
  // Respond to any UPnP control requests
  alexa_switch1->serverLoop();
  alexa_switch2->serverLoop();
  alexa_switch3->serverLoop();
  alexa_switch4->serverLoop();
}
<!-- gh-comment-id:270046872 --> @cosmocracy commented on GitHub (Jan 3, 2017): I am working on a fork of https://github.com/cosmocracy/LinkNode-R4-Controlled-By-Amazon-Alexa that integrates WiFiManager--specifically this issue: https://github.com/CharlesJGantt/LinkNode-R4-Controlled-By-Amazon-Alexa/issues/2. Here is the implementation that I am currently using--you are freely welcome to use it... Inside my ```setup()``` method I add a couple of variables to capture the SSID and PSK (```saved_ssid``` and ```saved_psk```)... these may not needed if this is added as a helper to WiFiManager since presumably these are held internally. And the helper: ```c /* If disconnected from Wifi, enter a blocking loop that periodically attempts reconnection */ void reconnectIfNecessary() { while(WiFi.status() != WL_CONNECTED) { Serial.println("Disconnected; Attempting reconnect to " + String(saved_ssid) + "..."); WiFi.disconnect(); WiFi.mode(WIFI_AP_STA); WiFi.begin(saved_ssid, saved_psk); // Output reconnection status info every second over the next 10 sec for( int i = 0; i < 10 ; i++ ) { delay(1000); Serial.print("WiFi status = "); if( WiFi.status() == WL_CONNECTED ) { Serial.println("Connected"); break; } else { Serial.println("Disconnected"); } } if(WiFi.status() != WL_CONNECTED) { Serial.println("Failure to establish connection after 10 sec. Will reattempt connection in 2 sec"); delay(2000); } } } ``` All that then remains is to call this helper in loop (at the beginning), for example: ```c void loop() { // Ensure wifi is connected (won't return until it has connected) reconnectIfNecessary(); // Respond to any Alexa/discovery requests upnpBroadcastResponder.serverLoop(); // Respond to any UPnP control requests alexa_switch1->serverLoop(); alexa_switch2->serverLoop(); alexa_switch3->serverLoop(); alexa_switch4->serverLoop(); } ```
Author
Owner

@cosmocracy commented on GitHub (Jan 3, 2017):

If you would like to add me as a contributor, I would be happy to fork and provide a PR that implements this., @tzapu. Thank you for this project--it's been immensely valuable to my efforts.

<!-- gh-comment-id:270046917 --> @cosmocracy commented on GitHub (Jan 3, 2017): If you would like to add me as a contributor, I would be happy to fork and provide a PR that implements this., @tzapu. Thank you for this project--it's been immensely valuable to my efforts.
Author
Owner

@tzapu commented on GitHub (Jan 3, 2017):

@cosmocracy hi Eric, thanks for this.

I am not sure why this would happen, but my nodes seem to reconnect themselves just fine.

I have not changed any settings on the modules in regards to reconnection, but I was under the impression that the SDK itself would retry connection at various intervals. Is this not the case any longer? (or maybe never was and it was just a set of circumstances that led to my modules reconnecting?)

Doing this: WiFi.begin(saved_ssid, saved_psk); creates unnecessary writes to the flash.Did you try with no parameters and it fails in this scenario?

Thanks for this

<!-- gh-comment-id:270051229 --> @tzapu commented on GitHub (Jan 3, 2017): @cosmocracy hi Eric, thanks for this. I am not sure why this would happen, but my nodes seem to reconnect themselves just fine. I have not changed any settings on the modules in regards to reconnection, but I was under the impression that the SDK itself would retry connection at various intervals. Is this not the case any longer? (or maybe never was and it was just a set of circumstances that led to my modules reconnecting?) Doing this: `WiFi.begin(saved_ssid, saved_psk);` creates unnecessary writes to the flash.Did you try with no parameters and it fails in this scenario? Thanks for this
Author
Owner

@cosmocracy commented on GitHub (Jan 3, 2017):

@tzapu I did find that I needed to explicitly provide the SSID and PSK in order for it to reconnect. That said, I see various people having inconsistent reconnect behavior with the latest Wifi library. Have you tried using the latest version to see if it is still stable/robust?

<!-- gh-comment-id:270051795 --> @cosmocracy commented on GitHub (Jan 3, 2017): @tzapu I did find that I needed to explicitly provide the SSID and PSK in order for it to reconnect. That said, I see various people having inconsistent reconnect behavior with the latest Wifi library. Have you tried using the latest version to see if it is still stable/robust?
Author
Owner

@tzapu commented on GitHub (Jan 3, 2017):

been out of action for a while, and most of my modules because they have been stable, don t even run the latest wifi manager :P

the following weeks i hope to be able to get up to speed a bit
cheers

<!-- gh-comment-id:270055326 --> @tzapu commented on GitHub (Jan 3, 2017): been out of action for a while, and most of my modules because they have been stable, don t even run the latest wifi manager :P the following weeks i hope to be able to get up to speed a bit cheers
Author
Owner

@tzapu commented on GitHub (Jan 3, 2017):

it seems a reconnect method is already provided, can you use that?
you could also possibly try

WiFi.persistent(false);
WiFi.disconnect();
WiFi.begin();

not entirely sure if that doesn't cause a flash write though... but shouldn't i think if the details are the same

<!-- gh-comment-id:270055931 --> @tzapu commented on GitHub (Jan 3, 2017): it seems a reconnect method is already provided, can you use that? you could also possibly try ``` WiFi.persistent(false); WiFi.disconnect(); WiFi.begin(); ``` not entirely sure if that doesn't cause a flash write though... but shouldn't i think if the details are the same
Author
Owner

@osos commented on GitHub (Jun 1, 2017):

Maybe have a look at this suggested reconnect handler: https://github.com/marvinroger/async-mqtt-client/issues/23

Seems to be event based and would not require a blocking loop.

<!-- gh-comment-id:305572708 --> @osos commented on GitHub (Jun 1, 2017): Maybe have a look at this suggested reconnect handler: https://github.com/marvinroger/async-mqtt-client/issues/23 Seems to be event based and would not require a blocking loop.
Author
Owner

@kdavid2 commented on GitHub (Dec 3, 2017):

wifi.disconnect erases the EEPROM data of SSID and password. I have tested your code using Wifi.begin() without parameters and it works fine. Furthermore I have removed the Serial writes in order not to delay the process.

<!-- gh-comment-id:348799252 --> @kdavid2 commented on GitHub (Dec 3, 2017): wifi.disconnect erases the EEPROM data of SSID and password. I have tested your code using Wifi.begin() without parameters and it works fine. Furthermore I have removed the Serial writes in order not to delay the process.
Sign in to join this conversation.
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set.

Reference
starred/WiFiManager#228
No description provided.