ESPHome  2024.2.2
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 namespace esphome {
17 namespace time {
18 
19 static const char *const TAG = "time";
20 
23  this->apply_timezone_();
25 }
26 void RealTimeClock::synchronize_epoch_(uint32_t epoch) {
27  // Update UTC epoch time.
28  struct timeval timev {
29  .tv_sec = static_cast<time_t>(epoch), .tv_usec = 0,
30  };
31  ESP_LOGVV(TAG, "Got epoch %" PRIu32, epoch);
32  struct timezone tz = {0, 0};
33  int ret = settimeofday(&timev, &tz);
34  if (ret == EINVAL) {
35  // Some ESP8266 frameworks abort when timezone parameter is not NULL
36  // while ESP32 expects it not to be NULL
37  ret = settimeofday(&timev, nullptr);
38  }
39 
40  // Move timezone back to local timezone.
41  this->apply_timezone_();
42 
43  if (ret != 0) {
44  ESP_LOGW(TAG, "setimeofday() failed with code %d", ret);
45  }
46 
47  auto time = this->now();
48  ESP_LOGD(TAG, "Synchronized time: %04d-%02d-%02d %02d:%02d:%02d", time.year, time.month, time.day_of_month, time.hour,
49  time.minute, time.second);
50 
51  this->time_sync_callback_.call();
52 }
53 
55  setenv("TZ", this->timezone_.c_str(), 1);
56  tzset();
57 }
58 
59 } // namespace time
60 } // 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
This is a workaround until we can figure out a way to get the tflite-micro idf component code availab...
Definition: a01nyub.cpp:7
void synchronize_epoch_(uint32_t epoch)
Report a unix epoch as current time.