optimize memory allocation for battery percentage template

This commit is contained in:
Nicu Hodos 2025-10-05 13:03:12 +02:00
parent 57b9494c98
commit 3dc31ff585

View File

@ -76,9 +76,11 @@ VoltageSensor* createVoltageSensor(const char* id) {
return new VoltageSensor{id, "Battery voltage", "{{ value_json.sensor.diagnostic.voltage }}"};
}
#define BATTERY_PERCENTAGE_TEMPLATE "{{ ((value_json.sensor.diagnostic.voltage|float-%.2f)|round(2)*100/%.2f)|int }}"
BatterySensor* createBatterySensor(const char* id, float min, float max) {
char* value_json = new char[128];
snprintf(value_json, 128, "{{ ((value_json.sensor.diagnostic.voltage|float-%.2f)|round(2)*100/%.2f)|int }}", min, max - min);
auto len = snprintf(nullptr, 0, BATTERY_PERCENTAGE_TEMPLATE, min, max - min) + 1;
char* value_json = new char[len];
snprintf(value_json, len, BATTERY_PERCENTAGE_TEMPLATE, min, max - min);
return new BatterySensor{id, "Battery level", value_json};
}