Forráskód Böngészése

Queue MQTT publishes outside the calling task

SybexXx 1 napja
szülő
commit
d5355331f6
1 módosított fájl, 60 hozzáadás és 46 törlés
  1. 60 46
      code/components/jomjol_mqtt/interface_mqtt.cpp

+ 60 - 46
code/components/jomjol_mqtt/interface_mqtt.cpp

@@ -2,9 +2,7 @@
 #include "interface_mqtt.h"
 #include "interface_mqtt.h"
 
 
 #include "esp_log.h"
 #include "esp_log.h"
-#if DEBUG_DETAIL_ON
-    #include "esp_timer.h"
-#endif
+#include "esp_timer.h"
 #include "connect_wlan.h"
 #include "connect_wlan.h"
 #include "mqtt_client.h"
 #include "mqtt_client.h"
 #include "ClassLogFile.h"
 #include "ClassLogFile.h"
@@ -15,16 +13,19 @@
 #include <new>
 #include <new>
 #include <utility>
 #include <utility>
 
 
-#if DEBUG_DETAIL_ON
-#include "esp_timer.h"
-#endif
-
 static const char *TAG = "MQTT IF";
 static const char *TAG = "MQTT IF";
 
 
 std::map<std::string, std::function<void()>>* connectFunktionMap = NULL;
 std::map<std::string, std::function<void()>>* connectFunktionMap = NULL;
 std::map<std::string, std::function<bool(std::string, char*, int)>>* subscribeFunktionMap = NULL;
 std::map<std::string, std::function<bool(std::string, char*, int)>>* subscribeFunktionMap = NULL;
 static std::mutex connectFunctionMutex;
 static std::mutex connectFunctionMutex;
 static std::mutex subscribeFunctionMutex;
 static std::mutex subscribeFunctionMutex;
+// Serialize the outbox-size check and enqueue operation across application tasks.
+static std::mutex mqttPublishMutex;
+
+// Keep the MQTT outbox bounded so a slow or unavailable broker cannot consume
+// an unbounded amount of internal heap. QoS acknowledgements release entries.
+static constexpr size_t MQTT_MAX_OUTBOX_BYTES = 12 * 1024;
+static constexpr size_t MQTT_OUTBOX_ENTRY_OVERHEAD = 64;
 
 
 int failedOnRound = -1;
 int failedOnRound = -1;
 int MQTTReconnectCnt = 0;
 int MQTTReconnectCnt = 0;
@@ -45,58 +46,71 @@ int keepalive;
 bool SetRetainFlag;
 bool SetRetainFlag;
 void (*callbackOnConnected)(std::string, bool) = NULL;
 void (*callbackOnConnected)(std::string, bool) = NULL;
 
 
