From b1fbb3067d0b594cfb81243a0204efbcda127bec Mon Sep 17 00:00:00 2001 From: deanlee Date: Thu, 25 Nov 2021 14:14:21 +0800 Subject: [PATCH] sync_time --- selfdrive/boardd/boardd.cc | 54 ++++++++++++++++++-------------------- 1 file changed, 26 insertions(+), 28 deletions(-) diff --git a/selfdrive/boardd/boardd.cc b/selfdrive/boardd/boardd.cc index bbaf28ca67..b68a18b6c2 100644 --- a/selfdrive/boardd/boardd.cc +++ b/selfdrive/boardd/boardd.cc @@ -78,6 +78,29 @@ bool check_all_connected(const std::vector &pandas) { return true; } +void sync_time(Panda *panda) { + if (!panda->has_rtc) return; + + setenv("TZ", "UTC", 1); + struct tm sys_time = util::get_time(); + struct tm rtc_time = panda->get_rtc(); + + if (util::time_valid(sys_time)) { + // Write time to RTC if it looks reasonable + double seconds = difftime(mktime(&rtc_time), mktime(&sys_time)); + if (std::abs(seconds) > 1.1) { + panda->set_rtc(sys_time); + LOGW("Updating panda RTC. dt = %.2f System: %s RTC: %s", + seconds, get_time_str(sys_time).c_str(), get_time_str(rtc_time).c_str()); + } + } else if (util::time_valid(rtc_time)) { + const struct timeval tv = {mktime(&rtc_time), 0}; + settimeofday(&tv, 0); + LOGE("System time wrong, setting from RTC. System: %s RTC: %s", + get_time_str(sys_time).c_str(), get_time_str(rtc_time).c_str()); + } +} + bool safety_setter_thread(std::vector pandas) { LOGD("Starting safety setter thread"); @@ -171,19 +194,7 @@ Panda *usb_connect(std::string serial="", uint32_t index=0) { std::call_once(connected_once, &Panda::set_usb_power_mode, panda, cereal::PeripheralState::UsbPowerMode::CDP); #endif - if (panda->has_rtc) { - setenv("TZ","UTC",1); - struct tm sys_time = util::get_time(); - struct tm rtc_time = panda->get_rtc(); - - if (!util::time_valid(sys_time) && util::time_valid(rtc_time)) { - LOGE("System time wrong, setting from RTC. System: %s RTC: %s", - get_time_str(sys_time).c_str(), get_time_str(rtc_time).c_str()); - const struct timeval tv = {mktime(&rtc_time), 0}; - settimeofday(&tv, 0); - } - } - + sync_time(panda.get()); return panda.release(); } @@ -516,21 +527,8 @@ void peripheral_control_thread(Panda *panda) { } // Write to rtc once per minute when no ignition present - if ((panda->has_rtc) && !ignition && (cnt % 120 == 1)) { - // Write time to RTC if it looks reasonable - setenv("TZ","UTC",1); - struct tm sys_time = util::get_time(); - - if (util::time_valid(sys_time)) { - struct tm rtc_time = panda->get_rtc(); - double seconds = difftime(mktime(&rtc_time), mktime(&sys_time)); - - if (std::abs(seconds) > 1.1) { - panda->set_rtc(sys_time); - LOGW("Updating panda RTC. dt = %.2f System: %s RTC: %s", - seconds, get_time_str(sys_time).c_str(), get_time_str(rtc_time).c_str()); - } - } + if (!ignition && (cnt % 120 == 1)) { + sync_time(panda); } } }