MQTT Client

API Reference

MQTTClientComponent

class MQTTClientComponent : public Component

Public Functions

MQTTClientComponent(const MQTTCredentials &credentials, const std::string &topic_prefix)
void set_last_will(MQTTMessage &&message)

Set the last will testament message.

void disable_last_will()

Remove the last will testament message.

void set_birth_message(MQTTMessage &&message)

Set the birth message.

void disable_birth_message()

Remove the birth message.

void set_shutdown_message(MQTTMessage &&message)
void disable_shutdown_message()
void set_keep_alive(uint16_t keep_alive_s)

Set the keep alive time in seconds, every 0.7*keep_alive a ping will be sent.

void set_discovery_info(std::string &&prefix, bool retain)

Set the Home Assistant discovery info.

See MQTT Discovery.

Parameters
  • prefix: The Home Assistant discovery prefix.
  • retain: Whether to retain discovery messages.

const MQTTDiscoveryInfo &get_discovery_info() const

Get Home Assistant discovery info.

void disable_discovery()

Globally disable Home Assistant discovery.

bool is_discovery_enabled() const
void set_client_id(std::string client_id)

Manually set the client id, by default it’s <name>-<MAC>, it’s automatically truncated to 23 chars.

void add_ssl_fingerprint(const std::array<uint8_t, SHA1_SIZE> &fingerprint)

Add a SSL fingerprint to use for TCP SSL connections to the MQTT broker.

To use this feature you first have to globally enable the ASYNC_TCP_SSL_ENABLED define flag. This function can be called multiple times and any certificate that matches any of the provided fingerprints will match. Calling this method will also automatically disable all non-ssl connections.

Warning
This is not secure and not how SSL is usually done. You’ll have to add a separate fingerprint for every certificate you use. Additionally, the hashing algorithm used here due to the constraints of the MCU, SHA1, is known to be insecure.
Parameters
  • fingerprint: The SSL fingerprint as a 20 value long std::array.

const Availability &get_availability()
void set_topic_prefix(std::string topic_prefix)

Set the topic prefix that will be prepended to all topics together with “/”.

This will, in most cases, be the name of your Application.

For example, if “livingroom” is passed to this method, all state topics will, by default, look like “livingroom/…/state”

Parameters
  • topic_prefix: The topic prefix. The last “/” is appended automatically.

const std::string &get_topic_prefix() const

Get the topic prefix of this device, using default if necessary.

void set_log_message_template(MQTTMessage &&message)

Manually set the topic used for logging.

void set_log_level(int level)
void disable_log_message()

Get the topic used for logging. Defaults to “<topic_prefix>/debug” and the value is cached for speed.

bool is_log_message_enabled() const
void subscribe(const std::string &topic, mqtt_callback_t callback, uint8_t qos = 0)

Subscribe to an MQTT topic and call callback when a message is received.

Parameters
  • topic: The topic. Wildcards are currently not supported.
  • callback: The callback function.
  • qos: The QoS of this subscription.

void subscribe_json(const std::string &topic, json_parse_t callback, uint8_t qos = 0)

Subscribe to a MQTT topic and automatically parse JSON payload.

If an invalid JSON payload is received, the callback will not be called.

Parameters
  • topic: The topic. Wildcards are currently not supported.
  • callback: The callback with a parsed JsonObject that will be called when a message with matching topic is received.
  • qos: The QoS of this subscription.

void publish(const MQTTMessage &message)

Publish a MQTTMessage.

Parameters
  • message: The message.

void publish(const std::string &topic, const std::string &payload, uint8_t qos = 0, bool retain = false)

Publish a MQTT message.

Parameters
  • topic: The topic.
  • payload: The payload.
  • retain: Whether to retain the message.

void publish(const std::string &topic, const char *payload, size_t payload_length, uint8_t qos = 0, bool retain = false)
void publish_json(const std::string &topic, const json_build_t &f, uint8_t qos = 0, bool retain = false)

Construct and send a JSON MQTT message.

Parameters
  • topic: The topic.
  • f: The Json Message builder.
  • retain: Whether to retain the message.

void setup()

Setup the MQTT client, registering a bunch of callbacks and attempting to connect.

void dump_config()
void loop()

Reconnect if required.

float get_setup_priority() const

MQTT client setup priority.

void on_message(const std::string &topic, const std::string &payload)
MQTTMessageTrigger *make_message_trigger(const std::string &topic, uint8_t qos = 0)
MQTTJsonMessageTrigger *make_json_message_trigger(const std::string &topic, uint8_t qos = 0)
template <typename T>
MQTTPublishAction<T> *make_publish_action()
template <typename T>
MQTTPublishJsonAction<T> *make_publish_json_action()
bool can_proceed()
void check_connected()
void set_reboot_timeout(uint32_t reboot_timeout)
void register_mqtt_component(MQTTComponent *component)
bool is_connected()

