MQTT broker limit reconnect attempts
Posted: Tue Oct 11, 2022 2:58 pm
Hi, I'm using an ESP8266 to send data to MQTT broker in 15 minute intervals (ESP is in deepsleep when not sending data). My ESP is battery powered so I'd like to limit the duration of reconnect attempts to prevent battery drain. Could someone help me with code bellow ? I'd like to exit reconnect loop if connection is not established within 45 secs and also this loop should run only once between deepsleep cycles.
I'm using pubsub library.
void reconnect() {
/* Loop until we're reconnected */
while (!mqttClient.connected()) {
/*#ifdef SERIAL_DEBUG*/
Serial.print("Attempting MQTT broker connection...");
/*#endif*/
/* Attempt to connect */
if (mqttClient.connect(clientId.c_str(),mqttUser,mqttPassword)) {
/*#ifdef SERIAL_DEBUG*/
Serial.println("connected");
/*#endif*/
/* Once connected, resubscribe */
mqttClient.subscribe(command1_topic,1); // subscribe the topics here
}
else {
/*#ifdef SERIAL_DEBUG*/
Serial.print("Failed, rc=");
Serial.print(mqttClient.state());
Serial.println(". Trying again in 5 seconds...");
/*#endif
/* Wait 5 seconds between retries */
delay(5000);
}
}
}
I'm using pubsub library.
void reconnect() {
/* Loop until we're reconnected */
while (!mqttClient.connected()) {
/*#ifdef SERIAL_DEBUG*/
Serial.print("Attempting MQTT broker connection...");
/*#endif*/
/* Attempt to connect */
if (mqttClient.connect(clientId.c_str(),mqttUser,mqttPassword)) {
/*#ifdef SERIAL_DEBUG*/
Serial.println("connected");
/*#endif*/
/* Once connected, resubscribe */
mqttClient.subscribe(command1_topic,1); // subscribe the topics here
}
else {
/*#ifdef SERIAL_DEBUG*/
Serial.print("Failed, rc=");
Serial.print(mqttClient.state());
Serial.println(". Trying again in 5 seconds...");
/*#endif
/* Wait 5 seconds between retries */
delay(5000);
}
}
}