ESPHome 2026.1.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
4namespace esphome {
5namespace analog_threshold {
6
7static const char *const TAG = "analog_threshold.binary_sensor";
8
10 float sensor_value = this->sensor_->get_state();
11
12 // TRUE state is defined to be when sensor is >= threshold
13 // so when undefined sensor value initialize to FALSE
14 if (std::isnan(sensor_value)) {
15 this->raw_state_ = false;
16 this->publish_initial_state(false);
17 } else {
18 this->raw_state_ = sensor_value >= (this->lower_threshold_.value() + this->upper_threshold_.value()) / 2.0f;
20 }
21}
22
24 this->sensor_ = analog_sensor;
25
26 this->sensor_->add_on_state_callback([this](float sensor_value) {
27 // if there is an invalid sensor reading, ignore the change and keep the current state
28 if (!std::isnan(sensor_value)) {
29 // Use raw_state_ for hysteresis logic, not this->state which is post-filter
30 this->raw_state_ =
31 sensor_value >= (this->raw_state_ ? this->lower_threshold_.value() : this->upper_threshold_.value());
32 this->publish_state(this->raw_state_);
33 }
34 });
35}
36
38 LOG_BINARY_SENSOR("", "Analog Threshold Binary Sensor", this);
39 LOG_SENSOR(" ", "Sensor", this->sensor_);
40 ESP_LOGCONFIG(TAG,
41 " Upper threshold: %.11f\n"
42 " Lower threshold: %.11f",
43 this->upper_threshold_.value(), this->lower_threshold_.value());
44}
45
46} // namespace analog_threshold
47} // namespace esphome
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:43
float get_state() const
Getter-syntax for .state.
Definition sensor.cpp:124
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:90
Providing packet encoding functions for exchanging data with a remote host.
Definition a01nyub.cpp:7