Sensor Average Filter Fix Floating Pointer Error Accumulating (#1624)

This commit is contained in:
Otto Winter 2021-04-09 10:27:18 +02:00 committed by Jesse Hills
parent 06f566346d
commit 6ec0f80b76
No known key found for this signature in database
GPG Key ID: BEAAE804EFD8E83A
2 changed files with 14 additions and 6 deletions

View File

@ -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;
}

View File

@ -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_;