Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

WiFi Auto Reconnect Still Not Working - Is there a best practice to guarantee connection? #653

Closed
vseven opened this issue Sep 21, 2017 · 155 comments

Comments

@vseven
Copy link
Contributor

@vseven vseven commented Sep 21, 2017

Board: ModeMCU ESP32 Dev Module
Core Installation/update date: 15/Sep/2017
IDE name: Arduino IDE

It seems there is no auto reconnect logic allowing the ESP32 to reconnect when the connection drops or if there is its not working properly. I have had completely random results with my ESP32 board, sometimes its up for as little as 30 minutes and at most 18 - 20 hours. WiFi is dropping and doesn't want to reconnect.

The library I am using for WiFi is watching the WiFi event and on a disconnect its trying to reconnect which helps but sometimes it fails the reconnect and then that's it...I have to reboot. There is no sleep/low power mode at all involved and the device is constantly powered by 3.3v in. There was a case opened regarding this, #353, but its closed without any real answer (says auto connect is kind of implemented...not sure what that means).

I guess the question comes down to is auto reconnect implemented in the code itself, reliably, and if not what is the best Arduino code way of making sure it is connected?

-Allan

@me-no-dev
Copy link
Member

@me-no-dev me-no-dev commented Sep 21, 2017

can you please enable debug in the board menu and see why it does not want to reconnect when you tell it to do so?

@vseven
Copy link
Contributor Author

@vseven vseven commented Sep 21, 2017

I can try that tonight. The Arduino code is pretty basic, watching the WiFi event and then has this:

case SYSTEM_EVENT_STA_DISCONNECTED:
	Serial.println("WiFi lost connection.  Attempting to reconnect...");
	WiFi.reconnect();
	break;

But shouldn't there be something that can be called to make this happen on it's own?

@nepeee
Copy link

@nepeee nepeee commented Sep 21, 2017

Just for a quick fix:
Start a timer in the SYSTEM_EVENT_STA_DISCONNECTED that calls the WiFi.reconnect(); function and stop it in the SYSTEM_EVENT_STA_CONNECTED. The main problem is with your idea is if the device cant connect than the SYSTEM_EVENT_STA_DISCONNECTED event is not called so its never try to reconnect again.

@vseven
Copy link
Contributor Author

@vseven vseven commented Sep 21, 2017

Unfortunately I'm adapting someone else library and I'm not very familiar with C++ but I'll see what I can do about adding a timer (I know VB.net...I can at least figure out the logical parts and hopefully adapt).

But I think you are right about it not reconnecting or better yet only trying on a disconnect which then if it fails just once it give up. Enabling debug might show me that so I'll start there.

But back to the original question and the previously closed issue: Is this functionality not built-in? And if not why was the previous issue closed as "kind of" working? Also if not will it be?

@vseven
Copy link
Contributor Author

@vseven vseven commented Sep 22, 2017

I switched the debug level to debug and opened serial monitor and got this over and over:

[WiFi-event] event: 5
WiFi lost connection.  Attempting to reconnect...
[WiFi-event] event: 5
WiFi lost connection.  Attempting to reconnect...
[WiFi-event] event: 5
WiFi lost connection.  Attempting to reconnect...

I checked the last time it sent data to another controller and that was over 24 hours ago so I'm assuming its stuck in this mode. So I powered it down and back up, it connected to WiFi just fine and transmitted data how it should for about 2 hours this time. Then without any other message it disconnected and started with the exact same message over and over. I let it go for a hour, rebooted the controller, and its connected again but I'm sure its just a matter of time before it starts over.

So the first question is how do I fix it. Second this still leads me to my previous questions about auto reconnect

@me-no-dev
Copy link
Member

@me-no-dev me-no-dev commented Sep 22, 2017

Guys please enable debug so you can see more verbose WiFi state output:
screen shot 2017-09-22 at 13 48 16

@everslick
Copy link
Contributor

@everslick everslick commented Sep 22, 2017

I use the following code to check if my device is still connected to the STA (call this from loop()). You get the idea? wifi_is_connected is a global that gets set and reset in the wifi event callback.

static void poll_watchdog_sta(void) {
  static uint32_t ms = millis();
  static uint8_t watchdog = 0;

  // watch out for STA disconnects and reboot if
  // connection cannot be reestablished after
  // X minutes

  // this watchdog MUST NOT reboot the device if
  // wifi is not enabled or never was connected
  // since last reboot

  if (wifi_is_enabled && watchdog_enabled && ((millis() - ms) > 1000 * 6)) {
    ms = millis();

    if (!wifi_is_connected) {
      if (++watchdog < watchdog_timeout * 10) { // timeout in minutes ( * 10 )
        if (watchdog == 1) {
          log_print(F("WIFI: arming network watchdog (reboot in %i min.)"),
            watchdog_timeout
          );
        }
      } else {
        log_print(F("WIFI: still not connected, triggering reboot ..."));
        system_reboot();
      }
    } else {
      if (watchdog) {
        log_print(F("WIFI: network is back, disarming watchdog"));
        watchdog = 0;
      }
    }
  }
}
@vseven
Copy link
Contributor Author

@vseven vseven commented Sep 22, 2017

Yeah, I don't see a Loop() in the library I'm using for WiFi (again, third party) but I understand what you are doing and can run with it.

Going to turn on the verbose logging and see if I get any more info first before changing anything.

Also the WiFi Events that are being checked and acted on are SYSTEM_EVENT_STA_GOT_IP, SYSTEM_EVENT_STA_DISCONNECTED, SYSTEM_EVENT_STA_START, and SYSTEM_EVENT_STA_CONNECTED. There are more however at https://github.com/espressif/esp-idf/blob/master/components/esp32/include/esp_event.h so I added a default: to the switch that should print out the event to see if the library is getting something but just not acting on it.

I saw in the library I'm using a //WiFi.setAutoReconnect(true); so I'm assuming the original author tried to use auto reconnect but it wasn't working so commented it out?

@vseven
Copy link
Contributor Author

@vseven vseven commented Sep 22, 2017

@me-no-dev - Verbose gave a much better explanation. Well...maybe to you:

Everything was fine then got this over and over, maybe 150 times:

[E][WiFiClient.cpp:97] connect(): lwip_connect_r: 113

Followed by this:

[D][WiFiGeneric.cpp:182] _eventCallback(): Event: 5 - STA_DISCONNECTED
[W][WiFiGeneric.cpp:187] _eventCallback(): Reason: 7 - NOT_ASSOCED
[WiFi-event] event: 5
WiFi lost connection.  Attempting to reconnect...
[D][WiFiGeneric.cpp:182] _eventCallback(): Event: 5 - STA_DISCONNECTED
[W][WiFiGeneric.cpp:187] _eventCallback(): Reason: 202 - ASSOC_FAIL
[WiFi-event] event: 5
WiFi lost connection.  Attempting to reconnect...
[D][WiFiGeneric.cpp:182] _eventCallback(): Event: 5 - STA_DISCONNECTED
[W][WiFiGeneric.cpp:187] _eventCallback(): Reason: 2 - AUTH_EXPIRE
[WiFi-event] event: 5
WiFi lost connection.  Attempting to reconnect...
[D][WiFiGeneric.cpp:182] _eventCallback(): Event: 5 - STA_DISCONNECTED
[W][WiFiGeneric.cpp:187] _eventCallback(): Reason: 2 - AUTH_EXPIRE
[WiFi-event] event: 5

