ESPHome
2025.5.0
Loading...
Searching...
No Matches
esphome
components
time
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
18
namespace
esphome
{
19
namespace
time {
20
21
static
const
char
*
const
TAG
=
"time"
;
22
23
RealTimeClock::RealTimeClock
() =
default
;
24
void
RealTimeClock::synchronize_epoch_
(uint32_t epoch) {
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
52
void
RealTimeClock::apply_timezone_
() {
53
setenv(
"TZ"
, this->
timezone_
.c_str(), 1);
54
tzset();
55
}
56
57
}
// namespace time
58
}
// namespace esphome
esphome::time::RealTimeClock::time_sync_callback_
CallbackManager< void()> time_sync_callback_
Definition
real_time_clock.h:52
esphome::time::RealTimeClock::now
ESPTime now()
Get the time in the currently defined timezone.
Definition
real_time_clock.h:33
esphome::time::RealTimeClock::apply_timezone_
void apply_timezone_()
Definition
real_time_clock.cpp:52
esphome::time::RealTimeClock::timezone_
std::string timezone_
Definition
real_time_clock.h:49
esphome::time::RealTimeClock::RealTimeClock
RealTimeClock()
esphome::time::RealTimeClock::synchronize_epoch_
void synchronize_epoch_(uint32_t epoch)
Report a unix epoch as current time.
Definition
real_time_clock.cpp:24
log.h
esphome::spi::TAG
const char *const TAG
Definition
spi.cpp:8
esphome
Providing packet encoding functions for exchanging data with a remote host.
Definition
a01nyub.cpp:7
real_time_clock.h
Generated by
1.12.0