ESPHome  2024.12.2
analog_threshold_binary_sensor.cpp
Go to the documentation of this file.
2 #include "esphome/core/log.h"
3 
4 namespace esphome {
5 namespace analog_threshold {
6 
7 static 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 >= (this->lower_threshold_ + this->upper_threshold_) / 2.0f);
18  }
19 }
20 
22  this->sensor_ = analog_sensor;
23 
24  this->sensor_->add_on_state_callback([this](float sensor_value) {
25  // if there is an invalid sensor reading, ignore the change and keep the current state
26  if (!std::isnan(sensor_value)) {
27  this->publish_state(sensor_value >= (this->state ? this->lower_threshold_ : this->upper_threshold_));
28  }
29  });
30 }
31 
33  LOG_BINARY_SENSOR("", "Analog Threshold Binary Sensor", this);
34  LOG_SENSOR(" ", "Sensor", this->sensor_);
35  ESP_LOGCONFIG(TAG, " Upper threshold: %.11f", this->upper_threshold_);
36  ESP_LOGCONFIG(TAG, " Lower threshold: %.11f", this->lower_threshold_);
37 }
38 
39 } // namespace analog_threshold
40 } // namespace esphome
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
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.
Definition: binary_sensor.h:61
void publish_state(bool state)
Publish a new state to the front-end.
float get_state() const
Getter-syntax for .state.
Definition: sensor.cpp:86
Implementation of SPI Controller mode.
Definition: a01nyub.cpp:7
Base-class for all sensors.
Definition: sensor.h:57