Skip to content

Commit

Permalink
improve MQTT example, remove topic leading slash
Browse files Browse the repository at this point in the history
The mqtt topic forward slash '/' counts towards tree levels in spec, thus best practise is to not lead topic paths with a slash.
  • Loading branch information
PathToLife authored Feb 20, 2025
1 parent c71d74e commit 790d4d1
Showing 1 changed file with 8 additions and 5 deletions.
13 changes: 8 additions & 5 deletions examples/protocols/mqtt/tcp/main/app_main.c
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,9 @@

static const char *TAG = "mqtt_example";

// MQTT Test Topics
static const char * topic_qos0 = "topic/qos0";
static const char * topic_qos1 = "topic/qos1";

static void log_error_if_nonzero(const char *message, int error_code)
{
Expand Down Expand Up @@ -50,16 +53,16 @@ static void mqtt_event_handler(void *handler_args, esp_event_base_t base, int32_
switch ((esp_mqtt_event_id_t)event_id) {
case MQTT_EVENT_CONNECTED:
ESP_LOGI(TAG, "MQTT_EVENT_CONNECTED");
msg_id = esp_mqtt_client_publish(client, "/topic/qos1", "data_3", 0, 1, 0);
msg_id = esp_mqtt_client_publish(client, topic_qos1, "data_3", 0, 1, 0);
ESP_LOGI(TAG, "sent publish successful, msg_id=%d", msg_id);

msg_id = esp_mqtt_client_subscribe(client, "/topic/qos0", 0);
msg_id = esp_mqtt_client_subscribe(client, topic_qos0, 0);
ESP_LOGI(TAG, "sent subscribe successful, msg_id=%d", msg_id);

msg_id = esp_mqtt_client_subscribe(client, "/topic/qos1", 1);
msg_id = esp_mqtt_client_subscribe(client, topic_qos1, 1);
ESP_LOGI(TAG, "sent subscribe successful, msg_id=%d", msg_id);

msg_id = esp_mqtt_client_unsubscribe(client, "/topic/qos1");
msg_id = esp_mqtt_client_unsubscribe(client, topic_qos1);
ESP_LOGI(TAG, "sent unsubscribe successful, msg_id=%d", msg_id);
break;
case MQTT_EVENT_DISCONNECTED:
Expand All @@ -68,7 +71,7 @@ static void mqtt_event_handler(void *handler_args, esp_event_base_t base, int32_

case MQTT_EVENT_SUBSCRIBED:
ESP_LOGI(TAG, "MQTT_EVENT_SUBSCRIBED, msg_id=%d", event->msg_id);
msg_id = esp_mqtt_client_publish(client, "/topic/qos0", "data", 0, 0, 0);
msg_id = esp_mqtt_client_publish(client, topic_qos0, "data", 0, 0, 0);
ESP_LOGI(TAG, "sent publish successful, msg_id=%d", msg_id);
break;
case MQTT_EVENT_UNSUBSCRIBED:
Expand Down

0 comments on commit 790d4d1

Please sign in to comment.