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