ESPHome 2026.11.0b6
Loading...
Searching...
No Matches
combination.cpp
Go to the documentation of this file.
1#include "combination.h"
2
3#include "esphome/core/log.h"
4#include "esphome/core/hal.h"
5
6#include <cmath>
7
9
10ESPHOME_LOG_TAG(TAG, "combination");
11
12static constexpr uint32_t NEW_VALUE_DEFER_ID = 0;
13
14void CombinationComponent::log_config_(const LogString *combo_type) {
15 LOG_SENSOR("", "Combination Sensor:", this);
16 ESP_LOGCONFIG(TAG, " Combination Type: %s", LOG_STR_ARG(combo_type));
17 this->log_source_sensors();
18}
19
20void CombinationNoParameterComponent::add_source(Sensor *sensor) { this->sensors_.emplace_back(sensor); }
21
22void CombinationOneParameterComponent::add_source(Sensor *sensor, std::function<float(float)> const &compute) {
23 this->sensor_sources_.push_back({sensor, compute, this});
24}
25
27 this->add_source(sensor, std::function<float(float)>{[value](float x) -> float { return value; }});
28}
29
31 ESP_LOGCONFIG(TAG, " Source Sensors:");
32 for (const auto &sensor : this->sensors_) {
33 ESP_LOGCONFIG(TAG, " - %s", LOG_STR_ARG(sensor->get_log_name()));
34 }
35}
36
38 ESP_LOGCONFIG(TAG, " Source Sensors:");
39 for (const auto &source : this->sensor_sources_) {
40 ESP_LOGCONFIG(TAG, " - %s", LOG_STR_ARG(source.sensor->get_log_name()));
41 }
42}
43
45 for (const auto &sensor : this->sensors_) {
46 // All sensor updates are deferred until the next loop. This avoids publishing the combined sensor's result
47 // repeatedly in the same loop if multiple source senors update.
48 sensor->add_on_state_callback([this](float value) -> void {
49 this->defer(NEW_VALUE_DEFER_ID, [this, value]() { this->handle_new_value(value); });
50 });
51 }
52}
53
55 this->log_config_(LOG_STR("kalman"));
56 ESP_LOGCONFIG(TAG, " Update variance: %f per ms", this->update_variance_value_);
57
58 if (this->std_dev_sensor_ != nullptr) {
59 LOG_SENSOR(" ", "Standard Deviation Sensor:", this->std_dev_sensor_);
60 }
61}
62
63void KalmanCombinationComponent::setup() {
64 for (auto &source : this->sensor_sources_) {
65 // [&source] is safe: source refers to a FixedVector element that never reallocates,
66 // so the reference remains valid for the component's lifetime.
67 source.sensor->add_on_state_callback([&source](float x) -> void {
68 static_cast<KalmanCombinationComponent *>(source.parent)->correct_(x, source.compute(x));
69 });
70 }
71}
72
74 uint32_t now = millis();
75
76 // Variance increases by update_variance_ each millisecond
77 auto dt = now - this->last_update_;
78 auto dv = this->update_variance_value_ * dt;
79 this->variance_ += dv;
80 this->last_update_ = now;
81}
82
84 if (std::isnan(value) || std::isinf(stddev)) {
85 return;
86 }
87
88 if (std::isnan(this->state_) || std::isinf(this->variance_)) {
89 this->state_ = value;
90 this->variance_ = stddev * stddev;
91 PUBLISH_STATE(this->std_dev_sensor_, stddev);
92 return;
93 }
94
95 this->update_variance_();
96
97 // Combine two gaussian distributions mu1+-var1, mu2+-var2 to a new one around mu
98 // Use the value with the smaller variance as mu1 to prevent precision errors
99 const bool this_first = this->variance_ < (stddev * stddev);
100 const float mu1 = this_first ? this->state_ : value;
101 const float mu2 = this_first ? value : this->state_;
102
103 const float var1 = this_first ? this->variance_ : stddev * stddev;
104 const float var2 = this_first ? stddev * stddev : this->variance_;
105
106 const float mu = mu1 + var1 * (mu2 - mu1) / (var1 + var2);
107 const float var = var1 - (var1 * var1) / (var1 + var2);
108
109 // Update and publish state
110 this->state_ = mu;
111 this->variance_ = var;
112
113 this->publish_state(mu);
114 PUBLISH_STATE(this->std_dev_sensor_, std::sqrt(var));
115}
116
118 for (auto &source : this->sensor_sources_) {
119 // All sensor updates are deferred until the next loop. This avoids publishing the combined sensor's result
120 // repeatedly in the same loop if multiple source senors update.
121 source.sensor->add_on_state_callback([this](float value) -> void {
122 this->defer(NEW_VALUE_DEFER_ID, [this, value]() { this->handle_new_value(value); });
123 });
124 }
125}
126
128 // Multiplies each sensor state by a configured coefficient and then sums
129
130 if (!std::isfinite(value))
131 return;
132
133 float sum = 0.0;
134
135 for (const auto &source : this->sensor_sources_) {
136 const float sensor_state = source.sensor->state;
137 if (std::isfinite(sensor_state)) {
138 sum += sensor_state * source.compute(sensor_state);
139 }
140 }
141
142 this->publish_state(sum);
143};
144
146 if (!std::isfinite(value))
147 return;
148
149 float max_value = (-1) * std::numeric_limits<float>::infinity(); // note x = max(x, -infinity)
150
151 for (const auto &sensor : this->sensors_) {
152 if (std::isfinite(sensor->state)) {
153 max_value = std::max(max_value, sensor->state);
154 }
155 }
156
157 this->publish_state(max_value);
158}
159
161 if (!std::isfinite(value))
162 return;
163
164 float sum = 0.0;
165 size_t count = 0;
166
167 for (const auto &sensor : this->sensors_) {
168 if (std::isfinite(sensor->state)) {
169 ++count;
170 sum += sensor->state;
171 }
172 }
173
174 if (count == 0) {
175 this->publish_state(NAN);
176 return;
177 }
178 float mean = sum / count;
179
180 this->publish_state(mean);
181}
182
184 // Sorts sensor states in ascending order and determines the middle value
185
186 if (!std::isfinite(value))
187 return;
188
189 std::vector<float> sensor_states;
190 for (const auto &sensor : this->sensors_) {
191 if (std::isfinite(sensor->state)) {
192 sensor_states.push_back(sensor->state);
193 }
194 }
195
196 sort(sensor_states.begin(), sensor_states.end());
197 size_t sensor_states_size = sensor_states.size();
198
199 float median = NAN;
200
201 if (sensor_states_size) {
202 if (sensor_states_size % 2) {
203 // Odd number of measurements, use middle measurement
204 median = sensor_states[sensor_states_size / 2];
205 } else {
206 // Even number of measurements, use the average of the two middle measurements
207 median = (sensor_states[sensor_states_size / 2] + sensor_states[sensor_states_size / 2 - 1]) / 2.0f;
208 }
209 }
210
211 this->publish_state(median);
212}
213
215 if (!std::isfinite(value))
216 return;
217
218 float min_value = std::numeric_limits<float>::infinity(); // note x = min(x, infinity)
219
220 for (const auto &sensor : this->sensors_) {
221 if (std::isfinite(sensor->state)) {
222 min_value = std::min(min_value, sensor->state);
223 }
224 }
225
226 this->publish_state(min_value);
227}
228
230
232 // Sorts sensor states then takes difference between largest and smallest states
233
234 if (!std::isfinite(value))
235 return;
236
237 std::vector<float> sensor_states;
238 for (const auto &sensor : this->sensors_) {
239 if (std::isfinite(sensor->state)) {
240 sensor_states.push_back(sensor->state);
241 }
242 }
243
244 if (sensor_states.empty()) {
245 this->publish_state(NAN);
246 return;
247 }
248
249 sort(sensor_states.begin(), sensor_states.end());
250
251 float range = sensor_states.back() - sensor_states.front();
252 this->publish_state(range);
253}
254
256 if (!std::isfinite(value))
257 return;
258
259 float sum = 0.0;
260 for (const auto &sensor : this->sensors_) {
261 if (std::isfinite(sensor->state)) {
262 sum += sensor->state;
263 }
264 }
265
266 this->publish_state(sum);
267}
268
269} // namespace esphome::combination
virtual void dump_config()
void defer(const char *name, std::function< void()> &&f)
Defer a callback to the next loop() call with a const char* name.
void log_config_(const LogString *combo_type)
Logs the sensor for use in dump_config.
virtual void log_source_sensors()=0
Logs all source sensor's names.
void setup() override
Adds a callback to each source sensor.
virtual void handle_new_value(float value)=0
Computes the combination.
void log_source_sensors() override
Logs all source sensor's names in sensors_.
void log_source_sensors() override
Logs all source sensors' names in sensor_sources_.
void add_source(Sensor *sensor, std::function< float(float)> const &compute)
void correct_(float value, float stddev)
void publish_state(float state)
Publish a new state to the front-end.
Definition sensor.cpp:65
unsigned count
Definition gif.cpp:51
Range range
Definition msa3xx.h:0
ESPHOME_LOG_TAG(TAG, "combination")
uint32_t value
Definition hal.cpp:41
uint32_t IRAM_ATTR HOT millis()
Definition hal.cpp:25
static void uint32_t
uint16_t x
Definition tt21100.cpp:5