read heap stats once and put them in both sensors and json attributes

This commit is contained in:
Nicu Hodos 2024-10-17 17:15:43 +02:00
parent df1b900b5d
commit 138c7b5cd8
2 changed files with 17 additions and 7 deletions

View File

@ -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 <class T>
Builder<T>& heapStats(Builder<T>& builder) {
builder.addDiagnostic(Builder<Sensor>::instance(new Sensor{ "Heap fragmentation", "heap_fragmentation" })
auto heap = new Sensor{ "Heap fragmentation", "heap_fragmentation" };
builder.addDiagnostic(Builder<Sensor>::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<Sensor>::instance(new Sensor{ "Heap free", "heap_free" })
.withDeviceClass("data_size")

View File

@ -205,8 +205,7 @@ namespace Ha {
return *this;
}
template <typename V>
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<string, Command*> 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;