The the last part (reconnect, event 5, reason 2) just repeats every 4 - 5 seconds.

@vseven
Copy link
Contributor Author

@vseven vseven commented Sep 25, 2017

Based on that first error that repeats over and over I found this: #180. In it you said "Try flushing the client or reading all available data. ". How would I go about doing that? I'm looking at the library I'm using and this is what they have to catch the WiFi Event:

//**************************************************************************************
/// Event Handler for ESP32 WiFi Events (needed to implement reconnect logic for now...)
//**************************************************************************************
	void MyESP32WiFi::WiFiEvent(WiFiEvent_t event)
	{
		Serial.printf("[WiFi-event] event: %d\n", event);

		switch (event) {
		case SYSTEM_EVENT_STA_GOT_IP:
			Serial.println("WiFi connected");
			Serial.println("IP address: ");
			Serial.println(WiFi.localIP());
			break;
		case SYSTEM_EVENT_STA_DISCONNECTED:
			Serial.println("WiFi lost connection.  Attempting to reconnect...");
			WiFi.reconnect();
			break;
		case SYSTEM_EVENT_STA_START:
			Serial.println("ESP32 station start");
			break;
		case SYSTEM_EVENT_STA_CONNECTED:
			Serial.println("ESP32 station connected to AP");
			break;
		default:			
			Serial.println("Unhandled WiFi Event raised.");
			break;
		}

	}

Based on the errors in the previous post I'm getting the "5" which is translating to the WiFi connection lost and then the code is trying to execute "WiFi.reconnect();" but its obviously not working. Should I have something else there? Maybe a counter kinda like @everslick example but simpler (just a i = i + 1) and if it end up on the same place after 20 tries it reboots? Or should this not happen/be prevented in the first place?

@me-no-dev
Copy link
Member

@me-no-dev me-no-dev commented Sep 25, 2017

Try calling WiFi.begin() instead of reconnect and report back :)

@vseven
Copy link
Contributor Author

@vseven vseven commented Sep 26, 2017

@me-no-dev - I changed it to WiFi.begin() instead of WiFi.reconnect() but it didn't help. Worked for about a hour then got the lwip_connect_r:113 line, each one about a minute or so apart followed by the disconnect every 5 or so seconds:

[E][WiFiClient.cpp:97] connect(): lwip_connect_r: 113
[E][WiFiClient.cpp:97] connect(): lwip_connect_r: 113
[E][WiFiClient.cpp:97] connect(): lwip_connect_r: 113
[E][WiFiClient.cpp:97] connect(): lwip_connect_r: 113
[D][WiFiGeneric.cpp:182] _eventCallback(): Event: 5 - STA_DISCONNECTED
[W][WiFiGeneric.cpp:187] _eventCallback(): Reason: 7 - NOT_ASSOCED
[WiFi-event] event: 5
WiFi lost connection.  Attempting to reconnect...
[D][WiFiGeneric.cpp:182] _eventCallback(): Event: 5 - STA_DISCONNECTED
[W][WiFiGeneric.cpp:187] _eventCallback(): Reason: 2 - AUTH_EXPIRE
[WiFi-event] event: 5
WiFi lost connection.  Attempting to reconnect...
[D][WiFiGeneric.cpp:182] _eventCallback(): Event: 5 - STA_DISCONNECTED
[W][WiFiGeneric.cpp:187] _eventCallback(): Reason: 2 - AUTH_EXPIRE

And then the 4 lines just repeat indefinitely until the control is rebooted. What else can I try? The fact @everslick is rebooting the controller when its in the same disconnected state is worrisome....I would think rebooting is the last option and something can be done to keep it online.

As a side note two ESP8266's connected to the same router (Netgear R8000) have no issues and have been stable for over a month without disconnects.

@me-no-dev
Copy link
Member

@me-no-dev me-no-dev commented Sep 26, 2017

hmmm.... this seems like an issue either in the lower stack or in your router.
you can see the first reason being NOT_ASSOCED and then you get AUTH_EXPIRE.
could you maybe turn off the STA and then turn it back on? The disconnect cause makes me think that something in the re-assoc request is either not changed or your router does not accept, so it refuses you to connect back. I'll see if I can raise an internal issue about this. What is the router firmware version that you are using?

@vseven
Copy link
Contributor Author

@vseven vseven commented Sep 26, 2017

Its a Netgear Nighthawk R8000. Currently on the latest firmware V1.0.3.54_1.1.37 although it did it on the last version also. I have 20 - 25 devices connected at any given time without issues including the previously mentioned two ESP8266's.

I will attempt to replace the Wi-Fi begin/reconnect line with the STA off and on and see what happens.

Edit: Knowing not much about this and using someone elses library....how do I "turn off the STA and then turn it back on"?

Second Edit: It couldn't be related to espressif/esp-idf#499 (comment) could it? One of the only things I've seen with the same NOT_ASSOCED and AUTH_EXPIRE. I wouldn't think so only because I compiled myself without the BLE stuff but never know.

@me-no-dev
Copy link
Member

@me-no-dev me-no-dev commented Sep 26, 2017

I have also alerted the wifi team :) we will see if anything comes out of this

@vseven
Copy link
Contributor Author

@vseven vseven commented Sep 26, 2017

Thanks. Should I be trying to do the STA off and on? If so can you guide me how or point me in the right direction?

I also saw this: espressif/esp-idf#738 (comment) which indicated that I can't call the WiFi.connect or WiFi.Begin from the event handler? Could that also be my issue? @rojer ?

@vseven
Copy link
Contributor Author

@vseven vseven commented Sep 28, 2017

So I bought a second ESP32, same one, to try and make sure it isn't a hardware issue. I recompiled the firmware yesterday night off a fresh pull from github (https://nodemcu.readthedocs.io/en/dev-esp32/en/build/) and flashed both the new chip and the old one. I also flashed both with the exact same sketch. The original is in my garage, a little ways from my router, and the other test one is in my living room where the WiFi is a lot stronger. Both have serial monitor running on a connected PC with verbose set. I'll report back anything I find.

With the above said is there anything else I can try? How do I do the STA off and on? Can that be done in the STA_Disconnect part where the WiFi.reconnect is?

