From 138c7b5cd8cc2a5a20ef98a7540320dd329f4c7f Mon Sep 17 00:00:00 2001 From: Nicu Hodos Date: Thu, 17 Oct 2024 17:15:43 +0200 Subject: [PATCH] read heap stats once and put them in both sensors and json attributes --- src/esp.h | 19 +++++++++++++++---- src/ha.h | 5 ++--- 2 files changed, 17 insertions(+), 7 deletions(-) diff --git a/src/esp.h b/src/esp.h index 0fe1095..7180f6b 100644 --- a/src/esp.h +++ b/src/esp.h @@ -12,9 +12,16 @@ namespace HaESP { } activeSensors; Task tHeap(5 * TASK_MINUTE, TASK_FOREVER, []() { - Sensor::mapSensors["heap_fragmentation"]->updateState(to_string(ESP.getHeapFragmentation()).c_str()); - Sensor::mapSensors["heap_free"]->updateState(to_string(ESP.getFreeHeap()).c_str()); - Sensor::mapSensors["heap_max_free_block"]->updateState(to_string(ESP.getMaxFreeBlockSize()).c_str()); + uint32_t hfree; + uint32_t hmax; + uint8_t hfrag; + ESP.getHeapStats(&hfree, &hmax, &hfrag); + + char value[256]; + sprintf(value, "{\"fragmentation\":%d,\"heap\":{\"Heap free\":\"%d B\",\"Heap max free block\":\"%d B\"}}", hfrag, hfree, hmax); + Sensor::mapSensors["heap_fragmentation"]->updateState(value); + Sensor::mapSensors["heap_free"]->updateState(to_string(hfree).c_str()); + Sensor::mapSensors["heap_max_free_block"]->updateState(to_string(hmax).c_str()); }, &ts); Task tRestartInfo(TASK_IMMEDIATE, TASK_ONCE, []() { @@ -23,9 +30,13 @@ namespace HaESP { template Builder& heapStats(Builder& builder) { - builder.addDiagnostic(Builder::instance(new Sensor{ "Heap fragmentation", "heap_fragmentation" }) + auto heap = new Sensor{ "Heap fragmentation", "heap_fragmentation" }; + builder.addDiagnostic(Builder::instance(heap) .withUnitMeasure("%") .withPrecision(0) + .withValueTemplate("{{ value_json.fragmentation }}") + .overrideConfig("json_attributes_topic", heap->stateTopic) + .overrideConfig("json_attributes_template", "{{ value_json.heap | tojson }}") .build()); builder.addDiagnostic(Builder::instance(new Sensor{ "Heap free", "heap_free" }) .withDeviceClass("data_size") diff --git a/src/ha.h b/src/ha.h index 7103b45..364fef8 100644 --- a/src/ha.h +++ b/src/ha.h @@ -205,8 +205,7 @@ namespace Ha { return *this; } - template - Builder& overrideConfig(const char* key, V value) { + Builder& overrideConfig(const char* key, float value) { cmp->jsonNumbers.add({key, value}); return *this; } @@ -293,6 +292,7 @@ namespace Ha { struct StateConfig { static unordered_map mapStateTopics; + char stateTopic[TOPIC_SIZE]; StateConfig(Component* cmp) : cmp(cmp) {} @@ -305,7 +305,6 @@ namespace Ha { } protected: - char stateTopic[TOPIC_SIZE]; Component* cmp; void buildConfig(JsonDocument& jsonDoc) { if (stateTopic[0]) jsonDoc["state_topic"] = stateTopic;