This commit is contained in:
2025-10-07 00:18:25 -04:00
parent 970e081f64
commit 909dddeb77
1612 changed files with 0 additions and 159018 deletions

View File

@@ -1,57 +0,0 @@
# This is Doxygen configuration file
#
# Doxygen provides over 260 configuration statements
# To make this file easier to follow,
# it contains only statements that are non-default
#
# NOTE:
# It is recommended not to change defaults unless specifically required
# Test any changes how they affect generated documentation
# Make sure that correct warnings are generated to flag issues with documented code
#
# For the complete list of configuration statements see:
# http://doxygen.nl/manual/config.html
PROJECT_NAME = "ESP-MQTT Programming Guide"
## The 'INPUT' statement below is used as input by script 'gen-df-input.py'
## to automatically generate API reference list files heder_file.inc
## These files are placed in '_inc' directory
## and used to include in API reference documentation
INPUT = \
$(PROJECT_PATH)/include/mqtt_client.h \
$(PROJECT_PATH)/include/mqtt5_client.h \
$(PROJECT_PATH)/include/mqtt_supported_features.h
## Get warnings for functions that have no documentation for their parameters or return value
##
WARN_NO_PARAMDOC = YES
## Enable preprocessing and remove __attribute__(...) expressions from the INPUT files
##
ENABLE_PREPROCESSING = YES
MACRO_EXPANSION = YES
EXPAND_ONLY_PREDEF = YES
PREDEFINED = \
$(ENV_DOXYGEN_DEFINES) \
## Do not complain about not having dot
##
HAVE_DOT = NO
## Generate XML that is required for Breathe
##
GENERATE_XML = YES
XML_OUTPUT = xml
GENERATE_HTML = NO
HAVE_DOT = NO
GENERATE_LATEX = NO
GENERATE_MAN = YES
GENERATE_RTF = NO
## Skip distracting progress messages
##
QUIET = YES

View File

@@ -1,39 +0,0 @@
# -*- coding: utf-8 -*-
#
# Common (non-language-specific) configuration for Sphinx
#
# type: ignore
# pylint: disable=wildcard-import
# pylint: disable=undefined-variable
from __future__ import print_function, unicode_literals
from esp_docs.conf_docs import * # noqa: F403,F401
# IDF_PATH validation removed - not needed for standalone component docs
# Only required when using ESP-IDF extensions that depend on IDF environment
extensions += ['sphinx_copybutton',
# Needed as a trigger for running doxygen
'esp_docs.esp_extensions.dummy_build_system',
'esp_docs.esp_extensions.run_doxygen'
]
# link roles config
github_repo = 'espressif/esp-mqtt'
# context used by sphinx_idf_theme
html_context['github_user'] = 'espressif'
html_context['github_repo'] = 'esp-mqtt'
# Extra options required by sphinx_idf_theme
project_slug = 'esp-mqtt'
versions_url = './_static/mqtt_docs_versions.js'
idf_targets = [ 'esp32' ]
languages = ['en']

View File

@@ -1,2 +0,0 @@
# Known doxygen warnings for ESP-MQTT documentation build
# Currently no known doxygen warnings expected

View File

@@ -1,27 +0,0 @@
# -*- coding: utf-8 -*-
#
# English Language RTD & Sphinx config file
#
# Uses ../conf_common.py for most non-language-specific settings.
# Importing conf_common adds all the non-language-specific
# parts to this conf module
try:
from conf_common import * # noqa: F403,F401
except ImportError:
import os
import sys
sys.path.insert(0, os.path.abspath('../'))
from conf_common import * # noqa: F403,F401
import datetime
current_year = datetime.datetime.now().year
# General information about the project.
project = u'ESP-MQTT Programming Guide'
copyright = u'2019 - {}, Espressif Systems (Shanghai) Co., Ltd'.format(current_year)
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
language = 'en'

View File

