mqtt.rst 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181
  1. ESP-MQTT
  2. ========
  3. Overview
  4. --------
  5. ESP-MQTT is an implementation of [MQTT](mqtt.org) protocol client (MQTT is a lightweight publish/subscribe messaging protocol).
  6. Features
  7. --------
  8. * Supports MQTT over TCP, SSL with mbedtls, MQTT over Websocket, MQTT over Websocket Secure.
  9. * Easy to setup with URI
  10. * Multiple instances (Multiple clients in one application)
  11. * Support subscribing, publishing, authentication, last will messages, keep alive pings and all 3 QoS levels (it should be a fully functional client).
  12. Application Example
  13. -------------------
  14. * :example:`protocols/mqtt/tcp`: MQTT over tcp, default port 1883
  15. * :example:`protocols/mqtt/ssl`: MQTT over tls, default port 8883
  16. * :example:`protocols/mqtt/ssl_ds`: MQTT over tls using digital signature peripheral for authentication, default port 8883.
  17. * :example:`protocols/mqtt/ssl_mutual_auth`: MQTT over tls using certificates for authentication, default port 8883
  18. * :example:`protocols/mqtt/ssl_psk`: MQTT over tls using pre-shared keys for authentication, default port 8883.
  19. * :example:`protocols/mqtt/ws`: MQTT over Websocket, default port 80
  20. * :example:`protocols/mqtt/wss`: MQTT over Websocket Secure, default port 443
  21. Configuration
  22. -------------
  23. The configuration is made by setting fields in ``esp_mqtt_client_config_t`` struct. The configuration struct has the following sub structs to configure different aspects of the client operation.
  24. * :cpp:member:`broker<esp_mqtt_client_config::broker>` - Allow to set address and security verification.
  25. * :cpp:member:`credentials<esp_mqtt_client_config::credentials>` - Client credentials for authentication.
  26. * :cpp:member:`session<esp_mqtt_client_config::session>` - Configuration for MQTT session aspects.
  27. * :cpp:member:`network<esp_mqtt_client_config::network>` - Networking related configuration.
  28. * :cpp:member:`task<esp_mqtt_client_config::task>` - Allow to configure FreeRTOS task.
  29. * :cpp:member:`buffer<esp_mqtt_client_config::buffer>` - Buffer size for input and output.
  30. In the following session the most common aspects are detailed.
  31. Broker
  32. ^^^^^^^^^^^
  33. ===========
  34. Address
  35. ===========
  36. Broker address can be set by usage of ``broker.address`` struct. The configuration can be made by usage of ``uri`` field
  37. or the combination of ``hostname``, ``transport`` and ``port``. Optionally, `path` could be set, this field is useful in
  38. websocket connections.
  39. The ``uri`` field is used in the following format ``scheme://hostname:port/path``.
  40. - Curently support ``mqtt``, ``mqtts``, ``ws``, ``wss`` schemes
  41. - MQTT over TCP samples:
  42. - ``mqtt://mqtt.eclipseprojects.io``: MQTT over TCP, default port 1883:
  43. - ``mqtt://mqtt.eclipseprojects.io:1884`` MQTT over TCP, port 1884:
  44. - ``mqtt://username:password@mqtt.eclipseprojects.io:1884`` MQTT over TCP,
  45. port 1884, with username and password
  46. - MQTT over SSL samples:
  47. - ``mqtts://mqtt.eclipseprojects.io``: MQTT over SSL, port 8883
  48. - ``mqtts://mqtt.eclipseprojects.io:8884``: MQTT over SSL, port 8884
  49. - MQTT over Websocket samples:
  50. - ``ws://mqtt.eclipseprojects.io:80/mqtt``
  51. - MQTT over Websocket Secure samples:
  52. - ``wss://mqtt.eclipseprojects.io:443/mqtt``
  53. - Minimal configurations:
  54. .. code:: c
  55. const esp_mqtt_client_config_t mqtt_cfg = {
  56. .broker.address.uri = "mqtt://mqtt.eclipseprojects.io",
  57. };
  58. esp_mqtt_client_handle_t client = esp_mqtt_client_init(&mqtt_cfg);
  59. esp_mqtt_client_register_event(client, ESP_EVENT_ANY_ID, mqtt_event_handler, client);
  60. esp_mqtt_client_start(client);
  61. - Note: By default mqtt client uses event loop library to post related mqtt events (connected, subscribed, published, etc.)
  62. ============
  63. Verification
  64. ============
  65. For secure connections TLS is used, and to guarantee Broker's identity the ``broker.verification`` struct must be set.
  66. The broker certificate may be set in PEM or DER format. To select DER the equivalent ``_len`` field must be set,
  67. otherwise a NULL terminated string in PEM format should be provided to ``certificate`` field.
  68. - Get certificate from server, example: ``mqtt.eclipseprojects.io``
  69. ``openssl s_client -showcerts -connect mqtt.eclipseprojects.io:8883 </dev/null 2>/dev/null|openssl x509 -outform PEM >mqtt_eclipse_org.pem``
  70. - Check the sample application: ``examples/mqtt_ssl``
  71. - Configuration:
  72. .. code:: c
  73. const esp_mqtt_client_config_t mqtt_cfg = {
  74. .broker = {
  75. .address.uri = "mqtts://mqtt.eclipseprojects.io:8883",
  76. .verification.certificate = (const char *)mqtt_eclipse_org_pem_start,
  77. },
  78. };
  79. To details on other fields check the Reference API and :ref:`esp_tls_server_verification`.
  80. Client Credentials
  81. ^^^^^^^^^^^^^^^^^^
  82. All client related credentials are under the ``credentials`` field.
  83. * ``username``: pointer to the username used for connecting to the broker, can also be set by URI.
  84. * ``client_id``: pointer to the client id, defaults to ``ESP32_%CHIPID%`` where %CHIPID% are the last 3 bytes of MAC address in hex format
  85. ==============
  86. Authentication
  87. ==============
  88. It's possible to set authentication parameters through the ``authentication`` field. The client supports the following authentication methods:
  89. * Using a password by setting ``authentication.password``.
  90. * Muthual authentication with TLS by setting ``authentication.certificate`` and ``authentication.key``, both can be provided in PEM or DER format.
  91. * Using secure element available in ESP32-WROOM-32SE, setting ``authentication.use_secure_element``.
  92. * Using Digital Signature Peripheral available in some Espressif devices, setting ``authentication.ds_data``.
  93. Session
  94. ^^^^^^^^^^^
  95. For MQTT session related configurations ``section`` fields should be used.
  96. =======================
  97. Last Will and Testament
  98. =======================
  99. 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
  100. in the ``esp_mqtt_client_config_t.session.last_will``-struct.
  101. * ``topic``: pointer to the LWT message topic
  102. * ``msg``: pointer to the LWT message
  103. * ``msg_len``: length of the LWT message, required if ``msg`` is not null-terminated
  104. * ``qos``: quality of service for the LWT message
  105. * ``retain``: specifies the retain flag of the LWT message
  106. Change settings in Project Configuration Menu
  107. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  108. The settings for MQTT can be found using ``idf.py menuconfig``, under Component config -> ESP-MQTT Configuration
  109. The following settings are available:
  110. - :ref:`CONFIG_MQTT_PROTOCOL_311`: Enables 3.1.1 version of MQTT protocol
  111. - :ref:`CONFIG_MQTT_TRANSPORT_SSL`, :ref:`CONFIG_MQTT_TRANSPORT_WEBSOCKET`: Enables specific MQTT transport layer, such as SSL, WEBSOCKET, WEBSOCKET_SECURE
  112. - :ref:`CONFIG_MQTT_CUSTOM_OUTBOX`: Disables default implementation of mqtt_outbox, so a specific implementaion can be supplied
  113. Events
  114. ------
  115. The following events may be posted by the MQTT client:
  116. * ``MQTT_EVENT_BEFORE_CONNECT``: The client is initialized and about to start connecting to the broker.
  117. * ``MQTT_EVENT_CONNECTED``: The client has successfully established a connection to the broker. The client is now ready to send and receive data.
  118. * ``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.
  119. * ``MQTT_EVENT_SUBSCRIBED``: The broker has acknowledged the client's subscribe request. The event data will contain the message ID of the subscribe message.
  120. * ``MQTT_EVENT_UNSUBSCRIBED``: The broker has acknowledged the client's unsubscribe request. The event data will contain the message ID of the unsubscribe message.
  121. * ``MQTT_EVENT_PUBLISHED``: The broker has acknowledged the client's publish message. This will only be posted for Quality of Service level 1 and 2, as level 0 does not use acknowledgements. The event data will contain the message ID of the publish message.
  122. * ``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` will be posted and `current_data_offset` and `total_data_len` from event data updated to keep track of the fragmented message.
  123. * ``MQTT_EVENT_ERROR``: The client has encountered an error. `esp_mqtt_error_type_t` from `error_handle` in the event data can be used to further determine the type of the error. The type of error will determine which parts of the `error_handle` struct is filled.
  124. API Reference
  125. -------------
  126. .. include-build-file:: inc/mqtt_client.inc