Update WiFiAPClient.cpp to replace blocking delay() with non-blocking

This commit is contained in:
Matt Smith 2025-05-29 22:33:41 -04:00 committed by GitHub
parent b6cb0b148c
commit eeb72f509d
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -46,6 +46,10 @@ uint8_t wifiDisconnectReason = 0;
// Stores our hostname
char ourHost[16];
// To replace blocking wifi connect delay with a non-blocking sleep
static unsigned long wifiReconnectStartMillis = 0;
static bool wifiReconnectPending = false;
bool APStartupComplete = 0;
unsigned long lastrun_ntp = 0;
@ -153,24 +157,38 @@ static int32_t reconnectWiFi()
isReconnecting = true;
// Make sure we clear old connection credentials
#ifdef ARCH_ESP32
#ifdef ARCH_ESP32
WiFi.disconnect(false, true);
#elif defined(ARCH_RP2040)
#elif defined(ARCH_RP2040)
WiFi.disconnect(false);
#endif
#endif
LOG_INFO("Reconnecting to WiFi access point %s", wifiName);
delay(5000);
// Start the non-blocking wait for 5 seconds
wifiReconnectStartMillis = millis();
wifiReconnectPending = true;
// Do not attempt to connect yet, wait for the next invocation
return 100; // Schedule next check soon
}
if (!WiFi.isConnected()) {
#ifdef CONFIG_IDF_TARGET_ESP32C3
WiFi.mode(WIFI_MODE_NULL);
WiFi.useStaticBuffers(true);
WiFi.mode(WIFI_STA);
#endif
WiFi.begin(wifiName, wifiPsw);
// Check if we are ready to proceed with the WiFi connection after the 5s wait
if (wifiReconnectPending) {
if (millis() - wifiReconnectStartMillis >= 5000) {
if (!WiFi.isConnected()) {
#ifdef CONFIG_IDF_TARGET_ESP32C3
WiFi.mode(WIFI_MODE_NULL);
WiFi.useStaticBuffers(true);
WiFi.mode(WIFI_STA);
#endif
WiFi.begin(wifiName, wifiPsw);
}
isReconnecting = false;
wifiReconnectPending = false;
return 300000; // Resume normal interval after reconnect
} else {
// Still waiting for 5s to elapse
return 100; // Check again soon
}
isReconnecting = false;
}
#ifndef DISABLE_NTP
@ -191,6 +209,20 @@ static int32_t reconnectWiFi()
}
#endif
if (config.network.wifi_enabled && !WiFi.isConnected()) {
#ifdef ARCH_RP2040 // (ESP32 handles this in WiFiEvent)
needReconnect = APStartupComplete;
#endif
return 1000; // check once per second
} else {
#ifdef ARCH_RP2040
onNetworkConnected(); // will only do anything once
#endif
return 300000; // every 5 minutes
}
}
#endif
if (config.network.wifi_enabled && !WiFi.isConnected()) {
#ifdef ARCH_RP2040 // (ESP32 handles this in WiFiEvent)
/* If APStartupComplete, but we're not connected, try again.
@ -474,4 +506,4 @@ uint8_t getWifiDisconnectReason()
{
return wifiDisconnectReason;
}
#endif
#endif