Skip to content

Commit 790d4d1

Browse files
authored
improve MQTT example, remove topic leading slash
The mqtt topic forward slash '/' counts towards tree levels in spec, thus best practise is to not lead topic paths with a slash.
1 parent c71d74e commit 790d4d1

File tree

1 file changed

+8
-5
lines changed

1 file changed

+8
-5
lines changed

examples/protocols/mqtt/tcp/main/app_main.c

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,9 @@
2323

2424
static const char *TAG = "mqtt_example";
2525

26+
// MQTT Test Topics
27+
static const char * topic_qos0 = "topic/qos0";
28+
static const char * topic_qos1 = "topic/qos1";
2629

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

56-
msg_id = esp_mqtt_client_subscribe(client, "/topic/qos0", 0);
59+
msg_id = esp_mqtt_client_subscribe(client, topic_qos0, 0);
5760
ESP_LOGI(TAG, "sent subscribe successful, msg_id=%d", msg_id);
5861

59-
msg_id = esp_mqtt_client_subscribe(client, "/topic/qos1", 1);
62+
msg_id = esp_mqtt_client_subscribe(client, topic_qos1, 1);
6063
ESP_LOGI(TAG, "sent subscribe successful, msg_id=%d", msg_id);
6164

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

6972
case MQTT_EVENT_SUBSCRIBED:
7073
ESP_LOGI(TAG, "MQTT_EVENT_SUBSCRIBED, msg_id=%d", event->msg_id);
71-
msg_id = esp_mqtt_client_publish(client, "/topic/qos0", "data", 0, 0, 0);
74+
msg_id = esp_mqtt_client_publish(client, topic_qos0, "data", 0, 0, 0);
7275
ESP_LOGI(TAG, "sent publish successful, msg_id=%d", msg_id);
7376
break;
7477
case MQTT_EVENT_UNSUBSCRIBED:

0 commit comments

Comments
 (0)