Protected Functions

void start_connect()

Reconnect to the MQTT broker if not already connected.

void recalculate_availability()

Re-calculate the availability property.

Protected Attributes

MQTTCredentials credentials_
MQTTMessage last_will_

The last will message.

Disabled optional denotes it being default and an empty topic denotes the the feature being disabled.

MQTTMessage birth_message_

The birth message (e.g.

the message that’s send on an established connection. See last_will_ for what different values denote.

MQTTMessage shutdown_message_
Availability availability_ = {}

Caches availability.

MQTTDiscoveryInfo discovery_info_

{

.prefix = “homeassistant”,

.retain = true

}


The discovery info options for Home Assistant.

Undefined optional means default and empty prefix means disabled.

std::string topic_prefix_ = {}
MQTTMessage log_message_
int log_level_ = {ESPHOMELIB_LOG_LEVEL}
std::vector<MQTTSubscription> subscriptions_
AsyncMqttClient mqtt_client_
MQTTClientState state_ = {MQTT_CLIENT_DISCONNECTED}
std::vector<MQTTComponent *> children_
uint32_t reboot_timeout_ = {300000}
uint32_t connect_begin_
uint32_t last_connected_ = {0}
optional<AsyncMqttClientDisconnectReason> disconnect_reason_ = {}
using mqtt::mqtt_callback_t = typedef std::function<void(const std::string &)>

Callback for MQTT subscriptions.

First parameter is the topic, the second one is the payload.

struct MQTTMessage

internal struct for MQTT messages.

Public Members

std::string topic
std::string payload
uint8_t qos

QoS. Only for last will testaments.

bool retain
struct MQTTSubscription

internal struct for MQTT subscriptions.

Public Members

std::string topic
uint8_t qos
mqtt_callback_t callback
struct MQTTCredentials

internal struct for MQTT credentials.

Public Members

std::string address

The address of the server without port number.

uint16_t port

The port number of the server.

std::string username
std::string password
std::string client_id

The client ID. Will automatically be truncated to 23 characters.

struct Availability

Simple data struct for Home Assistant component availability.

Public Members

std::string topic

Empty means disabled.

std::string payload_available
std::string payload_not_available
struct MQTTDiscoveryInfo

Internal struct for MQTT Home Assistant discovery.

See MQTT Discovery.

Public Members

std::string prefix

The Home Assistant discovery prefix. Empty means disabled.

bool retain

Whether to retain discovery messages.

MQTTClientComponent *mqtt::global_mqtt_client = nullptr

MQTTComponent

class MQTTComponent : public Component

MQTTComponent is the base class for all components that interact with MQTT to expose certain functionality or data from actuators or sensors to clients.

Although this class should work with all MQTT solutions, it has been specifically designed for use with Home Assistant. For example, this class supports Home Assistant MQTT discovery out of the box.

In order to implement automatic Home Assistant discovery, all sub-classes should:

  1. Implement send_discovery that creates a Home Assistant discovery payload.
  2. Override component_type() to return the appropriate component type such as “light” or “sensor”.
  3. Subscribe to command topics using subscribe() or subscribe_json() during setup().

In order to best separate the front- and back-end of esphomelib, all sub-classes should only parse/send MQTT messages and interact with back-end components via callbacks to ensure a clean separation.

Subclassed by binary_sensor::MQTTBinarySensorComponent, cover::MQTTCoverComponent, fan::MQTTFanComponent, light::MQTTJSONLightComponent, sensor::MQTTSensorComponent, switch_::MQTTSwitchComponent, text_sensor::MQTTTextSensor

Public Functions

MQTTComponent()

Constructs a MQTTComponent.

void setup_()

Override setup_ so that we can call send_discovery() when needed.

void loop_()

Public loop() functions.

These will be called by the Application instance.

Note: This should normally not be overriden, unless you know what you’re doing. They’re basically to make creating custom components easier. For example the SensorComponent can override these methods to not have the user call some super methods within their custom sensors. These methods should ALWAYS call the loop_internal() and setup_internal() methods.

Basically, it handles stuff like interval/timeout functions and eventually calls loop().

virtual void send_discovery(JsonObject &root, SendDiscoveryConfig &config) = 0

Send discovery info the Home Assistant, override this.

virtual void send_initial_state() = 0
virtual bool is_internal() = 0
void set_retain(bool retain)

Set whether state message should be retained.

bool get_retain() const
void disable_discovery()

Disable discovery. Sets friendly name to “”.

bool is_discovery_enabled() const
virtual std::string component_type() const = 0

Override this method to return the component type (e.g. “light”, “sensor”, …)

void set_custom_state_topic(const std::string &custom_state_topic)

Set a custom state topic. Set to “” for default behavior.

void set_custom_command_topic(const std::string &custom_command_topic)

Set a custom command topic. Set to “” for default behavior.

float get_setup_priority() const

MQTT_COMPONENT setup priority.

void set_availability(std::string topic, std::string payload_available, std::string payload_not_available)

Set the Home Assistant availability data.

See See Home Assistant for more info.

void disable_availability()
void schedule_resend_state()

Internal method for the MQTT client base to schedule a resend of the state on reconnect.

Protected Functions

std::string get_discovery_topic(const MQTTDiscoveryInfo &discovery_info) const

Helper method to get the discovery topic for this component.

std::string get_default_topic_for(const std::string &suffix) const

Get this components state/command/…

topic.

Return
The full topic.
Parameters
  • suffix: The suffix/key such as “state” or “command”.

virtual std::string friendly_name() const = 0

Get the friendly name of this MQTT component.

std::string unique_id()

A unique ID for this MQTT component, empty for no unique id.

See unique ID requirements: https://developers.home-assistant.io/docs/en/entity_registry_index.html#unique-id-requirements

Return
The unique id as a string.

const std::string get_state_topic() const

Get the MQTT topic that new states will be shared to.

const std::string get_command_topic() const

Get the MQTT topic for listening to commands.

void send_discovery_()

Internal method to start sending discovery info, this will call send_discovery().

void send_message(const std::string &topic, const std::string &payload, const optional<uint8_t> &qos = {}, const optional<bool> &retain = {})

Send a MQTT message.

Parameters
  • topic: The topic.
  • payload: The payload.
  • retain: Whether to retain the message. If not set, defaults to get_retain.

void send_json_message(const std::string &topic, const json_build_t &f, const optional<uint8_t> &qos = {}, const optional<bool> &retain = {})

Construct and send a JSON MQTT message.

Parameters
  • topic: The topic.
  • f: The Json Message builder.
  • retain: Whether to retain the message. If not set, defaults to get_retain.

void subscribe(const std::string &topic, mqtt_callback_t callback, uint8_t qos = 0)

Subscribe to a MQTT topic.

Parameters
  • topic: The topic. Wildcards are currently not supported.
  • callback: The callback that will be called when a message with matching topic is received.
  • qos: The MQTT quality of service. Defaults to 0.

void subscribe_json(const std::string &topic, json_parse_t callback, uint8_t qos = 0)

Subscribe to a MQTT topic and automatically parse JSON payload.

If an invalid JSON payload is received, the callback will not be called.

Parameters
  • topic: The topic. Wildcards are currently not supported.
  • callback: The callback with a parsed JsonObject that will be called when a message with matching topic is received.
  • qos: The MQTT quality of service. Defaults to 0.

std::string get_default_object_id() const

Generate the Home Assistant MQTT discovery object id by automatically transforming the friendly name.

Protected Attributes

std::string custom_state_topic_ = {}
std::string custom_command_topic_ = {}
bool retain_ = {true}
bool discovery_enabled_ = {true}
Availability *availability_ = {nullptr}
bool resend_state_ = {false}
struct SendDiscoveryConfig

Simple Helper struct used for Home Assistant MQTT send_discovery().

Public Members

bool state_topic = {true}

If the state topic should be included. Defaults to true.

bool command_topic = {true}

If the command topic should be included. Default to true.

const char *platform = {"mqtt"}

The platform of this component. Defaults to “mqtt”.

Triggers

class MQTTMessageTrigger : public Trigger<std::string>

Public Functions

MQTTMessageTrigger(const std::string &topic, uint8_t qos = 0)
class MQTTJsonMessageTrigger : public Trigger<const JsonObject&>

Public Functions

MQTTJsonMessageTrigger(const std::string &topic, uint8_t qos = 0)

Actions

template <typename T>
class MQTTPublishAction : public Action<T>

Public Functions

MQTTPublishAction()
void set_topic(std::function<std::string(T)> topic)
void set_topic(std::string topic)
void set_payload(std::function<std::string(T)> payload)
void set_payload(std::string payload)
void set_qos(std::function<uint8_t(T)> qos)
void set_qos(uint8_t qos)
void set_retain(std::function<bool(T)> retain)
void set_retain(bool retain)
void play(T x)

Protected Attributes

TemplatableValue<std::string, T> topic_
TemplatableValue<std::string, T> payload_
TemplatableValue<uint8_t, T> qos_ = {0}
TemplatableValue<bool, T> retain_ = {false}
template <typename T>
class MQTTPublishJsonAction : public Action<T>

Public Functions

MQTTPublishJsonAction()
void set_topic(std::function<std::string(T)> topic)
void set_topic(std::string topic)
void set_payload(std::function<void(T, JsonObject&)> payload)
void set_qos(uint8_t qos)
void set_retain(bool retain)
void play(T x)

Protected Attributes

TemplatableValue<std::string, T> topic_
std::function<void(T, JsonObject&)> payload_
uint8_t qos_ = {0}
bool retain_ = {false}