@@ -1,208 +0,0 @@
ESP-MQTT
========
:link_to_translation:`zh_CN:[中文]`
Overview
--------
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>`__.
Features
--------
* Support MQTT over TCP, SSL with Mbed TLS, MQTT over WebSocket, and MQTT over WebSocket Secure
* Easy to setup with URI
* Multiple instances (multiple clients in one application)
* 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)
Application Examples
--------------------
- :example:`tcp` demonstrates how to implement MQTT communication over TCP (default port 1883).
- :example:`ssl` demonstrates how to use SSL transport to implement MQTT communication over TLS (default port 8883).
- :example:`ssl_ds` demonstrates how to use digital signature peripheral for authentication to implement MQTT communication over TLS (default port 8883).
- :example:`ssl_mutual_auth` demonstrates how to use certificates for authentication to implement MQTT communication (default port 8883).
- :example:`ssl_psk` demonstrates how to use pre-shared keys for authentication to implement MQTT communication over TLS (default port 8883).
- :example:`ws` demonstrates how to implement MQTT communication over WebSocket (default port 80).
- :example:`wss` demonstrates how to implement MQTT communication over WebSocket Secure (default port 443).
- :example:`mqtt5` demonstrates how to use ESP-MQTT library to connect to broker with MQTT v5.0.
- :example:`custom_outbox` demonstrates how to customize the outbox in the ESP-MQTT library.
MQTT Message Retransmission
---------------------------
A new MQTT message can be 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()>`.
Messages with QoS 0 are sent only once. QoS 1 and 2 behave differently since the protocol requires additional steps to complete the process.
The ESP-MQTT library opts to always retransmit unacknowledged QoS 1 and 2 publish messages to prevent data loss 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).
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.
Configuration
-------------
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.
* :cpp:class:`esp_mqtt_client_config_t::broker_t` - Allow to set address and security verification.
* :cpp:class:`esp_mqtt_client_config_t::credentials_t` - Client credentials for authentication.
* :cpp:class:`esp_mqtt_client_config_t::session_t` - Configuration for MQTT session aspects.
* :cpp:class:`esp_mqtt_client_config_t::network_t` - Networking related configuration.
* :cpp:class:`esp_mqtt_client_config_t::task_t` - Allow to configure FreeRTOS task.
* :cpp:class:`esp_mqtt_client_config_t::buffer_t` - Buffer size for input and output.
In the following sections, the most common aspects are detailed.
Broker
^^^^^^^^^^^
===========
Address
===========
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.
The :cpp:member:`uri <esp_mqtt_client_config_t::broker_t::address_t::uri>` field is used in the format ``scheme://hostname:port/path``.
- Currently support ``mqtt``, ``mqtts``, ``ws``, ``wss`` schemes
- MQTT over TCP samples:
- ``mqtt://mqtt.eclipseprojects.io``: MQTT over TCP, default port 1883
- ``mqtt://mqtt.eclipseprojects.io:1884``: MQTT over TCP, port 1884
- ``mqtt://username:password@mqtt.eclipseprojects.io:1884``: MQTT over TCP,
port 1884, with username and password
- MQTT over SSL samples:
- ``mqtts://mqtt.eclipseprojects.io``: MQTT over SSL, port 8883
- ``mqtts://mqtt.eclipseprojects.io:8884``: MQTT over SSL, port 8884
- MQTT over WebSocket samples:
- ``ws://mqtt.eclipseprojects.io:80/mqtt``
- MQTT over WebSocket Secure samples:
- ``wss://mqtt.eclipseprojects.io:443/mqtt``
- Minimal configurations:
.. code-block:: c
const esp_mqtt_client_config_t mqtt_cfg = {
.broker.address.uri = "mqtt://mqtt.eclipseprojects.io",
};
esp_mqtt_client_handle_t client = esp_mqtt_client_init(&mqtt_cfg);
esp_mqtt_client_register_event(client, ESP_EVENT_ANY_ID, mqtt_event_handler, client);
esp_mqtt_client_start(client);
.. note::
By default MQTT client uses event loop library to post related MQTT events (connected, subscribed, published, etc.).
============
Verification
============
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.
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.
- Get certificate from server, example: ``mqtt.eclipseprojects.io``
.. code::
openssl s_client -showcerts -connect mqtt.eclipseprojects.io:8883 < /dev/null \
2> /dev/null | openssl x509 -outform PEM > mqtt_eclipse_org.pem
- Check the sample application: :example:`ssl`
- Configuration:
.. code:: c
const esp_mqtt_client_config_t mqtt_cfg = {
.broker = {
.address.uri = "mqtts://mqtt.eclipseprojects.io:8883",
.verification.certificate = (const char *)mqtt_eclipse_org_pem_start,
},
};
For details about other fields, please check the `API Reference`_ and :ref:`esp_tls_server_verification`.
Client Credentials
^^^^^^^^^^^^^^^^^^
All client related credentials are under the :cpp:class:`credentials <esp_mqtt_client_config_t::credentials_t>` field.
* :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
* :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
==============
Authentication
==============
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:
* :cpp:member:`password <esp_mqtt_client_config_t::credentials_t::authentication_t::password>`: use a password by setting
* :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
* :cpp:member:`use_secure_element <esp_mqtt_client_config_t::credentials_t::authentication_t::use_secure_element>`: use secure element (ATECC608A) interfaced to ESP32 series
* :cpp:member:`ds_data <esp_mqtt_client_config_t::credentials_t::authentication_t::ds_data>`: use Digital Signature Peripheral available in some Espressif devices
Session
^^^^^^^^^^^
For MQTT session-related configurations, :cpp:class:`session <esp_mqtt_client_config_t::session_t>` fields should be used.
=======================
Last Will and Testament
=======================
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.
* :cpp:member:`topic <esp_mqtt_client_config_t::session_t::last_will_t::topic>`: pointer to the LWT message topic
* :cpp:member:`msg <esp_mqtt_client_config_t::session_t::last_will_t::msg>`: pointer to the LWT message
* :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
* :cpp:member:`qos <esp_mqtt_client_config_t::session_t::last_will_t::qos>`: quality of service for the LWT message
* :cpp:member:`retain <esp_mqtt_client_config_t::session_t::last_will_t::retain>`: specifies the retain flag of the LWT message
Change Settings in Project Configuration Menu
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
The settings for MQTT can be found using :code:`idf.py menuconfig`, under ``Component config`` > ``ESP-MQTT Configuration``.
The following settings are available:
- :ref:`CONFIG_MQTT_PROTOCOL_311`: enable 3.1.1 version of MQTT protocol
- :ref:`CONFIG_MQTT_TRANSPORT_SSL` and :ref:`CONFIG_MQTT_TRANSPORT_WEBSOCKET`: enable specific MQTT transport layer, such as SSL, WEBSOCKET, and WEBSOCKET_SECURE
- :ref:`CONFIG_MQTT_CUSTOM_OUTBOX`: disable default implementation of mqtt_outbox, so a specific implementation can be supplied
Events
------
The following events may be posted by the MQTT client:
* ``MQTT_EVENT_BEFORE_CONNECT``: The client is initialized and about to start connecting to the broker.
* ``MQTT_EVENT_CONNECTED``: The client has successfully established a connection to the broker. The client is now ready to send and receive data.
* ``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.
* ``MQTT_EVENT_SUBSCRIBED``: The broker has acknowledged the client's subscribe request. The event data contains the message ID of the subscribe message.
* ``MQTT_EVENT_UNSUBSCRIBED``: The broker has acknowledged the client's unsubscribe request. The event data contains the message ID of the unsubscribe message.
* ``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.
* ``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.
* ``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.
API Reference
-------------
.. include-build-file:: inc/mqtt_client.inc
.. include-build-file:: inc/mqtt5_client.inc

