From ca18d2c8419e3bfcd5c33a046d72baae093f9502 Mon Sep 17 00:00:00 2001 From: Thomas Basler Date: Thu, 4 Jan 2024 14:09:58 +0100 Subject: [PATCH] Prevent empty HASS auto discovery topics if memory allocation fails --- include/Utils.h | 2 ++ src/MqttHandleHass.cpp | 24 ++++++++++++++++++++++++ src/Utils.cpp | 11 +++++++++++ 3 files changed, 37 insertions(+) diff --git a/include/Utils.h b/include/Utils.h index 6de962b0..4d4bfee3 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 @@ public: 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 88553e15..0f5c293c 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; +}