Chat freely about anything...

User avatar
By helpme
#38042 I am using SMING framework "MqttClient_Hello" example.

The code to connect to the MQTT broker is quite simple. The relevant code is below;

Code: Select allvoid startMqttClient();
void onMessageReceived(String topic, String message);
MqttClient mqtt("192.168.1.8", 1883, onMessageReceived);

// Run MQTT client
void startMqttClient()
{
   mqtt.connect("esp8266");
   mqtt.subscribe("TopicTest");
}


I want the MQTT connection to always be present at all time. If for whatever reason the connection is broken, I would like a reconnection to take place. How can this be done?
User avatar
By bluegiraffe
#38051 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();
User avatar
By spants
#38058 Why not use the Last Will and Testament feature of MQTT?
http://stackoverflow.com/questions/1727 ... -testament

Here is how I do it: (this is for the OpenSDK not SMING etc, but the principle is the same)

Set the LWT message: (sysCfg.mqtt_lwt is the topic, use the retain flag so that you can find the status)
MQTT_InitLWT(&mqttClient, (uint8_t *)sysCfg.mqtt_lwt, "offline", 0, 1);

On power up, publish "online" to the LWT topic:
MQTT_Publish(client, (uint8_t *)sysCfg.mqtt_lwt,"online",6,0,1);

When the connection dies, the broker will automatically publish "offline" to the Topic. Other tasks or alerts can see the current status and any changes.

edit: Just reread your post - mine is for finding out if a sensor has gone missing..... as mentioned previously, check the connect status on a timer is also the way that I do it...
User avatar
By bluegiraffe
#38117 I think the original question is if the ESP looses the connection to the MQTT broker. LWT will only warn subscribers that the publisher is gone, not making the publisher reconnect again.

Well this is at least what I've understood from the original question :)