ESPHome  2024.11.0
real_time_clock.cpp
Go to the documentation of this file.
1 #include "real_time_clock.h"
2 #include "esphome/core/log.h"
3 #ifdef USE_HOST
4 #include <sys/time.h>
5 #else
6 #include "lwip/opt.h"
7 #endif
8 #ifdef USE_ESP8266
9 #include "sys/time.h"
10 #endif
11 #ifdef USE_RP2040
12 #include <sys/time.h>
13 #endif
14 #include <cerrno>
15 
16 #include <cinttypes>
17 
18 namespace esphome {
19 namespace time {
20 
21 static const char *const TAG = "time";
22 
25  this->apply_timezone_();
27 }
28 void RealTimeClock::synchronize_epoch_(uint32_t epoch) {
29  // Update UTC epoch time.
30  struct timeval timev {
31  .tv_sec = static_cast<time_t>(epoch), .tv_usec = 0,
32  };
33  ESP_LOGVV(TAG, "Got epoch %" PRIu32, epoch);
34  struct timezone tz = {0, 0};
35  int ret = settimeofday(&timev, &tz);
36  if (ret == EINVAL) {
37  // Some ESP8266 frameworks abort when timezone parameter is not NULL
38  // while ESP32 expects it not to be NULL
39  ret = settimeofday(&timev, nullptr);
40  }
41 
42  // Move timezone back to local timezone.
43  this->apply_timezone_();
44 
45  if (ret != 0) {
46  ESP_LOGW(TAG, "setimeofday() failed with code %d", ret);
47  }
48 
49  auto time = this->now();
50  ESP_LOGD(TAG, "Synchronized time: %04d-%02d-%02d %02d:%02d:%02d", time.year, time.month, time.day_of_month, time.hour,
51  time.minute, time.second);
52 
53  this->time_sync_callback_.call();
54 }
55 
57  setenv("TZ", this->timezone_.c_str(), 1);
58  tzset();
59 }
60 
61 } // namespace time
62 } // 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:210
Implementation of SPI Controller mode.
Definition: a01nyub.cpp:7
void synchronize_epoch_(uint32_t epoch)
Report a unix epoch as current time.