From 0662dbb8a132a7d5c3b6a76f4f789c916f57b07b Mon Sep 17 00:00:00 2001 From: Joachim Zobel Date: Sun, 24 Dec 2023 15:00:04 +0100 Subject: [PATCH] MQTT client retries permanently --- include/mqtt.hpp | 1 + src/mqtt.cpp | 45 +++++++++++++++++++++++---------------------- 2 files changed, 24 insertions(+), 22 deletions(-) diff --git a/include/mqtt.hpp b/include/mqtt.hpp index 784b9a0b..f206e258 100644 --- a/include/mqtt.hpp +++ b/include/mqtt.hpp @@ -48,6 +48,7 @@ class MqttClient { std::string _id; int _qos = 0; bool _timestamp = false; + unsigned int _cntRetries; bool _isConnected = false; diff --git a/src/mqtt.cpp b/src/mqtt.cpp index 47f79d8f..12a05a1f 100644 --- a/src/mqtt.cpp +++ b/src/mqtt.cpp @@ -14,6 +14,21 @@ MqttClient *mqttClient = 0; volatile bool endMqttClientThread = false; +/** + * Determines the retry time [s] from the number of previous retries. + */ +static inline unsigned int retryTime(unsigned int _cnt) { + if (_cnt <= 10) { + return 0; + } + else if (_cnt <= 20) { + return 5; + } + else { + return 60; + } +} + // class impl. MqttClient::MqttClient(struct json_object *option) : _enabled(false) { @@ -171,28 +186,14 @@ MqttClient::MqttClient(struct json_object *option) : _enabled(false) { // now connect. we use sync interface with spe. thread calling mosquitto_loop res = mosquitto_connect(_mcs, _host.c_str(), _port, _keepalive); if (res != MOSQ_ERR_SUCCESS) { - switch (res) { - case MOSQ_ERR_CONN_REFUSED: // mqtt might accept us later only. - print(log_warning, "mosquitto_connect failed (but trying anyhow): %s", "mqtt", - mosquitto_strerror(res)); - break; - case MOSQ_ERR_ERRNO: - if (errno == 111) // con refused: - { - print(log_warning, "mosquitto_connect failed (but trying anyhow): %s", - "mqtt", mosquitto_strerror(res)); - } else { - print(log_alert, "mosquitto_connect failed, giving up: %s", "mqtt", - mosquitto_strerror(res)); - _enabled = false; - } - break; - default: - print(log_alert, "mosquitto_connect failed, stopped: %s", "mqtt", - mosquitto_strerror(res)); - _enabled = false; - break; - } + // We always retry, only the frequency is reduced + print(log_warning, "mosquitto_connect failed (but trying anyhow): %s", "mqtt", + mosquitto_strerror(res)); + sleep(retryTime(_cntRetries)); + _cntRetries++; + } + else { + _cntRetries = 0; } } }