diff --git a/include/Utils.h b/include/Utils.h index 6de962b02..4d4bfee37 100644 --- a/include/Utils.h +++ b/include/Utils.h @@ -1,6 +1,7 @@ // SPDX-License-Identifier: GPL-2.0-or-later #pragma once +#include #include class Utils { @@ -9,4 +10,5 @@ class Utils { static uint64_t generateDtuSerial(); static int getTimezoneOffset(); static void restartDtu(); + static bool checkJsonAlloc(const DynamicJsonDocument& doc, const char* function, const uint16_t line); }; diff --git a/src/MqttHandleHass.cpp b/src/MqttHandleHass.cpp index 88553e15e..0f5c293c8 100644 --- a/src/MqttHandleHass.cpp +++ b/src/MqttHandleHass.cpp @@ -135,6 +135,10 @@ void MqttHandleHassClass::publishInverterField(std::shared_ptr } DynamicJsonDocument root(1024); + if (!Utils::checkJsonAlloc(root, __FUNCTION__, __LINE__)) { + return; + } + root["name"] = name; root["stat_t"] = stateTopic; root["uniq_id"] = serial + "_ch" + chanNum + "_" + fieldName; @@ -179,6 +183,10 @@ void MqttHandleHassClass::publishInverterButton(std::shared_ptr uint32_t Utils::getChipId() @@ -65,3 +66,13 @@ void Utils::restartDtu() yield(); ESP.restart(); } + +bool Utils::checkJsonAlloc(const DynamicJsonDocument& doc, const char* function, const uint16_t line) +{ + if (doc.capacity() == 0) { + MessageOutput.printf("Alloc failed: %s, %d\r\n", function, line); + return false; + } + + return true; +}