With ESP32, I have these functions:
// try to connect
void Network::goStation()
{
Serial.print(F("[NET] Try to connect to:"));
Serial.println(wifiConfig.WiFi_Creds.wifi_ssid);
WiFi.mode(WIFI_STA);
WiFi.begin(wifiConfig.WiFi_Creds.wifi_ssid, wifiConfig.WiFi_Creds.wifi_pw);
if (WiFi.waitForConnectResult(5000) == WL_CONNECTED)
{
Serial.print(F("[NET] Connected to: "));
Serial.println(WiFi.SSID());
Serial.print(F("[NET] Local IP: "));
Serial.println(WiFi.localIP());
_mode = Modes::Station;
}
else goRetry();
}
// called after a failure
void Network::goRetry()
{
Serial.println(F("[NET] Connection failed. Retry in 60 s"));
WiFi.disconnect();
_timeRef = millis();
_mode = Modes::Retry;
}
I have an FSM to handle the different cases, I don't report all the code here since the machine itself is working (I mean the functions above are called as expected).
On power up I try to connect to the WiFi:
goStation();
Once connected, I check for disconnections:
if (WiFi.status() != WL_CONNECTED) goRetry();
and after 1 minute I call again goStation()
.
If on power up the WiFi network is available:
- it connects successfully with
goStation()
- after some time I turn off my router
- it detects the failure and calls
goRetry()
- I turn on the router
- after 1 minute, it calls again
goStation()
and connects as expected
So far, so good. But, If on power up the WiFi network is NOT available:
- it fails the first connection in
goStation()
and callsgoRetry()
- I turn on my router
- every minute it tries to connect calling
goStation()
but it always fails
The only way I found to connect again is to reset the MCU.
Do you see any evidence of errors in my code? Why if it does not connect the first time, it never connects?