Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 40 additions & 0 deletions src/main.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -180,6 +180,46 @@ void loop() {
LOG.handle(); // telnetspy handling
ArduinoOTA.handle();

#if WIFI_ENABLED
Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There is already a function to reconnectWifi which does exactly that declared in src/net/wifi.cpp (reconnectWifi).

// 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);
Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not sure about that. Mode is already set as per the initial configuration.

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();

Expand Down
4 changes: 2 additions & 2 deletions src/net/mqtt.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}

Expand Down