Skip to content

Commit

Permalink
MQTT client retries permanently
Browse files Browse the repository at this point in the history
  • Loading branch information
narc-Ontakac2 committed Dec 24, 2023
1 parent 5188375 commit 0662dbb
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 22 deletions.
1 change: 1 addition & 0 deletions include/mqtt.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ class MqttClient {
std::string _id;
int _qos = 0;
bool _timestamp = false;
unsigned int _cntRetries;

bool _isConnected = false;

Expand Down
45 changes: 23 additions & 22 deletions src/mqtt.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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) {

Expand Down Expand Up @@ -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;
}
}
}
Expand Down

0 comments on commit 0662dbb

Please sign in to comment.