ESPHome 2026.5.0-dev
Loading...
Searching...
No Matches
template_time.cpp
Go to the documentation of this file.
1#include "template_time.h"
2
3#ifdef USE_DATETIME_TIME
4
5#include "esphome/core/log.h"
6
7namespace esphome::template_ {
8
9static const char *const TAG = "template.time";
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->hour_ = state.hour;
32 this->minute_ = state.minute;
33 this->second_ = state.second;
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->hour_ = val->hour;
44 this->minute_ = val->minute;
45 this->second_ = val->second;
46 this->publish_state();
47 }
48}
49
51 auto opt_hour = call.get_hour();
52 auto opt_minute = call.get_minute();
53 auto opt_second = call.get_second();
54 bool has_hour = opt_hour.has_value();
55 bool has_minute = opt_minute.has_value();
56 bool has_second = opt_second.has_value();
57
58 ESPTime value = {};
59 if (has_hour)
60 value.hour = *opt_hour;
61
62 if (has_minute)
63 value.minute = *opt_minute;
64
65 if (has_second)
66 value.second = *opt_second;
67
68 this->set_trigger_.trigger(value);
69
70 if (this->optimistic_) {
71 if (has_hour)
72 this->hour_ = *opt_hour;
73 if (has_minute)
74 this->minute_ = *opt_minute;
75 if (has_second)
76 this->second_ = *opt_second;
77 this->publish_state();
78 }
79
80 if (this->restore_value_) {
82 if (has_hour) {
83 temp.hour = *opt_hour;
84 } else {
85 temp.hour = this->hour_;
86 }
87 if (has_minute) {
88 temp.minute = *opt_minute;
89 } else {
90 temp.minute = this->minute_;
91 }
92 if (has_second) {
93 temp.second = *opt_second;
94 } else {
95 temp.second = this->second_;
96 }
97
98 this->pref_.save(&temp);
99 }
100}
101
103 LOG_DATETIME_TIME("", "Template Time", 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_TIME
ESPPreferenceObject make_entity_preference(uint32_t version=0)
Create a preference object for storing this entity's state/settings.
void trigger(const Ts &...x) ESPHOME_ALWAYS_INLINE
Inform the parent automation that the event has triggered.
Definition automation.h:482
TemplateLambda< ESPTime > f_
void control(const datetime::TimeCall &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 minute
minutes after the hour [0-59]
Definition time.h:32
uint8_t second
seconds after the minute [0-60]
Definition time.h:30
uint8_t hour
hours since midnight [0-23]
Definition time.h:34