feat(timezones): public IANA timezone table with POSIX rules for device clocks

Firmware 3.0.0+ (project-vesper F-079) keeps the RTC in UTC and, in
timezone mode "auto", evaluates a POSIX TZ rule string sent by whoever sets
the timezone. Devices don't carry the IANA database and POSIX signs are
inverted, so the console and apps need one place to get the right rule.

GET /api/public/timezones[?country=GR] returns every country with its zones
(zone.tab), each with the POSIX rule (TZif footer), std/DST offsets in
minutes east of UTC, and the current offset/DST state.
GET /api/public/timezones/zone?name=... resolves one zone, including
aliases zone.tab doesn't list (e.g. a phone reporting Asia/Calcutta).

Public on purpose: IANA data, needed by the phone app (Firebase auth, MQTT)
and for the tablet app's offline bundle (save the full response, ~130 KB).
Source is the tzdata pip package, now pinned (2026.6 = IANA 2026f); bumping
the pin is how new DST rules arrive. Docs in docs/device-timezones.md;
tests in tests/test_timezones.py.

Stage 4 of project-vesper docs/features/timekeeper-overhaul.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-28 21:01:04 +02:00
co-authored by Claude Opus 5.5
parent 8837eb1e70
commit e4ea43a079
7 changed files with 409 additions and 1 deletions
+2
View File
@@ -29,6 +29,7 @@ from notes.router import router as notes_router
from tickets.router import router as tickets_router from tickets.router import router as tickets_router
from audit.router import router as audit_router from audit.router import router as audit_router
from search.router import router as search_router from search.router import router as search_router
from timezones.router import router as timezones_router
from crm.nextcloud import close_client as close_nextcloud_client, keepalive_ping as nextcloud_keepalive from crm.nextcloud import close_client as close_nextcloud_client, keepalive_ping as nextcloud_keepalive
from crm.mail_accounts import get_mail_accounts from crm.mail_accounts import get_mail_accounts
from mqtt.client import mqtt_manager from mqtt.client import mqtt_manager
@@ -78,6 +79,7 @@ app.include_router(notes_router)
app.include_router(tickets_router) app.include_router(tickets_router)
app.include_router(audit_router) app.include_router(audit_router)
app.include_router(search_router) app.include_router(search_router)
app.include_router(timezones_router)
async def nextcloud_keepalive_loop(): async def nextcloud_keepalive_loop():
+2
View File
@@ -18,3 +18,5 @@ pdf2image>=1.17.0
asyncpg==0.30.0 asyncpg==0.30.0
sqlalchemy[asyncio]==2.0.36 sqlalchemy[asyncio]==2.0.36
alembic==1.14.0 alembic==1.14.0
# IANA tz database for the device timezone table (timezones/). Bump to pick up new DST rules.
tzdata==2026.6
+117
View File
@@ -0,0 +1,117 @@
"""
Timezone table for device clock setup (timezones/). Pure tzdata — no Firestore, no MQTT.
"""
from datetime import datetime, timezone
import pytest
import tzdata
from fastapi import FastAPI
from fastapi.testclient import TestClient
from timezones import service
from timezones.router import router
SUMMER = datetime(2026, 7, 15, 12, tzinfo=timezone.utc)
WINTER = datetime(2026, 1, 15, 12, tzinfo=timezone.utc)
@pytest.mark.parametrize("posix, expected", [
("EET-2EEST,M3.5.0/3,M10.5.0/4", (120, 60, True)),
("EST5EDT,M3.2.0,M11.1.0", (-300, 60, True)),
("IST-5:30", (330, 0, False)),
("<+0545>-5:45", (345, 0, False)),
("<-03>3", (-180, 0, False)),
("IST-1GMT0,M10.5.0,M3.5.0/1", (60, -60, True)), # Dublin: negative DST
("<+1030>-10:30<+11>-11,M10.1.0,M4.1.0", (630, 30, True)), # Lord Howe: 30 min DST
("<+1245>-12:45<+1345>,M9.5.0/2:45,M4.1.0/3:45", (765, 60, True)), # Chatham
("IST-2IDT,M3.4.4/26,M10.5.0", (120, 60, True)), # Israel extended hours
])
def test_posix_offsets(posix, expected):
assert service.posix_offsets(posix) == expected
def test_posix_offsets_rejects_garbage():
with pytest.raises(ValueError):
service.posix_offsets("not a rule")
def test_table_shape_and_version():
table = service.get_table(now=WINTER)
assert table["tzdata_version"] == tzdata.IANA_VERSION
countries = table["countries"]
assert len(countries) > 200
assert [c["name"] for c in countries] == sorted(c["name"] for c in countries)
zone_count = 0
for country in countries:
assert country["zones"], country["code"]
for zone in country["zones"]:
zone_count += 1
assert zone["posix"] and len(zone["posix"]) < 64 # firmware POSIX_MAX_LEN
assert len(zone["name"]) < 48 # firmware NAME_MAX_LEN
assert country["code"] in zone["countries"]
assert zone_count > 300
def test_greece_and_australia():
gr = service.get_table("gr", now=SUMMER)["countries"]
assert len(gr) == 1 and gr[0]["name"] == "Greece"
athens = gr[0]["zones"][0]
assert athens["name"] == "Europe/Athens"
assert athens["posix"] == "EET-2EEST,M3.5.0/3,M10.5.0/4"
assert (athens["std_offset_min"], athens["dst_offset_min"], athens["has_dst"]) == (120, 60, True)
assert athens["current_offset_min"] == 180 and athens["current_dst"] is True
assert athens["display"] == "(UTC+03:00) Athens"
au = {z["name"]: z for z in service.get_table("AU", now=SUMMER)["countries"][0]["zones"]}
assert au["Australia/Sydney"]["current_offset_min"] == 600 # southern winter
assert au["Australia/Brisbane"]["has_dst"] is False
assert au["Australia/Lord_Howe"]["dst_offset_min"] == 30
def test_current_offset_follows_dst():
athens = service.get_zone("Europe/Athens", now=WINTER)
assert athens["current_offset_min"] == 120 and athens["current_dst"] is False
def test_rule_offsets_match_zoneinfo_once_rules_are_settled():
# By 2030 every zone runs on its POSIX footer, so the offset in force must be
# either the standard offset or standard + DST from that rule.
table = service.get_table()
for when in (datetime(2030, 1, 15, 12, tzinfo=timezone.utc), datetime(2030, 7, 15, 12, tzinfo=timezone.utc)):
for country in table["countries"]:
for zone in country["zones"]:
current = service.get_zone(zone["name"], now=when)["current_offset_min"]
allowed = {zone["std_offset_min"], zone["std_offset_min"] + zone["dst_offset_min"]}
assert current in allowed, (zone["name"], when, current, allowed)
def test_unknown_country_and_zone():
assert service.get_table("XX") is None
assert service.get_zone("Nowhere/Town") is None
assert service.get_zone("../../etc/passwd") is None
def test_alias_not_in_zone_tab_resolves():
zone = service.get_zone("Asia/Calcutta")
assert zone["posix"] == "IST-5:30" and zone["countries"] == []
@pytest.fixture
def client():
app = FastAPI()
app.include_router(router)
return TestClient(app)
def test_routes(client):
r = client.get("/api/public/timezones", params={"country": "GR"})
assert r.status_code == 200
assert r.json()["countries"][0]["zones"][0]["name"] == "Europe/Athens"
assert client.get("/api/public/timezones", params={"country": "XX"}).status_code == 404
r = client.get("/api/public/timezones/zone", params={"name": "Australia/Sydney"})
assert r.status_code == 200 and r.json()["posix"] == "AEST-10AEDT,M10.1.0,M4.1.0/3"
assert client.get("/api/public/timezones/zone", params={"name": "Nowhere/Town"}).status_code == 404
View File
+33
View File
@@ -0,0 +1,33 @@
"""
Public (no-auth) timezone table for device clock setup — see timezones/service.py.
Public on purpose: it is IANA data, and the phone app (Firebase auth, MQTT) and the tablet
bundle export both need it without console credentials.
"""
from fastapi import APIRouter, HTTPException, Query
from timezones import service
router = APIRouter(prefix="/api/public/timezones", tags=["timezones"])
@router.get("")
async def list_timezones(country: str | None = Query(None, description="ISO 3166 alpha-2 code, e.g. GR")):
"""All countries with their IANA zones, POSIX rules and current offsets.
The response is also the file the tablet app bundles (save it as-is; `tzdata_version`
tells which IANA release it came from).
"""
table = service.get_table(country)
if table is None:
raise HTTPException(status_code=404, detail=f"Unknown country code: {country}")
return table
@router.get("/zone")
async def get_timezone(name: str = Query(..., description="IANA zone name, e.g. Europe/Athens")):
"""One zone by IANA name — e.g. to turn a phone's own timezone into a device rule."""
zone = service.get_zone(name)
if zone is None:
raise HTTPException(status_code=404, detail=f"Unknown timezone: {name}")
return zone
+170
View File
@@ -0,0 +1,170 @@
"""
IANA timezone table for the device clock (firmware 3.0.0+, timezone mode "auto").
Devices evaluate a POSIX TZ rule string (e.g. "EET-2EEST,M3.5.0/3,M10.5.0/4"), not the
IANA database, so whoever sets a device's timezone has to send the rule. This module is the
single source of those rules for the console and the phone app (GET /api/public/timezones);
the tablet app, which only talks to devices over local WebSocket, bundles a saved copy of
the same response.
Everything comes from the `tzdata` package pinned in requirements.txt (IANA release in
`tzdata.IANA_VERSION`): the POSIX rule is the footer of each zone's TZif file, zone →
country from zone.tab, country names from iso3166.tab. To pick up new DST rules, bump the
pin — nothing is generated or committed by hand.
The firmware side is project-vesper src/TimeKeeper/TimeZone.cpp; its host tests check that
it evaluates every one of these rules the same way as CPython's zoneinfo.
"""
from __future__ import annotations
import importlib.resources
import re
from datetime import datetime, timezone
from functools import lru_cache
from zoneinfo import ZoneInfo
import tzdata
# POSIX TZ: std offset [dst [offset] [,rule]] — only the offsets are needed here.
_NAME = r"(?:<[^>]+>|[A-Za-z]{3,})"
_OFFSET = r"([+-]?\d{1,3}(?::\d{1,2}){0,2})"
_POSIX_RE = re.compile(rf"^{_NAME}{_OFFSET}(?:({_NAME}){_OFFSET}?(?:,.*)?)?$")
def _tzdata_file(name: str):
return importlib.resources.files("tzdata.zoneinfo").joinpath(*name.split("/"))
def _hms_to_min(text: str) -> int:
sign = -1 if text.startswith("-") else 1
parts = [int(p) for p in text.lstrip("+-").split(":")]
parts += [0] * (3 - len(parts))
return sign * (parts[0] * 60 + parts[1] + (1 if parts[2] >= 30 else 0))
def posix_offsets(posix: str) -> tuple[int, int, bool]:
"""(std_offset_min, dst_offset_min, has_dst), east-positive minutes.
POSIX offsets are west-positive ("EET-2" is UTC+2). dst_offset_min is the DST
*amount* (DST total - standard), default one hour, matching the firmware's
tz::makeAuto(). It can be negative (Europe/Dublin models winter as negative DST).
"""
m = _POSIX_RE.match(posix)
if not m:
raise ValueError(f"unparseable POSIX TZ rule: {posix!r}")
std = -_hms_to_min(m.group(1))
if not m.group(2):
return std, 0, False
total = -_hms_to_min(m.group(3)) if m.group(3) else std + 60
return std, total - std, True
def posix_rule(name: str) -> str | None:
"""POSIX TZ footer of a zone's TZif (v2+) file, or None."""
try:
data = _tzdata_file(name).read_bytes()
except (FileNotFoundError, IsADirectoryError, OSError):
return None
if not data.startswith(b"TZif") or data[4:5] < b"2":
return None
footer = data.rstrip(b"\n").rsplit(b"\n", 1)[-1].decode("ascii", "replace")
return footer or None
def _format_offset(minutes: int) -> str:
sign = "+" if minutes >= 0 else "-"
return f"UTC{sign}{abs(minutes) // 60:02d}:{abs(minutes) % 60:02d}"
@lru_cache(maxsize=1)
def _static_table() -> tuple[list[dict], dict[str, dict]]:
"""Countries (sorted by name) with their zones in zone.tab order, plus a name index.
Only the parts that never change at runtime; offsets "now" are added per request."""
countries_by_code = {}
for line in _tzdata_file("iso3166.tab").read_text(encoding="utf-8").splitlines():
if line and not line.startswith("#"):
code, name = line.split("\t", 1)
countries_by_code[code] = {"code": code, "name": name.strip(), "zones": []}
zones_by_name: dict[str, dict] = {}
for line in _tzdata_file("zone.tab").read_text(encoding="utf-8").splitlines():
if not line or line.startswith("#"):
continue
fields = line.split("\t")
code, name = fields[0], fields[2]
comment = fields[3].strip() if len(fields) > 3 else ""
posix = posix_rule(name)
country = countries_by_code.get(code)
if not posix or country is None:
continue
std, dst, has_dst = posix_offsets(posix)
zone = zones_by_name.get(name)
if zone is None:
zone = {
"name": name,
"city": name.rsplit("/", 1)[-1].replace("_", " "),
"comment": comment,
"posix": posix,
"std_offset_min": std,
"dst_offset_min": dst,
"has_dst": has_dst,
"countries": [],
}
zones_by_name[name] = zone
zone["countries"].append(code)
country["zones"].append(zone)
countries = sorted((c for c in countries_by_code.values() if c["zones"]), key=lambda c: c["name"])
return countries, zones_by_name
def _with_current(zone: dict, now: datetime) -> dict:
local = now.astimezone(ZoneInfo(zone["name"]))
offset = int(local.utcoffset().total_seconds() // 60)
out = {k: v for k, v in zone.items() if k != "countries"}
out["countries"] = list(zone["countries"])
out["current_offset_min"] = offset
out["current_dst"] = bool(local.dst())
out["display"] = f"({_format_offset(offset)}) {zone['city']}" + (f" — {zone['comment']}" if zone["comment"] else "")
return out
def tzdata_version() -> str:
return tzdata.IANA_VERSION
def get_table(country: str | None = None, now: datetime | None = None) -> dict | None:
"""Full table, or one country's (ISO 3166 alpha-2, case-insensitive). None if unknown."""
now = now or datetime.now(timezone.utc)
countries, _ = _static_table()
if country:
countries = [c for c in countries if c["code"] == country.upper()]
if not countries:
return None
return {
"tzdata_version": tzdata_version(),
"generated_at": now.isoformat(timespec="seconds"),
"countries": [
{"code": c["code"], "name": c["name"], "zones": [_with_current(z, now) for z in c["zones"]]}
for c in countries
],
}
def get_zone(name: str, now: datetime | None = None) -> dict | None:
"""One zone. Also resolves IANA names that zone.tab doesn't list (aliases such as
"Asia/Calcutta", or "UTC") — phones may report those as their own timezone."""
_, zones = _static_table()
zone = zones.get(name)
if zone is None:
posix = posix_rule(name) if re.fullmatch(r"[A-Za-z0-9_+\-]+(/[A-Za-z0-9_+\-]+)*", name) else None
if posix is None:
return None
std, dst, has_dst = posix_offsets(posix)
zone = {"name": name, "city": name.rsplit("/", 1)[-1].replace("_", " "), "comment": "",
"posix": posix, "std_offset_min": std, "dst_offset_min": dst, "has_dst": has_dst,
"countries": []}
result = _with_current(zone, now or datetime.now(timezone.utc))
result["tzdata_version"] = tzdata_version()
return result
+84
View File
@@ -0,0 +1,84 @@
# Device timezone table
Backend module `backend/timezones/` — the list of timezones that the console and the apps offer when
setting a device's clock, with the rule each device needs.
## Why it exists
Since firmware 3.0.0 the device RTC holds UTC and the device converts to local time itself
(project-vesper `src/TimeKeeper/`, catalog F-079). In timezone mode `auto` the device is sent:
```json
{ "mode": "auto", "name": "Europe/Athens", "posix": "EET-2EEST,M3.5.0/3,M10.5.0/4" }
```
`posix` is a POSIX TZ rule: the standard offset, the DST offset and when DST starts/ends every year. The
device evaluates it by itself, so DST switches without anyone touching the device. Devices don't carry the
IANA database, so whoever sets the timezone (console, phone app, tablet app) must send the rule — and must
never build it by hand (POSIX signs are inverted: `EET-2` means UTC+2). This module is where the rule comes
from.
## Source of truth
The pip package `tzdata` pinned in `backend/requirements.txt` (IANA release reported as `tzdata_version`):
- POSIX rule = the footer line of each zone's TZif file (the same string the firmware's host tests check
against CPython's `zoneinfo` for every zone — project-vesper `test/timezone/`).
- Zone → country: `zone.tab`. Country names: `iso3166.tab`.
Nothing is generated or committed by hand. **To pick up new DST rules** (a country changes or abolishes DST),
bump the `tzdata` pin, rebuild the backend, and re-send `clock.set_timezone` to affected devices — devices
keep the rule they were given until told otherwise. Re-export the tablet bundle too (below).
## Endpoints (public, no auth)
Public on purpose: it is public IANA data, and the phone app (Firebase auth over MQTT) and the tablet bundle
export need it without console credentials.
### `GET /api/public/timezones[?country=GR]`
```json
{
"tzdata_version": "2026f",
"generated_at": "2026-10-28T14:05:00+00:00",
"countries": [
{ "code": "GR", "name": "Greece", "zones": [
{ "name": "Europe/Athens", "city": "Athens", "comment": "",
"posix": "EET-2EEST,M3.5.0/3,M10.5.0/4",
"std_offset_min": 120, "dst_offset_min": 60, "has_dst": true,
"countries": ["GR"], "current_offset_min": 120, "current_dst": false,
"display": "(UTC+02:00) Athens" } ] }
]
}
```
- Countries sorted by name; zones in `zone.tab` order (roughly geographic). Most countries have one zone;
pick-country-then-zone UIs can skip the second step for those.
- `std_offset_min` / `dst_offset_min`: minutes east of UTC; `dst_offset_min` is the DST **amount** (0 without
DST, negative for Europe/Dublin, 30 for Lord Howe). Same values the device reports in `clock.get_timezone`.
- `current_offset_min` / `current_dst` / `display` are computed at request time.
- A zone used by several countries appears under each, with all of them in `countries`.
- `country` filter: ISO 3166 alpha-2, case-insensitive. Unknown → 404.
### `GET /api/public/timezones/zone?name=Europe/Athens`
One zone (same fields + `tzdata_version`). Also resolves IANA aliases that `zone.tab` doesn't list
(`Asia/Calcutta`, `UTC`, …) with `countries: []` — useful for "use this phone's timezone". Unknown → 404.
## Tablet app bundle
The tablet app only talks to devices over local WebSocket, often without internet, so it bundles the table:
save the response of `GET /api/public/timezones` as-is (≈ 130 KB) into the app. Ignore the `current_*` and
`display` fields there (they were "now" at export time) — compute the current offset on the tablet, or just
show `std_offset_min`. Re-export whenever the `tzdata` pin is bumped.
## Tests
`backend/tests/test_timezones.py` (pure tzdata, no Firestore/MQTT): POSIX offset parsing incl. negative,
half-hour and 45-minute cases; table shape and firmware length limits (name < 48, rule < 64 chars); Greece /
Australia spot checks; every zone's offset in 2030 is its standard or standard+DST offset; routes.
```
cd backend
python -m pytest tests/test_timezones.py
```