21#elif defined(USE_ESP8266)
23#elif defined(USE_LIBRETINY)
26#if defined(USE_MQTT_SESSION_PERSISTENCE) && !defined(USE_ESP32)
29#include "lwip/ip_addr.h"
35#if defined(USE_LOGGER) && defined(USE_CRASH_HANDLER)
36#define USE_MQTT_CRASH_LOG
45static constexpr size_t MQTT_COMPONENT_TYPE_MAX_LEN = 20;
46static constexpr size_t MQTT_SUFFIX_MAX_LEN = 32;
47static constexpr size_t MQTT_TOPIC_PREFIX_MAX_LEN = 64;
50static constexpr size_t MQTT_DEFAULT_TOPIC_MAX_LEN =
51 MQTT_TOPIC_PREFIX_MAX_LEN + 1 + MQTT_COMPONENT_TYPE_MAX_LEN + 1 + OBJECT_ID_MAX_LEN + 1 + MQTT_SUFFIX_MAX_LEN + 1;
62using mqtt_callback_t ESPDEPRECATED(
"subscribe() takes any callable; pass the lambda directly. Removed in 2027.5.0",
63 "2026.11.0") = std::function<void(
const std::string &,
const std::string &)>;
64using mqtt_json_callback_t ESPDEPRECATED(
65 "subscribe_json() takes any callable; pass the lambda directly. Removed in 2027.5.0",
66 "2026.11.0") = std::function<void(
const std::string &, JsonObject)>;
76 StringRef build(std::span<char, MQTT_DEFAULT_TOPIC_MAX_LEN> buf)
const {
return this->
builder(this->context, buf); }
187#if defined(USE_ESP32) && defined(USE_MQTT_TLS)
228 constexpr bool boxed = !mqtt_subscription_callback_t::fits_inline<F>();
230 boxed ? mqtt_subscription_callback_t::create_boxed(std::forward<F>(callback))
231 : mqtt_subscription_callback_t::create(std::forward<F>(callback)),
243 template<
typename F>
void subscribe(
const std::string &topic, F &&callback, uint8_t qos = 0) {
256 template<
typename T,
typename F>
void subscribe_json(T &&topic, F &&callback, uint8_t qos = 0) {
257 static_assert(std::is_invocable_v<const std::decay_t<F> &,
const std::string &, JsonObject>,
258 "subscribe_json() needs a callback that does not mutate its captures");
260 std::forward<T>(topic),
261 [cb = std::forward<F>(callback)](
const std::string &topic,
const std::string &payload) {
289 bool publish(
const std::string &topic,
const std::string &payload, uint8_t qos = 0,
bool retain =
false);
291 bool publish(
const std::string &topic,
const char *payload,
size_t payload_length, uint8_t qos = 0,
292 bool retain =
false);
295 bool publish(
const char *topic,
const char *payload,
size_t payload_length, uint8_t qos = 0,
bool retain =
false);
317 void on_log(uint8_t level,
const char *tag,
const char *
message,
size_t message_len);
320 void on_message(
const std::string &topic,
const std::string &payload);
366#if defined(USE_ESP8266) && LWIP_VERSION_MAJOR == 1
378 template<
typename F>
static void call_json(
const F &callback,
const std::string &topic,
const std::string &payload) {
380 if (doc.overflowed() || doc.isNull())
382 callback(topic, doc.as<JsonObject>());
385#ifdef USE_MQTT_CRASH_LOG
392#ifdef USE_MQTT_SESSION_PERSISTENCE
414 .prefix =
"homeassistant",
427#if defined(USE_ESP32)
429#elif defined(USE_ESP8266)
431#elif defined(USE_LIBRETINY)
440#ifdef USE_MQTT_CRASH_LOG
454#ifdef USE_MQTT_SESSION_PERSISTENCE
477 void set_payload(
std::function<
void(Ts..., JsonObject)> payload) { this->
payload_ = payload; }
479 void play(
const Ts &...
x)
override {
480 auto topic = this->topic_.value(
x...);
481 auto qos = this->qos_.value(
x...);
482 auto retain = this->retain_.value(
x...);
483 this->
parent_->
publish_json(topic, [
this,
x...](JsonObject root) { this->payload_(x..., root); }, qos, retain);
StringRef is a reference to a string owned by something else.
void set_ws_path(const char *path)
void set_ca_certificate(const char *cert)
void set_transport(MQTTTransport transport)
void set_skip_cert_cn_check(bool skip_check)
void set_cl_key(const char *key)
void set_cl_certificate(const char *cert)
void set_birth_message(MQTTMessage &&message)
Set the birth message.
MQTTMessage shutdown_message_
bool is_log_message_enabled() const
void start_connect_()
Reconnect to the MQTT broker if not already connected.
void set_ws_path(const char *path)
void setup() override
Setup the MQTT client, registering a bunch of callbacks and attempting to connect.
void set_password(const std::string &password)
void set_clean_session(const bool &clean_session)
uint32_t subscriptions_fingerprint_()
void disable_discovery()
Globally disable Home Assistant discovery.
void recalculate_availability_()
Re-calculate the availability property.
void erase_removed_subscriptions_()
void subscribe(MQTTTopicSource topic, F &&callback, uint8_t qos=0)
Subscribe to an MQTT topic and call callback when a message is received.
void set_discovery_info(std::string &&prefix, MQTTDiscoveryUniqueIdGenerator unique_id_generator, MQTTDiscoveryObjectIdGenerator object_id_generator, bool retain, bool discover_ip, bool clean=false)
Set the Home Assistant discovery info.
void set_reboot_timeout(uint32_t reboot_timeout)
bool can_proceed() override
float get_setup_priority() const override
MQTT client setup priority.
void disable_log_message()
Get the topic used for logging. Defaults to "<topic_prefix>/debug" and the value is cached for speed.
const std::string & get_topic_prefix() const
Get the topic prefix of this device, using default if necessary.
void subscribe_json(T &&topic, F &&callback, uint8_t qos=0)
Subscribe to a MQTT topic and automatically parse JSON payload.
void set_cl_certificate(const char *cert)
uint16_t subscribes_sent_
SUBSCRIBEs sent on this connection for the subscriptions the fingerprint covers.
void register_mqtt_component(MQTTComponent *component)
bool removed_while_dispatching_
bool is_discovery_ip_enabled() const
bool resubscribe_subscriptions_()
Returns true when every subscription is subscribed.
void set_last_will(MQTTMessage &&message)
Set the last will testament message.
void set_skip_cert_cn_check(bool skip_check)
bool publish(const MQTTMessage &message)
Publish a MQTTMessage.
void set_topic_prefix(std::string topic_prefix)
Set the topic prefix that will be prepended to all topics together with "/".
const MQTTDiscoveryInfo & get_discovery_info() const
Get Home Assistant discovery info.
void disable_birth_message()
Remove the birth message.
static void dns_found_callback(const char *name, ip_addr_t *ipaddr, void *callback_arg)
void set_broker_address(const std::string &address)
void on_shutdown() override
MQTTMessage last_will_
The last will message.
uint32_t session_fingerprint_
Fingerprint of the set the broker session is known to hold in full; 0 while a rebuild is in progress.
void set_shutdown_message(MQTTMessage &&message)
MQTTBackendLibreTiny mqtt_backend_
MQTTMessage birth_message_
The birth message (e.g.
MQTTCredentials credentials_
std::vector< MQTTComponent * > children_
void dump_config() override
void add_subscription_(MQTTTopicSource topic, mqtt_subscription_callback_t callback, bool boxed, uint8_t qos)
void set_on_connect(mqtt_on_connect_callback_t &&callback)
void set_session_fingerprint_(uint32_t fingerprint)
static void dns_found_callback(const char *name, const ip_addr_t *ipaddr, void *callback_arg)
void set_ca_certificate(const char *cert)
bool publish(const std::string &topic, const std::string &payload, uint8_t qos=0, bool retain=false)
Publish a MQTT message.
void set_enable_on_boot(bool enable_on_boot)
void set_cl_key(const char *key)
void set_wait_for_connection(bool wait_for_connection)
optional< MQTTClientDisconnectReason > disconnect_reason_
bool is_publish_nan_as_none() const
void set_username(const std::string &username)
static MQTTTopicSource copy_topic(StringRef topic)
A heap copy of topic, owned by the one subscription it is passed to and freed when that is erased.
bool subscribe_topic_(const MQTTTopicSource &topic, uint8_t qos)
void disable_shutdown_message()
void unsubscribe(const std::string &topic)
Unsubscribe from an MQTT topic.
void subscribe(const std::string &topic, F &&callback, uint8_t qos=0)
Subscribe to an MQTT topic and call callback when a message is received.
bool publish_json(const char *topic, const json::json_build_t &f, uint8_t qos=0, bool retain=false)
Publish JSON directly without heap allocation for topic.
void set_publish_nan_as_none(bool publish_nan_as_none)
void on_message(const std::string &topic, const std::string &payload)
void set_log_message_template(MQTTMessage &&message)
Manually set the topic used for logging.
void set_log_level(int level)
bool subacks_settled_
Set once every SUBACK of this connection is in (or the session was resumed without subscribing)
MQTTBackendESP8266 mqtt_backend_
void resubscribe_subscription_(MQTTSubscription *sub)
bool wait_for_connection_
void set_on_disconnect(mqtt_on_disconnect_callback_t &&callback)
bool publish(const char *topic, const char *payload, size_t payload_length, uint8_t qos=0, bool retain=false)
Publish directly without creating MQTTMessage (avoids heap allocation for topic)
bool subscribe_(const char *topic, uint8_t qos)
bool publish_nan_as_none_
void set_broker_port(uint16_t port)
void check_subacks_()
Once every SUBACK of this connection is in, saves the fingerprint if all were granted.
const Availability & get_availability()
std::string topic_prefix_
void on_log(uint8_t level, const char *tag, const char *message, size_t message_len)
std::vector< MQTTSubscription > subscriptions_
bool publish_json(const std::string &topic, const json::json_build_t &f, uint8_t qos=0, bool retain=false)
Construct and send a JSON MQTT message.
bool is_discovery_enabled() const
static void call_json(const F &callback, const std::string &topic, const std::string &payload)
MQTTBackendESP32 mqtt_backend_
void set_client_id(const std::string &client_id)
bool shutdown_message_sent_
void disable_last_will()
Remove the last will testament message.
void subscribe_crash_log_()
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 loop() override
Reconnect if required.
std::string payload_buffer_
MQTTDiscoveryInfo discovery_info_
The discovery info options for Home Assistant.
CallbackManager< MQTTBackend::on_disconnect_callback_t > on_disconnect_
void handle_crash_log_request_(const std::string &topic, const std::string &payload)
void set_transport(MQTTTransport transport)
Availability availability_
Caches availability.
bool publish(const std::string &topic, const char *payload, size_t payload_length, uint8_t qos=0, bool retain=false)
MQTTComponent is the base class for all components that interact with MQTT to expose certain function...
TEMPLATABLE_VALUE(std::string, topic) TEMPLATABLE_VALUE(uint8_t
MQTTPublishJsonAction(MQTTClientComponent *parent)
MQTTClientComponent * parent_
void play(const Ts &...x) override
std::function< void(Ts..., JsonObject)> payload_
SUBACKs received on the current connection.
const Component * component
const LogString * message
std::function< void(JsonObject)> json_build_t
Callback function typedef for building JsonObjects.
bool parse_json(const std::string &data, const json_parse_t &f)
Parse a JSON string and run the provided json parse function if it's valid.
std::function< MQTTBackend::on_disconnect_callback_t > mqtt_on_disconnect_callback_t
MQTTDiscoveryObjectIdGenerator
available discovery object_id generators
@ MQTT_DEVICE_NAME_OBJECT_ID_GENERATOR
@ MQTT_NONE_OBJECT_ID_GENERATOR
MQTTTopicSource progmem_topic(ProgmemStr topic)
A topic in flash, copied into the buffer when needed, so at most MQTT_DEFAULT_TOPIC_MAX_LEN - 1 chara...
MQTTDiscoveryUniqueIdGenerator
available discovery unique_id generators
@ MQTT_MAC_ADDRESS_UNIQUE_ID_GENERATOR
@ MQTT_LEGACY_UNIQUE_ID_GENERATOR
MQTTTransport
Transport for the broker connection; only the ESP-IDF backend supports WebSocket.
MQTTClientComponent * global_mqtt_client
@ MQTT_CLIENT_DISCONNECTED
@ MQTT_CLIENT_RESOLVING_ADDRESS
MQTTTopicSource static_topic(const char *topic)
A topic string that outlives the subscription, such as a literal; it is referenced,...
std::function< MQTTBackend::on_connect_callback_t > mqtt_on_connect_callback_t
Callback for MQTT events.
=std::function< void(const std::string &, JsonObject)> StringRef(*)(const void *context, std::span< char, MQTT_DEFAULT_TOPIC_MAX_LEN > buf) mqtt_topic_builder_t
Returns a subscription's topic, written into buf or referring to storage that outlives the subscripti...
const __FlashStringHelper * ProgmemStr
Simple data struct for Home Assistant component availability.
std::string payload_not_available
std::string topic
Empty means disabled.
std::string payload_available
internal struct for MQTT credentials.
uint16_t port
The port number of the server.
std::string address
The address of the server without port number.
bool clean_session
Whether the session will be cleaned or remembered between connects.
std::string client_id
The client ID. Will automatically be truncated to 23 characters.
Internal struct for MQTT Home Assistant discovery.
MQTTDiscoveryUniqueIdGenerator unique_id_generator
bool discover_ip
Enable the Home Assistant device discovery.
std::string prefix
The Home Assistant discovery prefix. Empty means disabled.
MQTTDiscoveryObjectIdGenerator object_id_generator
bool retain
Whether to retain discovery messages.
internal struct for MQTT messages.
internal struct for MQTT subscriptions.
uint32_t resubscribe_timeout
mqtt_subscription_callback_t callback
Where a subscription's topic comes from. The topic is rebuilt whenever it is needed,...
StringRef build(std::span< char, MQTT_DEFAULT_TOPIC_MAX_LEN > buf) const
mqtt_topic_builder_t builder