Skip to content

Commit

Permalink
fix: use mutex when writing MQTT power meter value
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
schlimmchen committed Jul 22, 2024
1 parent 5e5a525 commit 86a49a7
Showing 1 changed file with 13 additions and 7 deletions.
20 changes: 13 additions & 7 deletions src/PowerMeterMqtt.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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<std::mutex> 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());
Expand All @@ -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<std::mutex> 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();
Expand Down

0 comments on commit 86a49a7

Please sign in to comment.