Skip to content

Commit

Permalink
execute MQTT client synchronously in main loop() (#350)
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
schlimmchen authored Aug 1, 2023
1 parent 587b2dc commit 81864b3
Show file tree
Hide file tree
Showing 3 changed files with 11 additions and 2 deletions.
1 change: 1 addition & 0 deletions include/MqttSettings.h
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ class MqttSettingsClass {
public:
MqttSettingsClass();
void init();
void loop();
void performReconnect();
bool getConnected();
void publish(const String& subtopic, const String& payload);
Expand Down
10 changes: 8 additions & 2 deletions src/MqttSettings.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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<MqttClient*>(new espMqttClientSecure);
mqttClient = new espMqttClientSecure(espMqttClientTypes::UseInternalTask::NO);
} else {
mqttClient = static_cast<MqttClient*>(new espMqttClient);
mqttClient = new espMqttClient(espMqttClientTypes::UseInternalTask::NO);
}
}

Expand Down
2 changes: 2 additions & 0 deletions src/main.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -215,6 +215,8 @@ void loop()
VeDirect.loop();
yield();
}
MqttSettings.loop();
yield();
MqttHandleDtu.loop();
yield();
MqttHandleInverter.loop();
Expand Down

0 comments on commit 81864b3

Please sign in to comment.