mqtt.rst 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198
  1. ESP-MQTT
  2. ========
  3. :link_to_translation:`zh_CN:[中文]`
  4. Overview
  5. --------
  6. ESP-MQTT is an implementation of `MQTT <https://mqtt.org/>`__ protocol client, which is a lightweight publish/subscribe messaging protocol. Now ESP-MQTT supports `MQTT v5.0 <https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html>`__.
  7. Features
  8. --------
  9. * Support MQTT over TCP, SSL with Mbed TLS, MQTT over WebSocket, and MQTT over WebSocket Secure
  10. * Easy to setup with URI
  11. * Multiple instances (multiple clients in one application)
  12. * Support subscribing, publishing, authentication, last will messages, keep alive pings, and all 3 Quality of Service (QoS) levels (it should be a fully functional client)
  13. Application Examples
  14. ---------------------
  15. * :example:`protocols/mqtt/tcp`: MQTT over TCP, default port 1883
  16. * :example:`protocols/mqtt/ssl`: MQTT over TLS, default port 8883
  17. * :example:`protocols/mqtt/ssl_ds`: MQTT over TLS using digital signature peripheral for authentication, default port 8883
  18. * :example:`protocols/mqtt/ssl_mutual_auth`: MQTT over TLS using certificates for authentication, default port 8883
  19. * :example:`protocols/mqtt/ssl_psk`: MQTT over TLS using pre-shared keys for authentication, default port 8883
  20. * :example:`protocols/mqtt/ws`: MQTT over WebSocket, default port 80
  21. * :example:`protocols/mqtt/wss`: MQTT over WebSocket Secure, default port 443
  22. * :example:`protocols/mqtt5`: Uses ESP-MQTT library to connect to broker with MQTT v5.0
  23. MQTT Message Retransmission
  24. ---------------------------
  25. A new MQTT message is created by calling :cpp:func:`esp_mqtt_client_publish <esp_mqtt_client_publish()>` or its non blocking counterpart :cpp:func:`esp_mqtt_client_enqueue <esp_mqtt_client_enqueue()>`.
  26. Messages with QoS 0 is sent only once. QoS 1 and 2 have different behaviors since the protocol requires extra steps to complete the process.
  27. The ESP-MQTT library opts to always retransmit unacknowledged QoS 1 and 2 publish messages to avoid losses in faulty connections, even though the MQTT specification requires the re-transmission only on reconnect with Clean Session flag been set to 0 (set :cpp:member:`disable_clean_session <esp_mqtt_client_config_t::session_t::disable_clean_session>` to true for this behavior).
  28. QoS 1 and 2 messages that may need retransmission are always enqueued, but first transmission try occurs immediately if :cpp:func:`esp_mqtt_client_publish <esp_mqtt_client_publish>` is used. A transmission retry for unacknowledged messages will occur after :cpp:member:`message_retransmit_timeout <esp_mqtt_client_config_t::session_t::message_retransmit_timeout>`. After :ref:`CONFIG_MQTT_OUTBOX_EXPIRED_TIMEOUT_MS` messages will expire and be deleted. If :ref:`CONFIG_MQTT_REPORT_DELETED_MESSAGES` is set, an event will be sent to notify the user.
  29. Configuration
  30. -------------
  31. The configuration is made by setting fields in :cpp:class:`esp_mqtt_client_config_t` struct. The configuration struct has the following sub structs to configure different aspects of the client operation.
  32. * :cpp:class:`esp_mqtt_client_config_t::broker_t` - Allow to set address and security verification.
  33. * :cpp:class:`esp_mqtt_client_config_t::credentials_t` - Client credentials for authentication.
  34. * :cpp:class:`esp_mqtt_client_config_t::session_t` - Configuration for MQTT session aspects.
  35. * :cpp:class:`esp_mqtt_client_config_t::network_t` - Networking related configuration.
  36. * :cpp:class:`esp_mqtt_client_config_t::task_t` - Allow to configure FreeRTOS task.
  37. * :cpp:class:`esp_mqtt_client_config_t::buffer_t` - Buffer size for input and output.
  38. In the following sections, the most common aspects are detailed.
  39. Broker
  40. ^^^^^^^^^^^
  41. ===========
  42. Address
  43. ===========
  44. Broker address can be set by usage of :cpp:class:`address <esp_mqtt_client_config_t::broker_t::address_t>` struct. The configuration can be made by usage of :cpp:member:`uri <esp_mqtt_client_config_t::broker_t::address_t::uri>` field or the combination of :cpp:member:`hostname <esp_mqtt_client_config_t::broker_t::address_t::hostname>`, :cpp:member:`transport <esp_mqtt_client_config_t::broker_t::address_t::transport>` and :cpp:member:`port <esp_mqtt_client_config_t::broker_t::address_t::port>`. Optionally, :cpp:member:`path <esp_mqtt_client_config_t::broker_t::address_t::path>` could be set, this field is useful in WebSocket connections.
  45. The :cpp:member:`uri <esp_mqtt_client_config_t::broker_t::address_t::uri>` field is used in the format ``scheme://hostname:port/path``.
  46. - Curently support ``mqtt``, ``mqtts``, ``ws``, ``wss`` schemes
  47. - MQTT over TCP samples:
  48. - ``mqtt://mqtt.eclipseprojects.io``: MQTT over TCP, default port 1883
  49. - ``mqtt://mqtt.eclipseprojects.io:1884``: MQTT over TCP, port 1884
  50. - ``mqtt://username:password@mqtt.eclipseprojects.io:1884``: MQTT over TCP,
  51. port 1884, with username and password
  52. - MQTT over SSL samples:
  53. - ``mqtts://mqtt.eclipseprojects.io``: MQTT over SSL, port 8883
  54. - ``mqtts://mqtt.eclipseprojects.io:8884``: MQTT over SSL, port 8884
  55. - MQTT over WebSocket samples:
  56. - ``ws://mqtt.eclipseprojects.io:80/mqtt``
  57. - MQTT over WebSocket Secure samples:
  58. - ``wss://mqtt.eclipseprojects.io:443/mqtt``
  59. - Minimal configurations:
  60. .. code-block:: c
  61. const esp_mqtt_client_config_t mqtt_cfg = {
  62. .broker.address.uri = "mqtt://mqtt.eclipseprojects.io",
  63. };
  64. esp_mqtt_client_handle_t client = esp_mqtt_client_init(&mqtt_cfg);
  65. esp_mqtt_client_register_event(client, ESP_EVENT_ANY_ID, mqtt_event_handler, client);
  66. esp_mqtt_client_start(client);
  67. .. note::
  68. By default MQTT client uses event loop library to post related MQTT events (connected, subscribed, published, etc.).
  69. ============
  70. Verification
  71. ============
  72. For secure connections with TLS used, and to guarantee Broker's identity, the :cpp:class:`verification <esp_mqtt_client_config_t::broker_t::verification_t>` struct must be set.
  73. The broker certificate may be set in PEM or DER format. To select DER, the equivalent :cpp:member:`certificate_len <esp_mqtt_client_config_t::broker_t::verification_t::certificate_len>` field must be set. Otherwise, a null-terminated string in PEM format should be provided to :cpp:member:`certificate <esp_mqtt_client_config_t::broker_t::verification_t::certificate>` field.
  74. - Get certificate from server, example: ``mqtt.eclipseprojects.io``
  75. .. code::
  76. openssl s_client -showcerts -connect mqtt.eclipseprojects.io:8883 < /dev/null \
  77. 2> /dev/null | openssl x509 -outform PEM > mqtt_eclipse_org.pem
  78. - Check the sample application: :example:`protocols/mqtt/ssl`
  79. - Configuration:
  80. .. code:: c
  81. const esp_mqtt_client_config_t mqtt_cfg = {
  82. .broker = {
  83. .address.uri = "mqtts://mqtt.eclipseprojects.io:8883",
  84. .verification.certificate = (const char *)mqtt_eclipse_org_pem_start,
  85. },
  86. };
  87. For details about other fields, please check the `API Reference`_ and :ref:`esp_tls_server_verification`.
  88. Client Credentials
  89. ^^^^^^^^^^^^^^^^^^
  90. All client related credentials are under the :cpp:class:`credentials <esp_mqtt_client_config_t::credentials_t>` field.
  91. * :cpp:member:`username <esp_mqtt_client_config_t::credentials_t::username>`: pointer to the username used for connecting to the broker, can also be set by URI
  92. * :cpp:member:`client_id <esp_mqtt_client_config_t::credentials_t::client_id>`: pointer to the client ID, defaults to ``ESP32_%CHIPID%`` where ``%CHIPID%`` are the last 3 bytes of MAC address in hex format
  93. ==============
  94. Authentication
  95. ==============
  96. It is possible to set authentication parameters through the :cpp:class:`authentication <esp_mqtt_client_config_t::credentials_t::authentication_t>` field. The client supports the following authentication methods:
  97. * :cpp:member:`password <esp_mqtt_client_config_t::credentials_t::authentication_t::password>`: use a password by setting
  98. * :cpp:member:`certificate <esp_mqtt_client_config_t::credentials_t::authentication_t::certificate>` and :cpp:member:`key <esp_mqtt_client_config_t::credentials_t::authentication_t::key>`: mutual authentication with TLS, and both can be provided in PEM or DER format
  99. * :cpp:member:`use_secure_element <esp_mqtt_client_config_t::credentials_t::authentication_t::use_secure_element>`: use secure element available in ESP32-WROOM-32SE
  100. * :cpp:member:`ds_data <esp_mqtt_client_config_t::credentials_t::authentication_t::ds_data>`: use Digital Signature Peripheral available in some Espressif devices
  101. Session
  102. ^^^^^^^^^^^
  103. For MQTT session related configurations, :cpp:class:`session <esp_mqtt_client_config_t::session_t>` fields should be used.
  104. =======================
  105. Last Will and Testament
  106. =======================
  107. MQTT allows for a last will and testament (LWT) message to notify other clients when a client ungracefully disconnects. This is configured by the following fields in the :cpp:class:`last_will <esp_mqtt_client_config_t::session_t::last_will_t>` struct.
  108. * :cpp:member:`topic <esp_mqtt_client_config_t::session_t::last_will_t::topic>`: pointer to the LWT message topic
  109. * :cpp:member:`msg <esp_mqtt_client_config_t::session_t::last_will_t::msg>`: pointer to the LWT message
  110. * :cpp:member:`msg_len <esp_mqtt_client_config_t::session_t::last_will_t::msg_len>`: length of the LWT message, required if :cpp:member:`msg <esp_mqtt_client_config_t::session_t::last_will_t::msg>` is not null-terminated
  111. * :cpp:member:`qos <esp_mqtt_client_config_t::session_t::last_will_t::qos>`: quality of service for the LWT message
  112. * :cpp:member:`retain <esp_mqtt_client_config_t::session_t::last_will_t::retain>`: specifies the retain flag of the LWT message
  113. Change Settings in Project Configuration Menu
  114. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  115. The settings for MQTT can be found using :code:`idf.py menuconfig`, under ``Component config`` > ``ESP-MQTT Configuration``.
  116. The following settings are available:
  117. - :ref:`CONFIG_MQTT_PROTOCOL_311`: enable 3.1.1 version of MQTT protocol
  118. - :ref:`CONFIG_MQTT_TRANSPORT_SSL` and :ref:`CONFIG_MQTT_TRANSPORT_WEBSOCKET`: enable specific MQTT transport layer, such as SSL, WEBSOCKET, and WEBSOCKET_SECURE
  119. - :ref:`CONFIG_MQTT_CUSTOM_OUTBOX`: disable default implementation of mqtt_outbox, so a specific implementation can be supplied
  120. Events
  121. ------
  122. The following events may be posted by the MQTT client:
  123. * ``MQTT_EVENT_BEFORE_CONNECT``: The client is initialized and about to start connecting to the broker.
  124. * ``MQTT_EVENT_CONNECTED``: The client has successfully established a connection to the broker. The client is now ready to send and receive data.
  125. * ``MQTT_EVENT_DISCONNECTED``: The client has aborted the connection due to being unable to read or write data, e.g., because the server is unavailable.
  126. * ``MQTT_EVENT_SUBSCRIBED``: The broker has acknowledged the client's subscribe request. The event data contains the message ID of the subscribe message.
  127. * ``MQTT_EVENT_UNSUBSCRIBED``: The broker has acknowledged the client's unsubscribe request. The event data contains the message ID of the unsubscribe message.
  128. * ``MQTT_EVENT_PUBLISHED``: The broker has acknowledged the client's publish message. This is only posted for QoS level 1 and 2, as level 0 does not use acknowledgements. The event data contains the message ID of the publish message.
  129. * ``MQTT_EVENT_DATA``: The client has received a publish message. The event data contains: message ID, name of the topic it was published to, received data and its length. For data that exceeds the internal buffer, multiple ``MQTT_EVENT_DATA`` events are posted and :cpp:member:`current_data_offset <esp_mqtt_event_t::current_data_offset>` and :cpp:member:`total_data_len <esp_mqtt_event_t::total_data_len>` from event data updated to keep track of the fragmented message.
  130. * ``MQTT_EVENT_ERROR``: The client has encountered an error. The field :cpp:type:`error_handle <esp_mqtt_error_codes_t>` in the event data contains :cpp:type:`error_type <esp_mqtt_error_type_t>` that can be used to identify the error. The type of error determines which parts of the :cpp:type:`error_handle <esp_mqtt_error_codes_t>` struct is filled.
  131. API Reference
  132. -------------
  133. .. include-build-file:: inc/mqtt_client.inc