Merge pull request #325 from dirwin31:TimeZoneLookup

Time: Set the timezone automatically from GPS
This commit is contained in:
prabhaavp
2026-11-19 16:55:19 -05:00
committed by GitHub
10 changed files with 394 additions and 3 deletions
+1
View File
@@ -11,6 +11,7 @@ openpilot/selfdrive/modeld/models/big_*_tinygrad.pkl -text
*.woff -text
*.woff2 -text
*.wav -text
openpilot/common/timezone_grid.bin -text
openpilot/starpilot/galaxy/web/vendor/vue/vue.esm-browser.js -text
*.apk -text
openpilot/starpilot/galaxy/bin/hev-socks5-tunnel_linux_arm64 -text
+4
View File
@@ -15,6 +15,10 @@ provides source packages alongside the binaries.
Jetlink's comma client is copyright (c) 2026 Zeph Leggett and distributed under the MIT License. Its complete license and permission notice are retained in [jetlink_repo/LICENSE](jetlink_repo/LICENSE); source and revision are recorded in [CREDITS.md](CREDITS.md#jetlink-external-inference) and `upstream-sync.json`.
## Timezone boundaries
[`openpilot/common/timezone_grid.bin`](openpilot/common/timezone_grid.bin) is a grid derived from [timezone-boundary-builder](https://github.com/evansiroky/timezone-boundary-builder) release 2026f (`timezones.geojson`), which is made available under the [Open Database License](https://opendatacommons.org/licenses/odbl/1-0/) and contains data from © OpenStreetMap contributors. [`openpilot/tools/timezone_grid.py`](openpilot/tools/timezone_grid.py) rebuilds it from that release.
## MRR35 Hyundai angle and radar
The MRR35 radar generator and related Hyundai angle integration derive from the frozen StarPilot snapshot `678af783`, with relevant sunnypilot/opendbc angle-branch ancestry at `cc4b08625a98e94b318cab15e45e05dad58042bd`. Both upstream `LICENSE` and `LICENSE.md` were published for that source. Their scope is not unambiguous, so both applicable notices and the extension-file attribution are retained here without choosing between them. See [CREDITS.md](CREDITS.md) for the narrow source map.
@@ -0,0 +1,90 @@
import lzma
import struct
import pytest
from openpilot.common import time_helpers
from openpilot.common.timezone_lookup import COLS, ROWS, MAGIC, DEFAULT_PATH, TimezoneGrid, load_grid, pick_timezone
from openpilot.tools import timezone_grid
def test_timezone_lookup_regions():
grid = load_grid()
for lat, lon, zone in [(41.88, -87.63, "America/Chicago"), (52.13, -106.67, "America/Regina"),
(49.1, -116.51, "America/Creston"), (47.56, -52.71, "America/St_Johns"),
(53.28, -110.0, "America/Edmonton"), (31.76, -106.49, "America/Denver"),
(48.85, 2.35, "Europe/Paris"), (49.61, 6.13, "Europe/Luxembourg"), (60.17, 24.94, "Europe/Helsinki")]:
assert grid.candidates(lat, lon)[0] == zone
assert grid.candidates(0., -140.) == (None, set())
def test_pick_timezone_keeps_current_near_border():
grid = load_grid()
# Monaco cell borders France: an existing Paris zone is kept, anything else takes the cell's zone
assert pick_timezone(grid, 43.73, 7.42, "Europe/Paris") == "Europe/Paris"
assert pick_timezone(grid, 43.73, 7.42, "America/Los_Angeles") == "Europe/Monaco"
assert pick_timezone(grid, 0., -140., "America/Chicago") is None
def test_timezone_lookup_rejects_invalid_coordinates():
grid = load_grid()
for lat, lon in [(float("nan"), 0), (0, float("inf")), (91, 0), (-91, 0), (0, 181), (0, -181)]:
assert grid.candidates(lat, lon) == (None, set())
def test_grid_rejects_corrupt_data():
for data in [b"", b"not xz", lzma.compress(b"TZG1"), lzma.compress(struct.pack("<4sHHI", MAGIC, COLS, ROWS, 0))]:
with pytest.raises(ValueError):
TimezoneGrid(data)
@pytest.mark.parametrize("background", [False, True])
def test_builder_preserves_holes(monkeypatch, background):
monkeypatch.setattr(timezone_grid, "COLS", 10)
monkeypatch.setattr(timezone_grid, "ROWS", 10)
monkeypatch.setattr(timezone_grid, "RES", 1.)
def ring(left, top, right, bottom):
return [(left - 180, 90 - top), (right - 180, 90 - top), (right - 180, 90 - bottom), (left - 180, 90 - bottom)]
features = [{"properties": {"tzid": "Test/Zone"}, "geometry": {"type": "Polygon", "coordinates": [
ring(0, 0, 9, 9), ring(3, 3, 6, 6),
]}}]
if background:
features.append({"properties": {"tzid": "Test/Background"}, "geometry": {"type": "Polygon", "coordinates": [ring(0, 0, 10, 10)]}})
raw = lzma.decompress(timezone_grid.build(features))
_, cols, rows, name_len = struct.unpack_from("<4sHHI", raw)
pos = 12 + name_len
offsets = struct.unpack_from(f"<{rows + 1}I", raw, pos)
pos += (rows + 1) * 4
ends = struct.unpack_from(f"<{offsets[-1]}H", raw, pos)
zones = struct.unpack_from(f"<{offsets[-1]}H", raw, pos + offsets[-1] * 2)
assert (cols, rows) == (10, 10)
assert ends[offsets[4]:offsets[5]] == (3, 7, 10)
assert zones[offsets[4]:offsets[5]] == ((2, 1, 2) if background else (1, 0, 1))
def test_timezone_refresh_is_throttled(monkeypatch):
calls = []
now = iter([0., 1., 300.])
monkeypatch.setattr(time_helpers, "_next_tzset", 0.)
monkeypatch.setattr(time_helpers.time, "monotonic", lambda: next(now))
monkeypatch.setattr(time_helpers.time, "tzset", lambda: calls.append(True))
for _ in range(3):
time_helpers.refresh_local_timezone()
assert len(calls) == 2
@pytest.mark.parametrize("field", ["offset", "end", "zone"])
def test_grid_rejects_invalid_runs(field):
raw = bytearray(lzma.decompress(DEFAULT_PATH.read_bytes()))
name_len = struct.unpack_from("<I", raw, 8)[0]
offsets_pos = 12 + name_len
runs = struct.unpack_from("<I", raw, offsets_pos + ROWS * 4)[0]
ends_pos = offsets_pos + (ROWS + 1) * 4
if field == "offset":
struct.pack_into("<I", raw, offsets_pos, 1)
elif field == "end":
struct.pack_into("<H", raw, ends_pos, 0)
else:
struct.pack_into("<H", raw, ends_pos + runs * 2, 65535)
with pytest.raises(ValueError):
TimezoneGrid(lzma.compress(raw))
+11
View File
@@ -1,4 +1,5 @@
import datetime
import time
from pathlib import Path
MIN_DATE = datetime.datetime(year=2025, month=2, day=21)
@@ -14,3 +15,13 @@ def min_date():
def system_time_valid():
return min_date() < datetime.datetime.now() < MAX_DATE
_next_tzset = 0.
def refresh_local_timezone(interval=300.):
# Running processes only see a changed /etc/localtime after tzset().
global _next_tzset
now = time.monotonic()
if now >= _next_tzset:
_next_tzset = now + interval
time.tzset()
Binary file not shown.
+79
View File
@@ -0,0 +1,79 @@
"""Offline GPS to IANA timezone lookup from a run-length-encoded 0.02 degree grid."""
import lzma
import math
import struct
from array import array
from bisect import bisect_right
from functools import cache
from pathlib import Path
MAGIC = b"TZG1"
COLS, ROWS = 18000, 9000
RES = 360. / COLS
DEFAULT_PATH = Path(__file__).with_name("timezone_grid.bin")
class TimezoneGrid:
def __init__(self, data: bytes):
try:
raw = lzma.decompress(data)
except lzma.LZMAError as e:
raise ValueError("invalid compressed timezone grid") from e
if len(raw) < 12:
raise ValueError("truncated timezone grid")
if raw[:4] != MAGIC:
raise ValueError("bad timezone grid")
cols, rows, name_len = struct.unpack_from("<HHI", raw, 4)
if (cols, rows) != (COLS, ROWS):
raise ValueError("unexpected timezone grid size")
pos = 12
self.names = [""] + raw[pos:pos + name_len].decode().split("\n")
pos += name_len
if pos + (rows + 1) * 4 > len(raw):
raise ValueError("truncated timezone offsets")
self.offsets = array("I", raw[pos:pos + (rows + 1) * 4])
pos += (rows + 1) * 4
runs = self.offsets[-1]
if pos + runs * 4 != len(raw):
raise ValueError("invalid timezone run data")
self.ends = array("H", raw[pos:pos + runs * 2])
self.zones = array("H", raw[pos + runs * 2:pos + runs * 4])
if self.offsets[0] != 0 or any(a >= b for a, b in zip(self.offsets, self.offsets[1:], strict=False)):
raise ValueError("invalid timezone offsets")
if any(z >= len(self.names) for z in self.zones):
raise ValueError("invalid timezone index")
for row in range(rows):
ends = self.ends[self.offsets[row]:self.offsets[row + 1]]
if not ends or ends[0] == 0 or ends[-1] != COLS or any(a >= b for a, b in zip(ends, ends[1:], strict=False)):
raise ValueError("invalid timezone row")
def _cell(self, row: int, col: int) -> str | None:
if not 0 <= row < ROWS:
return None
col %= COLS
lo, hi = self.offsets[row], self.offsets[row + 1]
return self.names[self.zones[bisect_right(self.ends, col, lo, hi)]] or None
def candidates(self, lat: float, lon: float) -> tuple[str | None, set[str]]:
"""Zone at the point, plus every zone within one cell of it."""
if not math.isfinite(lat) or not math.isfinite(lon) or not -90 <= lat <= 90 or not -180 <= lon <= 180:
return None, set()
row = min(int((90. - lat) / RES), ROWS - 1)
col = int((lon + 180.) / RES)
center = self._cell(row, col)
near = {self._cell(row + dr, col + dc) for dr in (-1, 0, 1) for dc in (-1, 0, 1)}
return center, {z for z in near if z}
@cache
def load_grid(path: Path = DEFAULT_PATH) -> TimezoneGrid:
return TimezoneGrid(path.read_bytes())
def pick_timezone(grid: TimezoneGrid, lat: float, lon: float, current: str | None) -> str | None:
"""Keep the current zone while it is still plausible near a border."""
center, near = grid.candidates(lat, lon)
if current in near:
return current
return center
+2
View File
@@ -5,6 +5,7 @@ import time
from openpilot.cereal import messaging
from openpilot.common.hardware import COMMA_HARDWARE, HARDWARE
from openpilot.common.time_helpers import refresh_local_timezone
from openpilot.common.realtime import Priority, config_realtime_process, drop_realtime, set_core_affinity
from openpilot.system.ui.lib.application import gui_app
from openpilot.selfdrive.ui.layouts.main import MainLayout
@@ -19,6 +20,7 @@ BIG_UI = gui_app.big_ui()
def update_frame(preview=None, controllers=None, star=None, game_mode=None, arabesque=None):
gui_app.measure_frame_phase("ui_state", ui_state.update)
refresh_local_timezone()
if arabesque is not None:
arabesque()
if star is not None:
+64 -1
View File
@@ -1,5 +1,6 @@
import datetime
from openpilot.common.timezone_lookup import load_grid
from openpilot.system import timed
# drive 000000a8, 2026-11-09 04:15:03 CST
@@ -21,7 +22,8 @@ def test_learn_utc_offset():
assert timed.learn_utc_offset(local, A8_UTC - datetime.timedelta(days=100)) is None
def test_car_clock_to_utc():
def test_car_clock_to_utc(monkeypatch):
monkeypatch.setattr(timed, "current_timezone", lambda: None)
local = timed.parse_car_clock(A8_FRAME)
assert timed.car_clock_to_utc(local, datetime.timedelta(hours=-6)) == A8_UTC
assert timed.car_clock_to_utc(local, None) == A8_UTC
@@ -54,3 +56,64 @@ def test_delayed_clock_sample_does_not_claim_a_precise_pair(monkeypatch):
monkeypatch.setattr(timed, 'system_time_valid', lambda: True)
event = timed.clock_message()
assert event.clocks.deprecated.monotonicNanos == event.clocks.deprecated.bootTimeNanos == 0
def test_timezone_tracker_confirms_before_switching():
tracker = timed.TimezoneTracker(load_grid(), "America/Los_Angeles")
assert tracker.update(41.88, -87.63) is None
assert tracker.update(41.88, -87.63) == "America/Chicago"
# back in the current zone resets the pending switch
tracker = timed.TimezoneTracker(load_grid(), "America/Los_Angeles")
assert tracker.update(41.88, -87.63) is None
assert tracker.update(34.05, -118.24) is None
assert tracker.update(41.88, -87.63) is None
# no zone at sea keeps everything as is
assert tracker.update(0., -140.) is None
def test_current_timezone(tmp_path):
link = tmp_path / "localtime"
assert timed.current_timezone(str(link)) is None
link.symlink_to("/usr/share/zoneinfo/America/Chicago")
assert timed.current_timezone(str(link)) == "America/Chicago"
def test_set_timezone_swaps_link_and_name(monkeypatch):
calls = []
monkeypatch.setattr(timed.subprocess, 'run', lambda cmd, **kw: calls.append((cmd, kw.get('input'))))
monkeypatch.setattr(timed.os.path, 'isfile', lambda path: True)
assert timed.set_timezone("America/Chicago")
assert [c for c, _ in calls] == [
["sudo", "-n", "ln", "-sfn", "/usr/share/zoneinfo/America/Chicago", timed.LOCALTIME_PATH + ".tmp"],
["sudo", "-n", "mv", "-T", timed.LOCALTIME_PATH + ".tmp", timed.LOCALTIME_PATH],
["sudo", "-n", "tee", timed.TIMEZONE_NAME_PATH],
]
assert calls[-1][1] == "America/Chicago\n"
def test_set_timezone_rejects_bad_names(monkeypatch):
calls = []
monkeypatch.setattr(timed.subprocess, 'run', lambda cmd, **kw: calls.append(cmd))
monkeypatch.setattr(timed.os.path, 'isfile', lambda path: path.endswith("America/Chicago"))
assert not timed.set_timezone("../../etc/passwd")
assert not timed.set_timezone("Mars/Olympus")
assert not timed.set_timezone("/etc/passwd")
assert calls == []
def test_set_timezone_reports_sudo_failure(monkeypatch):
def fail(cmd, **kw):
raise timed.subprocess.CalledProcessError(1, cmd)
monkeypatch.setattr(timed.subprocess, 'run', fail)
monkeypatch.setattr(timed.os.path, 'isfile', lambda path: True)
assert not timed.set_timezone("America/Chicago")
def test_car_clock_uses_configured_timezone(monkeypatch):
monkeypatch.setattr(timed, "current_timezone", lambda: "America/New_York")
assert timed.car_clock_to_utc(datetime.datetime(2026, 7, 4, 12), None) == datetime.datetime(2026, 7, 4, 16)
def test_set_timezone_rejects_existing_absolute_path(monkeypatch):
monkeypatch.setattr(timed.os.path, "isfile", lambda path: True)
assert not timed.set_timezone("/etc/passwd")
+67 -2
View File
@@ -7,6 +7,7 @@ from typing import NoReturn
import openpilot.cereal.messaging as messaging
from openpilot.common.time_helpers import min_date, MAX_DATE, system_time_valid
from openpilot.common.timezone_lookup import load_grid, pick_timezone
from openpilot.common.swaglog import cloudlog
from openpilot.common.params import Params
from openpilot.common.gps import get_gps_location_service
@@ -31,6 +32,11 @@ CAR_CLOCK_LEARN_RETRY = 60.
CAR_CLOCK_MAX_DRIFT = datetime.timedelta(minutes=2)
MAX_UTC_OFFSET_MINUTES = 14 * 60
LOCALTIME_PATH = "/data/etc/localtime"
TIMEZONE_NAME_PATH = "/data/etc/timezone"
ZONEINFO_DIR = "/usr/share/zoneinfo"
TIMEZONE_CHECK_INTERVAL = 600.
def parse_car_clock(dat: bytes):
if len(dat) < 7 or dat[0] != CAR_CLOCK_MARKER:
@@ -98,7 +104,7 @@ def car_clock_to_utc(car_local, utc_offset):
if ZoneInfo is None:
return None
try:
tz = ZoneInfo(CAR_CLOCK_DEFAULT_TZ)
tz = ZoneInfo(current_timezone() or CAR_CLOCK_DEFAULT_TZ)
except Exception:
cloudlog.exception("timed.bad_timezone")
return None
@@ -106,6 +112,51 @@ def car_clock_to_utc(car_local, utc_offset):
return car_local.replace(tzinfo=tz, fold=0).astimezone(datetime.UTC).replace(tzinfo=None)
def current_timezone(path=LOCALTIME_PATH):
try:
target = os.readlink(path)
except OSError:
return None
prefix = ZONEINFO_DIR + "/"
return target[len(prefix):] if target.startswith(prefix) else None
def set_timezone(zone):
target = os.path.join(ZONEINFO_DIR, zone)
if not target.startswith(ZONEINFO_DIR + "/") or os.path.normpath(target) != target or not os.path.isfile(target):
cloudlog.error(f"timed: unknown timezone {zone}")
return False
tmp = LOCALTIME_PATH + ".tmp"
try:
for cmd in (["ln", "-sfn", target, tmp], ["mv", "-T", tmp, LOCALTIME_PATH]):
subprocess.run(["sudo", "-n", *cmd], check=True, timeout=5, stdin=subprocess.DEVNULL)
subprocess.run(["sudo", "-n", "tee", TIMEZONE_NAME_PATH], input=zone + "\n", text=True,
check=True, timeout=5, stdout=subprocess.DEVNULL)
except (OSError, subprocess.SubprocessError):
cloudlog.exception("timed.failed_setting_timezone")
return False
cloudlog.warning(f"timed: timezone set to {zone}")
return True
class TimezoneTracker:
"""Switch zones only when two checks in a row agree on the new one."""
def __init__(self, grid, current):
self.grid = grid
self.current = current
self.candidate = None
def update(self, lat, lon):
zone = pick_timezone(self.grid, lat, lon, self.current)
if zone is None or zone == self.current:
self.candidate = None
return None
if zone != self.candidate:
self.candidate = zone
return None
return zone
def set_time(new_time):
diff = datetime.datetime.now(datetime.UTC).replace(tzinfo=None) - new_time
if abs(diff) < datetime.timedelta(seconds=10):
@@ -135,8 +186,9 @@ def clock_message():
def main() -> NoReturn:
"""
timed has two responsibilities:
timed has three responsibilities:
- getting the current time from GPS, or the car's clock when GPS and NTP are unavailable
- setting the local timezone from the GPS position
- publishing the time in the logs
AGNOS will also use NTP to update the time.
@@ -152,6 +204,8 @@ def main() -> NoReturn:
utc_offset = load_utc_offset()
set_from_car_clock = False
next_offset_learn = 0.
tz_tracker = None
next_tz_check = 0.
while True:
sm.update(1000)
@@ -167,6 +221,17 @@ def main() -> NoReturn:
if gps_usable:
set_time(gps_time)
set_from_car_clock = False
if not PC and time.monotonic() >= next_tz_check:
next_tz_check = time.monotonic() + TIMEZONE_CHECK_INTERVAL
try:
if tz_tracker is None:
tz_tracker = TimezoneTracker(load_grid(), current_timezone())
zone = tz_tracker.update(gps.latitude, gps.longitude)
if zone is not None and set_timezone(zone):
tz_tracker.current = zone
except (OSError, ValueError):
cloudlog.exception("timed.failed_timezone_lookup")
elif not system_time_valid():
car_local = read_car_clock(can_sock)
car_utc = car_clock_to_utc(car_local, utc_offset) if car_local is not None else None
+76
View File
@@ -0,0 +1,76 @@
#!/usr/bin/env python3
"""Build timezone_grid.bin from timezone-boundary-builder's timezones.geojson: timezone_grid.py combined.json [out]"""
import json
import lzma
import math
import struct
import sys
from pathlib import Path
import numpy as np
from PIL import Image, ImageDraw
from openpilot.common.timezone_lookup import COLS, ROWS, MAGIC, RES, DEFAULT_PATH
def polygons(geometry):
if geometry["type"] == "Polygon":
return [geometry["coordinates"]]
return geometry["coordinates"]
def to_px(ring):
return [((lon + 180.) / RES, (90. - lat) / RES) for lon, lat in ring]
def area(ring):
xs, ys = np.asarray(ring).T
return abs(np.dot(xs, np.roll(ys, 1)) - np.dot(ys, np.roll(xs, 1))) / 2
def build(features):
names = sorted({f["properties"]["tzid"] for f in features})
index = {name: i + 1 for i, name in enumerate(names)}
shapes = [(area(poly[0]), index[f["properties"]["tzid"]], poly)
for f in features for poly in polygons(f["geometry"])]
# Largest first so enclaves drawn later win over the zone around them.
shapes.sort(key=lambda s: -s[0])
img = Image.new("I", (COLS, ROWS), 0)
for _, zone, poly in shapes:
exterior = to_px(poly[0])
xs, ys = zip(*exterior, strict=True)
left, top = max(0, math.floor(min(xs))), max(0, math.floor(min(ys)))
right, bottom = min(COLS, math.floor(max(xs)) + 1), min(ROWS, math.floor(max(ys)) + 1)
if right <= left or bottom <= top:
continue
mask = Image.new("1", (right - left, bottom - top))
draw = ImageDraw.Draw(mask)
for i, ring in enumerate(poly):
draw.polygon([(x - left, y - top) for x, y in to_px(ring)], fill=int(i == 0))
img.paste(zone, (left, top, right, bottom), mask)
grid = np.asarray(img, dtype=np.int32)
ends, zones, offsets = [], [], [0]
for row in grid:
change = np.flatnonzero(np.diff(row)) + 1
ends.extend(np.append(change, COLS).tolist())
zones.extend(row[np.insert(change, 0, 0)].tolist())
offsets.append(len(ends))
name_blob = "\n".join(names).encode()
raw = b"".join([
MAGIC, struct.pack("<HHI", COLS, ROWS, len(name_blob)), name_blob,
np.asarray(offsets, dtype="<u4").tobytes(),
np.asarray(ends, dtype="<u2").tobytes(),
np.asarray(zones, dtype="<u2").tobytes(),
])
return lzma.compress(raw, preset=9 | lzma.PRESET_EXTREME)
if __name__ == "__main__":
out = Path(sys.argv[2]) if len(sys.argv) > 2 else DEFAULT_PATH
with open(sys.argv[1]) as f:
data = build(json.load(f)["features"])
out.write_bytes(data)
print(f"wrote {out} ({len(data) / 1e6:.2f} MB)")