SensESP 3.4.1-alpha
Universal Signal K sensor toolkit ESP32
Loading...
Searching...
No Matches
moving_average.cpp
Go to the documentation of this file.
1#include "moving_average.h"
2
3namespace sensesp {
4
5// MovingAverage
6
7MovingAverage::MovingAverage(int sample_size, float multiplier,
8 const String& config_path)
9 : FloatTransform(config_path),
10 sample_size_{sample_size},
11 multiplier_{multiplier},
12 initialized_(false) {
13
14 buf_.resize(sample_size_, 0);
15
16 load();
17}
18
19void MovingAverage::set(const float& input) {
20 if (!initialized_) {
21 // Seed the whole buffer with the first value so the average doesn't start
22 // out diluted by zeros.
23 buf_.assign(sample_size_, input);
24 sum_ = static_cast<float>(sample_size_) * input;
25 initialized_ = true;
26 } else {
27 // Swap the oldest buffered value out of the running sum for the newest.
28 sum_ += input - buf_[ptr_];
29 buf_[ptr_] = input;
30 ptr_ = (ptr_ + 1) % sample_size_;
31 }
32 output_ = multiplier_ * sum_ / sample_size_;
33 notify();
34}
35
36bool MovingAverage::to_json(JsonObject& root) {
37 root["multiplier"] = multiplier_;
38 root["sample_size"] = sample_size_;
39 return true;
40}
41
42bool MovingAverage::from_json(const JsonObject& config) {
43 String const expected[] = {"multiplier", "sample_size"};
44 for (auto str : expected) {
45 if (!config[str].is<JsonVariant>()) {
46 return false;
47 }
48 }
49 multiplier_ = config["multiplier"];
50 int const n_new = config["sample_size"];
51 // need to reset the ring buffer if size changes
52 if (sample_size_ != n_new) {
53 sample_size_ = n_new;
54 buf_.assign(sample_size_, 0);
55 ptr_ = 0;
56 initialized_ = false;
57 }
58 return true;
59}
60const String ConfigSchema(const MovingAverage& obj) {
61 return R"({"type":"object","properties":{"sample_size":{"title":"Number of samples in average","type":"integer"},"multiplier":{"title":"Multiplier","type":"number"}}})";
62}
63
64} // namespace sensesp
virtual bool load() override
Load and populate the object from a persistent storage.
Definition saveable.cpp:8
Outputs the moving average of the last sample_size inputs.
virtual void set(const float &input) override
virtual bool to_json(JsonObject &root) override
virtual bool from_json(const JsonObject &config) override
MovingAverage(int sample_size, float multiplier=1.0, const String &config_path="")
const String ConfigSchema(const SmartSwitchController &obj)