@lonerzzz lonerzzz changed the title WiFi Auto Reconnect Still Not Working? Is there a best practice to guaranty connection? WiFi Auto Reconnect Still Not Working - Is there a best practice to guarantee connection? Sep 28, 2017
@vseven
Copy link
Contributor Author

@vseven vseven commented Sep 29, 2017

Well that didn't last long....I'm having the same issue with the new one. First the original one started with the same "[E][WiFiClient.cpp:97] connect(): lwip_connect_r: 113" error and not sending data after barely 30 minutes online. Usually got that error two at a time with about 5 or 6 seconds between then then 45 - 50 seconds between the next set but again kinda random. Did that for around 10 minutes then went into the same disconnect pattern:


[E][WiFiClient.cpp:97] connect(): lwip_connect_r: 113
[E][WiFiClient.cpp:97] connect(): lwip_connect_r: 113
Data: Sending: temperature1 -49.02
[E][WiFiClient.cpp:97] connect(): lwip_connect_r: 113
[E][WiFiClient.cpp:97] connect(): lwip_connect_r: 113
Data: Sending: humidity1 -5.02
[D][WiFiGeneric.cpp:182] _eventCallback(): Event: 5 - STA_DISCONNECTED
[W][WiFiGeneric.cpp:187] _eventCallback(): Reason: 7 - NOT_ASSOCED
[WiFi-event] event: 5
WiFi lost connection.  Attempting to reconnect...
[D][WiFiGeneric.cpp:182] _eventCallback(): Event: 5 - STA_DISCONNECTED
[W][WiFiGeneric.cpp:187] _eventCallback(): Reason: 202 - ASSOC_FAIL
[WiFi-event] event: 5
WiFi lost connection.  Attempting to reconnect...
[D][WiFiGeneric.cpp:182] _eventCallback(): Event: 5 - STA_DISCONNECTED
[W][WiFiGeneric.cpp:187] _eventCallback(): Reason: 2 - AUTH_EXPIRE
[WiFi-event] event: 5

And repeated the last 4 lines over and over. At one point it did do something different...the error message changed slightly:

[E][WiFiClient.cpp:97] connect(): lwip_connect_r: 113
[E][WiFiClient.cpp:97] connect(): lwip_connect_r: 118
Data: Sending: temperature2 -1.00
[E][WiFiClient.cpp:97] connect(): lwip_connect_r: 118
[E][WiFiClient.cpp:97] connect(): lwip_connect_r: 118
Data: Sending: humidity2 -1.00
[E][WiFiClient.cpp:97] connect(): lwip_connect_r: 118
[E][WiFiClient.cpp:97] connect(): lwip_connect_r: 118
[D][WiFiGeneric.cpp:182] _eventCallback(): Event: 5 - STA_DISCONNECTED
[W][WiFiGeneric.cpp:187] _eventCallback(): Reason: 2 - AUTH_EXPIRE
[WiFi-event] event: 5

Notice the error switched to ending in 118 as opposed to 113. But from that point on it just repeated the 118 error randomly along with the STA_DISCONNECTED and AUTH_EXPIRED over and over.

Then the new ESP32 started doing the exact same thing. mostly 113 error then the same pattern of NOT_ASSOCED, ASSOC_FAIL, and AUTH_EXPIRE followed by just the disconnect and AUTH_EXPIRE over and over.

They failed at different times, 25 minutes apart, while they were started at the exact same time. WiFi signal doesn't seem to be a factor nor does any certain timing.

Edit: Just to be clear on a reboot it connects instantly on the first try every time:

rst:0x1 (POWERON_RESET),boot:0x13 (SPI_FAST_FLASH_BOOT)
flash read err, 1000
ets_main.c 371 
ets Jun  8 2016 00:22:57

rst:0x10 (RTCWDT_RTC_RESET),boot:0x13 (SPI_FAST_FLASH_BOOT)
configsip: 0, SPIWP:0xee
clk_drv:0x00,q_drv:0x00,d_drv:0x00,cs0_drv:0x00,hd_drv:0x00,wp_drv:0x00
mode:DIO, clock div:1
load:0x3fff0010,len:4
load:0x3fff0014,len:708
load:0x40078000,len:0
load:0x40078000,len:11460
entry 0x400789f4
Everything: init started
Everything: Free RAM = -1
Disabling ESP32 WiFi Access Point
[D][WiFiGeneric.cpp:182] _eventCallback(): Event: 2 - STA_START
[WiFi-event] event: 2
Initializing ESP32 WiFi network.  Please be patient...
ESP32 station start
Attempting to connect to WPA SSID: (SSIDRemoved)
..[D][WiFiGeneric.cpp:182] _eventCallback(): Event: 4 - STA_CONNECTED
[WiFi-event] event: 4
ESP32 station connected to AP
[D][WiFiGeneric.cpp:182] _eventCallback(): Event: 7 - STA_GOT_IP
[WiFi-event] event: 7
WiFi connected
IP address: 
192.168.xx.xx
@me-no-dev
Copy link
Member

@me-no-dev me-no-dev commented Sep 29, 2017

Still waiting on response from the WiFi team. Will make some more noise as this is annoying to me as well. Issue is somewhere way below Arduino and in the closed source wifi lib.

@vseven
Copy link
Contributor Author

@vseven vseven commented Sep 29, 2017

Thanks. I'm going to attempt to add a counter to the STA_DISCONNECTED event switch statement that I keep getting and after 5 try to re-init the wifi and after 10 reboot the controller and on a connect reset the counter to 0, see if that at least keeps the controller up.

If there is anything else I can provide you to help get this fixed or code to try please let me know. If it matters the ESP32 I'm using is being used for two voltage inputs, one binary input, and a DTH22 (temp + humidity) then that data is being sent to a controller through HTTP.

@liuzfesp
Copy link

@liuzfesp liuzfesp commented Sep 29, 2017

Hi @vseven, I just can't reproduce this issue myself, could you let me know the firmware version of WiFi? You can get if from the startup log, it looks like "I (588) wifi: wifi firmware version: 2cd69aa", then I can provide a debug version wifi lib to you to debug this issue.

@liuzfesp
Copy link

@liuzfesp liuzfesp commented Sep 29, 2017

@vseven could you let me know the WiFi reconnect logic? I means when to call esp_wifi_connect()? It will be helpful if you can paste the implementation logic.

@me-no-dev
Copy link
Member

@me-no-dev me-no-dev commented Sep 29, 2017

@liuzfesp wifi logging is disabled in Arduino.
@vseven comment this line to get it to show

@vseven
Copy link
Contributor Author

@vseven vseven commented Sep 29, 2017