View File

@@ -1,37 +0,0 @@
mqtt_client.inc:line: WARNING: Duplicate C++ declaration, also defined at index:line.
Declaration is '.. cpp:type:: struct esp_mqtt_event_t esp_mqtt_event_t'.
mqtt_client.inc:line: WARNING: Duplicate C++ declaration, also defined at index:line.
Declaration is '.. cpp:type:: struct esp_mqtt_client_config_t esp_mqtt_client_config_t'.
mqtt_client.inc:line: WARNING: Duplicate C++ declaration, also defined at index:line.
Declaration is '.. cpp:enum:: esp_mqtt_event_id_t'.
mqtt_client.inc:line: WARNING: Duplicate C++ declaration, also defined at index:line.
Declaration is '.. cpp:enum:: esp_mqtt_connect_return_code_t'.
mqtt_client.inc:line: WARNING: Duplicate C++ declaration, also defined at index:line.
Declaration is '.. cpp:enum:: esp_mqtt_error_type_t'.
mqtt_client.inc:line: WARNING: Duplicate C++ declaration, also defined at index:line.
Declaration is '.. cpp:enum:: esp_mqtt_transport_t'.
mqtt_client.inc:line: WARNING: Duplicate C++ declaration, also defined at index:line.
Declaration is '.. cpp:enum:: esp_mqtt_protocol_ver_t'.
mqtt5_client.inc:line: WARNING: Duplicate C++ declaration, also defined at index:line.
Declaration is '.. cpp:enumerator:: __attribute__'.
index.rst:line: CRITICAL: Duplicate ID: "mqtt5__client_8h_1a4504a6557b6b27d66613101e758693f4a8c1dfc1ccf00a08192611433ee7f17b4".
index.rst:line: WARNING: Duplicate explicit target name: "mqtt5__client_8h_1a4504a6557b6b27d66613101e758693f4a8c1dfc1ccf00a08192611433ee7f17b4".
mqtt5_client.inc:line: WARNING: Duplicate C++ declaration, also defined at index:line.
Declaration is '.. cpp:enumerator:: __attribute__'.
index.rst:line: CRITICAL: Duplicate ID: "mqtt5__client_8h_1a4504a6557b6b27d66613101e758693f4a8c1dfc1ccf00a08192611433ee7f17b4".
index.rst:line: WARNING: Duplicate explicit target name: "mqtt5__client_8h_1a4504a6557b6b27d66613101e758693f4a8c1dfc1ccf00a08192611433ee7f17b4".
mqtt5_client.inc:line: WARNING: Duplicate C++ declaration, also defined at index:line.
Declaration is '.. cpp:enumerator:: __attribute__'.
index.rst:line: CRITICAL: Duplicate ID: "mqtt5__client_8h_1a4504a6557b6b27d66613101e758693f4a8c1dfc1ccf00a08192611433ee7f17b4".
index.rst:line: WARNING: Duplicate explicit target name: "mqtt5__client_8h_1a4504a6557b6b27d66613101e758693f4a8c1dfc1ccf00a08192611433ee7f17b4".
mqtt5_client.inc:line: WARNING: Duplicate C++ declaration, also defined at index:line.
Declaration is '.. cpp:enumerator:: __attribute__'.
index.rst:line: CRITICAL: Duplicate ID: "mqtt5__client_8h_1a4504a6557b6b27d66613101e758693f4a8c1dfc1ccf00a08192611433ee7f17b4".
index.rst:line: WARNING: Duplicate explicit target name: "mqtt5__client_8h_1a4504a6557b6b27d66613101e758693f4a8c1dfc1ccf00a08192611433ee7f17b4".
index.rst:line: WARNING: undefined label: 'config_mqtt_outbox_expired_timeout_ms'
index.rst:line: WARNING: undefined label: 'config_mqtt_report_deleted_messages'
index.rst:line: WARNING: undefined label: 'esp_tls_server_verification'
index.rst:line: WARNING: undefined label: 'config_mqtt_protocol_311'
index.rst:line: WARNING: undefined label: 'config_mqtt_transport_ssl'
index.rst:line: WARNING: undefined label: 'config_mqtt_transport_websocket'
index.rst:line: WARNING: undefined label: 'config_mqtt_custom_outbox'

