From e8acf33a69478a30a7694c502a5ece5e3629ab7a Mon Sep 17 00:00:00 2001 From: Maxim Prokhorov Date: Fri, 1 Nov 2019 23:43:48 +0300 Subject: [PATCH] ha: more cancelation reasons --- code/espurna/homeassistant.ino | 22 ++++++++++++++++++++-- 1 file changed, 20 insertions(+), 2 deletions(-) diff --git a/code/espurna/homeassistant.ino b/code/espurna/homeassistant.ino index 4155526c..93379a73 100644 --- a/code/espurna/homeassistant.ino +++ b/code/espurna/homeassistant.ino @@ -97,8 +97,11 @@ struct ha_config_t { struct ha_discovery_t { constexpr static const unsigned long SEND_TIMEOUT = 1000; + constexpr static const unsigned char SEND_RETRY = 5; - ha_discovery_t() { + ha_discovery_t() : + _retry(SEND_RETRY) + { #if SENSOR_SUPPORT _messages.reserve(magnitudeCount() + relayCount()); #else @@ -106,6 +109,10 @@ struct ha_discovery_t { #endif } + ~ha_discovery_t() { + DEBUG_MSG_P(PSTR("[HA] Discovery %s\n"), empty() ? "OK" : "FAILED"); + } + // TODO: is this expected behaviour? void add(String& topic, String& message) { _messages.emplace_back(std::move(topic), std::move(message)); @@ -125,6 +132,11 @@ struct ha_discovery_t { return !_messages.size(); } + bool retry() { + if (!_retry) return false; + return --_retry; + } + void prepareSwitches(ha_config_t& config); #if SENSOR_SUPPORT void prepareMagnitudes(ha_config_t& config); @@ -132,6 +144,7 @@ struct ha_discovery_t { Ticker timer; std::vector _messages; + unsigned char _retry; }; @@ -141,7 +154,12 @@ void _haSendDiscovery() { if (!_ha_discovery) return; - if (_ha_discovery->empty()) { + const bool connected = mqttConnected(); + const bool retry = _ha_discovery->retry(); + const bool empty = _ha_discovery->empty(); + + if (!connected || !retry || empty) { + _ha_discovery = nullptr; return; }