ESPHome  2024.4.0
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 
9 namespace esphome {
10 namespace mqtt {
11 
12 static const char *const TAG = "mqtt.text_sensor";
13 
14 using namespace esphome::text_sensor;
15 
16 MQTTTextSensor::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 
31 bool 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 }
39 std::string MQTTTextSensor::component_type() const { return "sensor"; }
40 const EntityBase *MQTTTextSensor::get_entity() const { return this->sensor_; }
41 std::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.
Definition: entity_base.cpp:78
void add_on_state_callback(std::function< void(std::string)> callback)
Definition: text_sensor.cpp:52
virtual std::string unique_id()
Override this method to set the unique ID of this sensor.
Definition: text_sensor.cpp:68
MQTTTextSensor(text_sensor::TextSensor *sensor)
std::string unique_id() override
bool command_topic
If the command topic should be included. Default to true.
bool publish(const std::string &topic, const std::string &payload)
Send a MQTT message.
bool publish_state(const std::string &value)
Simple Helper struct used for Home Assistant MQTT send_discovery().
const EntityBase * get_entity() const override
constexpr const char * c_str() const
Definition: string_ref.h:68
This is a workaround until we can figure out a way to get the tflite-micro idf component code availab...
Definition: a01nyub.cpp:7
constexpr const char *const MQTT_DEVICE_CLASS
Definition: mqtt_const.h:57
std::string get_state_topic_() const
Get the MQTT topic that new states will be shared to.
text_sensor::TextSensor * sensor_
void send_discovery(JsonObject root, mqtt::SendDiscoveryConfig &config) override
const StringRef & get_name() const
Definition: entity_base.cpp:10
std::string component_type() const override
bool state
Definition: fan.h:34