From 694f6ca2b44b01ec71df3788f4a26c2c735177b7 Mon Sep 17 00:00:00 2001 From: Adam Goode Date: Mon, 1 Jan 2024 00:20:33 -0500 Subject: [PATCH] analog_threshold: Publish initial state only when available This avoids spurious triggers since most sensors won't have state during setup(). --- .../analog_threshold_binary_sensor.cpp | 20 +++++++------------ .../analog_threshold_binary_sensor.h | 1 - 2 files changed, 7 insertions(+), 14 deletions(-) diff --git a/esphome/components/analog_threshold/analog_threshold_binary_sensor.cpp b/esphome/components/analog_threshold/analog_threshold_binary_sensor.cpp index f679b9994f..aada883d2e 100644 --- a/esphome/components/analog_threshold/analog_threshold_binary_sensor.cpp +++ b/esphome/components/analog_threshold/analog_threshold_binary_sensor.cpp @@ -6,25 +6,19 @@ namespace analog_threshold { static const char *const TAG = "analog_threshold.binary_sensor"; -void AnalogThresholdBinarySensor::setup() { - float sensor_value = this->sensor_->get_state(); - - // TRUE state is defined to be when sensor is >= threshold - // so when undefined sensor value initialize to FALSE - if (std::isnan(sensor_value)) { - this->publish_initial_state(false); - } else { - this->publish_initial_state(sensor_value >= (this->lower_threshold_ + this->upper_threshold_) / 2.0f); - } -} - void AnalogThresholdBinarySensor::set_sensor(sensor::Sensor *analog_sensor) { this->sensor_ = analog_sensor; this->sensor_->add_on_state_callback([this](float sensor_value) { // if there is an invalid sensor reading, ignore the change and keep the current state if (!std::isnan(sensor_value)) { - this->publish_state(sensor_value >= (this->state ? this->lower_threshold_ : this->upper_threshold_)); + bool threshold_value = sensor_value >= (this->state ? this->lower_threshold_ : this->upper_threshold_); + if (this->has_state()) { + // This is not the initial state. + this->publish_state(threshold_value); + } else { + this->publish_initial_state(threshold_value); + } } }); } diff --git a/esphome/components/analog_threshold/analog_threshold_binary_sensor.h b/esphome/components/analog_threshold/analog_threshold_binary_sensor.h index 619aef1075..88298a3cd8 100644 --- a/esphome/components/analog_threshold/analog_threshold_binary_sensor.h +++ b/esphome/components/analog_threshold/analog_threshold_binary_sensor.h @@ -10,7 +10,6 @@ namespace analog_threshold { class AnalogThresholdBinarySensor : public Component, public binary_sensor::BinarySensor { public: void dump_config() override; - void setup() override; float get_setup_priority() const override { return setup_priority::DATA; }