From 6474447e53a99baff6b626da0baed340954dbe0a Mon Sep 17 00:00:00 2001 From: Cameron Sharp Date: Fri, 25 Jan 2019 14:33:24 +0000 Subject: [PATCH] Attempt to fix blocking mqtt reconnect --- buttons.cpp | 59 +++++++++++++++++++++++++++++++---------------------- 1 file changed, 35 insertions(+), 24 deletions(-) diff --git a/buttons.cpp b/buttons.cpp index c6029c2..a0e313f 100644 --- a/buttons.cpp +++ b/buttons.cpp @@ -17,11 +17,13 @@ int input3_value = 0; int input4_value = 0; int led_timeout = 1000; - long led_time = 0; long last_wifi_check_time = 0; +long lastReconnectAttempt = 0; +long reconnectAttempts = 0; + long debouncing_time = 1000; volatile unsigned long last_micros; @@ -94,25 +96,21 @@ void setup_wifi() { Serial.println(WiFi.localIP()); } -void reconnect() { - // Loop until we're reconnected - while (!client.connected()) { - Serial.print("Attempting MQTT connection..."); - // Create a random client ID - String clientId = "ESP8266Client-"; - clientId += String(random(0xffff), HEX); - // Attempt to connect - if (client.connect(clientId.c_str())) { - Serial.println("connected"); - // Once connected, publish an announcement... - } else { - Serial.print("failed, rc= "); - Serial.print(client.state()); - Serial.println(" try again in 1 second"); - // Wait 1 seconds before retrying - delay(1000); - } +boolean reconnect() { + reconnectAttempts++; + # + String clientID = "ESP8266Client-"; + clientID += String(random(0xffff), HEX); + + if (client.connect(clientID.c_str())) { + Serial.println("MQTT Connected"); + } else { + Serial.print("failed, rc = "); + Serial.print(client.state()); + Serial.println("Trying again"); } + + return client.connected(); } void setup() { @@ -191,10 +189,6 @@ void Interrupt4() { void loop() { long now = millis(); - if (!client.connected()) { - reconnect(); // mqtt - } - if (now - last_wifi_check_time > WIFI_TIMEOUT) { Serial.print("Checking WiFi... "); if (WiFi.status() != WL_CONNECTED) { @@ -206,10 +200,27 @@ void loop() { last_wifi_check_time = now; } + if (!client.connected()) { + if (now - lastReconnectAttempt > 5000) { + lastReconnectAttempt = now; + // Attempt to reconnect + Serial.println("Attempting MQTT reconnect"); + if (reconnect()) { + reconnectAttempts = 0; + lastReconnectAttempt = 0; + } + if (reconnectAttempts > 5) { + Serial.println("mqtt failed too many times, restarting wifi"); + setup_wifi(); + } + } + } else { + client.loop(); + } + if (now - led_time > led_timeout) { digitalWrite(LED_PIN, 0); } - client.loop(); // mqtt client ArduinoOTA.handle(); }