Skip to content

Commit

Permalink
Fix topic subscription information during MQTTClient::addTopicSub whe…
Browse files Browse the repository at this point in the history
…n the client is connected
  • Loading branch information
paclema committed May 19, 2023
1 parent d09e5a5 commit de26611
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 6 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ HEAD
* Removed unnecessary break line in log message
* Include ESP_LOGE, ESP_LOGD and ESP_LOGV definitions for esp8266 logging
* Add MQTTClient::getMQTTClientId method
* Fix topic subscription information during MQTTClient::addTopicSub when the client is connected

v0.2.0 (2023-05-16)
------
Expand Down
24 changes: 18 additions & 6 deletions src/MQTTClient.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -676,25 +676,37 @@ void MQTTClient::addTopicSub(const char* topic, int qos) {
.subs_status = ANY
};

// Add the new topic to the subscription topic list
subTopics.push_back(newTopic);

// If the client is already connected, subscribe to the new topic
if (currentState == MQTT_CONNECTED) {
#ifdef ESP32
newTopic.subs_msg_id = esp_mqtt_client_subscribe(client, newTopic.topic.c_str(), newTopic.qos);
if(newTopic.subs_msg_id > 0) {
newTopic.subs_status = SUBSCRIPTION_REQUESTED;
}
else
newTopic.subs_status = ERROR;
#elif defined(ESP8266)
newTopic.subs_msg_id = this->lastTopicId;
this->lastTopicId++;
if(mqttClient.subscribe(newTopic.topic.c_str(), newTopic.qos)) {
newTopic.subs_status = SUBSCRIBED;
this->onSubscribed(this, &newTopic);
}
else
newTopic.subs_status = ERROR;
this->onTopicUpdate(this, &newTopic);
#endif
};
} else {
ESP_LOGW(TAG, "MQTT client not connected, topic %s will be subscribed when connected", topic);
}

// Add the new topic to the subscription topic list
subTopics.push_back(newTopic);

// Notify Observers for topic updates in case there is any
if (newTopic.subs_status != ANY){
this->onTopicUpdate(this, &newTopic);
if (newTopic.subs_status == SUBSCRIBED) this->onSubscribed(this, &newTopic);
}

}

Expand Down Expand Up @@ -728,7 +740,7 @@ int MQTTClient::publish(const char *topic, const char *data, int len, int qos, i
// mqtt client return -1 if the message was not published successfully,
// or the message id number if the message was published successfully.
// Also for QoS 0 messages, the return will be 0.
ESP_LOGI(TAG, "MQTT TX -> topic: %s, message: %s", topic, data);
ESP_LOGV(TAG, "MQTT TX -> topic: %s, message: %s", topic, data);
return esp_mqtt_client_publish(client, topic, data, len, qos, retain);
#elif defined(ESP8266)
// PubSubClient publish return true if the message was published successfully,
Expand Down

0 comments on commit de26611

Please sign in to comment.