ESPHome 2025.5.0
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 {
10namespace mqtt {
11
12static const char *const TAG = "mqtt.text_sensor";
13
14using namespace esphome::text_sensor;
15
16MQTTTextSensor::MQTTTextSensor(TextSensor *sensor) : sensor_(sensor) {}
18 if (!this->sensor_->get_device_class().empty())
20 config.command_topic = false;
21}
23 this->sensor_->add_on_state_callback([this](const std::string &state) { this->publish_state(state); });
24}
25
27 ESP_LOGCONFIG(TAG, "MQTT Text Sensor '%s':", this->sensor_->get_name().c_str());
28 LOG_MQTT_COMPONENT(true, false);
29}
30
31bool MQTTTextSensor::publish_state(const std::string &value) { return this->publish(this->get_state_topic_(), value); }
33 if (this->sensor_->has_state()) {
34 return this->publish_state(this->sensor_->state);
35 } else {
36 return true;
37 }
38}
39std::string MQTTTextSensor::component_type() const { return "sensor"; }
40const EntityBase *MQTTTextSensor::get_entity() const { return this->sensor_; }
41std::string MQTTTextSensor::unique_id() { return this->sensor_->unique_id(); }
42
43} // namespace mqtt
44} // namespace esphome
45
46#endif
47#endif // USE_MQTT
std::string get_device_class()
Get the device class, using the manual override if set.
const StringRef & get_name() const
constexpr const char * c_str() const
Definition string_ref.h:68
bool publish(const std::string &topic, const std::string &payload)
Send a MQTT message.
std::string get_state_topic_() const
Get the MQTT topic that new states will be shared to.
std::string component_type() const override
std::string unique_id() override
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)
const EntityBase * get_entity() const override
virtual std::string unique_id()
Override this method to set the unique ID of this sensor.
void add_on_state_callback(std::function< void(std::string)> callback)
bool state
Definition fan.h:0
constexpr const char *const MQTT_DEVICE_CLASS
Definition mqtt_const.h:58
Providing packet encoding functions for exchanging data with a remote host.
Definition a01nyub.cpp:7
Simple Helper struct used for Home Assistant MQTT send_discovery().
bool command_topic
If the command topic should be included. Default to true.