On epoch sync, restore local TZ (#3462)

Co-authored-by: Maurice Makaay <mmakaay1@xs4all.net>
This commit is contained in:
Maurice Makaay 2022-05-11 23:25:00 +02:00 committed by Jesse Hills
parent c2a59cb476
commit 63096ac2bc
No known key found for this signature in database
GPG key ID: BEAAE804EFD8E83A
2 changed files with 11 additions and 2 deletions

View file

@ -13,11 +13,11 @@ static const char *const TAG = "time";
RealTimeClock::RealTimeClock() = default;
void RealTimeClock::call_setup() {
setenv("TZ", this->timezone_.c_str(), 1);
tzset();
this->apply_timezone_();
PollingComponent::call_setup();
}
void RealTimeClock::synchronize_epoch_(uint32_t epoch) {
// Update UTC epoch time.
struct timeval timev {
.tv_sec = static_cast<time_t>(epoch), .tv_usec = 0,
};
@ -30,6 +30,9 @@ void RealTimeClock::synchronize_epoch_(uint32_t epoch) {
ret = settimeofday(&timev, nullptr);
}
// Move timezone back to local timezone.
this->apply_timezone_();
if (ret != 0) {
ESP_LOGW(TAG, "setimeofday() failed with code %d", ret);
}
@ -41,6 +44,11 @@ void RealTimeClock::synchronize_epoch_(uint32_t epoch) {
this->time_sync_callback_.call();
}
void RealTimeClock::apply_timezone_() {
setenv("TZ", this->timezone_.c_str(), 1);
tzset();
}
size_t ESPTime::strftime(char *buffer, size_t buffer_len, const char *format) {
struct tm c_tm = this->to_c_tm();
return ::strftime(buffer, buffer_len, format, &c_tm);

View file

@ -137,6 +137,7 @@ class RealTimeClock : public PollingComponent {
void synchronize_epoch_(uint32_t epoch);
std::string timezone_{};
void apply_timezone_();
CallbackManager<void()> time_sync_callback_;
};