bluegiraffe wrote:Use a timer:
// Connect to the MQTT broker.
// If BRUSER is not empty, connect with user and password.
void startMqttClient()
{
Serial.println("Mqtt server connect & subscribe..");
mqtt.setKeepAlive(180);
String mqttId = "esp8266-" + String(system_get_chip_id());
if ( strlen( BRUSER ) == 0 ) {
mqtt.connect( mqttId );
}
else
mqtt.connect( mqttId, BRUSER , BRPWD );
// Let's subscribe topics
mqtt.subscribe("/data");
}
void checkMQTT() {
if (mqtt.getConnectionState() != eTCS_Connected) {
Serial.println("MQTT Server: Lost connection... ");
Serial.println("MQTT Server: Reconnect");
startMqttClient(); // Auto reconnect
}
}
On the main program:
// After a while it seems that I lose the connection to the MQTT server....
// Periodically check for the MQTT connection
checkTimer.initializeMs( 60 * 1000 , checkMQTT).start();
Thanks. This solution works fine. I wish I could somehow upvote your post like stackoverflow . However, the presence of timers will raise the power consumption. I was hoping if there could be some kind of callback function when connection is broken.