app_main.c 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  1. /*
  2. * SPDX-FileCopyrightText: 2022-2023 Espressif Systems (Shanghai) CO LTD
  3. *
  4. * SPDX-License-Identifier: Apache-2.0
  5. */
  6. #include <stdio.h>
  7. #include <stdint.h>
  8. #include <stddef.h>
  9. #include <string.h>
  10. #include "esp_system.h"
  11. #include "nvs_flash.h"
  12. #include "esp_event.h"
  13. #include "esp_netif.h"
  14. #include "protocol_examples_common.h"
  15. #include "esp_log.h"
  16. #include "mqtt_client.h"
  17. static const char *TAG = "mqtt5_example";
  18. static void log_error_if_nonzero(const char *message, int error_code)
  19. {
  20. if (error_code != 0) {
  21. ESP_LOGE(TAG, "Last error %s: 0x%x", message, error_code);
  22. }
  23. }
  24. static esp_mqtt5_user_property_item_t user_property_arr[] = {
  25. {"board", "esp32"},
  26. {"u", "user"},
  27. {"p", "password"}
  28. };
  29. #define USE_PROPERTY_ARR_SIZE sizeof(user_property_arr)/sizeof(esp_mqtt5_user_property_item_t)
  30. static esp_mqtt5_publish_property_config_t publish_property = {
  31. .payload_format_indicator = 1,
  32. .message_expiry_interval = 1000,
  33. .topic_alias = 0,
  34. .response_topic = "/topic/test/response",
  35. .correlation_data = "123456",
  36. .correlation_data_len = 6,
  37. };
  38. static esp_mqtt5_subscribe_property_config_t subscribe_property = {
  39. .subscribe_id = 25555,
  40. .no_local_flag = false,
  41. .retain_as_published_flag = false,
  42. .retain_handle = 0,
  43. .is_share_subscribe = true,
  44. .share_name = "group1",
  45. };
  46. static esp_mqtt5_subscribe_property_config_t subscribe1_property = {
  47. .subscribe_id = 25555,
  48. .no_local_flag = true,
  49. .retain_as_published_flag = false,
  50. .retain_handle = 0,
  51. };
  52. static esp_mqtt5_unsubscribe_property_config_t unsubscribe_property = {
  53. .is_share_subscribe = true,
  54. .share_name = "group1",
  55. };
  56. static esp_mqtt5_disconnect_property_config_t disconnect_property = {
  57. .session_expiry_interval = 60,
  58. .disconnect_reason = 0,
  59. };
  60. static void print_user_property(mqtt5_user_property_handle_t user_property)
  61. {
  62. if (user_property) {
  63. uint8_t count = esp_mqtt5_client_get_user_property_count(user_property);
  64. if (count) {
  65. esp_mqtt5_user_property_item_t *item = malloc(count * sizeof(esp_mqtt5_user_property_item_t));
  66. if (esp_mqtt5_client_get_user_property(user_property, item, &count) == ESP_OK) {
  67. for (int i = 0; i < count; i ++) {
  68. esp_mqtt5_user_property_item_t *t = &item[i];
  69. ESP_LOGI(TAG, "key is %s, value is %s", t->key, t->value);
  70. free((char *)t->key);
  71. free((char *)t->value);
  72. }
  73. }
  74. free(item);
  75. }
  76. }
  77. }
  78. /*
  79. * @brief Event handler registered to receive MQTT events
  80. *
  81. * This function is called by the MQTT client event loop.
  82. *
  83. * @param handler_args user data registered to the event.
  84. * @param base Event base for the handler(always MQTT Base in this example).
  85. * @param event_id The id for the received event.
  86. * @param event_data The data for the event, esp_mqtt_event_handle_t.
  87. */
  88. static void mqtt5_event_handler(void *handler_args, esp_event_base_t base, int32_t event_id, void *event_data)
  89. {
  90. ESP_LOGD(TAG, "Event dispatched from event loop base=%s, event_id=%" PRIi32, base, event_id);
  91. esp_mqtt_event_handle_t event = event_data;
  92. esp_mqtt_client_handle_t client = event->client;
  93. int msg_id;
  94. ESP_LOGD(TAG, "free heap size is %" PRIu32 ", minimum %" PRIu32, esp_get_free_heap_size(), esp_get_minimum_free_heap_size());
  95. switch ((esp_mqtt_event_id_t)event_id) {
  96. case MQTT_EVENT_CONNECTED:
  97. ESP_LOGI(TAG, "MQTT_EVENT_CONNECTED");
  98. print_user_property(event->property->user_property);
  99. esp_mqtt5_client_set_user_property(&publish_property.user_property, user_property_arr, USE_PROPERTY_ARR_SIZE);
  100. esp_mqtt5_client_set_publish_property(client, &publish_property);
  101. msg_id = esp_mqtt_client_publish(client, "/topic/qos1", "data_3", 0, 1, 1);
  102. esp_mqtt5_client_delete_user_property(publish_property.user_property);
  103. publish_property.user_property = NULL;
  104. ESP_LOGI(TAG, "sent publish successful, msg_id=%d", msg_id);
  105. esp_mqtt5_client_set_user_property(&subscribe_property.user_property, user_property_arr, USE_PROPERTY_ARR_SIZE);
  106. esp_mqtt5_client_set_subscribe_property(client, &subscribe_property);
  107. msg_id = esp_mqtt_client_subscribe(client, "/topic/qos0", 0);
  108. esp_mqtt5_client_delete_user_property(subscribe_property.user_property);
  109. subscribe_property.user_property = NULL;
  110. ESP_LOGI(TAG, "sent subscribe successful, msg_id=%d", msg_id);
  111. esp_mqtt5_client_set_user_property(&subscribe1_property.user_property, user_property_arr, USE_PROPERTY_ARR_SIZE);
  112. esp_mqtt5_client_set_subscribe_property(client, &subscribe1_property);
  113. msg_id = esp_mqtt_client_subscribe(client, "/topic/qos1", 2);
  114. esp_mqtt5_client_delete_user_property(subscribe1_property.user_property);
  115. subscribe1_property.user_property = NULL;
  116. ESP_LOGI(TAG, "sent subscribe successful, msg_id=%d", msg_id);
  117. esp_mqtt5_client_set_user_property(&unsubscribe_property.user_property, user_property_arr, USE_PROPERTY_ARR_SIZE);
  118. esp_mqtt5_client_set_unsubscribe_property(client, &unsubscribe_property);
  119. msg_id = esp_mqtt_client_unsubscribe(client, "/topic/qos0");
  120. ESP_LOGI(TAG, "sent unsubscribe successful, msg_id=%d", msg_id);
  121. esp_mqtt5_client_delete_user_property(unsubscribe_property.user_property);
  122. unsubscribe_property.user_property = NULL;
  123. break;
  124. case MQTT_EVENT_DISCONNECTED:
  125. ESP_LOGI(TAG, "MQTT_EVENT_DISCONNECTED");
  126. print_user_property(event->property->user_property);
  127. break;
  128. case MQTT_EVENT_SUBSCRIBED:
  129. ESP_LOGI(TAG, "MQTT_EVENT_SUBSCRIBED, msg_id=%d", event->msg_id);
  130. print_user_property(event->property->user_property);
  131. esp_mqtt5_client_set_publish_property(client, &publish_property);
  132. msg_id = esp_mqtt_client_publish(client, "/topic/qos0", "data", 0, 0, 0);
  133. ESP_LOGI(TAG, "sent publish successful, msg_id=%d", msg_id);
  134. break;
  135. case MQTT_EVENT_UNSUBSCRIBED:
  136. ESP_LOGI(TAG, "MQTT_EVENT_UNSUBSCRIBED, msg_id=%d", event->msg_id);
  137. print_user_property(event->property->user_property);
  138. esp_mqtt5_client_set_user_property(&disconnect_property.user_property, user_property_arr, USE_PROPERTY_ARR_SIZE);
  139. esp_mqtt5_client_set_disconnect_property(client, &disconnect_property);
  140. esp_mqtt5_client_delete_user_property(disconnect_property.user_property);
  141. disconnect_property.user_property = NULL;
  142. esp_mqtt_client_disconnect(client);
  143. break;
  144. case MQTT_EVENT_PUBLISHED:
  145. ESP_LOGI(TAG, "MQTT_EVENT_PUBLISHED, msg_id=%d", event->msg_id);
  146. print_user_property(event->property->user_property);
  147. break;
  148. case MQTT_EVENT_DATA:
  149. ESP_LOGI(TAG, "MQTT_EVENT_DATA");
  150. print_user_property(event->property->user_property);
  151. ESP_LOGI(TAG, "payload_format_indicator is %d", event->property->payload_format_indicator);
  152. ESP_LOGI(TAG, "response_topic is %.*s", event->property->response_topic_len, event->property->response_topic);
  153. ESP_LOGI(TAG, "correlation_data is %.*s", event->property->correlation_data_len, event->property->correlation_data);
  154. ESP_LOGI(TAG, "content_type is %.*s", event->property->content_type_len, event->property->content_type);
  155. ESP_LOGI(TAG, "TOPIC=%.*s", event->topic_len, event->topic);
  156. ESP_LOGI(TAG, "DATA=%.*s", event->data_len, event->data);
  157. break;
  158. case MQTT_EVENT_ERROR:
  159. ESP_LOGI(TAG, "MQTT_EVENT_ERROR");
  160. print_user_property(event->property->user_property);
  161. ESP_LOGI(TAG, "MQTT5 return code is %d", event->error_handle->connect_return_code);
  162. if (event->error_handle->error_type == MQTT_ERROR_TYPE_TCP_TRANSPORT) {
  163. log_error_if_nonzero("reported from esp-tls", event->error_handle->esp_tls_last_esp_err);
  164. log_error_if_nonzero("reported from tls stack", event->error_handle->esp_tls_stack_err);
  165. log_error_if_nonzero("captured as transport's socket errno", event->error_handle->esp_transport_sock_errno);
  166. ESP_LOGI(TAG, "Last errno string (%s)", strerror(event->error_handle->esp_transport_sock_errno));
  167. }
  168. break;
  169. default:
  170. ESP_LOGI(TAG, "Other event id:%d", event->event_id);
  171. break;
  172. }
  173. }
  174. static void mqtt5_app_start(void)
  175. {
  176. esp_mqtt5_connection_property_config_t connect_property = {
  177. .session_expiry_interval = 10,
  178. .maximum_packet_size = 1024,
  179. .receive_maximum = 65535,
  180. .topic_alias_maximum = 2,
  181. .request_resp_info = true,
  182. .request_problem_info = true,
  183. .will_delay_interval = 10,
  184. .payload_format_indicator = true,
  185. .message_expiry_interval = 10,
  186. .response_topic = "/test/response",
  187. .correlation_data = "123456",
  188. .correlation_data_len = 6,
  189. };
  190. esp_mqtt_client_config_t mqtt5_cfg = {
  191. .broker.address.uri = CONFIG_BROKER_URL,
  192. .session.protocol_ver = MQTT_PROTOCOL_V_5,
  193. .network.disable_auto_reconnect = true,
  194. .credentials.username = "123",
  195. .credentials.authentication.password = "456",
  196. .session.last_will.topic = "/topic/will",
  197. .session.last_will.msg = "i will leave",
  198. .session.last_will.msg_len = 12,
  199. .session.last_will.qos = 1,
  200. .session.last_will.retain = true,
  201. };
  202. #if CONFIG_BROKER_URL_FROM_STDIN
  203. char line[128];
  204. if (strcmp(mqtt5_cfg.uri, "FROM_STDIN") == 0) {
  205. int count = 0;
  206. printf("Please enter url of mqtt broker\n");
  207. while (count < 128) {
  208. int c = fgetc(stdin);
  209. if (c == '\n') {
  210. line[count] = '\0';
  211. break;
  212. } else if (c > 0 && c < 127) {
  213. line[count] = c;
  214. ++count;
  215. }
  216. vTaskDelay(10 / portTICK_PERIOD_MS);
  217. }
  218. mqtt5_cfg.broker.address.uri = line;
  219. printf("Broker url: %s\n", line);
  220. } else {
  221. ESP_LOGE(TAG, "Configuration mismatch: wrong broker url");
  222. abort();
  223. }
  224. #endif /* CONFIG_BROKER_URL_FROM_STDIN */
  225. esp_mqtt_client_handle_t client = esp_mqtt_client_init(&mqtt5_cfg);
  226. /* Set connection properties and user properties */
  227. esp_mqtt5_client_set_user_property(&connect_property.user_property, user_property_arr, USE_PROPERTY_ARR_SIZE);
  228. esp_mqtt5_client_set_user_property(&connect_property.will_user_property, user_property_arr, USE_PROPERTY_ARR_SIZE);
  229. esp_mqtt5_client_set_connect_property(client, &connect_property);
  230. /* If you call esp_mqtt5_client_set_user_property to set user properties, DO NOT forget to delete them.
  231. * esp_mqtt5_client_set_connect_property will malloc buffer to store the user_property and you can delete it after
  232. */
  233. esp_mqtt5_client_delete_user_property(connect_property.user_property);
  234. esp_mqtt5_client_delete_user_property(connect_property.will_user_property);
  235. /* The last argument may be used to pass data to the event handler, in this example mqtt_event_handler */
  236. esp_mqtt_client_register_event(client, ESP_EVENT_ANY_ID, mqtt5_event_handler, NULL);
  237. esp_mqtt_client_start(client);
  238. }
  239. void app_main(void)
  240. {
  241. ESP_LOGI(TAG, "[APP] Startup..");
  242. ESP_LOGI(TAG, "[APP] Free memory: %" PRIu32 " bytes", esp_get_free_heap_size());
  243. ESP_LOGI(TAG, "[APP] IDF version: %s", esp_get_idf_version());
  244. esp_log_level_set("*", ESP_LOG_INFO);
  245. esp_log_level_set("mqtt_client", ESP_LOG_VERBOSE);
  246. esp_log_level_set("mqtt_example", ESP_LOG_VERBOSE);
  247. esp_log_level_set("transport_base", ESP_LOG_VERBOSE);
  248. esp_log_level_set("esp-tls", ESP_LOG_VERBOSE);
  249. esp_log_level_set("transport", ESP_LOG_VERBOSE);
  250. esp_log_level_set("outbox", ESP_LOG_VERBOSE);
  251. ESP_ERROR_CHECK(nvs_flash_init());
  252. ESP_ERROR_CHECK(esp_netif_init());
  253. ESP_ERROR_CHECK(esp_event_loop_create_default());
  254. /* This helper function configures Wi-Fi or Ethernet, as selected in menuconfig.
  255. * Read "Establishing Wi-Fi or Ethernet Connection" section in
  256. * examples/protocols/README.md for more information about this function.
  257. */
  258. ESP_ERROR_CHECK(example_connect());
  259. mqtt5_app_start();
  260. }