From 7894f0c6214b71ca0dcd71697a13c8e878cb9a6a Mon Sep 17 00:00:00 2001 From: Alex Hope-O'Connor Date: Thu, 16 Apr 2026 17:39:42 +1000 Subject: [PATCH] Fix MQTT client ownership and base device cleanup. Store the production PubSubClient instance directly on HAMqtt and release base device serializers on destruction to avoid invalid deletes and leaked serializer allocations. --- src/HAMqtt.cpp | 5 ++++- src/HAMqtt.h | 7 +++++-- src/device-types/HABaseDeviceType.cpp | 5 +++++ src/device-types/HABaseDeviceType.h | 2 ++ 4 files changed, 16 insertions(+), 3 deletions(-) diff --git a/src/HAMqtt.cpp b/src/HAMqtt.cpp index 7ff1a5a..af3a35b 100644 --- a/src/HAMqtt.cpp +++ b/src/HAMqtt.cpp @@ -60,7 +60,8 @@ HAMqtt::HAMqtt( HADevice& device, uint8_t maxDevicesTypesNb ) : - _mqtt(new PubSubClient(netClient)), + _mqttStorage(netClient), + _mqtt(&_mqttStorage), HAMQTT_INIT { _instance = this; @@ -71,9 +72,11 @@ HAMqtt::~HAMqtt() { delete[] _devicesTypes; +#ifdef ARDUINOHA_TEST if (_mqtt) { delete _mqtt; } +#endif _instance = nullptr; } diff --git a/src/HAMqtt.h b/src/HAMqtt.h index e0b3188..915f8ea 100644 --- a/src/HAMqtt.h +++ b/src/HAMqtt.h @@ -14,7 +14,7 @@ #ifdef ARDUINOHA_TEST class PubSubClientMock; #else -class PubSubClient; +#include #endif #if defined(__AVR_ATmega328P__) || defined(__AVR_ATmega168__) @@ -417,7 +417,10 @@ private: #ifdef ARDUINOHA_TEST PubSubClientMock* _mqtt; #else - /// Instance of the PubSubClient class. It's initialized in the constructor. + /// Storage for the PubSubClient instance used in production builds. + PubSubClient _mqttStorage; + + /// Pointer to the active MQTT client implementation. PubSubClient* _mqtt; #endif diff --git a/src/device-types/HABaseDeviceType.cpp b/src/device-types/HABaseDeviceType.cpp index 17583e3..d5ce93c 100644 --- a/src/device-types/HABaseDeviceType.cpp +++ b/src/device-types/HABaseDeviceType.cpp @@ -20,6 +20,11 @@ HABaseDeviceType::HABaseDeviceType( } } +HABaseDeviceType::~HABaseDeviceType() +{ + destroySerializer(); +} + void HABaseDeviceType::setAvailability(bool online) { _availability = (online ? AvailabilityOnline : AvailabilityOffline); diff --git a/src/device-types/HABaseDeviceType.h b/src/device-types/HABaseDeviceType.h index 0d6fa32..8514bce 100644 --- a/src/device-types/HABaseDeviceType.h +++ b/src/device-types/HABaseDeviceType.h @@ -37,6 +37,8 @@ public: const char* uniqueId ); + virtual ~HABaseDeviceType(); + /** * Returns unique ID of the device type. */