MQTT: Implements reconnecting in publish thread in case thread is waken-up but client is disconnected.
authorEdouard Tisserant <edouard@beremiz.fr>
Mon, 22 Jul 2024 16:13:27 +0200
changeset 3996 4eb23bb4bc2f
parent 3995 84a668564748
child 3997 364e09f5faea
MQTT: Implements reconnecting in publish thread in case thread is waken-up but client is disconnected.

Note: paho's lostConnection callback got already disabled in previous commit.
mqtt/mqtt_template.c
--- a/mqtt/mqtt_template.c	Mon Jul 22 16:09:12 2024 +0200
+++ b/mqtt/mqtt_template.c	Mon Jul 22 16:13:27 2024 +0200
@@ -233,11 +233,20 @@
     int rc = 0;
     while((rc = pthread_mutex_lock(&MQTT_mutex)) == 0 && !MQTT_stop_thread){{
         pthread_cond_wait(&MQTT_new_data, &MQTT_mutex);
-        if(MQTT_any_pub_var_changed && MQTTClient_isConnected(client)){{
+        {{
+            int is_connected = MQTTClient_isConnected(client);
+            if(MQTT_any_pub_var_changed && is_connected){{
 
             /* publish changes, and reset variable's state to UNCHANGED */
 {publish_changes}
-            MQTT_any_pub_var_changed = 0;
+                MQTT_any_pub_var_changed = 0;
+            }} else if(!is_connected){{
+                rc = _connect_mqtt();
+                if (rc != MQTTCLIENT_SUCCESS) {{
+                    LogError("MQTT Reconnect Failed, return code %d\n", rc);
+                    sleep(5);
+                }}
+            }}
         }}
 
         pthread_mutex_unlock(&MQTT_mutex);