Ok, I commented out that line and recompiled. I'll report back. As a side note I tried to add a counter to reconnect by recalling my init() but it didn't do anything....it was like the init() was never called. I might be doing it wrong though. But when the counter got to 10 the ESP.restart defiantly was called and rebooted correctly which afterward it reconnected:

	void SmartThingsESP32WiFi::WiFiEvent(WiFiEvent_t event)
	{
		Serial.printf("[WiFi-event] event: %d\n", event);
		switch (event) {
		case SYSTEM_EVENT_STA_GOT_IP:
			Serial.println("WiFi connected");
			Serial.println("IP address: ");
			Serial.println(WiFi.localIP());
			break;
		case SYSTEM_EVENT_STA_DISCONNECTED:
			Serial.println("WiFi lost connection.  Attempting to reconnect...");
			WiFi.reconnect();
			disconnectCounter++;
			if (disconnectCounter > 5) {
				Serial.println("We have recieved the STA_DISCONNECTED event 5 times now.  Re-init...");
				void init();
			}
			if (disconnectCounter > 10) {
				Serial.println("We have recieved the STA_DISCONNECTED event 10 times now.  Reboot...");
				ESP.restart();
			}
			break;
		case SYSTEM_EVENT_STA_START:
			Serial.println("ESP32 station start");
			break;
		case SYSTEM_EVENT_STA_CONNECTED:
			Serial.println("ESP32 station connected to AP");
			disconnectCounter = 0;
			break;
		}
	}

@liuzfesp - here is the extra info with that line commented out:

I (243) wifi: wifi firmware version: c1b8a2f
I (243) wifi: config NVS flash: enabled
I (243) wifi: config nano formating: disabled
I (257) wifi: Init dynamic tx buffer num: 32
I (257) wifi: Init data frame dynamic rx buffer num: 64
I (257) wifi: Init management frame dynamic rx buffer num: 64
I (261) wifi: wifi driver task: 3ffd0d8c, prio:23, stack:4096
I (267) wifi: Init static rx buffer num: 10
I (270) wifi: Init dynamic rx buffer num: 0
I (274) wifi: Init rx ampdu len mblock:7
I (278) wifi: Init lldesc rx ampdu entry mblock:4
I (282) wifi: wifi power manager task: 0x3ffd60f0 prio: 21 stack: 2560
I (290) wifi: wifi timer task: 3ffd7148, prio:22, stack:3584
I (314) wifi: mode : null
Disabling ESP32 WiFi Access Point

I (815) wifi: Init Ampdu: 1 tx baw=6 rx baw=6
I (815) wifi: mode : sta (30:ae:a4:25:78:64)
[D][WiFiGeneric.cpp:182] _eventCallback(): Event: 2 - STA_START

Initializing ESP32 WiFi network.  Please be patient...
[WiFi-event] event: 2
ESP32 station start
Attempting to connect to WPA SSID: (SSIDREMOVED)
.I (1946) wifi: n:1 0, o:1 0, ap:255 255, sta:1 0, prof:1
.I (2603) wifi: state: init -> auth (b0)
I (2605) wifi: state: auth -> assoc (0)
I (2612) wifi: state: assoc -> run (10)
I (2670) wifi: connected with (SSIDREMOVED), channel 1
[D][WiFiGeneric.cpp:182] _eventCallback(): Event: 4 - STA_CONNECTED
[WiFi-event] event: 4
ESP32 station connected to AP
[D][WiFiGeneric.cpp:182] _eventCallback(): Event: 7 - STA_GOT_IP
[WiFi-event] event: 7
WiFi connected

And the files I'm using (before I added the disconnect counter):

SmartThingsESP32WiFi.h.txt
SmartThingsESP32WiFi.cpp.txt

@vseven
Copy link
Contributor Author

@vseven vseven commented Sep 30, 2017

@liuzfesp - So it did the same thing with the debug enabled, hopefully something in here will tell you something. It ran fine for a hour or so then started throwing the 113 error randomly. After about 15 minutes of random 113 errors in between the actual data sending routines it did this:

I (5427111) wifi: state: run -> auth (7c0)
I (5427111) wifi: pm stop, total sleep time: 0/1119534452

