ESPHome 2026.3.3
Loading...
Searching...
No Matches
template_date.cpp
Go to the documentation of this file.
1#include "template_date.h"
2
3#ifdef USE_DATETIME_DATE
4
5#include "esphome/core/log.h"
6
7namespace esphome::template_ {
8
9static const char *const TAG = "template.date";
10
12 if (this->f_.has_value())
13 return;
14
15 ESPTime state{};
16
17 if (!this->restore_value_) {
18 state = this->initial_value_;
19 } else {
22 if (this->pref_.load(&temp)) {
23 temp.apply(this);
24 return;
25 } else {
26 // set to inital value if loading from pref failed
27 state = this->initial_value_;
28 }
29 }
30
31 this->year_ = state.year;
32 this->month_ = state.month;
33 this->day_ = state.day_of_month;
34 this->publish_state();
35}
36
38 if (!this->f_.has_value())
39 return;
40
41 auto val = this->f_();
42 if (val.has_value()) {
43 this->year_ = val->year;
44 this->month_ = val->month;
45 this->day_ = val->day_of_month;
46 this->publish_state();
47 }
48}
49
51 auto opt_year = call.get_year();
52 auto opt_month = call.get_month();
53 auto opt_day = call.get_day();
54 bool has_year = opt_year.has_value();
55 bool has_month = opt_month.has_value();
56 bool has_day = opt_day.has_value();
57
58 ESPTime value = {};
59 if (has_year)
60 value.year = *opt_year;
61
62 if (has_month)
63 value.month = *opt_month;
64
65 if (has_day)
66 value.day_of_month = *opt_day;
67
68 this->set_trigger_.trigger(value);
69
70 if (this->optimistic_) {
71 if (has_year)
72 this->year_ = *opt_year;
73 if (has_month)
74 this->month_ = *opt_month;
75 if (has_day)
76 this->day_ = *opt_day;
77 this->publish_state();
78 }
79
80 if (this->restore_value_) {
82 if (has_year) {
83 temp.year = *opt_year;
84 } else {
85 temp.year = this->year_;
86 }
87 if (has_month) {
88 temp.month = *opt_month;
89 } else {
90 temp.month = this->month_;
91 }
92 if (has_day) {
93 temp.day = *opt_day;
94 } else {
95 temp.day = this->day_;
96 }
97
98 this->pref_.save(&temp);
99 }
100}
101
103 LOG_DATETIME_DATE("", "Template Date", this);
104 ESP_LOGCONFIG(TAG, " Optimistic: %s", YESNO(this->optimistic_));
105 LOG_UPDATE_INTERVAL(this);
106}
107
108} // namespace esphome::template_
109
110#endif // USE_DATETIME_DATE
bool save(const T *src)
Definition preferences.h:21
ESPPreferenceObject make_entity_preference(uint32_t version=0)
Create a preference object for storing this entity's state/settings.
void trigger(const Ts &...x)
Inform the parent automation that the event has triggered.
Definition automation.h:325
TemplateLambda< ESPTime > f_
void control(const datetime::DateCall &call) override
bool state
Definition fan.h:2
mopeka_std_values val[3]
const char *const TAG
Definition spi.cpp:7
A more user-friendly version of struct tm from time.h.
Definition time.h:23
uint8_t day_of_month
day of the month [1-31]
Definition time.h:38
uint16_t year
year
Definition time.h:44
uint8_t month
month; january=1 [1-12]
Definition time.h:42