MQTT: WIP, prevent crash after disconnect. Disable auto-reconnect on connection lost callback.
authorEdouard Tisserant <edouard@beremiz.fr>
Mon, 22 Jul 2024 12:12:33 +0200
changeset 3994 c399fe412dbd
parent 3993 78f9abfb32a0
child 3995 84a668564748
MQTT: WIP, prevent crash after disconnect. Disable auto-reconnect on connection lost callback.
mqtt/mqtt_client_gen.py
--- a/mqtt/mqtt_client_gen.py	Thu Jul 18 12:05:26 2024 +0200
+++ b/mqtt/mqtt_client_gen.py	Mon Jul 22 12:12:33 2024 +0200
@@ -302,8 +302,10 @@
         template = """/* code generated by beremiz MQTT extension */
 
 #include <stdint.h>
+#include <unistd.h>
 #include <pthread.h>
 #include <string.h>
+#include <stdio.h>
 
 #include "MQTTClient.h"
 #include "MQTTClientPersistence.h"
@@ -314,6 +316,7 @@
         snprintf(mstr, 255, __VA_ARGS__);                                                         \\
         LogMessage(level, mstr, strlen(mstr));                                                    \\
         printf(__VA_ARGS__);                                                                      \\
+        fflush(stdout);                                                                           \\
     }}
 
 #define LogInfo(...) _Log(LOG_INFO, __VA_ARGS__);
@@ -415,9 +418,15 @@
 
 void connectionLost(void* context, char* reason)
 {{
+    int rc;
     LogWarning("ConnectionLost, reconnecting\\n");
-    _connect_mqtt();
-    /* TODO wait if error */
+    // rc = _connect_mqtt();
+
+    // if (rc != MQTTCLIENT_SUCCESS) {{
+    //     LogError("MQTT reconnect Failed, waiting 5 seconds, return code %d\\n", rc);
+    //     /* wait if error */
+    //     sleep(5);
+    // }}
 }}
 
 int messageArrived(void *context, char *topicName, int topicLen, MQTTClient_message *message)
@@ -538,7 +547,7 @@
     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){{
+        if(MQTT_any_pub_var_changed && MQTTClient_isConnected(client)){{
 
             /* publish changes, and reset variable's state to UNCHANGED */
 {publish_changes}