mirror of
https://github.com/esphome/esphome.git
synced 2024-11-10 09:17:46 +01:00
Sensor Average Filter Fix Floating Pointer Error Accumulating (#1624)
This commit is contained in:
parent
af616473aa
commit
d8e4f5d56b
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) {
|
||||
if (!isnan(value)) {
|
||||
if (this->queue_.size() == this->window_size_) {
|
||||
this->sum_ -= this->queue_.front();
|
||||
this->queue_.pop();
|
||||
this->sum_ -= this->queue_[0];
|
||||
this->queue_.pop_front();
|
||||
}
|
||||
this->queue_.push(value);
|
||||
this->queue_.push_back(value);
|
||||
this->sum_ += value;
|
||||
}
|
||||
float average;
|
||||
|
@ -161,8 +161,16 @@ optional<float> SlidingWindowMovingAverageFilter::new_value(float value) {
|
|||
average = this->sum_ / this->queue_.size();
|
||||
ESP_LOGVV(TAG, "SlidingWindowMovingAverageFilter(%p)::new_value(%f) -> %f", this, value, average);
|
||||
|
||||
if (++this->send_at_ >= this->send_every_) {
|
||||
this->send_at_ = 0;
|
||||
if (++this->send_at_ % this->send_every_ == 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);
|
||||
return average;
|
||||
}
|
||||
|
|
|
@ -162,7 +162,7 @@ class SlidingWindowMovingAverageFilter : public Filter {
|
|||
|
||||
protected:
|
||||
float sum_{0.0};
|
||||
std::queue<float> queue_;
|
||||
std::deque<float> queue_;
|
||||
size_t send_every_;
|
||||
size_t send_at_;
|
||||
size_t window_size_;
|
||||
|
|
Loading…
Reference in a new issue