The use of the ESP8266 in the world of IoT

User avatar
By Vertigoxx
#95369 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);
}
}
}
User avatar
By EdwinGomez
#95546 Hey, Vertigoxx. Have you tried configuring the Loop function with delay for ESP8266 MQTT implementation? I think it’s the only option that makes sense in your situation. When I had the same problem configuring that function helped me solve that. So, I also recommend reading that article for more detailed information about the configuration. My friend shared that article with me. He’s currently working as a software engineer. So, I hope it will be helpful. Let me know if you need more detailed help with your issue.
Last edited by EdwinGomez on Tue Dec 06, 2022 5:54 pm, edited 1 time in total.