Skip to content

Commit

Permalink
Make sure MQTT config is updated for current connection if changed
Browse files Browse the repository at this point in the history
  • Loading branch information
gskjold committed Dec 22, 2023
1 parent 32ad71b commit 557ba65
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 4 deletions.
1 change: 1 addition & 0 deletions lib/AmsMqttHandler/include/AmsMqttHandler.h
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ class AmsMqttHandler {
};

void setCaVerification(bool);
void setConfig(MqttConfig& mqttConfig);

bool connect();
void disconnect();
Expand Down
13 changes: 13 additions & 0 deletions lib/AmsMqttHandler/src/AmsMqttHandler.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,10 @@ void AmsMqttHandler::setCaVerification(bool caVerification) {
this->caVerification = caVerification;
}

void AmsMqttHandler::setConfig(MqttConfig& mqttConfig) {
this->mqttConfig = mqttConfig;
}

bool AmsMqttHandler::connect() {
if(millis() - lastMqttRetry < 10000) {
yield();
Expand Down Expand Up @@ -93,10 +97,19 @@ bool AmsMqttHandler::connect() {
if(debugger->isActive(RemoteDebug::INFO)) debugger->printf_P(PSTR("CA verification disabled\n"));
mqttSecureClient->setInsecure();
}
if(mqttClient != NULL) {
mqttClient->stop();
delete mqttClient;
}
mqttClient = mqttSecureClient;

if(debugger->isActive(RemoteDebug::DEBUG)) debugger->printf_P(PSTR("MQTT SSL setup complete (%dkb free heap)\n"), ESP.getFreeHeap());
}
} else if(mqttSecureClient != NULL) {
mqttSecureClient->stop();
delete mqttSecureClient;
mqttSecureClient = NULL;
mqttClient = NULL;
}

if(mqttClient == NULL) {
Expand Down
20 changes: 16 additions & 4 deletions src/AmsToMqttBridge.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -557,8 +557,15 @@ void loop() {

if (mqttEnabled || config.isMqttChanged()) {
if(mqttHandler == NULL || !mqttHandler->connected() || config.isMqttChanged()) {
if(mqttHandler != NULL && config.isMqttChanged()) {
MqttConfig mqttConfig;
if(config.getMqttConfig(mqttConfig)) {
mqttHandler->disconnect();
mqttHandler->setConfig(mqttConfig);
config.ackMqttChange();
}
}
MQTT_connect();
config.ackMqttChange();
}
} else if(mqttHandler != NULL) {
mqttHandler->disconnect();
Expand Down Expand Up @@ -1859,9 +1866,14 @@ void MQTT_connect() {
mqttEnabled = true;
ws.setMqttEnabled(true);

if(mqttHandler != NULL && mqttHandler->getFormat() != mqttConfig.payloadFormat) {
delete mqttHandler;
mqttHandler = NULL;
if(mqttHandler != NULL) {
mqttHandler->disconnect();
if(mqttHandler->getFormat() != mqttConfig.payloadFormat) {
delete mqttHandler;
mqttHandler = NULL;
} else if(config.isMqttChanged()) {
mqttHandler->setConfig(mqttConfig);
}
}

if(mqttHandler == NULL) {
Expand Down

0 comments on commit 557ba65

Please sign in to comment.