I (5427111) wifi: n:1 0, o:1 0, ap:255 255, sta:1 0, prof:1
[D][WiFiGeneric.cpp:182] _eventCallback(): Event: 5 - STA_DISCONNECTED
[W][WiFiGeneric.cpp:187] _eventCallback(): Reason: 7 - NOT_ASSOCED
[WiFi-event] event: 5
WiFi lost connection.  Attempting to reconnect...
I (5427133) wifi: state: auth -> init (0)
[D][WiFiGeneric.cpp:182] _eventCallback(): Event: 5 - STA_DISCONNECTED
[W][WiFiGeneric.cpp:187] _eventCallback(): Reason: 202 - ASSOC_FAIL
[WiFi-event] event: 5
WiFi lost connection.  Attempting to reconnect...
I (5427276) wifi: n:1 0, o:1 0, ap:255 255, sta:1 0, prof:1
I (5427276) wifi: state: init -> auth (b0)
I (5428276) wifi: state: auth -> init (2)
I (5428277) wifi: n:1 0, o:1 0, ap:255 255, sta:1 0, prof:1
[D][WiFiGeneric.cpp:182] _eventCallback(): Event: 5 - STA_DISCONNECTED
[W][WiFiGeneric.cpp:187] _eventCallback(): Reason: 2 - AUTH_EXPIRE
[WiFi-event] event: 5
WiFi lost connection.  Attempting to reconnect...
I (5428413) wifi: n:1 0, o:1 0, ap:255 255, sta:1 0, prof:1
I (5428414) wifi: state: init -> auth (b0)
I (5429414) wifi: state: auth -> init (2)
I (5429414) wifi: n:1 0, o:1 0, ap:255 255, sta:1 0, prof:1
[D][WiFiGeneric.cpp:182] _eventCallback(): Event: 5 - STA_DISCONNECTED
[W][WiFiGeneric.cpp:187] _eventCallback(): Reason: 2 - AUTH_EXPIRE
[WiFi-event] event: 5
WiFi lost connection.  Attempting to reconnect...
I (5429551) wifi: n:1 0, o:1 0, ap:255 255, sta:1 0, prof:1
I (5429551) wifi: state: init -> auth (b0)
I (5430551) wifi: state: auth -> init (2)
I (5430551) wifi: n:1 0, o:1 0, ap:255 255, sta:1 0, prof:1
[D][WiFiGeneric.cpp:182] _eventCallback(): Event: 5 - STA_DISCONNECTED
[W][WiFiGeneric.cpp:187] _eventCallback(): Reason: 2 - AUTH_EXPIRE
[WiFi-event] event: 5
WiFi lost connection.  Attempting to reconnect...
I (5430688) wifi: n:1 0, o:1 0, ap:255 255, sta:1 0, prof:1
I (5430688) wifi: state: init -> auth (b0)
I (5431689) wifi: state: auth -> init (2)
I (5431689) wifi: n:1 0, o:1 0, ap:255 255, sta:1 0, prof:1
[D][WiFiGeneric.cpp:182] _eventCallback(): Event: 5 - STA_DISCONNECTED
[W][WiFiGeneric.cpp:187] _eventCallback(): Reason: 2 - AUTH_EXPIRE
[WiFi-event] event: 5
WiFi lost connection.  Attempting to reconnect...
We have recieved the STA_DISCONNECTED event 5 times now.  Re-init...
I (5431826) wifi: n:1 0, o:1 0, ap:255 255, sta:1 0, prof:1
I (5431826) wifi: state: init -> auth (b0)
I (5432826) wifi: state: auth -> init (2)
I (5432826) wifi: n:1 0, o:1 0, ap:255 255, sta:1 0, prof:1
[D][WiFiGeneric.cpp:182] _eventCallback(): Event: 5 - STA_DISCONNECTED
[W][WiFiGeneric.cpp:187] _eventCallback(): Reason: 2 - AUTH_EXPIRE
[WiFi-event] event: 5
WiFi lost connection.  Attempting to reconnect...
We have recieved the STA_DISCONNECTED event 5 times now.  Re-init...
I (5432963) wifi: n:1 0, o:1 0, ap:255 255, sta:1 0, prof:1
I (5432963) wifi: state: init -> auth (b0)
I (5433964) wifi: state: auth -> init (2)
I (5433964) wifi: n:1 0, o:1 0, ap:255 255, sta:1 0, prof:1
[D][WiFiGeneric.cpp:182] _eventCallback(): Event: 5 - STA_DISCONNECTED
[W][WiFiGeneric.cpp:187] _eventCallback(): Reason: 2 - AUTH_EXPIRE
[WiFi-event] event: 5
WiFi lost connection.  Attempting to reconnect...
We have recieved the STA_DISCONNECTED event 5 times now.  Re-init...
I (5434100) wifi: n:1 0, o:1 0, ap:255 255, sta:1 0, prof:1
I (5434101) wifi: state: init -> auth (b0)
I (5435101) wifi: state: auth -> init (2)
I (5435101) wifi: n:1 0, o:1 0, ap:255 255, sta:1 0, prof:1
[D][WiFiGeneric.cpp:182] _eventCallback(): Event: 5 - STA_DISCONNECTED
[W][WiFiGeneric.cpp:187] _eventCallback(): Reason: 2 - AUTH_EXPIRE
[WiFi-event] event: 5
WiFi lost connection.  Attempting to reconnect...
We have recieved the STA_DISCONNECTED event 5 times now.  Re-init...
I (5435238) wifi: n:1 0, o:1 0, ap:255 255, sta:1 0, prof:1
I (5435238) wifi: state: init -> auth (b0)
I (5436238) wifi: state: auth -> init (2)
I (5436239) wifi: n:1 0, o:1 0, ap:255 255, sta:1 0, prof:1
[D][WiFiGeneric.cpp:182] _eventCallback(): Event: 5 - STA_DISCONNECTED
[W][WiFiGeneric.cpp:187] _eventCallback(): Reason: 2 - AUTH_EXPIRE
[WiFi-event] event: 5
WiFi lost connection.  Attempting to reconnect...
We have recieved the STA_DISCONNECTED event 5 times now.  Re-init...
I (5436375) wifi: n:1 0, o:1 0, ap:255 255, sta:1 0, prof:1
I (5436376) wifi: state: init -> auth (b0)
I (5437376) wifi: state: auth -> init (2)
I (5437376) wifi: n:1 0, o:1 0, ap:255 255, sta:1 0, prof:1
[D][WiFiGeneric.cpp:182] _eventCallback(): Event: 5 - STA_DISCONNECTED
[W][WiFiGeneric.cpp:187] _eventCallback(): Reason: 2 - AUTH_EXPIRE
[WiFi-event] event: 5
WiFi lost connection.  Attempting to reconnect...
We have recieved the STA_DISCONNECTED event 5 times now.  Re-init...
We have recieved the STA_DISCONNECTED event 10 times now.  Reboot...
I (5437405) wifi: flush txq
I (5437407) wifi: stop sw txq
I (5437410) wifi: lmac stop hw txq
ets Jun  8 2016 00:22:57

rst:0xc (SW_CPU_RESET),boot:0x13 (SPI_FAST_FLASH_BOOT)

So for each STA_DISCONNECT it tried calling WiFi.reconnect with no apparent success then it tried running init() after more then 5 disconnects which also didn't help then once it hit 10 disconnects it rebooted which did reboot and reconnect.

@vseven
Copy link
Contributor Author

@vseven vseven commented Oct 2, 2017

I kept serial monitor running on my ESP32 all weekend and it rebooted about 10 times between 6pm Friday night and 9pm Sunday night. Each time it was exactly like the above logs.

@me-no-dev - can you guide me in a way to just turn off and back on the STA to see if that also works for reconnecting and I can try that after 5 failed attempts? The reboot after 10 works but I plan on using this to control RGB lighting and I really don't want to have lights turning off and on.

@liuzfesp - Is there anything else I can provide you with for debugging? Or anything that stands out I can try?

@vseven
Copy link
Contributor Author

@vseven vseven commented Oct 6, 2017

Any updates? Still have constant disconnects with both devices.

@me-no-dev
Copy link
Member

@me-no-dev me-no-dev commented Oct 10, 2017

@liuzfesp any news here?

@maxdd
Copy link

@maxdd maxdd commented Mar 21, 2019

@vseven

Newer firmware seems to help, gonna close this.

Hello there,
I always thought platformio by updating the arduino-esp32 library was also able to update what you called the firmware. Am i wrong? I'm still suffering from this problem!

@Miq1
Copy link

@Miq1 Miq1 commented Mar 22, 2019

@vseven
Newer firmware seems to help, gonna close this.

Hello there,
I always thought platformio by updating the arduino-esp32 library was also able to update what you called the firmware. Am i wrong? I'm still suffering from this problem!

Same here. Would like to have a pointer to how to update firmware by platformio to get around the disconnect issue myself...

@mickeypop
Copy link

@mickeypop mickeypop commented Mar 22, 2019

@vseven
Platform IO setup instructions and update are addressed here
https://github.com/espressif/arduino-esp32/blob/master/docs/platformio.md

a tid bit however: on both Arduino and Platform IO when i use git to update the SDK i have on some occasions found the update was not complete and had issues.

Rename the esp32 folder and re-install from a fresh git and i have always gotten a clean update.
Just follow their instructions.

@Miq1
Copy link

@Miq1 Miq1 commented Mar 22, 2019

@mickeypop: well, my platformio is on the latest stable version, but I still have the disconnect issue. Do you suggest using the stage or upstream versions instead? The stable was only updated a few days ago, by the way.

@liuzfesp
Copy link

@liuzfesp liuzfesp commented Mar 24, 2019

@Miq1 does this issue exist if only use IDF example?

@Miq1
Copy link

@Miq1 Miq1 commented Mar 24, 2019

