ESP MQTT C++ client

Overview

The ESP MQTT client is a wrapper over the esp_mqtt client with the goal of providing a higher level API.

Features

  • Supports MQTT version 3.11

  • Adds a Filter validation class for topic filters

  • Split the event handlers to member functions

Configuration

The current design uses exception as an error handling mechanism, therefore exceptions need to be enabled in menuconfig.

Usage

User code needs to inherit fromm idf::mqtt::Client and provide overloads for the event handlers.

Note

The handler is available to allow user code to interact directly with it in case of need. This member will likely be made private in the future once the class API stabilizes.

class Client

Base class for MQTT client.

Should be inherited to provide event handlers.

Public Functions

Client(const BrokerConfiguration &broker, const ClientCredentials &credentials, const Configuration &config)

Constructor of the client.

Parameters
  • brokerConfiguration for broker connection

  • credentials – client credentials to be presented to the broker

  • config – Mqtt client configuration

Client(const esp_mqtt_client_config_t &config)

Constructs Client using the same configuration used for esp_mqtt_client

Parameters

config – config struct to esp_mqtt_client

std::optional<MessageID> subscribe(const std::string &topic_filter, QoS qos = QoS::AtLeastOnce)

Subscribe to topic.

Parameters
  • topic_filter – MQTT topic filter

  • qos – QoS subscription, defaulted as QoS::AtLeastOnce

Returns

Optional MessageID. In case of failure std::nullopt is returned.

template<class Container>
inline std::optional<MessageID> publish(const std::string &topic, const Message<Container> &message)

publish message to topic

Template Parameters

Container – Type for data container. Must be a contiguous memory.

Parameters
  • topic – Topic name

  • messageMessage struct containing data, qos and retain configuration.

Returns

Optional MessageID. In case of failure std::nullopt is returned.

template<class InputIt>
inline std::optional<MessageID> publish(const std::string &topic, InputIt first, InputIt last, QoS qos = QoS::AtLeastOnce, Retain retain = Retain::NotRetained)

publish message to topic

Template Parameters

InputIt – Input data iterator type.

Parameters
  • topic – Topic name

  • first, last – Iterator pair of data to publish

  • qos – Set qos message

  • retain – Set if message should be retained

Returns

Optional MessageID. In case of failure std::nullopt is returned.

Protected Types

using ClientHandler = std::unique_ptr<esp_mqtt_client, MqttClientDeleter>

Type of the handler for the underlying mqtt_client handler. It uses std::unique_ptr for lifetime management.

Protected Functions

virtual void on_error(const esp_mqtt_event_handle_t event)

Called if there is an error event.

Parameters

event – mqtt event data

virtual void on_disconnected(const esp_mqtt_event_handle_t event)

Called if there is an disconnection event.

Parameters

event – mqtt event data

virtual void on_subscribed(const esp_mqtt_event_handle_t event)

Called if there is an subscribed event.

Parameters

event – mqtt event data

virtual void on_unsubscribed(const esp_mqtt_event_handle_t event)

Called if there is an unsubscribed event.

Parameters

event – mqtt event data

virtual void on_published(const esp_mqtt_event_handle_t event)

Called if there is an published event.

Parameters

event – mqtt event data

virtual void on_before_connect(const esp_mqtt_event_handle_t event)

Called if there is an before connect event.

Parameters

event – mqtt event data

virtual void on_connected(const esp_mqtt_event_handle_t event) = 0

Called if there is an connected event.

Parameters

event – mqtt event data

virtual void on_data(const esp_mqtt_event_handle_t event) = 0

Called if there is an data event.

Parameters

event – mqtt event data

Protected Attributes

ClientHandler handler

esp_mqtt_client handler

struct MqttClientDeleter

Helper type to be used as custom deleter for std::unique_ptr.

Event Handling

Events are dispatched throug calls to member functions each one dedicated to a type of event.

Application Example

API Reference

Header File

Structures

struct MQTTException : public ESPException
template<typename T>
struct Message

Message class template to publish.

Public Members

T data

Data for publish. Should be a contiguous type

QoS qos = QoS::AtLeastOnce

QoS for the message

Retain retain = Retain::NotRetained

Retention mark for the message.

Classes

class Filter

Filter for mqtt topic subscription.

Topic filter.

Public Functions

explicit Filter(std::string user_filter)

Constructs the topic filter from the user filter.

Throws

std::domain_error – if the filter is invalid.

Parameters

user_filterFilter to be used.

const std::string &get()

Get the filter string used.

Returns

Reference to the topic filter.

