ESPHome 2026.1.4
Loading...
Searching...
No Matches
mqtt_sensor.cpp
Go to the documentation of this file.
1#include <cinttypes>
2#include "mqtt_sensor.h"
3#include "esphome/core/log.h"
4
5#include "mqtt_const.h"
6
7#ifdef USE_MQTT
8#ifdef USE_SENSOR
9
10#ifdef USE_DEEP_SLEEP
12#endif
13
14namespace esphome::mqtt {
15
16static const char *const TAG = "mqtt.sensor";
17
18using namespace esphome::sensor;
19
21
23 this->sensor_->add_on_state_callback([this](float state) { this->publish_state(state); });
24}
25
27 ESP_LOGCONFIG(TAG, "MQTT Sensor '%s':", this->sensor_->get_name().c_str());
28 if (this->get_expire_after() > 0) {
29 ESP_LOGCONFIG(TAG, " Expire After: %" PRIu32 "s", this->get_expire_after() / 1000);
30 }
31 LOG_MQTT_COMPONENT(true, false)
32}
33
35const EntityBase *MQTTSensorComponent::get_entity() const { return this->sensor_; }
36
38 if (this->expire_after_.has_value())
39 return *this->expire_after_;
40 return 0;
41}
42void MQTTSensorComponent::set_expire_after(uint32_t expire_after) { this->expire_after_ = expire_after; }
44
46 // NOLINTBEGIN(clang-analyzer-cplusplus.NewDeleteLeaks) false positive with ArduinoJson
47 const auto device_class = this->sensor_->get_device_class_ref();
48 if (!device_class.empty()) {
49 root[MQTT_DEVICE_CLASS] = device_class;
50 }
51
52 const auto unit_of_measurement = this->sensor_->get_unit_of_measurement_ref();
53 if (!unit_of_measurement.empty()) {
54 root[MQTT_UNIT_OF_MEASUREMENT] = unit_of_measurement;
55 }
56 // NOLINTEND(clang-analyzer-cplusplus.NewDeleteLeaks)
57
58 if (this->get_expire_after() > 0)
59 root[MQTT_EXPIRE_AFTER] = this->get_expire_after() / 1000;
60
61 if (this->sensor_->get_force_update())
62 root[MQTT_FORCE_UPDATE] = true;
63
65#ifdef USE_STORE_LOG_STR_IN_FLASH
66 root[MQTT_STATE_CLASS] = (const __FlashStringHelper *) state_class_to_string(this->sensor_->get_state_class());
67#else
68 root[MQTT_STATE_CLASS] = LOG_STR_ARG(state_class_to_string(this->sensor_->get_state_class()));
69#endif
70 }
71
72 config.command_topic = false;
73}
75 if (this->sensor_->has_state()) {
76 return this->publish_state(this->sensor_->state);
77 } else {
78 return true;
79 }
80}
82 if (mqtt::global_mqtt_client->is_publish_nan_as_none() && std::isnan(value))
83 return this->publish(this->get_state_topic_(), "None", 4);
84 int8_t accuracy = this->sensor_->get_accuracy_decimals();
85 char buf[VALUE_ACCURACY_MAX_LEN];
86 size_t len = value_accuracy_to_buf(buf, value, accuracy);
87 return this->publish(this->get_state_topic_(), buf, len);
88}
89
90} // namespace esphome::mqtt
91
92#endif
93#endif // USE_MQTT
StringRef get_device_class_ref() const
Get the device class as StringRef.
StringRef get_unit_of_measurement_ref() const
Get the unit of measurement 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.
std::string get_state_topic_() const
Get the MQTT topic that new states will be shared to.
uint32_t get_expire_after() const
Get the expire_after in milliseconds used for Home Assistant discovery, first checks override.
optional< uint32_t > expire_after_
Definition mqtt_sensor.h:50
MQTTSensorComponent(sensor::Sensor *sensor)
Construct this MQTTSensorComponent instance with the provided friendly_name and sensor.
void send_discovery(JsonObject root, mqtt::SendDiscoveryConfig &config) override
void set_expire_after(uint32_t expire_after)
Setup an expiry, 0 disables it.
void disable_expire_after()
Disable Home Assistant value expiry.
void setup() override
Override setup.
bool has_value() const
Definition optional.h:92
Base-class for all sensors.
Definition sensor.h:42
void add_on_state_callback(std::function< void(float)> &&callback)
Add a callback that will be called every time a filtered value arrives.
Definition sensor.cpp:89
float state
This member variable stores the last state that has passed through all filters.
Definition sensor.h:116
StateClass get_state_class()
Get the state class, using the manual override if set.
Definition sensor.cpp:70
int8_t get_accuracy_decimals()
Get the accuracy in decimals, using the manual override if set.
Definition sensor.cpp:56
bool get_force_update() const
Get whether force update mode is enabled.
Definition sensor.h:63
bool state
Definition fan.h:0
MQTT_COMPONENT_TYPE(MQTTAlarmControlPanelComponent, "alarm_control_panel") const EntityBase *MQTTAlarmControlPanelComponent
MQTTClientComponent * global_mqtt_client
const LogString * state_class_to_string(StateClass state_class)
Definition sensor.cpp:38
size_t value_accuracy_to_buf(std::span< char, VALUE_ACCURACY_MAX_LEN > buf, float value, int8_t accuracy_decimals)
Format value with accuracy to buffer, returns chars written (excluding null)
Definition helpers.cpp:448
std::string size_t len
Definition helpers.h:595
Simple Helper struct used for Home Assistant MQTT send_discovery().
bool command_topic
If the command topic should be included. Default to true.