SensESP 3.0.1
Universal Signal K sensor toolkit ESP32
Loading...
Searching...
No Matches
median.cpp
Go to the documentation of this file.
1#include "median.h"
2
3namespace sensesp {
4
5Median::Median(unsigned int sample_size, const String& config_path)
6 : FloatTransform(config_path), sample_size_{sample_size} {
7 load();
8 buf_.reserve(sample_size_);
9 buf_.clear();
10}
11
12void Median::set(const float& input) {
13 buf_.push_back(input);
14 if (buf_.size() >= sample_size_) {
15 // Its time to output a value
16 sort(buf_.begin(), buf_.end());
17 const unsigned int mid = sample_size_ / 2;
18 output_ = buf_[mid];
19 buf_.clear();
20 notify();
21 }
22}
23
24bool Median::to_json(JsonObject& root) {
25 root["sample_size"] = sample_size_;
26 return true;
27}
28
29bool Median::from_json(const JsonObject& config) {
30 String const expected[] = {"sample_size"};
31 for (auto str : expected) {
32 if (!config[str].is<JsonVariant>()) {
33 return false;
34 }
35 }
36 unsigned int const sample_size_new = config["sample_size"];
37 if (sample_size_ != sample_size_new) {
38 sample_size_ = sample_size_new;
39 buf_.reserve(sample_size_);
40 buf_.clear();
41 }
42 return true;
43}
44
45const String ConfigSchema(const Median& obj) {
46 return R"({"type":"object","properties":{"sample_size":{"title":"Sample size","description":"Number of samples to take before outputing a value","type":"integer"}}})";
47}
48
49} // namespace sensesp
virtual bool load() override
Load and populate the object from a persistent storage.
Definition saveable.cpp:8
Outputs the median value of sample_size inputs.
Definition median.h:21
virtual void set(const float &input) override
Definition median.cpp:12
virtual bool from_json(const JsonObject &config) override
Definition median.cpp:29
virtual bool to_json(JsonObject &root) override
Definition median.cpp:24
Median(unsigned int sample_size=10, const String &config_path="")
Definition median.cpp:5
const String ConfigSchema(const SmartSwitchController &obj)