I must confess that I am using the Arduino in Platformio environment only - I never dealt with the IDF. I will look into it today to see if I can set up a basic version of my application there.

@Miq1
Copy link

@Miq1 Miq1 commented Mar 25, 2019

Just for the records: I found that the workaround with disconnect() and subsequent begin() works for me if I do a mode(WIFI_OFF) and mode(WIFI_STA) in between. I am currently trying the reconnect 5 times in a row and would do an esp.restart() if all attempts failed, but so far no restart was necessary.

@Miq1
Copy link

@Miq1 Miq1 commented Mar 26, 2019

I observed a few restarts in the meantime, so the workaround seems not to be as effective.

@bsayiner
Copy link

@bsayiner bsayiner commented Sep 22, 2019

Is there any update about this bug?

@davydnorris
Copy link

@davydnorris davydnorris commented Nov 12, 2019

FWIW I see this often on ESP8266 units too - exact same symptoms. I've found I can change the connect quite drastically simply by orienting the unit differently - so it seems to be related to how the units (both ESP8266 and ESP32) respond to bad signal.

Given I am using NonOS and an ESP8266, the common denominator seems to be the low level networking below lwIP

@mcpicoli
Copy link

@mcpicoli mcpicoli commented Dec 17, 2019

(Using 1.0.4 version of Arduino-esp32)

I had the same problem here (using ESP32). Found that rebooting the router solves the problem... once. That is, after the reboot, the ESP32 is able to connect to the AP, get an IP address and stay connected, but if something causes the connection to fail (like rebooting the ESP32), the ESP32 then is never able to connect to the AP again.

The router is a TP-Link TL-MR2030 that I keep around for wired ethernet tests and has firmware that is hopelessly outdated by years and no newer official firmware exists.

However, if I try to use other APs, like some quite new Ubiquiti units at the office, the problem simply does not happen at all. I even raised some suspicion on the IT staff by forcing the board to purposely reboot and reconnect repeatedly as fast as possible for hours on end... and no trouble at all.

So, in the end, while it is possible that something is wrong or incomplete in the ESP32's libraries, I am ready to put all the blame on the old router's firmware. Time to get a new router for tests, not from TP-LINK, however.

@tablatronix
Copy link
Contributor

@tablatronix tablatronix commented Dec 17, 2019

I usually suspect dns for things like this. Or sometimes the router still thinks you are connected and never allows you to reconnect

@daald
Copy link

@daald daald commented Dec 28, 2019

No, the router is not to blame. At least in my case. Sure, it's not the newest (wnr2200) but with an up-to-date DD-WRT installed and several android, linux and windows devices working without issues.

To finally solve this issue for myself, I started over with a completely new implementation, based on WiFiClientEvents.ino - so it's event-based. I also read the newest commit messages of arduino-esp32 which revealed very recent but relevant commits. I had to do some debugging in WiFiGeneric.cpp and found that mode doesn't always do what's expected (#1306).

Final result: with a little patch on WiFiGeneric.cpp (see end of file), I was able to connect and disconnect several times to/from my AP - hurray :)

Let me know if you see something to improve.

/*
 * This is a very stable example of repeated connecting and disconnecting to/from a wifi access point on STA32
 * Unfortunately, it needs patching of the WiFiGeneric.cpp library file
 * Author: Daniel Alder, based on the example WiFiClientEvents.ino
 * Tested with Arduino 1.8.5 and 1.8.10 with ESP library from Nov 11 2019 (cec3fca4) + patch
*/

#include <WiFi.h>   

#include "HomeWifiConfig.h" // use an extra include or uncomment the following 2 lines
//const char* ssid     = "myssid"; // your network SSID (name of wifi network)
//const char* password = "****";   // your network password

typedef enum {
  MYSTATE_OFFLINE = 0,
  MYSTATE_CONNECTING,
  MYSTATE_ONLINE,
  MYSTATE_DISCONNECTING
} mystate_t;
mystate_t mystate = MYSTATE_OFFLINE;
long state_since = 0;

#define TIMEOUT_ONLINE     20  // reconnect after this [s] offline time
#define TIMEOUT_OFFLINE    20  // disconnect after this [s] online time
#define TIMEOUT_CONNECTING 20  // cancel connecting after this [s] without success

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

long getUptime() {
  return esp_timer_get_time() / 1000000L;
}

void changeState(mystate_t state) {
  mystate = state;
  state_since = getUptime();
}

void WiFiEvent(WiFiEvent_t event, WiFiEventInfo_t info)
{
    Serial.printf("[WiFi-event] event: %d\n", event);

    switch (event) {
        case SYSTEM_EVENT_WIFI_READY: 
            Serial.println("WiFi interface ready");
            break;
        case SYSTEM_EVENT_SCAN_DONE:
            Serial.println("Completed scan for access points");
            break;
        case SYSTEM_EVENT_STA_START:
            Serial.println("WiFi client started");
            break;
        case SYSTEM_EVENT_STA_STOP:
            Serial.println("WiFi client stopped");
            changeState(MYSTATE_OFFLINE);
            break;
        case SYSTEM_EVENT_STA_CONNECTED:
            Serial.println("Connected to access point");
            break;
        case SYSTEM_EVENT_STA_DISCONNECTED:
            Serial.println("Disconnected from WiFi access point");
            break;
        case SYSTEM_EVENT_STA_AUTHMODE_CHANGE:
            Serial.println("Authentication mode of access point has changed");
            break;
        case SYSTEM_EVENT_STA_GOT_IP:
            Serial.print("Obtained IP address: ");
            //Serial.println(WiFi.localIP());
            //Serial.println("WiFi connected");
            //Serial.print("IP address: ");
            Serial.println(IPAddress(info.got_ip.ip_info.ip.addr));

            changeState(MYSTATE_ONLINE);

            break;
        case SYSTEM_EVENT_STA_LOST_IP:
            Serial.println("Lost IP address and IP address is reset to 0");
            //changeState(MYSTATE_OFFLINE);
            break;
        case SYSTEM_EVENT_STA_WPS_ER_SUCCESS:
            Serial.println("WiFi Protected Setup (WPS): succeeded in enrollee mode");
            break;
        case SYSTEM_EVENT_STA_WPS_ER_FAILED:
            Serial.println("WiFi Protected Setup (WPS): failed in enrollee mode");
            break;
        case SYSTEM_EVENT_STA_WPS_ER_TIMEOUT:
            Serial.println("WiFi Protected Setup (WPS): timeout in enrollee mode");
            break;
        case SYSTEM_EVENT_STA_WPS_ER_PIN:
            Serial.println("WiFi Protected Setup (WPS): pin code in enrollee mode");
            break;
        case SYSTEM_EVENT_AP_START:
            Serial.println("WiFi access point started");
            break;
        case SYSTEM_EVENT_AP_STOP:
            Serial.println("WiFi access point  stopped");
            break;
        case SYSTEM_EVENT_AP_STACONNECTED:
            Serial.println("Client connected");
            break;
        case SYSTEM_EVENT_AP_STADISCONNECTED:
            Serial.println("Client disconnected");
            break;
        case SYSTEM_EVENT_AP_STAIPASSIGNED:
            Serial.println("Assigned IP address to client");
            break;
        case SYSTEM_EVENT_AP_PROBEREQRECVED:
            Serial.println("Received probe request");
            break;
        case SYSTEM_EVENT_GOT_IP6:
            Serial.println("IPv6 is preferred");
            break;
        case SYSTEM_EVENT_ETH_START:
            Serial.println("Ethernet started");
            break;
        case SYSTEM_EVENT_ETH_STOP:
            Serial.println("Ethernet stopped");
            break;
        case SYSTEM_EVENT_ETH_CONNECTED:
            Serial.println("Ethernet connected");
            break;
        case SYSTEM_EVENT_ETH_DISCONNECTED:
            Serial.println("Ethernet disconnected");
            break;
        case SYSTEM_EVENT_ETH_GOT_IP:
            Serial.println("Obtained IP address");
            break;
        default: break;
    }
}