bool match(std::string::const_iterator topic_begin, std::string::const_iterator topic_end) const noexcept

Checks the filter string against a topic name.

Parameters
  • topic_begin – Iterator to the beginning of the sequence.

  • topic_end – Iterator to the end of the sequence.

Returns

true if the topic name match the filter

bool match(const std::string &topic) const noexcept

Checks the filter string against a topic name.

Parameters

topic – topic name

Returns

true if the topic name match the filter

bool match(char *begin, int size) const noexcept

Checks the filter string against a topic name.

Parameters
  • begin – Char array with topic name.

  • size – Size of given topic name.

Returns

true if the topic name match the filter

Header File

Structures

struct Host

Broker addresss.

Use this to set the broker without parsing the URI string.

Public Members

std::string address

Host name

std::string path

Route path of the broker in host

esp_mqtt_transport_t transport

Transport scheme to use.

struct URI

Broker addresss URI.

Use this to set the broker address using the URI.

Public Members

std::string address

Broker adddress URI

struct BrokerAddress

Broker addresss.

Public Members

std::variant<Host, URI> address

Address, defined by URI or Host struct

uint32_t port = 0

Port used, defaults to 0 to select common port for the scheme used

struct PEM

PEM formated data.

Store certificates, keys and cryptographic data.

struct DER

DER formated data.

Store certificates, keys and cryptographic data.

struct Insecure

Do not verify broker certificate.

To be used when doing MQTT over TLS connection but not verify broker’s certificates.

struct GlobalCAStore

Use global CA store.

To be used when client should use the Global CA Store to get trusted certificates for the broker.

struct PSK

Use a pre shared key for broker authentication.

To be used when client should use a PSK to authenticate the broker.

struct Password

Password related data.

struct ClientCertificate

Data to authenticate client with certificates.

Public Members

CryptographicInformation certificate

Certificate in PEM or DER format.

CryptographicInformation key

Key data in PEM or DER format.

std::optional<Password> key_password = std::nullopt

Optional password for key

struct SecureElement

Used to select usage of Secure Element.

Enables the usage of the secure element present in ESP32-WROOM-32SE.

struct DigitalSignatureData

Used to select usage of Digital Signature Peripheral.

Enables the usage of the Digital Signature hardware accelerator.

struct BrokerConfiguration
struct ClientCredentials

Public Members

std::vector<std::string> alpn_protos

List of supported application protocols to be used for ALPN

Warning

doxygenstruct: Cannot find class “idf::mqtt::Event” in doxygen xml output for project “esp-docs” from directory: /home/runner/work/esp-protocols/esp-protocols/docs/esp_mqtt_cxx/_build/en/esp32/xml_in/

struct LastWill

Public Members

const char *lwt_topic

LWT (Last Will and Testament) message topic (NULL by default)

const char *lwt_msg

LWT message (NULL by default)

int lwt_qos

LWT message qos

int lwt_retain

LWT retained message flag

int lwt_msg_len

LWT message length

struct Session

Public Members

int disable_clean_session

mqtt clean session, default clean_session is true

int keepalive

mqtt keepalive, default is 120 seconds

bool disable_keepalive

Set disable_keepalive=true to turn off keep-alive mechanism, false by default (keepalive is active by default). Note: setting the config value keepalive to 0 doesn’t disable keepalive feature, but uses a default keepalive period

esp_mqtt_protocol_ver_t protocol_ver

MQTT protocol version used for connection, defaults to value from menuconfig

struct Task

Public Members

int task_prio

MQTT task priority, default is 5, can be changed in make menuconfig

int task_stack

MQTT task stack size, default is 6144 bytes, can be changed in make menuconfig

struct Connection

Public Members

esp_mqtt_transport_t transport

overrides URI transport

int reconnect_timeout_ms

Reconnect to the broker after this value in miliseconds if auto reconnect is not disabled (defaults to 10s)

int network_timeout_ms

Abort network operation if it is not completed after this value, in milliseconds (defaults to 10s)

int refresh_connection_after_ms

Refresh connection after this value (in milliseconds)

bool disable_auto_reconnect

this mqtt client will reconnect to server (when errors/disconnect). Set disable_auto_reconnect=true to disable

struct Configuration

Public Members

void *user_context

pass user context to this option, then can receive that context in event->user_context

int buffer_size

size of MQTT send/receive buffer, default is 1024 (only receive buffer size if out_buffer_size defined)

int out_buffer_size

size of MQTT output buffer. If not defined, both output and input buffers have the same size defined as buffer_size