From c2b8fbd1367de41d3a54100dc44ed8871cb50cc7 Mon Sep 17 00:00:00 2001 From: Matthias Behr Date: Sun, 5 Aug 2018 12:48:02 +0200 Subject: [PATCH] added reconnect handling if con. refused at startup This should allow startups where the mqtt server will be available later --- src/mqtt.cpp | 25 ++++++++++++++++++++++--- 1 file changed, 22 insertions(+), 3 deletions(-) diff --git a/src/mqtt.cpp b/src/mqtt.cpp index c579de8c..a041e02f 100644 --- a/src/mqtt.cpp +++ b/src/mqtt.cpp @@ -188,9 +188,28 @@ MqttClient::MqttClient(struct json_object *option) : _enabled(false) res = mosquitto_connect(_mcs, _host.c_str(), _port, _keepalive); if (res != MOSQ_ERR_SUCCESS) { - print(log_alert, "mosquitto_connect failed. res=%d (%s)! Stopped!", "mqtt", - res, strerror(errno)); - _enabled = false; + switch (res) + { + case MOSQ_ERR_CONN_REFUSED: // mqtt might accept us later only. + print(log_warning, "mosquitto_connect failed. res=%d (%s)! Trying anyhow.", "mqtt", + res, strerror(errno)); + break; + case MOSQ_ERR_ERRNO: + if (errno == 111) // con refused: + { + print(log_warning, "mosquitto_connect failed. res=%d (%d %s)! Trying anyhow.", "mqtt", + res, errno, strerror(errno)); + } else { + print(log_alert, "mosquitto_connect failed. res=%d (%d %s)! Stopped!", "mqtt", + res, errno, strerror(errno)); + _enabled = false; + } + break; + default: + print(log_alert, "mosquitto_connect failed. res=%d! Stopped!", "mqtt", res); + _enabled = false; + break; + } } } }