#include "esp_wifi.h" // only for fixWifiPersistencyFlag()
/**
 * Disable persistent mode, see https://github.com/espressif/arduino-esp32/issues/1393
 */
void fixWifiPersistencyFlag() {
  wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
  Serial.printf("cfg.nvs_enable before: %d\n", cfg.nvs_enable);
  cfg.nvs_enable = 0;
}

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

void setup()
{
  Serial.begin(115200);
  Serial.println("-----------------------------------------");
  Serial.println("THIS IS: newWifiImplementationUsingEvents");
  Serial.println("-----------------------------------------");

  WiFi.persistent(false);
  fixWifiPersistencyFlag();

  //Serial.setDebugOutput(true); 
  //WiFi.printDiag(Serial); 

  // delete old config
  WiFi.disconnect(true);

  state_since = getUptime();

  delay(1000);

  // warning: only the last defined event handler gets events!
  WiFi.onEvent(WiFiEvent);

  Serial.println("End of setup");
}

bool firstTime = true;

void loop()
{
  long uptime = getUptime();
  if (mystate == MYSTATE_ONLINE && state_since + TIMEOUT_ONLINE < uptime) {
    Serial.println("Disconnecting NOW");
    changeState(MYSTATE_DISCONNECTING);
    WiFi.disconnect(true);
    WiFi.mode(WIFI_OFF);
  } else if (mystate == MYSTATE_OFFLINE && state_since+TIMEOUT_OFFLINE < uptime) {
    Serial.println("Connecting NOW");
    changeState(MYSTATE_CONNECTING);
    if (firstTime) {
      Serial.println("(firstTime)");
      WiFi.begin(ssid, password);
      firstTime = false;
    } else {
      // doesn't work without WiFiGeneric.cpp patch below
      WiFi.mode(WIFI_STA);
      WiFi.reconnect();
    }
  } else if (mystate == MYSTATE_CONNECTING && state_since+TIMEOUT_CONNECTING < uptime) {
    Serial.println("Cancelling NOW after no connect success");
    changeState(MYSTATE_DISCONNECTING);
    WiFi.disconnect(true);
    WiFi.mode(WIFI_OFF);
  }

  delay(1000);
  if (uptime % 10 == 0) {
    Serial.printf("uptime %d\n", uptime);
  }
}

/* PATH FOR LIBRARY
diff --git a/libraries/WiFi/src/WiFiGeneric.cpp b/libraries/WiFi/src/WiFiGeneric.cpp
index e562921..aab5805 100644
--- a/libraries/WiFi/src/WiFiGeneric.cpp
+++ b/libraries/WiFi/src/WiFiGeneric.cpp
@@ -483,8 +483,10 @@ void WiFiGenericClass::enableLongRange(bool enable)
 bool WiFiGenericClass::mode(wifi_mode_t m)
 {
     wifi_mode_t cm = getMode();
+    log_d("mode() cm=%d, m=%d", cm, m);
     if(cm == m) {
-        return true;
+        log_d("HACK: skip return true");
+        //return true;
     }
     if(!cm && m){
         if(!wifiLowLevelInit(_persistent)){
*/


/* ISSUES:
 *  
 * 1) The example WiFiClientEvents.ino says:
 * 
 *   WiFi.onEvent(WiFiEvent);
 *   WiFi.onEvent(WiFiGotIP, WiFiEvent_t::SYSTEM_EVENT_STA_GOT_IP);
 *   
 *   but the WiFiEvent function never receives a SYSTEM_EVENT_STA_GOT_IP!
 *   
 * 2) I used code from https://github.com/espressif/arduino-esp32/issues/1393 to fix the persistent config issue
 * 
 * 3) The list of events in WiFiClientEvents.ino (comment block) is missing an event. Same bug as fixed in 188560e7f33
 * 
 * 4) Without pathing of WiFiGeneric.cpp, the mode() function doesn't do anything anymore once WiFi it was initialized (not even connected)
 * 
 *   see also: https://github.com/espressif/arduino-esp32/issues/1306 (but the this patch is not yet mentioned there)
 * 
 * 5) just a note: there is a STA_LOST_IP event, 2 minutes after disconnecting. 
 *   So if you want to make your code stable, you should also test with TIMEOUT_OFFLINE > 130
 */
@mrarmyant
Copy link

@mrarmyant mrarmyant commented Jan 8, 2020

Has anyone wiresharked this?