View File

@@ -1,27 +0,0 @@
# -*- coding: utf-8 -*-
#
# English Language RTD & Sphinx config file
#
# Uses ../conf_common.py for most non-language-specific settings.
# Importing conf_common adds all the non-language-specific
# parts to this conf module
try:
from conf_common import * # noqa: F403,F401
except ImportError:
import os
import sys
sys.path.insert(0, os.path.abspath('../'))
from conf_common import * # noqa: F403,F401
import datetime
current_year = datetime.datetime.now().year
# General information about the project.
project = u'ESP-MQTT Programming Guide'
copyright = u'2019 - {}, Espressif Systems (Shanghai) Co., Ltd'.format(current_year)
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
language = 'zh_CN'

View File

@@ -1,208 +0,0 @@
ESP-MQTT
========
:link_to_translation:`en:[English]`
概述
--------
ESP-MQTT 是 `MQTT <https://mqtt.org/>`__ 协议客户端的实现MQTT 是一种基于发布/订阅模式的轻量级消息传输协议。ESP-MQTT 当前支持 `MQTT v5.0 <https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html>`__
特性
--------
* 支持基于 TCP 的 MQTT、基于 Mbed TLS 的 SSL、基于 WebSocket 的 MQTT 以及基于 WebSocket Secure 的 MQTT
* 通过 URI 简化配置流程
* 多个实例(一个应用程序中有多个客户端)
* 支持订阅、发布、认证、遗嘱消息、保持连接心跳机制以及 3 个服务质量 (QoS) 级别(组成全功能客户端)
应用示例
-------------------
- :example:`tcp` 演示了如何通过 TCP 实现 MQTT 通信(默认端口 1883
- :example:`ssl` 演示了如何使用 SSL 传输来实现基于 TLS 的 MQTT 通信(默认端口 8883
- :example:`ssl_ds` 演示了如何使用数字签名外设进行身份验证,以实现基于 TLS 的 MQTT 通信(默认端口 8883
- :example:`ssl_mutual_auth` 演示了如何使用证书进行身份验证实现 MQTT 通信(默认端口 8883
- :example:`ssl_psk` 演示了如何使用预共享密钥进行身份验证,以实现基于 TLS 的 MQTT 通信(默认端口 8883
- :example:`ws` 演示了如何通过 WebSocket 实现 MQTT 通信(默认端口 80
- :example:`wss` 演示了如何通过 WebSocket Secure 实现 MQTT 通信(默认端口 443
- :example:`mqtt5` 演示了如何使用 ESP-MQTT 库通过 MQTT v5.0 连接到代理。
- :example:`custom_outbox` 演示了如何自定义 ESP-MQTT 库中的 outbox。
MQTT 消息重传
--------------------------
调用 :cpp:func:`esp_mqtt_client_publish <esp_mqtt_client_publish()>` 或其非阻塞形式 :cpp:func:`esp_mqtt_client_enqueue <esp_mqtt_client_enqueue()>`,可以创建新的 MQTT 消息。
QoS 0 的消息将只发送一次QoS 1 和 2 具有不同行为,因为协议需要执行额外步骤来完成该过程。
ESP-MQTT 库将始终重新传输未确认的 QoS 1 和 2 发布消息,以避免连接错误导致信息丢失,虽然 MQTT 规范要求仅在重新连接且 Clean Session 标志设置为 0 时重新传输(针对此行为,将 :cpp:member:`disable_clean_session <esp_mqtt_client_config_t::session_t::disable_clean_session>` 设置为 true
可能需要重传的 QoS 1 和 2 消息总是处于排队状态,但若使用 :cpp:func:`esp_mqtt_client_publish <esp_mqtt_client_publish>` 则会立即进行第一次传输尝试。未确认消息的重传将在 :cpp:member:`message_retransmit_timeout <esp_mqtt_client_config_t::session_t::message_retransmit_timeout>` 之后进行。在 :ref:`CONFIG_MQTT_OUTBOX_EXPIRED_TIMEOUT_MS` 之后,消息会过期并被删除。如已设置 :ref:`CONFIG_MQTT_REPORT_DELETED_MESSAGES`,则会发送事件来通知用户。
配置
-------------
通过设置 :cpp:class:`esp_mqtt_client_config_t` 结构体中的字段来进行配置。配置结构体包含以下子结构体,用于配置客户端的多种操作。
* :cpp:class:`esp_mqtt_client_config_t::broker_t` - 允许设置地址和安全验证。
* :cpp:class:`esp_mqtt_client_config_t::credentials_t` - 用于身份验证的客户端凭据。
* :cpp:class:`esp_mqtt_client_config_t::session_t` - MQTT 会话相关配置。
* :cpp:class:`esp_mqtt_client_config_t::network_t` - 网络相关配置。
* :cpp:class:`esp_mqtt_client_config_t::task_t` - 允许配置 FreeRTOS 任务。
* :cpp:class:`esp_mqtt_client_config_t::buffer_t` - 输入输出的缓冲区大小。
下文将详细介绍不同配置。
服务器
^^^^^^^^^^^^
===========
地址
===========
通过 :cpp:class:`address <esp_mqtt_client_config_t::broker_t::address_t>` 结构体的 :cpp:member:`uri <esp_mqtt_client_config_t::broker_t::address_t::uri>` 字段或者 :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>` 以及 :cpp:member:`port <esp_mqtt_client_config_t::broker_t::address_t::port>` 的组合,可以设置服务器地址。也可以选择设置 :cpp:member:`path <esp_mqtt_client_config_t::broker_t::address_t::path>`,该字段对 WebSocket 连接而言非常有用。
使用 :cpp:member:`uri <esp_mqtt_client_config_t::broker_t::address_t::uri>` 字段的格式为 ``scheme://hostname:port/path``
- 当前支持 ``mqtt````mqtts````ws````wss`` 协议
- 基于 TCP 的 MQTT 示例:
- ``mqtt://mqtt.eclipseprojects.io``:基于 TCP 的 MQTT默认端口 1883
- ``mqtt://mqtt.eclipseprojects.io:1884``:基于 TCP 的 MQTT端口 1884
- ``mqtt://username:password@mqtt.eclipseprojects.io:1884``:基于 TCP 的 MQTT
端口 1884带有用户名和密码
- 基于 SSL 的 MQTT 示例:
- ``mqtts://mqtt.eclipseprojects.io``:基于 SSL 的 MQTT端口 8883
- ``mqtts://mqtt.eclipseprojects.io:8884``:基于 SSL 的 MQTT端口 8884
- 基于 WebSocket 的 MQTT 示例:
- ``ws://mqtt.eclipseprojects.io:80/mqtt``
- 基于 WebSocket Secure 的 MQTT 示例:
- ``wss://mqtt.eclipseprojects.io:443/mqtt``
- 最简配置:
.. code-block:: c
const esp_mqtt_client_config_t mqtt_cfg = {
.broker.address.uri = "mqtt://mqtt.eclipseprojects.io",
};
esp_mqtt_client_handle_t client = esp_mqtt_client_init(&mqtt_cfg);
esp_mqtt_client_register_event(client, ESP_EVENT_ANY_ID, mqtt_event_handler, client);
esp_mqtt_client_start(client);
.. note::
默认情况下MQTT 客户端使用事件循环库来发布相关 MQTT 事件(已连接、已订阅、已发布等)。
=============
验证
=============
为验证服务器身份,对于使用 TLS 的安全链接,必须设置 :cpp:class:`verification <esp_mqtt_client_config_t::broker_t::verification_t>` 结构体。
服务器证书可设置为 PEM 或 DER 格式。如要选择 DER 格式,必须设置等效 :cpp:member:`certificate_len <esp_mqtt_client_config_t::broker_t::verification_t::certificate_len>` 字段,否则应在 :cpp:member:`certificate <esp_mqtt_client_config_t::broker_t::verification_t::certificate>` 字段传入以空字符结尾的 PEM 格式字符串。
- 从服务器获取证书,例如:``mqtt.eclipseprojects.io``
.. code::
openssl s_client -showcerts -connect mqtt.eclipseprojects.io:8883 < /dev/null \
2> /dev/null | openssl x509 -outform PEM > mqtt_eclipse_org.pem
- 检查示例应用程序::example:`ssl`
- 配置:
.. code:: c
const esp_mqtt_client_config_t mqtt_cfg = {
.broker = {
.address.uri = "mqtts://mqtt.eclipseprojects.io:8883",
.verification.certificate = (const char *)mqtt_eclipse_org_pem_start,
},
};
了解其他字段的详细信息,请查看 `API 参考`_ 以及 :ref:`esp_tls_server_verification`
客户端凭据
^^^^^^^^^^^^^^^^^^^^^^^^
:cpp:class:`credentials <esp_mqtt_client_config_t::credentials_t>` 字段下包含所有客户端相关凭据。
* :cpp:member:`username <esp_mqtt_client_config_t::credentials_t::username>`:指向用于连接服务器用户名的指针,也可通过 URI 设置
* :cpp:member:`client_id <esp_mqtt_client_config_t::credentials_t::client_id>`:指向客户端 ID 的指针,默认为 ``ESP32_%CHIPID%``,其中 ``%CHIPID%`` 是十六进制 MAC 地址的最后 3 个字节
===============
认证
===============
可以通过 :cpp:class:`authentication <esp_mqtt_client_config_t::credentials_t::authentication_t>` 字段设置认证参数。客户端支持以下认证方式:
* :cpp:member:`password <esp_mqtt_client_config_t::credentials_t::authentication_t::password>`:使用密码
* * :cpp:member:`certificate <esp_mqtt_client_config_t::credentials_t::authentication_t::certificate>`:cpp:member:`key <esp_mqtt_client_config_t::credentials_t::authentication_t::key>`:进行双向 TLS 身份验证PEM 或 DER 格式均可
* :cpp:member:`use_secure_element <esp_mqtt_client_config_t::credentials_t::authentication_t::use_secure_element>`:使用 ESP32 系列中的安全元素 (ATECC608A)
* :cpp:member:`ds_data <esp_mqtt_client_config_t::credentials_t::authentication_t::ds_data>`:使用某些乐鑫设备的数字签名外设
会话
^^^^^^^^^^^^
使用 :cpp:class:`session <esp_mqtt_client_config_t::session_t>` 字段进行 MQTT 会话相关配置。
========================
遗嘱消息 (LWT)
========================
通过设置 :cpp:class:`last_will <esp_mqtt_client_config_t::session_t::last_will_t>` 结构体的以下字段MQTT 会在一个客户端意外断开连接时通过遗嘱消息通知其他客户端。
* :cpp:member:`topic <esp_mqtt_client_config_t::session_t::last_will_t::topic>`:指向 LWT 消息主题的指针
* :cpp:member:`msg <esp_mqtt_client_config_t::session_t::last_will_t::msg>`:指向 LWT 消息的指针
* :cpp:member:`msg_len <esp_mqtt_client_config_t::session_t::last_will_t::msg_len>`LWT 消息的长度,:cpp:member:`msg <esp_mqtt_client_config_t::session_t::last_will_t::msg>` 不以空字符结尾时需要该字段
* :cpp:member:`qos <esp_mqtt_client_config_t::session_t::last_will_t::qos>`LWT 消息的服务质量
* :cpp:member:`retain <esp_mqtt_client_config_t::session_t::last_will_t::retain>`:指定 LWT 消息的保留标志
在项目配置菜单中设置 MQTT
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
通过 :code:`idf.py menuconfig`,可以在 ``Component config`` > ``ESP-MQTT Configuration`` 中找到 MQTT 设置。
相关设置如下:
- :ref:`CONFIG_MQTT_PROTOCOL_311`:启用 MQTT 协议 3.1.1 版本
- :ref:`CONFIG_MQTT_TRANSPORT_SSL`:ref:`CONFIG_MQTT_TRANSPORT_WEBSOCKET`:启用特定 MQTT 传输层,例如 SSL、WEBSOCKET 和 WEBSOCKET_SECURE
- :ref:`CONFIG_MQTT_CUSTOM_OUTBOX`:禁用 mqtt_outbox 默认实现,因此可以提供特定实现
事件
------------
MQTT 客户端可能会发布以下事件:
* ``MQTT_EVENT_BEFORE_CONNECT``:客户端已初始化并即将开始连接至服务器。
* ``MQTT_EVENT_CONNECTED``:客户端已成功连接至服务器。客户端已准备好收发数据。
* ``MQTT_EVENT_DISCONNECTED``:由于无法读取或写入数据,例如因为服务器无法使用,客户端已终止连接。
* ``MQTT_EVENT_SUBSCRIBED``:服务器已确认客户端的订阅请求。事件数据将包含订阅消息的消息 ID。
* ``MQTT_EVENT_UNSUBSCRIBED``:服务器已确认客户端的退订请求。事件数据将包含退订消息的消息 ID。
* ``MQTT_EVENT_PUBLISHED``:服务器已确认客户端的发布消息。消息将仅针对 QoS 级别 1 和 2 发布,因为级别 0 不会进行确认。事件数据将包含发布消息的消息 ID。
* ``MQTT_EVENT_DATA``:客户端已收到发布消息。事件数据包含:消息 ID、发布消息所属主题名称、收到的数据及其长度。对于超出内部缓冲区的数据将发布多个 ``MQTT_EVENT_DATA``,并更新事件数据的 :cpp:member:`current_data_offset <esp_mqtt_event_t::current_data_offset>` 和 :cpp:member:`total_data_len<esp_mqtt_event_t::total_data_len>` 以跟踪碎片化消息。
* ``MQTT_EVENT_ERROR``:客户端遇到错误。使用事件数据 :cpp:type:`error_handle <esp_mqtt_error_codes_t>` 字段中的 :cpp:type:`error_type <esp_mqtt_error_type_t>`,可以发现错误。错误类型决定 :cpp:type:`error_handle <esp_mqtt_error_codes_t>` 结构体的哪些部分会被填充。
API 参考
-------------
.. include-build-file:: inc/mqtt_client.inc
.. include-build-file:: inc/mqtt5_client.inc