From bb59ca6f6fbd36878e5ffb1785186ac514bb550c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andreas=20Bo=CC=88hm?= Date: Sat, 7 Dec 2024 20:27:38 +0100 Subject: [PATCH] Feature: auto-detect SoC precision for MQTT Battery provider --- include/MqttBattery.h | 1 + src/MqttBattery.cpp | 15 ++++++++++++--- 2 files changed, 13 insertions(+), 3 deletions(-) diff --git a/include/MqttBattery.h b/include/MqttBattery.h index 7698e4c94..04d4a6ab4 100644 --- a/include/MqttBattery.h +++ b/include/MqttBattery.h @@ -19,6 +19,7 @@ class MqttBattery : public BatteryProvider { String _voltageTopic; String _dischargeCurrentLimitTopic; std::shared_ptr _stats = std::make_shared(); + uint8_t _socPrecision = 0; void onMqttMessageSoC(espMqttClientTypes::MessageProperties const& properties, char const* topic, uint8_t const* payload, size_t len, size_t index, size_t total, diff --git a/src/MqttBattery.cpp b/src/MqttBattery.cpp index cd17cf7d2..24d29582f 100644 --- a/src/MqttBattery.cpp +++ b/src/MqttBattery.cpp @@ -98,11 +98,20 @@ void MqttBattery::onMqttMessageSoC(espMqttClientTypes::MessageProperties const& return; } - _stats->setSoC(*soc, 0/*precision*/, millis()); + unsigned factor = 10; + uint8_t precision = 0; + while (precision < 2) { + if (std::floor(*soc * factor) == std::floor(*soc) * factor) { break; } + ++precision; + factor *= 10; + } + _socPrecision = std::max(_socPrecision, precision); + + _stats->setSoC(*soc, _socPrecision, millis()); if (_verboseLogging) { - MessageOutput.printf("MqttBattery: Updated SoC to %d from '%s'\r\n", - static_cast(*soc), topic); + MessageOutput.printf("MqttBattery: Updated SoC to %.*f from '%s'\r\n", + _socPrecision, *soc, topic); } }