prevent double subscriptions when mqtt connecting

This commit is contained in:
proddy
2020-11-15 17:51:18 +01:00
parent 6ae61d742f
commit 4bfdb017b9
2 changed files with 27 additions and 18 deletions

View File

@@ -41,6 +41,7 @@ std::vector<Mqtt::MQTTSubFunction> Mqtt::mqtt_subfunctions_;
uint16_t Mqtt::mqtt_publish_fails_ = 0;
bool Mqtt::connecting_ = false;
uint8_t Mqtt::connectcount_ = 0;
uint16_t Mqtt::mqtt_message_id_ = 0;
std::list<Mqtt::QueuedMqttMessage> Mqtt::mqtt_messages_;
char will_topic_[Mqtt::MQTT_TOPIC_MAX_SIZE]; // because MQTT library keeps only char pointer
@@ -109,6 +110,7 @@ void Mqtt::resubscribe() {
}
for (const auto & mqtt_subfunction : mqtt_subfunctions_) {
LOG_INFO("got %s", mqtt_subfunction.topic_.c_str()); // TODO
queue_subscribe_message(mqtt_subfunction.topic_);
}
}
@@ -469,9 +471,10 @@ void Mqtt::on_connect() {
}
connecting_ = true;
connectcount_++;
LOG_INFO(F("MQTT connected"));
// first time to connect
if (connectcount_ == 1) {
// send info topic appended with the version information as JSON
StaticJsonDocument<90> doc;
doc["event"] = "start";
@@ -481,15 +484,20 @@ void Mqtt::on_connect() {
#endif
publish(F_(info), doc.as<JsonObject>());
publish_retain(F("status"), "online", true); // say we're alive to the Last Will topic, with retain on
reset_publish_fails(); // reset fail count to 0
resubscribe(); // in case this is a reconnect, re-subscribe again to all MQTT topics
// create the EMS-ESP device in HA, which is MQTT retained
if (mqtt_format() == Format::HA) {
ha_status(); // create a device in HA
ha_status();
}
publish_retain(F("status"), "online", true); // say we're alive to the Last Will topic, with retain on
} else {
// we doing a re-connect from a TCP break
// only re-subscribe again to all MQTT topics
resubscribe();
}
LOG_INFO(F("MQTT connected"));
reset_publish_fails(); // reset fail count to 0
}
// Home Assistant Discovery - the main master Device

View File

@@ -218,6 +218,7 @@ class Mqtt {
static bool connecting_;
static uint16_t mqtt_publish_fails_;
static uint8_t connectcount_;
// settings, copied over
static std::string hostname_;