2024-01-23 10:35:11 +08:00
|
|
|
#!/usr/bin/env python3
|
|
|
|
import datetime
|
|
|
|
import subprocess
|
|
|
|
import time
|
|
|
|
from typing import NoReturn
|
|
|
|
|
|
|
|
import cereal.messaging as messaging
|
2024-03-31 08:47:21 +08:00
|
|
|
from openpilot.common.time import system_time_valid
|
2024-01-23 10:35:11 +08:00
|
|
|
from openpilot.common.swaglog import cloudlog
|
2024-08-23 14:30:29 +08:00
|
|
|
from openpilot.common.params import Params
|
|
|
|
from openpilot.common.gps import get_gps_location_service
|
2024-01-23 10:35:11 +08:00
|
|
|
|
|
|
|
|
|
|
|
def set_time(new_time):
|
|
|
|
diff = datetime.datetime.now() - new_time
|
|
|
|
if diff < datetime.timedelta(seconds=10):
|
|
|
|
cloudlog.debug(f"Time diff too small: {diff}")
|
|
|
|
return
|
|
|
|
|
|
|
|
cloudlog.debug(f"Setting time to {new_time}")
|
|
|
|
try:
|
|
|
|
subprocess.run(f"TZ=UTC date -s '{new_time}'", shell=True, check=True)
|
|
|
|
except subprocess.CalledProcessError:
|
|
|
|
cloudlog.exception("timed.failed_setting_time")
|
|
|
|
|
|
|
|
|
|
|
|
def main() -> NoReturn:
|
|
|
|
"""
|
2024-06-20 11:34:57 +08:00
|
|
|
timed has one responsibility:
|
2024-01-23 10:35:11 +08:00
|
|
|
- getting the current time
|
|
|
|
|
2024-06-20 11:34:57 +08:00
|
|
|
GPS directly gives time.
|
2024-01-23 10:35:11 +08:00
|
|
|
AGNOS will also use NTP to update the time.
|
|
|
|
"""
|
|
|
|
|
2024-08-23 14:30:29 +08:00
|
|
|
params = Params()
|
|
|
|
gps_location_service = get_gps_location_service(params)
|
|
|
|
|
2024-02-14 06:22:46 +08:00
|
|
|
pm = messaging.PubMaster(['clocks'])
|
2024-08-23 14:30:29 +08:00
|
|
|
sm = messaging.SubMaster([gps_location_service])
|
2024-01-23 10:35:11 +08:00
|
|
|
while True:
|
|
|
|
sm.update(1000)
|
|
|
|
|
2024-03-31 08:47:21 +08:00
|
|
|
msg = messaging.new_message('clocks')
|
|
|
|
msg.valid = system_time_valid()
|
2024-02-14 06:22:46 +08:00
|
|
|
msg.clocks.wallTimeNanos = time.time_ns()
|
|
|
|
pm.send('clocks', msg)
|
|
|
|
|
2024-08-23 14:30:29 +08:00
|
|
|
gps = sm[gps_location_service]
|
|
|
|
if not sm.updated[gps_location_service] or (time.monotonic() - sm.logMonoTime[gps_location_service] / 1e9) > 2.0:
|
2024-01-23 10:35:11 +08:00
|
|
|
continue
|
|
|
|
|
|
|
|
# set time
|
|
|
|
# TODO: account for unixTimesatmpMillis being a (usually short) time in the past
|
2024-08-23 14:30:29 +08:00
|
|
|
gps_time = datetime.datetime.fromtimestamp(gps.unixTimestampMillis / 1000.)
|
2024-01-23 10:35:11 +08:00
|
|
|
set_time(gps_time)
|
|
|
|
|
|
|
|
time.sleep(10)
|
|
|
|
|
|
|
|
if __name__ == "__main__":
|
|
|
|
main()
|