diff --git a/src/mqtt.cpp b/src/mqtt.cpp index 28f8b0436..7be71f867 100644 --- a/src/mqtt.cpp +++ b/src/mqtt.cpp @@ -39,9 +39,9 @@ bool Mqtt::mqtt_enabled_; std::vector Mqtt::mqtt_subfunctions_; -uint16_t Mqtt::mqtt_publish_fails_ = 0; -// size_t Mqtt::maximum_mqtt_messages_ = Mqtt::MAX_MQTT_MESSAGES; -uint16_t Mqtt::mqtt_message_id_ = 0; +uint16_t Mqtt::mqtt_publish_fails_ = 0; +bool Mqtt::connecting_ = false; +uint16_t Mqtt::mqtt_message_id_ = 0; std::list Mqtt::mqtt_messages_; char will_topic_[Mqtt::MQTT_TOPIC_MAX_SIZE]; // because MQTT library keeps only char pointer @@ -364,6 +364,7 @@ void Mqtt::start() { mqttClient_->onConnect([this](bool sessionPresent) { on_connect(); }); mqttClient_->onDisconnect([this](AsyncMqttClientDisconnectReason reason) { + connecting_ = false; if (reason == AsyncMqttClientDisconnectReason::TCP_DISCONNECTED) { LOG_INFO(F("MQTT disconnected: TCP")); } @@ -463,6 +464,14 @@ void Mqtt::set_format(uint8_t mqtt_format) { // MQTT onConnect - when a connect is established void Mqtt::on_connect() { + if (connecting_) { + return; + } + + connecting_ = true; + + LOG_INFO(F("MQTT connected")); + // send info topic appended with the version information as JSON StaticJsonDocument<90> doc; doc["event"] = "start"; @@ -481,8 +490,6 @@ void Mqtt::on_connect() { if (mqtt_format() == Format::HA) { ha_status(); // create a device in HA } - - LOG_INFO(F("MQTT connected")); } // Home Assistant Discovery - the main master Device diff --git a/src/mqtt.h b/src/mqtt.h index 7e5080a79..cadcc9948 100644 --- a/src/mqtt.h +++ b/src/mqtt.h @@ -85,6 +85,8 @@ class Mqtt { static constexpr uint8_t MQTT_TOPIC_MAX_SIZE = 128; // note this should really match the user setting in mqttSettings.maxTopicLength + static void on_connect(); + static void subscribe(const uint8_t device_type, const std::string & topic, mqtt_subfunction_p cb); static void subscribe(const std::string & topic, mqtt_subfunction_p cb); static void resubscribe(); @@ -112,7 +114,6 @@ class Mqtt { static void show_topic_handlers(uuid::console::Shell & shell, const uint8_t device_type); static void show_mqtt(uuid::console::Shell & shell); - static void on_connect(); static void ha_status(); void disconnect() { @@ -189,8 +190,6 @@ class Mqtt { void on_message(const char * topic, const char * payload, size_t len); void process_queue(); - static uint16_t mqtt_publish_fails_; - // function handlers for MQTT subscriptions struct MQTTSubFunction { uint8_t device_type_; // which device type, from DeviceType:: @@ -216,6 +215,9 @@ class Mqtt { uint32_t last_publish_other_ = 0; uint32_t last_publish_sensor_ = 0; + static bool connecting_; + static uint16_t mqtt_publish_fails_; + // settings, copied over static std::string hostname_; static uint8_t mqtt_qos_;