mirror of
https://github.com/esphome/esphome.git
synced 2024-11-26 17:05:21 +01:00
Sensor Average Filter Fix Floating Pointer Error Accumulating (#1624)
This commit is contained in:
parent
06f566346d
commit
6ec0f80b76
2 changed files with 14 additions and 6 deletions
|
@ -148,10 +148,10 @@ void SlidingWindowMovingAverageFilter::set_window_size(size_t window_size) { thi
|
||||||
optional<float> SlidingWindowMovingAverageFilter::new_value(float value) {
|
optional<float> SlidingWindowMovingAverageFilter::new_value(float value) {
|
||||||
if (!isnan(value)) {
|
if (!isnan(value)) {
|
||||||
if (this->queue_.size() == this->window_size_) {
|
if (this->queue_.size() == this->window_size_) {
|
||||||
this->sum_ -= this->queue_.front();
|
this->sum_ -= this->queue_[0];
|
||||||
this->queue_.pop();
|
this->queue_.pop_front();
|
||||||
}
|
}
|
||||||
this->queue_.push(value);
|
this->queue_.push_back(value);
|
||||||
this->sum_ += value;
|
this->sum_ += value;
|
||||||
}
|
}
|
||||||
float average;
|
float average;
|
||||||
|
@ -161,8 +161,16 @@ optional<float> SlidingWindowMovingAverageFilter::new_value(float value) {
|
||||||
average = this->sum_ / this->queue_.size();
|
average = this->sum_ / this->queue_.size();
|
||||||
ESP_LOGVV(TAG, "SlidingWindowMovingAverageFilter(%p)::new_value(%f) -> %f", this, value, average);
|
ESP_LOGVV(TAG, "SlidingWindowMovingAverageFilter(%p)::new_value(%f) -> %f", this, value, average);
|
||||||
|
|
||||||
if (++this->send_at_ >= this->send_every_) {
|
if (++this->send_at_ % this->send_every_ == 0) {
|
||||||
this->send_at_ = 0;
|
if (this->send_at_ >= 10000) {
|
||||||
|
// Recalculate to prevent floating point error accumulating
|
||||||
|
this->sum_ = 0;
|
||||||
|
for (auto v : this->queue_)
|
||||||
|
this->sum_ += v;
|
||||||
|
average = this->sum_ / this->queue_.size();
|
||||||
|
this->send_at_ = 0;
|
||||||
|
}
|
||||||
|
|
||||||
ESP_LOGVV(TAG, "SlidingWindowMovingAverageFilter(%p)::new_value(%f) SENDING", this, value);
|
ESP_LOGVV(TAG, "SlidingWindowMovingAverageFilter(%p)::new_value(%f) SENDING", this, value);
|
||||||
return average;
|
return average;
|
||||||
}
|
}
|
||||||
|
|
|
@ -162,7 +162,7 @@ class SlidingWindowMovingAverageFilter : public Filter {
|
||||||
|
|
||||||
protected:
|
protected:
|
||||||
float sum_{0.0};
|
float sum_{0.0};
|
||||||
std::queue<float> queue_;
|
std::deque<float> queue_;
|
||||||
size_t send_every_;
|
size_t send_every_;
|
||||||
size_t send_at_;
|
size_t send_at_;
|
||||||
size_t window_size_;
|
size_t window_size_;
|
||||||
|
|
Loading…
Reference in a new issue