ESPHome  2024.11.1
total_daily_energy.cpp
Go to the documentation of this file.
1 #include "total_daily_energy.h"
2 #include "esphome/core/log.h"
3 
4 namespace esphome {
5 namespace total_daily_energy {
6 
7 static const char *const TAG = "total_daily_energy";
8 
10  float initial_value = 0;
11 
12  if (this->restore_) {
14  this->pref_.load(&initial_value);
15  }
16  this->publish_state_and_save(initial_value);
17 
18  this->last_update_ = millis();
19 
20  this->parent_->add_on_state_callback([this](float state) { this->process_new_state_(state); });
21 }
22 
23 void TotalDailyEnergy::dump_config() { LOG_SENSOR("", "Total Daily Energy", this); }
24 
26  auto t = this->time_->now();
27  if (!t.is_valid())
28  return;
29 
30  if (this->last_day_of_year_ == 0) {
31  this->last_day_of_year_ = t.day_of_year;
32  return;
33  }
34 
35  if (t.day_of_year != this->last_day_of_year_) {
36  this->last_day_of_year_ = t.day_of_year;
37  this->total_energy_ = 0;
38  this->publish_state_and_save(0);
39  }
40 }
41 
43  this->total_energy_ = state;
44  this->publish_state(state);
45  if (this->restore_) {
46  this->pref_.save(&state);
47  }
48 }
49 
51  if (std::isnan(state))
52  return;
53  const uint32_t now = millis();
54  const float old_state = this->last_power_state_;
55  const float new_state = state;
56  float delta_hours = (now - this->last_update_) / 1000.0f / 60.0f / 60.0f;
57  float delta_energy = 0.0f;
58  switch (this->method_) {
60  delta_energy = delta_hours * (old_state + new_state) / 2.0;
61  break;
63  delta_energy = delta_hours * old_state;
64  break;
66  delta_energy = delta_hours * new_state;
67  break;
68  }
69  this->last_power_state_ = new_state;
70  this->last_update_ = now;
71  this->publish_state_and_save(this->total_energy_ + delta_energy);
72 }
73 
74 } // namespace total_daily_energy
75 } // namespace esphome
ESPTime now()
Get the time in the currently defined timezone.
uint32_t IRAM_ATTR HOT millis()
Definition: core.cpp:25
bool save(const T *src)
Definition: preferences.h:21
float state
This member variable stores the last state that has passed through all filters.
Definition: sensor.h:131
ESPPreferences * global_preferences
void publish_state(float state)
Publish a new state to the front-end.
Definition: sensor.cpp:39
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