44 char buf[MQTT_DEFAULT_TOPIC_MAX_LEN];
61 char sanitized_name[ESPHOME_DEVICE_NAME_MAX_LEN + 1];
64 char object_id_buf[OBJECT_ID_MAX_LEN];
71 p =
append_str(p, comp_type, strlen(comp_type));
73 p =
append_str(p, sanitized_name, strlen(sanitized_name));
79 return StringRef(buf.data(), p - buf.data());
83 size_t suffix_len)
const {
85 if (topic_prefix.empty()) {
90 char object_id_buf[OBJECT_ID_MAX_LEN];
95 p =
append_str(p, topic_prefix.data(), topic_prefix.size());
97 p =
append_str(p, comp_type, strlen(comp_type));
104 return StringRef(buf.data(), p - buf.data());
108 char buf[MQTT_DEFAULT_TOPIC_MAX_LEN];
110 return std::string(
ref.c_str(),
ref.size());
131 char buf[MQTT_DEFAULT_TOPIC_MAX_LEN];
138 char buf[MQTT_DEFAULT_TOPIC_MAX_LEN];
140 return std::string(
ref.c_str(),
ref.size());
144 char buf[MQTT_DEFAULT_TOPIC_MAX_LEN];
146 return std::string(
ref.c_str(),
ref.size());
150 return this->
publish(topic.c_str(), payload.data(), payload.size());
154 return this->
publish(topic.c_str(), payload, payload_length);
158 if (topic[0] ==
'\0')
164 return this->
publish(topic, payload, strlen(payload));
169 return this->
publish(topic.c_str(), payload);
173 if (topic[0] ==
'\0')
177 strncpy_P(buf,
reinterpret_cast<const char *
>(payload),
sizeof(buf) - 1);
178 buf[
sizeof(buf) - 1] =
'\0';
185 return this->
publish(topic,
"None", 4);
186 char buf[VALUE_ACCURACY_MAX_LEN];
196 if (topic[0] ==
'\0')
204 char discovery_topic_buf[MQTT_DISCOVERY_TOPIC_MAX_LEN];
207 if (discovery_info.
clean) {
208 ESP_LOGV(TAG,
"'%s': Cleaning discovery", LOG_STR_ARG(this->
log_name_()));
212 ESP_LOGV(TAG,
"'%s': Sending discovery", LOG_STR_ARG(this->
log_name_()));
216 discovery_topic.
c_str(),
217 [
this](JsonObject root) {
218 SendDiscoveryConfig config;
219 config.state_topic = true;
220 config.command_topic = true;
222 this->send_discovery(root, config);
224 if (this->subscribe_qos_ != 0) {
225 root[MQTT_QOS] = this->subscribe_qos_;
236 root[MQTT_ENABLED_BY_DEFAULT] =
false;
248 root[MQTT_ENTITY_CATEGORY] = EntityCategoryMqttStrings::get_progmem_str(
252 if (config.state_topic) {
253 char state_topic_buf[MQTT_DEFAULT_TOPIC_MAX_LEN];
256 if (config.command_topic) {
257 char command_topic_buf[MQTT_DEFAULT_TOPIC_MAX_LEN];
261 root[MQTT_COMMAND_RETAIN] =
true;
265 if (!avail.
topic.empty()) {
266 root[MQTT_AVAILABILITY_TOPIC] = avail.
topic;
274 char object_id_buf[OBJECT_ID_MAX_LEN];
277 char name_buf[ENTITY_NAME_BUF_SIZE];
278 char friendly_name_hash[9];
279 buf_append_printf(friendly_name_hash,
sizeof(friendly_name_hash), 0,
"%08" PRIx32,
283 char unique_id[MAC_ADDRESS_BUFFER_SIZE + ESPHOME_DOMAIN_MAX_LEN + 11];
284 char mac_buf[MAC_ADDRESS_BUFFER_SIZE];
286 buf_append_printf(unique_id,
sizeof(unique_id), 0,
"%s-%s-%s", mac_buf, this->
component_type(),
288 root[MQTT_UNIQUE_ID] = unique_id;
293 char unique_id_buf[3 + MQTT_COMPONENT_TYPE_MAX_LEN + OBJECT_ID_MAX_LEN + 1];
294 buf_append_printf(unique_id_buf,
sizeof(unique_id_buf), 0,
"ESP%s%s", this->
component_type(),
296 root[MQTT_UNIQUE_ID] = unique_id_buf;
302 char object_id_full[ESPHOME_DEVICE_NAME_MAX_LEN + 1 + OBJECT_ID_MAX_LEN + 1];
303 buf_append_printf(object_id_full,
sizeof(object_id_full), 0,
"%s_%s", node_name.c_str(), object_id.
c_str());
304 root[MQTT_OBJECT_ID] = object_id_full;
308 const auto &node_friendly_name = friendly_name_ref.
empty() ? node_name : friendly_name_ref;
311 JsonObject device_info = root[MQTT_DEVICE].to<JsonObject>();
312 char mac[MAC_ADDRESS_BUFFER_SIZE];
314 device_info[MQTT_DEVICE_IDENTIFIERS] = mac;
315 device_info[MQTT_DEVICE_NAME] = node_friendly_name;
316#ifdef ESPHOME_PROJECT_NAME
317 device_info[MQTT_DEVICE_SW_VERSION] = ESPHOME_PROJECT_VERSION
" (ESPHome " ESPHOME_VERSION
")";
318 const char *model = std::strchr(ESPHOME_PROJECT_NAME,
'.');
319 device_info[MQTT_DEVICE_MODEL] = model ==
nullptr ? ESPHOME_BOARD : model + 1;
320 if (model ==
nullptr) {
321 device_info[MQTT_DEVICE_MANUFACTURER] = ESPHOME_PROJECT_NAME;
326 char manufacturer[
sizeof(ESPHOME_PROJECT_NAME)];
327 size_t len = model - ESPHOME_PROJECT_NAME;
328 memcpy(manufacturer, ESPHOME_PROJECT_NAME,
len);
329 manufacturer[
len] =
'\0';
330 device_info[MQTT_DEVICE_MANUFACTURER] = manufacturer;
333 static const char ver_fmt[]
PROGMEM = ESPHOME_VERSION
" (config hash 0x%08" PRIx32
")";
336 char version_buf[
sizeof(ver_fmt) + 8];
338 device_info[MQTT_DEVICE_SW_VERSION] = version_buf;
339 device_info[MQTT_DEVICE_MODEL] = ESPHOME_BOARD;
340#if defined(USE_ESP8266) || defined(USE_ESP32)
341 device_info[MQTT_DEVICE_MANUFACTURER] =
"Espressif";
342#elif defined(USE_RP2)
343 device_info[MQTT_DEVICE_MANUFACTURER] =
"Raspberry Pi";
344#elif defined(USE_BK72XX)
345 device_info[MQTT_DEVICE_MANUFACTURER] =
"Beken";
346#elif defined(USE_RTL87XX)
347 device_info[MQTT_DEVICE_MANUFACTURER] =
"Realtek";
348#elif defined(USE_HOST)
349 device_info[MQTT_DEVICE_MANUFACTURER] =
"Host";
352 if (node_area[0] !=
'\0') {
353 device_info[MQTT_DEVICE_SUGGESTED_AREA] = node_area;
356 device_info[MQTT_DEVICE_CONNECTIONS][0][0] =
"mac";
357 device_info[MQTT_DEVICE_CONNECTIONS][0][1] = mac;
359 this->qos_, discovery_info.retain);
363bool MQTTComponent::is_discovery_enabled()
const {
367MQTTComponent::MQTTComponent() =
default;
370void MQTTComponent::disable_discovery() { this->discovery_enabled_ =
false; }
371void MQTTComponent::set_command_retain(
bool command_retain) { this->command_retain_ = command_retain; }
373void MQTTComponent::set_availability(std::string topic, std::string payload_available,
374 std::string payload_not_available) {
375 this->availability_ = make_unique<Availability>();
376 this->availability_->topic = std::move(topic);
377 this->availability_->payload_available = std::move(payload_available);
378 this->availability_->payload_not_available = std::move(payload_not_available);
380void MQTTComponent::disable_availability() { this->set_availability(
"",
"",
""); }
381void MQTTComponent::call_setup() {
383 this->is_internal_ = this->compute_is_internal_();
384 if (this->is_internal_)
391 if (!this->is_connected_())
394 if (this->is_discovery_enabled()) {
395 if (!this->send_discovery_()) {
396 this->schedule_resend_state();
399 if (!this->send_initial_state()) {
400 this->schedule_resend_state();
404void MQTTComponent::process_resend() {
407 if (!this->resend_state_)
410 this->resend_state_ =
false;
411 if (this->is_discovery_enabled()) {
412 if (!this->send_discovery_()) {
413 this->schedule_resend_state();
416 if (!this->send_initial_state()) {
417 this->schedule_resend_state();
420void MQTTComponent::schedule_resend_state() { this->resend_state_ =
true; }
424#pragma GCC diagnostic push
425#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
426const StringRef &MQTTComponent::friendly_name_()
const {
return this->get_entity()->get_name(); }
427#pragma GCC diagnostic pop
428const LogString *MQTTComponent::log_name_()
const {
return this->get_entity()->get_log_name(); }
429StringRef MQTTComponent::get_default_object_id_to_(std::span<char, OBJECT_ID_MAX_LEN> buf)
const {
430 return this->get_entity()->get_object_id_to(buf);
432bool MQTTComponent::is_disabled_by_default_()
const {
return this->get_entity()->is_disabled_by_default(); }
433bool MQTTComponent::compute_is_internal_() {
434 if (this->custom_state_topic_.has_value()) {
438 return this->custom_state_topic_.is_empty();
441 if (this->custom_command_topic_.has_value()) {
445 return this->custom_command_topic_.is_empty();
455 return this->get_entity()->is_internal();
const StringRef & get_name() const
Get the name of this Application set by pre_setup().
uint32_t get_config_hash()
Get the config hash as a 32-bit integer.
const StringRef & get_friendly_name() const
Get the friendly name of this Application set by pre_setup().
const char * get_area() const
Get the area of this Application set by pre_setup().
ProgmemStringRef get_device_class_progmem() const
The device class as stored (in flash on ESP8266), for consumers that read flash themselves.
ProgmemStringRef get_icon_progmem() const
The icon as stored (in flash on ESP8266), for consumers that read flash themselves.
const LogString * get_log_name() const
Get the name for a "%s" log argument (LOG_STR_ARG).
EntityCategory get_entity_category() const
A string that may live in flash (on ESP8266): pointer and length, with no byte-reading operations.
constexpr bool empty() const
StringRef is a reference to a string owned by something else.
constexpr const char * c_str() const
constexpr bool empty() const
constexpr size_type size() const
const std::string & get_topic_prefix() const
Get the topic prefix of this device, using default if necessary.
void register_mqtt_component(MQTTComponent *component)
bool publish(const MQTTMessage &message)
Publish a MQTTMessage.
const MQTTDiscoveryInfo & get_discovery_info() const
Get Home Assistant discovery info.
bool is_publish_nan_as_none() const
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.
const Availability & get_availability()
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
MQTTComponent is the base class for all components that interact with MQTT to expose certain function...
StringRef get_command_topic_to_(std::span< char, MQTT_DEFAULT_TOPIC_MAX_LEN > buf) const
Get the MQTT command topic into a buffer (no heap allocation for non-lambda custom topics).
TemplatableValue< std::string > custom_state_topic_
TemplatableValue< std::string > custom_command_topic_
std::unique_ptr< Availability > availability_
StringRef get_discovery_topic_to_(std::span< char, MQTT_DISCOVERY_TOPIC_MAX_LEN > buf, const MQTTDiscoveryInfo &discovery_info) const
Helper method to get the discovery topic for this component into a buffer.
bool is_disabled_by_default_() const
Get whether the underlying Entity is disabled by default.
const LogString * log_name_() const
Entity name for a "%s" log argument.
MQTTTopicSource command_topic_source_() const
The command topic as a subscription source. A lambda topic is read once and copied,...
void set_qos(uint8_t qos)
Set QOS for state messages.
StringRef get_default_topic_for_to_(std::span< char, MQTT_DEFAULT_TOPIC_MAX_LEN > buf, const char *suffix, size_t suffix_len) const
Get this components state/command/... topic into a buffer.
bool publish(const std::string &topic, const std::string &payload)
Send a MQTT message.
bool send_discovery_()
Internal method to start sending discovery info, this will call send_discovery().
void set_subscribe_qos(uint8_t qos)
Set the QOS for subscribe messages (used in discovery).
bool publish_float_(StringRef topic, float value, int8_t accuracy)
Publish a float formatted to accuracy, or "None" for NaN when publish_nan_as_none is set.
bool publish_json(const std::string &topic, const json::json_build_t &f)
Construct and send a JSON MQTT message.
std::string get_default_topic_for_(const std::string &suffix) const
Get this components state/command/... topic (allocates std::string).
StringRef get_default_object_id_to_(std::span< char, OBJECT_ID_MAX_LEN > buf) const
Get the object ID for this MQTT component, writing to the provided buffer.
void set_retain(bool retain)
Set whether state message should be retained.
virtual const EntityBase * get_entity() const =0
Gets the Entity served by this MQTT component.
std::string get_state_topic_() const
Get the MQTT topic that new states will be shared to (allocates std::string).
MQTTTopicSource topic_source_() const
A topic built by one of this component's get_*_topic_to getters, rebuilt when needed.
StringRef get_state_topic_to_(std::span< char, MQTT_DEFAULT_TOPIC_MAX_LEN > buf) const
Get the MQTT state topic into a buffer (no heap allocation for non-lambda custom topics).
std::string get_command_topic_() const
Get the MQTT topic for listening to commands (allocates std::string).
virtual const char * component_type() const =0
Override this method to return the component type (e.g. "light", "sensor", ...)
PROGMEM_STRING_TABLE(AlarmControlPanelStateStrings, "DISARMED", "ARMED_HOME", "ARMED_AWAY", "ARMED_NIGHT", "ARMED_VACATION", "ARMED_CUSTOM_BYPASS", "PENDING", "ARMING", "DISARMING", "TRIGGERED", "UNKNOWN")
ESPHOME_LOG_TAG(TAG, "alarm_control_panel")
std::function< void(JsonObject)> json_build_t
Callback function typedef for building JsonObjects.
JsonString linked(const char *s)
constexpr ColorMode COLOR_MODE_LOOKUP[] PROGMEM
@ MQTT_DEVICE_NAME_OBJECT_ID_GENERATOR
@ MQTT_MAC_ADDRESS_UNIQUE_ID_GENERATOR
char * append_char(char *p, char c)
char * append_str(char *p, const char *s, size_t len)
MQTTClientComponent * global_mqtt_client
void log_mqtt_component(const char *tag, MQTTComponent *obj, bool state_topic, bool command_topic)
constexpr float AFTER_CONNECTION
For components that should be initialized after a data connection (API/MQTT) is connected.
size_t value_accuracy_to_buf(std::span< char, VALUE_ACCURACY_MAX_LEN > buf, float value, int8_t accuracy_decimals)
Format value with accuracy to buffer, returns chars written (excluding null)
uint32_t fnv1_hash(const char *str)
Calculate a FNV-1 hash of str.
char * str_sanitize_to(char *buffer, size_t buffer_size, const char *str)
Sanitize a string to buffer, keeping only alphanumerics, dashes, and underscores.
void get_mac_address_into_buffer(std::span< char, MAC_ADDRESS_BUFFER_SIZE > buf)
Get the device MAC address into the given buffer, in lowercase hex notation.
Application App
Global storage of Application pointer - only one Application can exist.
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 Home Assistant discovery.
MQTTDiscoveryUniqueIdGenerator unique_id_generator
std::string prefix
The Home Assistant discovery prefix. Empty means disabled.
MQTTDiscoveryObjectIdGenerator object_id_generator
Where a subscription's topic comes from. The topic is rebuilt whenever it is needed,...