Had a similar issue with an arduino wifi rev 2 (different hardware, but issues negotiating between ap's and the device was eerily similar.)

arduino/nina-fw#14

@daald
Copy link

@daald daald commented Jan 8, 2020

@mrarmyant What do you expect to see using wireshark? I think we are talking about issues on OSI layers 1 and 2. Differently said: no SSID, no frequency, no packets

My code (above your post) runs stable since I posted it. But I don't think the problem is portable to something different than ESP* chips because it addresses issues of the ESP SDK, not Arduino

@tablatronix
Copy link
Contributor

@tablatronix tablatronix commented Jan 9, 2020

I blame issues like this on power supply

@mickeypop
Copy link

@mickeypop mickeypop commented Jan 9, 2020

i wouldn't blame the PS, it's very unlikely unless you have a really weak supply this will not happen.

Wireshark is really useless here.

To understand you have to dig deep into the RTOS libraries where the real work is done, not the Arduino libs as they are a wrapper.

If you are using WiFi.reconnect() instead of WiFi.begin() you need to know a few things.

WiFi.begin() starts by setting all needed registers on the wifi chip and RTOS states before connecting, reconnect() does not.
This was reported over 2 years ago.

WiFi.reconnect() often makes only half of the connection, establishing a chip level MAC connection with UDP but never making the TCP/IP connection as these are separate protocols. This is due to needed states not being preset by reconnect() it simply assumes they are there.
This is why some of you are not getting the SYSTEM_EVENT_STA_GOT_IP on reconnect.

Remember; reconnecting is needed because the states have already changed.

I ALWAYS reconnect with WiFi.begin() and have never failed.

======
as to a reset not connecting and saying there is already a connection you need to know DHCP.
DHCP IP address is commonly re-established every 15 seconds.
Now let's say 2 second after reestablishing you press the reset.
The DHCP server isn't going to release the IP for another 13 seconds and on trying to connect it will report it in use.

A simple delay on boot before connecting has fixed this for me every time.
If you are setting up multiple other libraries, set them all first before WiFi.begin().

A good start timer will help here.
take a long var = millis(); in the first line of setup() and Serial.print( millis()-var); just before WiFi.begin() and find out just how fast you are actually booting. Then adjust accordingly.

I have been using the ESP32 for over 6 years and this has always worked.

@mickeypop
Copy link

@mickeypop mickeypop commented Jan 9, 2020

UPDATE; i see a lot of WiFiEvent used and for debugging its good but to simply detect wifi down and reconnect the IF/ELSE below works reliably every time.

this works because it takes about 18 seconds from down to reporting WL_CONNECTED change, this gives the DHCP server time to release the IP for a reliable re connect later.

It has been working for over 6 years and counting.

loop()
{
  if ( WiFi.status() ==  WL_CONNECTED ) 
  {
    // WiFi is UP,  do what ever
  } else
  {
    // wifi down, reconnect here
   WiFi.begin(  );
    int WLcount = 0;
    while (WiFi.status() != WL_CONNECTED && WLcount < 200 ) 
    {
      delay( 100 );
         Serial.printf(".");
         if (UpCount >= 60)  // just keep terminal from scrolling sideways
         {
            UpCount = 0;
               Serial.printf("\n");
         }
         ++UpCount;
      ++WLcount;
    }
  }
} // END loop()

take a look at the skeleton code i posted on #1100

though it was for setup with SmartConfig it just works.

@mrarmyant
Copy link

@mrarmyant mrarmyant commented Jan 9, 2020

@mrarmyant What do you expect to see using wireshark? I think we are talking about issues on OSI layers 1 and 2. Differently said: no SSID, no frequency, no packets

My code (above your post) runs stable since I posted it. But I don't think the problem is portable to something different than ESP* chips because it addresses issues of the ESP SDK, not Arduino

I wasn't referring really to arduino, but the wifi soc that is onboard that particular unit. It had issues with reconnect based on being hinky with dhcp. Someone reported that restarting their router fixed it, which is the problem we had (well restarting a windows dhcp server). There was an issue with the way it was acknowledging wether or not it had been disconnected. Just thought it might help with those issues up there, because neither unit would ever show as connected on the reconnects, and wireshark showed us why. Static IP's had no problem. It ended up being the wifi soc firmware that had to be fixed to handle the delay mentioned for DHCP issues. All of which were discovered via wireshark.

@Anton2k
Copy link

@Anton2k Anton2k commented Jan 7, 2021

Hey, don't mean to bring up an old issue, but currently on my esp32 board Lilygo TTGO T5, if I kill power to it whilst it is connected to the network then power it back up, it will not auto reconnect unless I power it off and on again, it will connect on the second attempt. If I add a delay of 35 seconds before the wifi connection portion it always reconnects. If I do (wifi.disconnect();) to kill the wifi cleanly once I an done using the wifi then kill the power it reconnects fine each time. The delay is a work around but not ideal, would be good to get to the root cause of this issues, is it a access point thing it an esp32 thing?

See here for more detailed info Hieromon/AutoConnect#292

@mickeypop
Copy link

@mickeypop mickeypop commented Jan 7, 2021

@Anton2k
if you look at my earlier post( UPDATE) and look for: "complete SmartConfig / WiFi skeleton" on link below
in wifiInit(); i have a 3 sec delay
as in my earlier post, DHCP takes time to reset and know a bit about the WiFi init process.

When connecting the ESP32 will request the same IP if possible.
Since the DHCP server has not reset yet it will return that IP is taken and fail connect.
This is a library issue.
On successive reboot the DHCP server has caught up and all goes well.

your delay is a well founded solution

this WiFi skeleton code has served me well for over years thru several processors.
[(https://github.com//issues/1100 )]

@Anton2k
Copy link

@Anton2k Anton2k commented Jan 7, 2021

@mickeypop Thanks again for your suggestion, I have had a deeper look into the lib I am using and the auto reconnect time out is set at 30 seconds, mine needs 35, so by changing the time out figure I should be good! thanks again for your help.

One little thing that is still niggling me, if power of the ESP32 and power it back on and then off again and back on (both in quick succession, within 2 or 3 seconds of each other) it will always reconnect on the second attempt regardless of how long I have waiting, again I will really need to test this again to make sure I remember it correctly, but I am fairly certain. Do you think it's possible that if the ESP32 makes a connection attempt soon after another that the router might be auto releasing the DHCP ip?

Thanks

@asepms1211
Copy link

@asepms1211 asepms1211 commented Feb 13, 2021

@Anton2k

Hey, don't mean to bring up an old issue, but currently on my esp32 board Lilygo TTGO T5, if I kill power to it whilst it is connected to the network then power it back up, it will not auto reconnect unless I power it off and on again, it will connect on the second attempt. If I add a delay of 35 seconds before the wifi connection portion it always reconnects. If I do (wifi.disconnect();) to kill the wifi cleanly once I an done using the wifi then kill the power it reconnects fine each time. The delay is a work around but not ideal, would be good to get to the root cause of this issues, is it a access point thing it an esp32 thing?

See here for more detailed info Hieromon/AutoConnect#292

thank you thank you thank you very much, I've been looking for this solution for a week ... and now you and this page have helped me ;)

35 second :)

@Anton2k
Copy link

@Anton2k Anton2k commented Feb 14, 2021

@Anton2k

Hey, don't mean to bring up an old issue, but currently on my esp32 board Lilygo TTGO T5, if I kill power to it whilst it is connected to the network then power it back up, it will not auto reconnect unless I power it off and on again, it will connect on the second attempt. If I add a delay of 35 seconds before the wifi connection portion it always reconnects. If I do (wifi.disconnect();) to kill the wifi cleanly once I an done using the wifi then kill the power it reconnects fine each time. The delay is a work around but not ideal, would be good to get to the root cause of this issues, is it a access point thing it an esp32 thing?
See here for more detailed info Hieromon/AutoConnect#292

thank you thank you thank you very much, I've been looking for this solution for a week ... and now you and this page have helped me ;)

35 second :)

Very welcome and glad it helped someone! :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Linked pull requests

Successfully merging a pull request may close this issue.

None yet