From 3dc31ff58546cdd3f4735e47fb3dbed310e22e82 Mon Sep 17 00:00:00 2001 From: Nicu Hodos Date: Sun, 5 Oct 2025 13:03:12 +0200 Subject: [PATCH] optimize memory allocation for battery percentage template --- include/rc_devices.h | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/include/rc_devices.h b/include/rc_devices.h index 1b33534..32d5c90 100644 --- a/include/rc_devices.h +++ b/include/rc_devices.h @@ -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}; }