From eeb72f509d360e71d86bbc0ca22ae316934bafdf Mon Sep 17 00:00:00 2001 From: Matt Smith Date: Thu, 29 May 2025 22:33:41 -0400 Subject: [PATCH] Update WiFiAPClient.cpp to replace blocking delay() with non-blocking --- src/mesh/wifi/WiFiAPClient.cpp | 58 ++++++++++++++++++++++++++-------- 1 file changed, 45 insertions(+), 13 deletions(-) diff --git a/src/mesh/wifi/WiFiAPClient.cpp b/src/mesh/wifi/WiFiAPClient.cpp index 789f8ac44..f85e6684f 100644 --- a/src/mesh/wifi/WiFiAPClient.cpp +++ b/src/mesh/wifi/WiFiAPClient.cpp @@ -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 \ No newline at end of file +#endif