mirror of
https://github.com/esphome/esphome.git
synced 2026-06-02 11:08:06 +08:00
[analog_threshold] Fix oscillation when using invert filter (#12251)
Co-authored-by: Claude <noreply@anthropic.com>
This commit is contained in:
@@ -12,10 +12,11 @@ void AnalogThresholdBinarySensor::setup() {
|
|||||||
// TRUE state is defined to be when sensor is >= threshold
|
// TRUE state is defined to be when sensor is >= threshold
|
||||||
// so when undefined sensor value initialize to FALSE
|
// so when undefined sensor value initialize to FALSE
|
||||||
if (std::isnan(sensor_value)) {
|
if (std::isnan(sensor_value)) {
|
||||||
|
this->raw_state_ = false;
|
||||||
this->publish_initial_state(false);
|
this->publish_initial_state(false);
|
||||||
} else {
|
} else {
|
||||||
this->publish_initial_state(sensor_value >=
|
this->raw_state_ = sensor_value >= (this->lower_threshold_.value() + this->upper_threshold_.value()) / 2.0f;
|
||||||
(this->lower_threshold_.value() + this->upper_threshold_.value()) / 2.0f);
|
this->publish_initial_state(this->raw_state_);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -25,8 +26,10 @@ void AnalogThresholdBinarySensor::set_sensor(sensor::Sensor *analog_sensor) {
|
|||||||
this->sensor_->add_on_state_callback([this](float sensor_value) {
|
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 there is an invalid sensor reading, ignore the change and keep the current state
|
||||||
if (!std::isnan(sensor_value)) {
|
if (!std::isnan(sensor_value)) {
|
||||||
this->publish_state(sensor_value >=
|
// Use raw_state_ for hysteresis logic, not this->state which is post-filter
|
||||||
(this->state ? this->lower_threshold_.value() : this->upper_threshold_.value()));
|
this->raw_state_ =
|
||||||
|
sensor_value >= (this->raw_state_ ? this->lower_threshold_.value() : this->upper_threshold_.value());
|
||||||
|
this->publish_state(this->raw_state_);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -20,6 +20,7 @@ class AnalogThresholdBinarySensor : public Component, public binary_sensor::Bina
|
|||||||
sensor::Sensor *sensor_{nullptr};
|
sensor::Sensor *sensor_{nullptr};
|
||||||
TemplatableValue<float> upper_threshold_{};
|
TemplatableValue<float> upper_threshold_{};
|
||||||
TemplatableValue<float> lower_threshold_{};
|
TemplatableValue<float> lower_threshold_{};
|
||||||
|
bool raw_state_{false}; // Pre-filter state for hysteresis logic
|
||||||
};
|
};
|
||||||
|
|
||||||
} // namespace analog_threshold
|
} // namespace analog_threshold
|
||||||
|
|||||||
Reference in New Issue
Block a user