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