From 81864b3420ed02a6eefe7aaaac0760b34620ddd0 Mon Sep 17 00:00:00 2001 From: Bernhard Kirchen Date: Tue, 1 Aug 2023 09:20:04 +0200 Subject: [PATCH] execute MQTT client synchronously in main loop() (#350) processing a published valued on a subscribed topic is currently running in a task that is not the task executing the main loop(). that's because the espMqttClient(Secure) was constructed without arguments, which selects the constructor with two arguments priority and core, both of which have default values. that constructor selects espMqttClientTypes::UseInternalTask::YES, causing a task to be created in which context the MQTT client loop is executed. MQTT subscribers assume they are running in the same context as the main loop(). most code assumes exactly that. as the scheduler is preemptive and very little (none at all?) code is interlocked, we have to make sure to meet the programmer's expectations. this changeset calls the MQTT client loop in the context of the main loop() and enforces the use of espMqttClientTypes::UseInternalTask::NO. --- include/MqttSettings.h | 1 + src/MqttSettings.cpp | 10 ++++++++-- src/main.cpp | 2 ++ 3 files changed, 11 insertions(+), 2 deletions(-) diff --git a/include/MqttSettings.h b/include/MqttSettings.h index 47b4f0a9e..6653d75a7 100644 --- a/include/MqttSettings.h +++ b/include/MqttSettings.h @@ -10,6 +10,7 @@ class MqttSettingsClass { public: MqttSettingsClass(); void init(); + void loop(); void performReconnect(); bool getConnected(); void publish(const String& subtopic, const String& payload); diff --git a/src/MqttSettings.cpp b/src/MqttSettings.cpp index ccf6ca811..e432e061c 100644 --- a/src/MqttSettings.cpp +++ b/src/MqttSettings.cpp @@ -182,15 +182,21 @@ void MqttSettingsClass::init() createMqttClientObject(); } +void MqttSettingsClass::loop() +{ + if (nullptr == mqttClient) { return; } + mqttClient->loop(); +} + void MqttSettingsClass::createMqttClientObject() { if (mqttClient != nullptr) delete mqttClient; const CONFIG_T& config = Configuration.get(); if (config.Mqtt_Tls) { - mqttClient = static_cast(new espMqttClientSecure); + mqttClient = new espMqttClientSecure(espMqttClientTypes::UseInternalTask::NO); } else { - mqttClient = static_cast(new espMqttClient); + mqttClient = new espMqttClient(espMqttClientTypes::UseInternalTask::NO); } } diff --git a/src/main.cpp b/src/main.cpp index 6152a61db..51a17b33e 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -215,6 +215,8 @@ void loop() VeDirect.loop(); yield(); } + MqttSettings.loop(); + yield(); MqttHandleDtu.loop(); yield(); MqttHandleInverter.loop();