-bool MQTTPublish(std::string _key, std::string _content, int qos, bool retained_flag) 
+bool MQTTPublish(std::string _key, std::string _content, int qos, bool retained_flag)
 {
 {
-    if (!mqtt_enabled) {                            // MQTT sevice not started / configured (MQTT_Init not called before)      
+    if (!mqtt_enabled) {
         return false;
         return false;
     }
     }
 
 
-    if (failedOnRound == getCountFlowRounds()) {    // we already failed in this round, do not retry until the next round
-        return true; // Fail quietly
+    if (failedOnRound == getCountFlowRounds()) {
+        return true; // A previous queue failure already stopped MQTT publishing for this round.
     }
     }
 
 
-    #ifdef DEBUG_DETAIL_ON  
-        LogFile.WriteHeapInfo("MQTT Publish");
-    #endif
+#ifdef DEBUG_DETAIL_ON
+    LogFile.WriteHeapInfo("MQTT Publish");
+#endif
 
 
     MQTT_Init(); // Re-Init client if not initialized yet/anymore
     MQTT_Init(); // Re-Init client if not initialized yet/anymore
 
 
-    if (mqtt_initialized && mqtt_connected) {
-        #ifdef DEBUG_DETAIL_ON 
-            long long int starttime = esp_timer_get_time();
-        #endif
-        int msg_id = esp_mqtt_client_publish(client, _key.c_str(), _content.c_str(), 0, qos, retained_flag);
-        #ifdef DEBUG_DETAIL_ON 
-            ESP_LOGD(TAG, "Publish msg_id %d in %lld ms", msg_id, (esp_timer_get_time() - starttime)/1000);
-        #endif
-        if (msg_id == -1) {
-            LogFile.WriteToFile(ESP_LOG_WARN, TAG, "Failed to publish topic '" + _key + "', re-trying...");   
-            #ifdef DEBUG_DETAIL_ON 
-                starttime = esp_timer_get_time();
-            #endif
-            msg_id = esp_mqtt_client_publish(client, _key.c_str(), _content.c_str(), 0, qos, retained_flag);
-            #ifdef DEBUG_DETAIL_ON 
-                ESP_LOGD(TAG, "Publish msg_id %d in %lld ms", msg_id, (esp_timer_get_time() - starttime)/1000);
-            #endif
-            if (msg_id == -1) {
-                LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Failed to publish topic '" + _key + "', skipping all MQTT publishings in this round!");
-                failedOnRound = getCountFlowRounds();
-                return false;
-            }
-        }
-
-        if (_content.length() > 80) { // Truncate message if too long
-            _content.resize(80);
-            _content.append("..");
-        }
+    if (!mqtt_initialized || !mqtt_connected || client == NULL) {
+        LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Publish skipped. Client not initialized or not connected. (topic: " + _key + ")");
+        return false;
+    }
 
 
-        LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Published topic: " + _key + ", content: " + _content);
-        return true;
+    // esp_mqtt_client_enqueue() only adds the message to the outbox. The MQTT task
+    // performs the network operation, keeping socket waits out of the calling task.
+    // Serialize the size check with enqueue so concurrent publishers respect the cap.
+    std::lock_guard<std::mutex> publishLock(mqttPublishMutex);
+
+    const int outboxSize = esp_mqtt_client_get_outbox_size(client);
+    const size_t estimatedEntrySize = _key.length() + _content.length() + MQTT_OUTBOX_ENTRY_OVERHEAD;
+    if (outboxSize < 0 ||
+        static_cast<size_t>(outboxSize) + estimatedEntrySize > MQTT_MAX_OUTBOX_BYTES) {
+        failedOnRound = getCountFlowRounds();
+        LogFile.WriteToFile(ESP_LOG_WARN, TAG,
+                            "MQTT outbox limit reached (" + std::to_string(outboxSize) +
+                            " bytes); skipping further MQTT messages in this round");
+        return false;
     }
     }
-    else {
-        LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Publish skipped. Client not initalized or not connected. (topic: " + _key + ")");
+
+    const int64_t enqueueStartUs = esp_timer_get_time();
+    const int msg_id = esp_mqtt_client_enqueue(client, _key.c_str(), _content.c_str(), 0, qos, retained_flag, true);
+    const int64_t enqueueDurationUs = esp_timer_get_time() - enqueueStartUs;
+
+    if (msg_id < 0) {
+        failedOnRound = getCountFlowRounds();
+        LogFile.WriteToFile(ESP_LOG_WARN, TAG,
+                            "Failed to enqueue MQTT topic '" + _key +
+                            "' (outbox=" + std::to_string(outboxSize) + " bytes); skipping further MQTT messages in this round");
         return false;
         return false;
     }
     }
+
+    // Log only unusually slow enqueue operations. Normal publishes should not
+    // generate an additional SD-card write just for timing instrumentation.
+    if (enqueueDurationUs >= 10000) {
+        LogFile.WriteToFile(ESP_LOG_WARN, TAG,
+                            "MQTT enqueue for topic '" + _key + "' took " +
+                            std::to_string(enqueueDurationUs / 1000) + " ms (outbox=" +
+                            std::to_string(outboxSize) + " bytes)");
+    }
+
+    if (_content.length() > 80) {
+        _content.resize(80);
+        _content.append("..");
+    }
+
+    LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Queued topic: " + _key + ", content: " + _content);
+    return true;
 }
 }
 
 
 static esp_err_t mqtt_event_handler_cb(esp_mqtt_event_handle_t event) {
 static esp_err_t mqtt_event_handler_cb(esp_mqtt_event_handle_t event) {