ESPHome 2026.6.0-dev
Loading...
Searching...
No Matches
analog_threshold_binary_sensor.cpp
Go to the documentation of this file.
2#include "esphome/core/log.h"
3
5
6static const char *const TAG = "analog_threshold.binary_sensor";
7
9 float sensor_value = this->sensor_->get_state();
10
11 // TRUE state is defined to be when sensor is >= threshold
12 // so when undefined sensor value initialize to FALSE
13 if (std::isnan(sensor_value)) {
14 this->raw_state_ = false;
15 this->publish_initial_state(false);
16 } else {
17 this->raw_state_ = sensor_value >= (this->lower_threshold_.value() + this->upper_threshold_.value()) / 2.0f;
19 }
20}
21
23 this->sensor_ = analog_sensor;
24
25 this->sensor_->add_on_state_callback([this](float sensor_value) {
26 // if there is an invalid sensor reading, ignore the change and keep the current state
27 if (!std::isnan(sensor_value)) {
28 // Use raw_state_ for hysteresis logic, not this->state which is post-filter
29 this->raw_state_ =
30 sensor_value >= (this->raw_state_ ? this->lower_threshold_.value() : this->upper_threshold_.value());
31 this->publish_state(this->raw_state_);
32 }
33 });
34}
35
37 LOG_BINARY_SENSOR("", "Analog Threshold Binary Sensor", this);
38 LOG_SENSOR(" ", "Sensor", this->sensor_);
39 ESP_LOGCONFIG(TAG,
40 " Upper threshold: %.11f\n"
41 " Lower threshold: %.11f",
42 this->upper_threshold_.value(), this->lower_threshold_.value());
43}
44
45} // namespace esphome::analog_threshold
T value(X... x) const
Definition automation.h:58
void publish_state(bool new_state)
Publish a new state to the front-end.
void publish_initial_state(bool new_state)
Publish the initial state, this will not make the callback manager send callbacks and is meant only f...
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:119
float get_state() const
Getter-syntax for .state.
Definition sensor.h:98