ESPHome 2026.1.0-dev
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#elif defined(USE_ZEPHYR)
6#include <zephyr/posix/time.h>
7#else
8#include "lwip/opt.h"
9#endif
10#ifdef USE_ESP8266
11#include "sys/time.h"
12#endif
13#if defined(USE_RP2040) || defined(USE_ZEPHYR)
14#include <sys/time.h>
15#endif
16#include <cerrno>
17
18#include <cinttypes>
19
20namespace esphome::time {
21
22static const char *const TAG = "time";
23
25
27#ifdef USE_TIME_TIMEZONE
28 ESP_LOGCONFIG(TAG, "Timezone: '%s'", this->timezone_.c_str());
29#endif
30}
31
33 ESP_LOGVV(TAG, "Got epoch %" PRIu32, epoch);
34 // Update UTC epoch time.
35#ifdef USE_ZEPHYR
36 struct timespec ts;
37 ts.tv_nsec = 0;
38 ts.tv_sec = static_cast<time_t>(epoch);
39
40 int ret = clock_settime(CLOCK_REALTIME, &ts);
41
42 if (ret != 0) {
43 ESP_LOGW(TAG, "clock_settime() failed with code %d", ret);
44 }
45#else
46 struct timeval timev {
47 .tv_sec = static_cast<time_t>(epoch), .tv_usec = 0,
48 };
49 struct timezone tz = {0, 0};
50 int ret = settimeofday(&timev, &tz);
51 if (ret == EINVAL) {
52 // Some ESP8266 frameworks abort when timezone parameter is not NULL
53 // while ESP32 expects it not to be NULL
54 ret = settimeofday(&timev, nullptr);
55 }
56
57#ifdef USE_TIME_TIMEZONE
58 // Move timezone back to local timezone.
59 this->apply_timezone_();
60#endif
61
62 if (ret != 0) {
63 ESP_LOGW(TAG, "setimeofday() failed with code %d", ret);
64 }
65#endif
66 auto time = this->now();
67 ESP_LOGD(TAG, "Synchronized time: %04d-%02d-%02d %02d:%02d:%02d", time.year, time.month, time.day_of_month, time.hour,
68 time.minute, time.second);
69
70 this->time_sync_callback_.call();
71}
72
73#ifdef USE_TIME_TIMEZONE
75 setenv("TZ", this->timezone_.c_str(), 1);
76 tzset();
77}
78#endif
79
80} // namespace esphome::time
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:7