From 56f7566409ae74b5cf4829fd6346e7e76a2d6835 Mon Sep 17 00:00:00 2001 From: matth-x <63792403+matth-x@users.noreply.github.com> Date: Thu, 10 Oct 2024 08:53:29 +0000 Subject: [PATCH] implement memory stats to JSON --- src/MicroOcpp/Core/Memory.cpp | 37 ++++++++++++++++++++++++++++++++++- 1 file changed, 36 insertions(+), 1 deletion(-) diff --git a/src/MicroOcpp/Core/Memory.cpp b/src/MicroOcpp/Core/Memory.cpp index f8ea7a2b..a352e9ac 100644 --- a/src/MicroOcpp/Core/Memory.cpp +++ b/src/MicroOcpp/Core/Memory.cpp @@ -207,7 +207,7 @@ void mo_mem_print_stats() { for (const auto& heapEntry : memBlocks) { size += heapEntry.second.size; - #if MO_DBG_LEVEL >= MO_DL_DEBUG + #if MO_DBG_LEVEL >= MO_DL_VERBOSE { MO_CONSOLE_PRINTF("@%p - %zu B (%s)\n", heapEntry.first, heapEntry.second.size, heapEntry.second.tag.c_str()); } @@ -254,6 +254,41 @@ void mo_mem_print_stats() { #endif } +int mo_mem_write_stats_json(char *buf, size_t size) { + DynamicJsonDocument doc {size * 2}; + + doc["total_current"] = memTotal; + doc["total_max"] = memTotalMax; + doc["total_blocks"] = memBlocks.size(); + + JsonArray by_tag = doc.createNestedArray("by_tag"); + for (const auto& tag : memTags) { + JsonObject entry = by_tag.createNestedObject(); + entry["tag"] = tag.first.c_str(); + entry["current"] = tag.second.current_size; + entry["max"] = tag.second.max_size; + } + + size_t untagged = 0, untagged_size = 0; + + for (const auto& heapEntry : memBlocks) { + if (heapEntry.second.tag.empty()) { + untagged ++; + untagged_size += heapEntry.second.size; + } + } + + doc["untagged_blocks"] = untagged; + doc["untagged_size"] = untagged_size; + + if (doc.overflowed()) { + MO_DBG_ERR("exceeded JSON capacity"); + return -1; + } + + return (int)serializeJson(doc, buf, size); +} + #endif //MO_OVERRIDE_ALLOCATION && MO_ENABLE_HEAP_PROFILER namespace MicroOcpp {