SensESP 3.0.1
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 // So the first value to be included in the average doesn't default to 0.0
21 if (!initialized_) {
22 buf_.assign(sample_size_, input);
23 output_ = input;
24 initialized_ = true;
25 } else {
26 // Subtract 1/nth of the oldest value and add 1/nth of the newest value
27 output_ += -multiplier_ * buf_[ptr_] / sample_size_;
28 output_ += multiplier_ * input / sample_size_;
29
30 // Save the most recent input, then advance to the next storage location.
31 // When storage location n is reached, start over again at 0.
32 buf_[ptr_] = input;
33 ptr_ = (ptr_ + 1) % sample_size_;
34 }
35 notify();
36}
37
38bool MovingAverage::to_json(JsonObject& root) {
39 root["multiplier"] = multiplier_;
40 root["sample_size"] = sample_size_;
41 return true;
42}
43
44bool MovingAverage::from_json(const JsonObject& config) {
45 String const expected[] = {"multiplier", "sample_size"};
46 for (auto str : expected) {
47 if (!config[str].is<JsonVariant>()) {
48 return false;
49 }
50 }
51 multiplier_ = config["multiplier"];
52 int const n_new = config["sample_size"];
53 // need to reset the ring buffer if size changes
54 if (sample_size_ != n_new) {
55 buf_.assign(sample_size_, 0);
56 ptr_ = 0;
57 initialized_ = false;
58 sample_size_ = n_new;
59 }
60 return true;
61}
62const String ConfigSchema(const MovingAverage& obj) {
63 return R"({"type":"object","properties":{"sample_size":{"title":"Number of samples in average","type":"integer"},"multiplier":{"title":"Multiplier","type":"number"}}})";
64}
65
66} // 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)