Chat freely about anything...

User avatar
By helpme
#38663 My intention is more for the subscriber than for the publisher. I want the subscriber to automatically subscribe to the topic again if for some reason, the MQTT broker goes missing and then appear again. Is the Last Will and Testament feature relevant? Or would a timer checking the MQTT connection, then keep reconnecting if the connection is missing, be more appropriate?
User avatar
By helpme
#38721
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.