diff --git a/application.cpp b/application.cpp index 58321bf..aea85da 100644 --- a/application.cpp +++ b/application.cpp @@ -282,8 +282,12 @@ void callback(char* topic, byte* payload, unsigned int length) { void reconnect() { + uint32_t currentMillis = millis(); + static uint32_t lastMillis = 0; + // Loop until we're reconnected - while (!client.connected()) { + if (!client.connected() && (currentMillis > (lastMillis + RECONNECT_DELAY))) { + lastMillis = currentMillis; #ifdef DEBUG Serial.print("Attempting MQTT connection..."); #endif @@ -308,23 +312,11 @@ void reconnect() { Serial.print(client.state()); Serial.println(" try again in 5 seconds"); #endif - // Wait 5 seconds before retrying - delay(5000); } } } -bool mqtt_connect() { - bool reconnected = false; - if (!client.connected()) { - reconnect(); - reconnected = true; - } - client.loop(); - return reconnected; -} - void setupApplication() { client.setServer(configBlock.mqttBroker, configBlock.mqttPort); @@ -344,10 +336,10 @@ void setupApplication() { void loopApplication() { - bool reconnected = mqtt_connect(); - static uint32_t reconnectTime = 0; - if (reconnected) { - reconnectTime = millis(); + if (!client.connected()) { + reconnect(); + } else { + client.loop(); } } diff --git a/defines.h b/defines.h index ef66c29..245fca5 100644 --- a/defines.h +++ b/defines.h @@ -43,4 +43,6 @@ #define NUM_OF_LEDs 16 +#define RECONNECT_DELAY 5000 + #endif /* DEFINES_H_ */