-->
Page 1 of 2

How to ensure that MQTT connection is always present?

PostPosted: Wed Jan 06, 2016 5:26 am
by helpme
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?

Re: How to ensure that MQTT connection is always present?

PostPosted: Wed Jan 06, 2016 8:16 am
by bluegiraffe
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();

Re: How to ensure that MQTT connection is always present?

PostPosted: Wed Jan 06, 2016 11:31 am
by spants
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...

Re: How to ensure that MQTT connection is always present?

PostPosted: Thu Jan 07, 2016 4:29 am
by bluegiraffe
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 :)