ESPHome 2025.5.0
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->publish_initial_state(false);
16 } else {
17 this->publish_initial_state(sensor_value >=
18 (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 this->publish_state(sensor_value >=
29 (this->state ? this->lower_threshold_.value() : this->upper_threshold_.value()));
30 }
31 });
32}
33
35 LOG_BINARY_SENSOR("", "Analog Threshold Binary Sensor", this);
36 LOG_SENSOR(" ", "Sensor", this->sensor_);
37 ESP_LOGCONFIG(TAG, " Upper threshold: %.11f", this->upper_threshold_.value());
38 ESP_LOGCONFIG(TAG, " Lower threshold: %.11f", this->lower_threshold_.value());
39}
40
41} // namespace analog_threshold
42} // namespace esphome
void publish_initial_state(bool state)
Publish the initial state, this will not make the callback manager send callbacks and is meant only f...
bool state
The current reported state of the binary sensor.
void publish_state(bool state)
Publish a new state to the front-end.
Base-class for all sensors.
Definition sensor.h:57
float get_state() const
Getter-syntax for .state.
Definition sensor.cpp:86
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:52
Providing packet encoding functions for exchanging data with a remote host.
Definition a01nyub.cpp:7