ESPHome 2026.10.1
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"
5
6#include "mqtt_const.h"
7
8#ifdef USE_MQTT
9#ifdef USE_SENSOR
10
11#ifdef USE_DEEP_SLEEP
13#endif
14
15namespace esphome::mqtt {
16
17static const char *const TAG = "mqtt.sensor";
18
19using namespace esphome::sensor;
20
22
24 this->sensor_->add_on_state_callback([this](float state) { this->publish_state(state); });
25}
26
28 ESP_LOGCONFIG(TAG, "MQTT Sensor '%s':", this->sensor_->get_name().c_str());
29 if (this->get_expire_after() > 0) {
30 ESP_LOGCONFIG(TAG, " Expire After: %" PRIu32 "s", this->get_expire_after() / 1000);
31 }
32 LOG_MQTT_COMPONENT(true, false);
33}
34
36const EntityBase *MQTTSensorComponent::get_entity() const { return this->sensor_; }
37
39 if (this->expire_after_.has_value())
40 return *this->expire_after_;
41 return 0;
42}
43
45 // NOLINTBEGIN(clang-analyzer-cplusplus.NewDeleteLeaks) false positive with ArduinoJson
46 if (this->sensor_->has_accuracy_decimals()) {
47 root[MQTT_SUGGESTED_DISPLAY_PRECISION] = this->sensor_->get_accuracy_decimals();
48 }
49
50 const auto unit_of_measurement = this->sensor_->get_unit_of_measurement_ref();
51 if (!unit_of_measurement.empty()) {
52 root[MQTT_UNIT_OF_MEASUREMENT] = unit_of_measurement;
53 }
54 // NOLINTEND(clang-analyzer-cplusplus.NewDeleteLeaks)
55
56 if (this->get_expire_after() > 0)
57 root[MQTT_EXPIRE_AFTER] = this->get_expire_after() / 1000;
58
59 if (this->sensor_->get_force_update())
60 root[MQTT_FORCE_UPDATE] = true;
61
63 root[MQTT_STATE_CLASS] = reinterpret_cast<ProgmemStr>(state_class_to_string(this->sensor_->get_state_class()));
64 }
65
66 config.command_topic = false;
67}
69 if (this->sensor_->has_state()) {
70 return this->publish_state(this->sensor_->state);
71 } else {
72 return true;
73 }
74}
76 char topic_buf[MQTT_DEFAULT_TOPIC_MAX_LEN];
77 if (mqtt::global_mqtt_client->is_publish_nan_as_none() && std::isnan(value))
78 return this->publish(this->get_state_topic_to_(topic_buf), "None", 4);
79 int8_t accuracy = this->sensor_->get_accuracy_decimals();
80 char buf[VALUE_ACCURACY_MAX_LEN];
81 size_t len = value_accuracy_to_buf(buf, value, accuracy);
82 return this->publish(this->get_state_topic_to_(topic_buf), buf, len);
83}
84
85} // namespace esphome::mqtt
86
87#endif
88#endif // USE_MQTT
const StringRef & get_name() const
Definition entity_base.h:71
StringRef get_unit_of_measurement_ref() const
bool has_state() const
constexpr const char * c_str() const
Definition string_ref.h:77
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).
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 setup() override
Override setup.
Base-class for all sensors.
Definition sensor.h:47
void add_on_state_callback(F &&callback)
Add a callback that will be called every time a filtered value arrives.
Definition sensor.h:121
bool has_accuracy_decimals() const
Check if the accuracy in decimals has been manually set.
Definition sensor.h:56
float state
This member variable stores the last state that has passed through all filters.
Definition sensor.h:140
StateClass get_state_class()
Get the state class, using the manual override if set.
Definition sensor.cpp:59
int8_t get_accuracy_decimals()
Get the accuracy in decimals, using the manual override if set.
Definition sensor.cpp:45
bool get_force_update() const
Get whether force update mode is enabled.
Definition sensor.h:70
bool state
Definition fan.h:2
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:566
const void size_t len
Definition hal.h:64
const __FlashStringHelper * ProgmemStr
Definition progmem.h:29
Simple Helper struct used for Home Assistant MQTT send_discovery().
bool command_topic
If the command topic should be included. Default to true.