ESPHome  2022.6.3
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->rtc_.load(&preference_value);
16  this->result_ = preference_value;
17  }
18 
19  this->last_update_ = millis();
20  this->last_save_ = this->last_update_;
21 
22  this->publish_and_save_(this->result_);
23  this->sensor_->add_on_state_callback([this](float state) { this->process_sensor_value_(state); });
24 }
25 void IntegrationSensor::dump_config() { LOG_SENSOR("", "Integration Sensor", this); }
27  const uint32_t now = millis();
28  const double old_value = this->last_value_;
29  const double new_value = value;
30  const uint32_t dt_ms = now - this->last_update_;
31  const double dt = dt_ms * this->get_time_factor_();
32  double area = 0.0f;
33  switch (this->method_) {
35  area = dt * (old_value + new_value) / 2.0;
36  break;
38  area = dt * old_value;
39  break;
41  area = dt * new_value;
42  break;
43  }
44  this->last_value_ = new_value;
45  this->last_update_ = now;
46  this->publish_and_save_(this->result_ + area);
47 }
48 
49 } // namespace integration
50 } // 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:83
uint32_t IRAM_ATTR HOT millis()
Definition: core.cpp:26
float state
This member variable stores the last state that has passed through all filters.
Definition: sensor.h:132
ESPPreferences * global_preferences
virtual ESPPreferenceObject make_preference(size_t length, uint32_t type, bool in_flash)=0
Definition: a4988.cpp:4
uint32_t get_object_id_hash()
Definition: entity_base.cpp:42