ESPHome 2025.5.0
Loading...
Searching...
No Matches
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
18namespace esphome {
19namespace time {
20
21static const char *const TAG = "time";
22
25 // Update UTC epoch time.
26 struct timeval timev {
27 .tv_sec = static_cast<time_t>(epoch), .tv_usec = 0,
28 };
29 ESP_LOGVV(TAG, "Got epoch %" PRIu32, epoch);
30 struct timezone tz = {0, 0};
31 int ret = settimeofday(&timev, &tz);
32 if (ret == EINVAL) {
33 // Some ESP8266 frameworks abort when timezone parameter is not NULL
34 // while ESP32 expects it not to be NULL
35 ret = settimeofday(&timev, nullptr);
36 }
37
38 // Move timezone back to local timezone.
39 this->apply_timezone_();
40
41 if (ret != 0) {
42 ESP_LOGW(TAG, "setimeofday() failed with code %d", ret);
43 }
44
45 auto time = this->now();
46 ESP_LOGD(TAG, "Synchronized time: %04d-%02d-%02d %02d:%02d:%02d", time.year, time.month, time.day_of_month, time.hour,
47 time.minute, time.second);
48
49 this->time_sync_callback_.call();
50}
51
53 setenv("TZ", this->timezone_.c_str(), 1);
54 tzset();
55}
56
57} // namespace time
58} // namespace esphome
CallbackManager< void()> time_sync_callback_
ESPTime now()
Get the time in the currently defined timezone.
void synchronize_epoch_(uint32_t epoch)
Report a unix epoch as current time.
const char *const TAG
Definition spi.cpp:8
Providing packet encoding functions for exchanging data with a remote host.
Definition a01nyub.cpp:7