ESPHome 2025.11.0b4
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 // NOLINTBEGIN(clang-analyzer-cplusplus.NewDeleteLeaks) false positive with ArduinoJson
19 const auto device_class = this->sensor_->get_device_class_ref();
20 if (!device_class.empty()) {
21 root[MQTT_DEVICE_CLASS] = device_class;
22 }
23 // NOLINTEND(clang-analyzer-cplusplus.NewDeleteLeaks)
24 config.command_topic = false;
25}
27 this->sensor_->add_on_state_callback([this](const std::string &state) { this->publish_state(state); });
28}
29
31 ESP_LOGCONFIG(TAG, "MQTT Text Sensor '%s':", this->sensor_->get_name().c_str());
32 LOG_MQTT_COMPONENT(true, false);
33}
34
35bool MQTTTextSensor::publish_state(const std::string &value) { return this->publish(this->get_state_topic_(), value); }
37 if (this->sensor_->has_state()) {
38 return this->publish_state(this->sensor_->state);
39 } else {
40 return true;
41 }
42}
43std::string MQTTTextSensor::component_type() const { return "sensor"; }
44const EntityBase *MQTTTextSensor::get_entity() const { return this->sensor_; }
45
46} // namespace mqtt
47} // namespace esphome
48
49#endif
50#endif // USE_MQTT
StringRef get_device_class_ref() const
Get the device class as StringRef.
const StringRef & get_name() const
bool has_state() const
Definition entity_base.h:90
constexpr const char * c_str() const
Definition string_ref.h:69
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
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
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.