Bläddra i källkod

throttle MQTT connection attempts

Chris Mullins 8 år sedan
förälder
incheckning
657a6076d2
2 ändrade filer med 13 tillägg och 1 borttagningar
  1. 8 1
      lib/MQTT/MqttClient.cpp
  2. 5 0
      lib/MQTT/MqttClient.h

+ 8 - 1
lib/MQTT/MqttClient.cpp

@@ -7,7 +7,8 @@
 
 MqttClient::MqttClient(Settings& settings, MiLightClient*& milightClient)
   : milightClient(milightClient),
-    settings(settings)
+    settings(settings),
+    lastConnectAttempt(0)
 {
   String strDomain = settings.mqttServer();
   this->domain = new char[strDomain.length() + 1];
@@ -60,6 +61,10 @@ bool MqttClient::connect() {
 }
 
 void MqttClient::reconnect() {
+  if (lastConnectAttempt > 0 && (millis() - lastConnectAttempt) < MQTT_CONNECTION_ATTEMPT_FREQUENCY) {
+    return;
+  }
+  
   if (! mqttClient->connected()) {
     if (connect()) {
       subscribe();
@@ -67,6 +72,8 @@ void MqttClient::reconnect() {
       Serial.println(F("ERROR: Failed to connect to MQTT server"));
     }
   }
+
+  lastConnectAttempt = millis();
 }
 
 void MqttClient::handleClient() {

+ 5 - 0
lib/MQTT/MqttClient.h

@@ -3,6 +3,10 @@
 #include <PubSubClient.h>
 #include <WiFiClient.h>
 
+#ifndef MQTT_CONNECTION_ATTEMPT_FREQUENCY
+#define MQTT_CONNECTION_ATTEMPT_FREQUENCY 5000
+#endif
+
 #ifndef _MQTT_CLIENT_H
 #define _MQTT_CLIENT_H
 
@@ -21,6 +25,7 @@ private:
   MiLightClient*& milightClient;
   Settings& settings;
   char* domain;
+  unsigned long lastConnectAttempt;
 
   bool connect();
   void subscribe();