diff --git a/src/main.cpp b/src/main.cpp index 5b36b77..f094209 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -180,6 +180,46 @@ void loop() { LOG.handle(); // telnetspy handling ArduinoOTA.handle(); + #if WIFI_ENABLED + // Escalating WiFi reconnection after beacon timeout disconnects + // Phase 1 (attempts 1-3): WiFi.reconnect() every 5s + // Phase 2 (attempts 4+): Full disconnect + begin cycle every 10s + { + static unsigned long lastWifiCheck = 0; + static uint8_t reconnectAttempts = 0; + unsigned long now = millis(); + unsigned long interval = reconnectAttempts < 3 ? 5000 : 10000; + + if (now - lastWifiCheck > interval) { + lastWifiCheck = now; + if (WiFi.status() != WL_CONNECTED) { + if (reconnectAttempts < UINT8_MAX) reconnectAttempts++; + + if (reconnectAttempts <= 3) { + // Phase 1: soft reconnect + LOG.print("WiFi disconnected, reconnecting (attempt "); + LOG.print(reconnectAttempts); + LOG.println(")..."); + WiFi.reconnect(); + } else { + // Phase 2: full disconnect + begin cycle + LOG.print("WiFi reconnect failed, full reconnect (attempt "); + LOG.print(reconnectAttempts); + LOG.println(")..."); + WiFi.disconnect(true); + delay(100); + WiFi.mode(WIFI_STA); + WiFi.begin(); + } + } else if (reconnectAttempts > 0) { + LOG.print("WiFi reconnected to "); + LOG.println(WiFi.SSID()); + reconnectAttempts = 0; + } + } + } + #endif // WIFI_ENABLED + #if MQTT_ENABLED g_mqtt->loop(); diff --git a/src/net/mqtt.cpp b/src/net/mqtt.cpp index 5bc305f..6151813 100644 --- a/src/net/mqtt.cpp +++ b/src/net/mqtt.cpp @@ -81,8 +81,8 @@ void Mqtt::clearSubscriptions() { // force=false by default bool Mqtt::reconnect(bool force) { - // No configuration available - if (this->MqttConfig::isEmpty()) { + // No configuration available or WiFi not connected + if (this->MqttConfig::isEmpty() || WiFi.status() != WL_CONNECTED) { return false; }