ESPHome 2026.2.1
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
11static const char *const TAG = "mqtt.text_sensor";
12
13using namespace esphome::text_sensor;
14
15MQTTTextSensor::MQTTTextSensor(TextSensor *sensor) : sensor_(sensor) {}
17 // NOLINTBEGIN(clang-analyzer-cplusplus.NewDeleteLeaks) false positive with ArduinoJson
18 const auto device_class = this->sensor_->get_device_class_ref();
19 if (!device_class.empty()) {
20 root[MQTT_DEVICE_CLASS] = device_class;
21 }
22 // NOLINTEND(clang-analyzer-cplusplus.NewDeleteLeaks)
23 config.command_topic = false;
24}
26 this->sensor_->add_on_state_callback([this](const std::string &state) { this->publish_state(state); });
27}
28
30 ESP_LOGCONFIG(TAG, "MQTT Text Sensor '%s':", this->sensor_->get_name().c_str());
31 LOG_MQTT_COMPONENT(true, false);
32}
33
34bool MQTTTextSensor::publish_state(const std::string &value) {
35 char topic_buf[MQTT_DEFAULT_TOPIC_MAX_LEN];
36 return this->publish(this->get_state_topic_to_(topic_buf), value.data(), value.size());
37}
39 if (this->sensor_->has_state()) {
40 return this->publish_state(this->sensor_->state);
41 } else {
42 return true;
43 }
44}
46const EntityBase *MQTTTextSensor::get_entity() const { return this->sensor_; }
47
48} // namespace esphome::mqtt
49
50#endif
51#endif // USE_MQTT
StringRef get_device_class_ref() const
Get the device class as StringRef.
const StringRef & get_name() const
bool has_state() const
constexpr const char * c_str() const
Definition string_ref.h:73
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(std::function< void(const std::string &)> callback)
bool state
Definition fan.h:2
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.