Skip to content

Commit

Permalink
Allocate smaller amount of buffer for JSON (esphome#3384)
Browse files Browse the repository at this point in the history
  • Loading branch information
dz0ny authored Apr 14, 2022
1 parent 6bac551 commit 93b628d
Showing 1 changed file with 7 additions and 7 deletions.
14 changes: 7 additions & 7 deletions esphome/components/json/json_util.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -23,21 +23,21 @@ std::string build_json(const json_build_t &f) {
#ifdef USE_ESP8266
const size_t free_heap = ESP.getMaxFreeBlockSize(); // NOLINT(readability-static-accessed-through-instance)
#elif defined(USE_ESP32)
const size_t free_heap = heap_caps_get_largest_free_block(MALLOC_CAP_INTERNAL);
const size_t free_heap = heap_caps_get_largest_free_block(MALLOC_CAP_8BIT);
#endif

const size_t request_size = std::min(free_heap - 2048, (size_t) 5120);
const size_t request_size = std::min(free_heap, (size_t) 512);

DynamicJsonDocument json_document(request_size);
if (json_document.memoryPool().buffer() == nullptr) {
if (json_document.capacity() == 0) {
ESP_LOGE(TAG, "Could not allocate memory for JSON document! Requested %u bytes, largest free heap block: %u bytes",
request_size, free_heap);
return "{}";
}
JsonObject root = json_document.to<JsonObject>();
f(root);
json_document.shrinkToFit();

ESP_LOGV(TAG, "Size after shrink %u bytes", json_document.capacity());
std::string output;
serializeJson(json_document, output);
return output;
Expand All @@ -51,13 +51,13 @@ void parse_json(const std::string &data, const json_parse_t &f) {
#ifdef USE_ESP8266
const size_t free_heap = ESP.getMaxFreeBlockSize(); // NOLINT(readability-static-accessed-through-instance)
#elif defined(USE_ESP32)
const size_t free_heap = heap_caps_get_largest_free_block(MALLOC_CAP_INTERNAL);
const size_t free_heap = heap_caps_get_largest_free_block(MALLOC_CAP_8BIT);
#endif
bool pass = false;
size_t request_size = std::min(free_heap - 2048, (size_t)(data.size() * 1.5));
size_t request_size = std::min(free_heap, (size_t)(data.size() * 1.5));
do {
DynamicJsonDocument json_document(request_size);
if (json_document.memoryPool().buffer() == nullptr) {
if (json_document.capacity() == 0) {
ESP_LOGE(TAG, "Could not allocate memory for JSON document! Requested %u bytes, free heap: %u", request_size,
free_heap);
return;
Expand Down

0 comments on commit 93b628d

Please sign in to comment.