ESPHome  2024.10.2
integration_sensor.cpp
Go to the documentation of this file.
1 #include "integration_sensor.h"
2 #include "esphome/core/helpers.h"
3 #include "esphome/core/log.h"
4 #include "esphome/core/hal.h"
5 
6 namespace esphome {
7 namespace integration {
8 
9 static const char *const TAG = "integration";
10 
12  if (this->restore_) {
14  float preference_value = 0;
15  this->pref_.load(&preference_value);
16  this->result_ = preference_value;
17  }
18 
19  this->last_update_ = millis();
20 
21  this->publish_and_save_(this->result_);
22  this->sensor_->add_on_state_callback([this](float state) { this->process_sensor_value_(state); });
23 }
24 void IntegrationSensor::dump_config() { LOG_SENSOR("", "Integration Sensor", this); }
26  if (std::isnan(value))
27  return;
28  const uint32_t now = millis();
29  const double old_value = this->last_value_;
30  const double new_value = value;
31  const uint32_t dt_ms = now - this->last_update_;
32  const double dt = dt_ms * this->get_time_factor_();
33  double area = 0.0f;
34  switch (this->method_) {
36  area = dt * (old_value + new_value) / 2.0;
37  break;
39  area = dt * old_value;
40  break;
42  area = dt * new_value;
43  break;
44  }
45  this->last_value_ = new_value;
46  this->last_update_ = now;
47  this->publish_and_save_(this->result_ + area);
48 }
49 
50 } // namespace integration
51 } // namespace esphome
void add_on_state_callback(std::function< void(float)> &&callback)
Add a callback that will be called every time a filtered value arrives.
Definition: sensor.cpp:52
uint32_t IRAM_ATTR HOT millis()
Definition: core.cpp:25
float state
This member variable stores the last state that has passed through all filters.
Definition: sensor.h:131
ESPPreferences * global_preferences
virtual ESPPreferenceObject make_preference(size_t length, uint32_t type, bool in_flash)=0
Implementation of SPI Controller mode.
Definition: a01nyub.cpp:7
uint32_t get_object_id_hash()
Definition: entity_base.cpp:76