ESPHome  2022.6.3
real_time_clock.cpp
Go to the documentation of this file.
1 #include "real_time_clock.h"
2 #include "esphome/core/log.h"
3 #include "lwip/opt.h"
4 #ifdef USE_ESP8266
5 #include "sys/time.h"
6 #endif
7 #include <cerrno>
8 
9 namespace esphome {
10 namespace time {
11 
12 static const char *const TAG = "time";
13 
16  this->apply_timezone_();
18 }
19 void RealTimeClock::synchronize_epoch_(uint32_t epoch) {
20  // Update UTC epoch time.
21  struct timeval timev {
22  .tv_sec = static_cast<time_t>(epoch), .tv_usec = 0,
23  };
24  ESP_LOGVV(TAG, "Got epoch %u", epoch);
25  timezone tz = {0, 0};
26  int ret = settimeofday(&timev, &tz);
27  if (ret == EINVAL) {
28  // Some ESP8266 frameworks abort when timezone parameter is not NULL
29  // while ESP32 expects it not to be NULL
30  ret = settimeofday(&timev, nullptr);
31  }
32 
33  // Move timezone back to local timezone.
34  this->apply_timezone_();
35 
36  if (ret != 0) {
37  ESP_LOGW(TAG, "setimeofday() failed with code %d", ret);
38  }
39 
40  auto time = this->now();
41  ESP_LOGD(TAG, "Synchronized time: %04d-%02d-%02d %02d:%02d:%02d", time.year, time.month, time.day_of_month, time.hour,
42  time.minute, time.second);
43 
44  this->time_sync_callback_.call();
45 }
46 
48  setenv("TZ", this->timezone_.c_str(), 1);
49  tzset();
50 }
51 
52 size_t ESPTime::strftime(char *buffer, size_t buffer_len, const char *format) {
53  struct tm c_tm = this->to_c_tm();
54  return ::strftime(buffer, buffer_len, format, &c_tm);
55 }
56 ESPTime ESPTime::from_c_tm(struct tm *c_tm, time_t c_time) {
57  ESPTime res{};
58  res.second = uint8_t(c_tm->tm_sec);
59  res.minute = uint8_t(c_tm->tm_min);
60  res.hour = uint8_t(c_tm->tm_hour);
61  res.day_of_week = uint8_t(c_tm->tm_wday + 1);
62  res.day_of_month = uint8_t(c_tm->tm_mday);
63  res.day_of_year = uint16_t(c_tm->tm_yday + 1);
64  res.month = uint8_t(c_tm->tm_mon + 1);
65  res.year = uint16_t(c_tm->tm_year + 1900);
66  res.is_dst = bool(c_tm->tm_isdst);
67  res.timestamp = c_time;
68  return res;
69 }
70 struct tm ESPTime::to_c_tm() {
71  struct tm c_tm {};
72  c_tm.tm_sec = this->second;
73  c_tm.tm_min = this->minute;
74  c_tm.tm_hour = this->hour;
75  c_tm.tm_mday = this->day_of_month;
76  c_tm.tm_mon = this->month - 1;
77  c_tm.tm_year = this->year - 1900;
78  c_tm.tm_wday = this->day_of_week - 1;
79  c_tm.tm_yday = this->day_of_year - 1;
80  c_tm.tm_isdst = this->is_dst;
81  return c_tm;
82 }
83 std::string ESPTime::strftime(const std::string &format) {
84  std::string timestr;
85  timestr.resize(format.size() * 4);
86  struct tm c_tm = this->to_c_tm();
87  size_t len = ::strftime(&timestr[0], timestr.size(), format.c_str(), &c_tm);
88  while (len == 0) {
89  timestr.resize(timestr.size() * 2);
90  len = ::strftime(&timestr[0], timestr.size(), format.c_str(), &c_tm);
91  }
92  timestr.resize(len);
93  return timestr;
94 }
95 
96 template<typename T> bool increment_time_value(T &current, uint16_t begin, uint16_t end) {
97  current++;
98  if (current >= end) {
99  current = begin;
100  return true;
101  }
102  return false;
103 }
104 
105 static bool is_leap_year(uint32_t year) { return (year % 4) == 0 && ((year % 100) != 0 || (year % 400) == 0); }
106 
107 static uint8_t days_in_month(uint8_t month, uint16_t year) {
108  static const uint8_t DAYS_IN_MONTH[] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
109  uint8_t days = DAYS_IN_MONTH[month];
110  if (month == 2 && is_leap_year(year))
111  return 29;
112  return days;
113 }
114 
116  this->timestamp++;
117  if (!increment_time_value(this->second, 0, 60))
118  return;
119 
120  // second roll-over, increment minute
121  if (!increment_time_value(this->minute, 0, 60))
122  return;
123 
124  // minute roll-over, increment hour
125  if (!increment_time_value(this->hour, 0, 24))
126  return;
127 
128  // hour roll-over, increment day
129  increment_time_value(this->day_of_week, 1, 8);
130 
131  if (increment_time_value(this->day_of_month, 1, days_in_month(this->month, this->year) + 1)) {
132  // day of month roll-over, increment month
133  increment_time_value(this->month, 1, 13);
134  }
135 
136  uint16_t days_in_year = (this->year % 4 == 0) ? 366 : 365;
137  if (increment_time_value(this->day_of_year, 1, days_in_year + 1)) {
138  // day of year roll-over, increment year
139  this->year++;
140  }
141 }
143  this->timestamp += 86400;
144 
145  // increment day
146  increment_time_value(this->day_of_week, 1, 8);
147 
148  if (increment_time_value(this->day_of_month, 1, days_in_month(this->month, this->year) + 1)) {
149  // day of month roll-over, increment month
150  increment_time_value(this->month, 1, 13);
151  }
152 
153  uint16_t days_in_year = (this->year % 4 == 0) ? 366 : 365;
154  if (increment_time_value(this->day_of_year, 1, days_in_year + 1)) {
155  // day of year roll-over, increment year
156  this->year++;
157  }
158 }
159 void ESPTime::recalc_timestamp_utc(bool use_day_of_year) {
160  time_t res = 0;
161 
162  if (!this->fields_in_range()) {
163  this->timestamp = -1;
164  return;
165  }
166 
167  for (int i = 1970; i < this->year; i++)
168  res += is_leap_year(i) ? 366 : 365;
169 
170  if (use_day_of_year) {
171  res += this->day_of_year - 1;
172  } else {
173  for (int i = 1; i < this->month; i++)
174  res += days_in_month(i, this->year);
175 
176  res += this->day_of_month - 1;
177  }
178 
179  res *= 24;
180  res += this->hour;
181  res *= 60;
182  res += this->minute;
183  res *= 60;
184  res += this->second;
185  this->timestamp = res;
186 }
187 
189  int32_t offset = 0;
190  time_t now = ::time(nullptr);
191  auto local = ESPTime::from_epoch_local(now);
192  auto utc = ESPTime::from_epoch_utc(now);
193  bool negative = utc.hour > local.hour && local.day_of_year <= utc.day_of_year;
194 
195  if (utc.minute > local.minute) {
196  local.minute += 60;
197  local.hour -= 1;
198  }
199  offset += (local.minute - utc.minute) * 60;
200 
201  if (negative) {
202  offset -= (utc.hour - local.hour) * 3600;
203  } else {
204  if (utc.hour > local.hour) {
205  local.hour += 24;
206  }
207  offset += (local.hour - utc.hour) * 3600;
208  }
209  return offset;
210 }
211 
212 bool ESPTime::operator<(ESPTime other) { return this->timestamp < other.timestamp; }
213 bool ESPTime::operator<=(ESPTime other) { return this->timestamp <= other.timestamp; }
214 bool ESPTime::operator==(ESPTime other) { return this->timestamp == other.timestamp; }
215 bool ESPTime::operator>=(ESPTime other) { return this->timestamp >= other.timestamp; }
216 bool ESPTime::operator>(ESPTime other) { return this->timestamp > other.timestamp; }
217 
218 } // namespace time
219 } // namespace esphome
ESPTime now()
Get the time in the currently defined timezone.
time_t timestamp
unix epoch time (seconds since UTC Midnight January 1, 1970)
static ESPTime from_c_tm(struct tm *c_tm, time_t c_time)
Convert a C tm struct instance with a C unix epoch timestamp to an ESPTime instance.
size_t strftime(char *buffer, size_t buffer_len, const char *format)
Convert this ESPTime struct to a null-terminated c string buffer as specified by the format argument...
void increment_second()
Increment this clock instance by one second.
bool increment_time_value(T &current, uint16_t begin, uint16_t end)
static ESPTime from_epoch_local(time_t epoch)
Convert an UTC epoch timestamp to a local time ESPTime instance.
CallbackManager< void()> time_sync_callback_
void increment_day()
Increment this clock instance by one day.
A more user-friendly version of struct tm from time.h.
bool operator<=(ESPTime other)
static ESPTime from_epoch_utc(time_t epoch)
Convert an UTC epoch timestamp to a UTC time ESPTime instance.
uint8_t second
seconds after the minute [0-60]
bool operator==(ESPTime other)
bool operator>(ESPTime other)
bool operator<(ESPTime other)
void call_setup() override
Definition: component.cpp:182
std::string size_t len
Definition: helpers.h:278
Definition: a4988.cpp:4
void synchronize_epoch_(uint32_t epoch)
Report a unix epoch as current time.
void recalc_timestamp_utc(bool use_day_of_year=true)
Recalculate the timestamp field from the other fields of this ESPTime instance (must be UTC)...
static int32_t timezone_offset()
bool operator>=(ESPTime other)