From 86a49a781a38769b39a8e14bd15edd5c1207c157 Mon Sep 17 00:00:00 2001 From: Bernhard Kirchen Date: Mon, 22 Jul 2024 17:19:11 +0200 Subject: [PATCH] fix: use mutex when writing MQTT power meter value we previously used the mutex to protect writing the target variable. however, we would only do that for the old usecase, where a plain float value in Watts was expected as the topic's payload. --- src/PowerMeterMqtt.cpp | 20 +++++++++++++------- 1 file changed, 13 insertions(+), 7 deletions(-) diff --git a/src/PowerMeterMqtt.cpp b/src/PowerMeterMqtt.cpp index 5789c9114..0bb8fd61c 100644 --- a/src/PowerMeterMqtt.cpp +++ b/src/PowerMeterMqtt.cpp @@ -48,10 +48,11 @@ void PowerMeterMqtt::onMessage(PowerMeterMqtt::MsgProperties const& properties, MessageOutput.println(); }; + float newValue = 0; + if (strlen(cfg->JsonPath) == 0) { try { - std::lock_guard l(_mutex); - *targetVariable = std::stof(value); + newValue = std::stof(value); } catch (std::invalid_argument const& e) { return log("cannot parse payload '%s' as float", logValue.c_str()); @@ -74,25 +75,30 @@ void PowerMeterMqtt::onMessage(PowerMeterMqtt::MsgProperties const& properties, return log("%s", pathResolutionResult.second.c_str()); } - *targetVariable = pathResolutionResult.first; + newValue = pathResolutionResult.first; } using Unit_t = PowerMeterMqttValue::Unit; switch (cfg->PowerUnit) { case Unit_t::MilliWatts: - *targetVariable /= 1000; + newValue /= 1000; break; case Unit_t::KiloWatts: - *targetVariable *= 1000; + newValue *= 1000; break; default: break; } - if (cfg->SignInverted) { *targetVariable *= -1; } + if (cfg->SignInverted) { newValue *= -1; } + + { + std::lock_guard l(_mutex); + *targetVariable = newValue; + } if (_verboseLogging) { - log("new value: %5.2f, total: %5.2f", *targetVariable, getPowerTotal()); + log("new value: %5.2f, total: %5.2f", newValue, getPowerTotal()); } gotUpdate();