ESPHome 2026.11.0-dev
Loading...
Searching...
No Matches
mqtt_text_sensor.cpp
Go to the documentation of this file.
1#include "mqtt_text_sensor.h"
2#include "esphome/core/log.h"
3
4#include "mqtt_const.h"
5
6#ifdef USE_MQTT
7#ifdef USE_TEXT_SENSOR
8
9namespace esphome::mqtt {
10
11ESPHOME_LOG_TAG(TAG, "mqtt.text_sensor");
12
13using namespace esphome::text_sensor;
14
15MQTTTextSensor::MQTTTextSensor(TextSensor *sensor) : sensor_(sensor) {}
17 config.command_topic = false;
18}
20 this->sensor_->add_on_state_callback([this](const std::string &state) { this->publish_state(state); });
21}
22
23void MQTTTextSensor::dump_config() { LOG_MQTT_COMPONENT(true, false); }
24
25bool MQTTTextSensor::publish_state(const std::string &value) {
26 char topic_buf[MQTT_DEFAULT_TOPIC_MAX_LEN];
27 return this->publish(this->get_state_topic_to_(topic_buf), value.data(), value.size());
28}
30 if (this->sensor_->has_state()) {
31 return this->publish_state(this->sensor_->state);
32 } else {
33 return true;
34 }
35}
37const EntityBase *MQTTTextSensor::get_entity() const { return this->sensor_; }
38
39} // namespace esphome::mqtt
40
41#endif
42#endif // USE_MQTT
bool has_state() const
bool publish(const std::string &topic, const std::string &payload)
Send a MQTT message.
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).
text_sensor::TextSensor * sensor_
bool publish_state(const std::string &value)
void send_discovery(JsonObject root, mqtt::SendDiscoveryConfig &config) override
MQTTTextSensor(text_sensor::TextSensor *sensor)
void add_on_state_callback(F &&callback)
Definition text_sensor.h:65
bool state
Definition fan.h:2
ESPHOME_LOG_TAG(TAG, "alarm_control_panel")
MQTT_COMPONENT_TYPE(MQTTAlarmControlPanelComponent, "alarm_control_panel") const EntityBase *MQTTAlarmControlPanelComponent
Simple Helper struct used for Home Assistant MQTT send_discovery().
bool command_topic
If the command topic should be included. Default to true.