ESPHome  2023.11.6
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 #ifdef USE_RP2040
8 #include <sys/time.h>
9 #endif
10 #include <cerrno>
11 
12 namespace esphome {
13 namespace time {
14 
15 static const char *const TAG = "time";
16 
19  this->apply_timezone_();
21 }
22 void RealTimeClock::synchronize_epoch_(uint32_t epoch) {
23  // Update UTC epoch time.
24  struct timeval timev {
25  .tv_sec = static_cast<time_t>(epoch), .tv_usec = 0,
26  };
27  ESP_LOGVV(TAG, "Got epoch %" PRIu32, epoch);
28  timezone tz = {0, 0};
29  int ret = settimeofday(&timev, &tz);
30  if (ret == EINVAL) {
31  // Some ESP8266 frameworks abort when timezone parameter is not NULL
32  // while ESP32 expects it not to be NULL
33  ret = settimeofday(&timev, nullptr);
34  }
35 
36  // Move timezone back to local timezone.
37  this->apply_timezone_();
38 
39  if (ret != 0) {
40  ESP_LOGW(TAG, "setimeofday() failed with code %d", ret);
41  }
42 
43  auto time = this->now();
44  ESP_LOGD(TAG, "Synchronized time: %04d-%02d-%02d %02d:%02d:%02d", time.year, time.month, time.day_of_month, time.hour,
45  time.minute, time.second);
46 
47  this->time_sync_callback_.call();
48 }
49 
51  setenv("TZ", this->timezone_.c_str(), 1);
52  tzset();
53 }
54 
55 } // namespace time
56 } // namespace esphome
ESPTime now()
Get the time in the currently defined timezone.
CallbackManager< void()> time_sync_callback_
const char *const TAG
Definition: spi.cpp:8
void call_setup() override
Definition: component.cpp:187
Implementation of SPI Controller mode.
Definition: a01nyub.cpp:7
void synchronize_epoch_(uint32_t epoch)
Report a unix epoch as current time.