Compare commits
8
Commits
bbd356d846
...
fba5110cc0
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
fba5110cc0 | ||
|
|
cdf5fc79a0 | ||
|
|
e4ea43a079 | ||
|
|
8837eb1e70 | ||
|
|
d1799bd3b1 | ||
|
|
ca53d2e871 | ||
|
|
65ff2372ca | ||
|
|
c2767ca7e0 |
@@ -57,6 +57,9 @@ class DeviceClockSettings(BaseModel):
|
||||
backlightTurnOffTime: str = ""
|
||||
isBacklightAutomationOn: bool = False
|
||||
backlightOutput: int = 0
|
||||
# Firmware 3.2.0+ face sync policy (clock.set_config face_sync_mode / smart_max_wait_min)
|
||||
faceSyncMode: str = "force"
|
||||
smartMaxWaitMin: int = 61
|
||||
|
||||
|
||||
class DeviceAttributes(BaseModel):
|
||||
|
||||
@@ -29,6 +29,7 @@ from notes.router import router as notes_router
|
||||
from tickets.router import router as tickets_router
|
||||
from audit.router import router as audit_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.mail_accounts import get_mail_accounts
|
||||
from mqtt.client import mqtt_manager
|
||||
@@ -78,6 +79,7 @@ app.include_router(notes_router)
|
||||
app.include_router(tickets_router)
|
||||
app.include_router(audit_router)
|
||||
app.include_router(search_router)
|
||||
app.include_router(timezones_router)
|
||||
|
||||
|
||||
async def nextcloud_keepalive_loop():
|
||||
|
||||
@@ -17,4 +17,6 @@ Pillow>=10.0.0
|
||||
pdf2image>=1.17.0
|
||||
asyncpg==0.30.0
|
||||
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
|
||||
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
```
|
||||
@@ -0,0 +1,120 @@
|
||||
// frontend/src/lib/deviceTimezone.js
|
||||
// Helpers for device clock timezones (firmware 3.0.0+, project-vesper F-079).
|
||||
//
|
||||
// The device RTC holds UTC; a timezone object tells it how to show local time:
|
||||
// { mode: 'auto', name, posix } — DST switches by itself
|
||||
// { mode: 'manual', name, std_offset_min, dst_offset_min, dst_start, dst_end } — one DST season
|
||||
// { mode: 'fixed', name, std_offset_min, dst_offset_min } — never switches
|
||||
// { mode: 'local' } — offset 0, no NTP
|
||||
// Offsets are minutes EAST of UTC. dst_start / dst_end are UTC epoch seconds.
|
||||
// The rule list comes from the backend (GET /api/public/timezones, docs/device-timezones.md).
|
||||
|
||||
import api from '@/lib/api'
|
||||
import { fmtUtcOffset } from '@/lib/formatters'
|
||||
|
||||
export const TZ_MODES = [
|
||||
{ value: 'auto', label: 'Automatic' },
|
||||
{ value: 'manual', label: 'Manual DST' },
|
||||
{ value: 'fixed', label: 'Fixed offset' },
|
||||
{ value: 'local', label: 'Local only' },
|
||||
]
|
||||
|
||||
export const TZ_MODE_LABELS = Object.fromEntries(TZ_MODES.map(m => [m.value, m.label]))
|
||||
|
||||
// UTC-12:00 … UTC+14:00 in 15-minute steps (covers Nepal +5:45, Chatham +12:45)
|
||||
export const STD_OFFSET_OPTIONS = Array.from({ length: (840 + 720) / 15 + 1 }, (_, i) => {
|
||||
const value = -720 + i * 15
|
||||
return { value, label: fmtUtcOffset(value) }
|
||||
})
|
||||
|
||||
export const DST_AMOUNT_OPTIONS = [
|
||||
{ value: 30, label: '+30 min' },
|
||||
{ value: 60, label: '+1 hour' },
|
||||
{ value: 120, label: '+2 hours' },
|
||||
]
|
||||
|
||||
export const MONTHS = ['January', 'February', 'March', 'April', 'May', 'June', 'July',
|
||||
'August', 'September', 'October', 'November', 'December']
|
||||
export const WEEKS = [
|
||||
{ value: 1, label: '1st' }, { value: 2, label: '2nd' }, { value: 3, label: '3rd' },
|
||||
{ value: 4, label: '4th' }, { value: 5, label: 'Last' },
|
||||
]
|
||||
export const WEEKDAYS = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']
|
||||
|
||||
// ── Timezone table (cached for the session) ───────────────────────────────────
|
||||
|
||||
let tablePromise = null
|
||||
|
||||
/** { tzdata_version, countries: [{ code, name, zones: [...] }] } — fetched once. */
|
||||
export function loadTimezoneTable() {
|
||||
if (!tablePromise) {
|
||||
tablePromise = api.get('/public/timezones').catch(err => {
|
||||
tablePromise = null // allow a retry after a failure
|
||||
throw err
|
||||
})
|
||||
}
|
||||
return tablePromise
|
||||
}
|
||||
|
||||
/** The country containing an IANA zone, or null. */
|
||||
export function findCountryOfZone(table, zoneName) {
|
||||
return table?.countries.find(c => c.zones.some(z => z.name === zoneName)) || null
|
||||
}
|
||||
|
||||
// ── POSIX rule builder (custom recurring DST) ─────────────────────────────────
|
||||
|
||||
// POSIX offsets are WEST-positive h[:mm] — the opposite sign of our minutes-east values.
|
||||
function posixOffset(minutesEast) {
|
||||
const west = -minutesEast
|
||||
const sign = west < 0 ? '-' : ''
|
||||
const abs = Math.abs(west)
|
||||
const mm = abs % 60
|
||||
return `${sign}${Math.floor(abs / 60)}${mm ? `:${String(mm).padStart(2, '0')}` : ''}`
|
||||
}
|
||||
|
||||
// Abbreviation for a numeric offset: "<+02>", "<+0545>", "<-03>"
|
||||
function posixName(minutesEast) {
|
||||
const sign = minutesEast < 0 ? '-' : '+'
|
||||
const abs = Math.abs(minutesEast)
|
||||
const mm = abs % 60
|
||||
return `<${sign}${String(Math.floor(abs / 60)).padStart(2, '0')}${mm ? String(mm).padStart(2, '0') : ''}>`
|
||||
}
|
||||
|
||||
// "HH:MM" → "/H" or "/H:MM"
|
||||
function posixTime(hhmm) {
|
||||
const [h, m] = hhmm.split(':').map(Number)
|
||||
return `/${h}${m ? `:${String(m).padStart(2, '0')}` : ''}`
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds a POSIX TZ rule for a recurring DST schedule, e.g. std +120, DST +60,
|
||||
* last Sunday of March 03:00 → last Sunday of October 04:00:
|
||||
* "<+02>-2<+03>,M3.5.0/3,M10.5.0/4"
|
||||
* `start.time` is local standard time, `end.time` local DST time (POSIX convention).
|
||||
* dstAmountMin 0 → no DST part.
|
||||
*/
|
||||
export function buildPosixRule({ stdOffsetMin, dstAmountMin, start, end }) {
|
||||
const std = `${posixName(stdOffsetMin)}${posixOffset(stdOffsetMin)}`
|
||||
if (!dstAmountMin) return std
|
||||
const total = stdOffsetMin + dstAmountMin
|
||||
const dst = `${posixName(total)}${dstAmountMin === 60 ? '' : posixOffset(total)}`
|
||||
const date = r => `M${r.month}.${r.week}.${r.weekday}${posixTime(r.time)}`
|
||||
return `${std}${dst},${date(start)},${date(end)}`
|
||||
}
|
||||
|
||||
// ── Wall-clock helpers ────────────────────────────────────────────────────────
|
||||
|
||||
/** "2026-03-29T03:00[:SS]" → epoch seconds, read as if it were UTC (no browser timezone). */
|
||||
export function wallClockToEpoch(value) {
|
||||
if (!value) return null
|
||||
const ms = Date.parse(`${value.length === 16 ? `${value}:00` : value}Z`)
|
||||
return Number.isNaN(ms) ? null : Math.floor(ms / 1000)
|
||||
}
|
||||
|
||||
/** Epoch seconds → "YYYY-MM-DDTHH:MM" wall clock at the given offset (for datetime-local inputs). */
|
||||
export function epochToWallClock(utcSeconds, offsetMin) {
|
||||
if (!utcSeconds) return ''
|
||||
// toISOString() is intentional here: the epoch is already shifted to the device's wall
|
||||
// clock, so reading it back as UTC gives exactly those fields (no browser timezone involved).
|
||||
return new Date((utcSeconds + offsetMin * 60) * 1000).toISOString().slice(0, 16)
|
||||
}
|
||||
@@ -175,3 +175,35 @@ export function fmtEuro(n) {
|
||||
const f = parseFloat(n) || 0
|
||||
return f.toLocaleString('el-GR', { minimumFractionDigits: 2, maximumFractionDigits: 2 }) + ' €'
|
||||
}
|
||||
|
||||
// ─── Device wall-clock time ──────────────────────────────────────────────────
|
||||
// A device's local time is in the DEVICE's timezone, not the browser's. These never
|
||||
// convert through the browser timezone: they format wall-clock values as devices report
|
||||
// them (firmware 3.0.0+: "local": "2026-10-28T14:05:00", or a UTC epoch + offset).
|
||||
|
||||
// Formats in UTC so the wall-clock fields come out untouched
|
||||
const WALL_DATETIME = new Intl.DateTimeFormat(LOCALE_LONG, {
|
||||
day: 'numeric', month: 'short', year: 'numeric',
|
||||
hour: '2-digit', minute: '2-digit', hour12: false, timeZone: 'UTC',
|
||||
})
|
||||
|
||||
/** "28 Oct 2026, 14:05" — a device wall-clock string "2026-10-28T14:05:00" */
|
||||
export function fmtWallClock(localIso) {
|
||||
if (!localIso) return '—'
|
||||
const d = safeDate(`${localIso}Z`)
|
||||
return d ? WALL_DATETIME.format(d) : '—'
|
||||
}
|
||||
|
||||
/** "28 Oct 2026, 14:05" — a UTC epoch (seconds) shown in a device's local time */
|
||||
export function fmtDeviceDateTime(utcSeconds, offsetMin) {
|
||||
if (!utcSeconds) return '—'
|
||||
return WALL_DATETIME.format(new Date((utcSeconds + (offsetMin || 0) * 60) * 1000))
|
||||
}
|
||||
|
||||
/** "UTC+02:00" / "UTC-03:30" — minutes east of UTC */
|
||||
export function fmtUtcOffset(minutes) {
|
||||
if (minutes == null) return '—'
|
||||
const sign = minutes >= 0 ? '+' : '-'
|
||||
const abs = Math.abs(minutes)
|
||||
return `UTC${sign}${String(Math.floor(abs / 60)).padStart(2, '0')}:${String(abs % 60).padStart(2, '0')}`
|
||||
}
|
||||
|
||||
@@ -1,10 +1,13 @@
|
||||
// frontend/src/modals/bellcloud/devices/EditClockSettingsModal.jsx
|
||||
// Edits: master switch, ODD/EVEN outputs, pulse and pause durations (sliders).
|
||||
// Edits: master switch, ODD/EVEN outputs, pulse and pause durations (sliders), and the
|
||||
// face sync policy (firmware 3.2.0+: force = run a full lap when the face is ahead,
|
||||
// smart = wait if it is at most N minutes ahead).
|
||||
|
||||
import { useState } from 'react'
|
||||
import Modal from '@/components/ui/Modal'
|
||||
import Button from '@/components/ui/Button'
|
||||
import FormField from '@/components/ui/FormField'
|
||||
import SegmentedControl from '@/components/ui/SegmentedControl'
|
||||
import api from '@/lib/api'
|
||||
|
||||
// Pulse options in milliseconds — shown as sliders with labelled steps
|
||||
@@ -68,6 +71,8 @@ export default function EditClockSettingsModal({ open, onClose, onSaved, attr, s
|
||||
const [clockOut2, setClockOut2] = useState(String(existingClockOutputs[1] ?? 0))
|
||||
const [runPulse, setRunPulse] = useState(existingTimings[0] || PULSE_STEPS[3]) // default 500ms
|
||||
const [pauseMs, setPauseMs] = useState(existingTimings[1] || PAUSE_STEPS[1]) // default 1000ms
|
||||
const [faceSync, setFaceSync] = useState(clock.faceSyncMode || 'force')
|
||||
const [maxWait, setMaxWait] = useState(String(clock.smartMaxWaitMin ?? 61))
|
||||
const [saving, setSaving] = useState(false)
|
||||
const [error, setError] = useState('')
|
||||
|
||||
@@ -78,7 +83,11 @@ export default function EditClockSettingsModal({ open, onClose, onSaved, attr, s
|
||||
const validationMsg = hasClock && (out1 === 0 || out2 === 0)
|
||||
? 'Both outputs must be assigned when the clock is enabled.'
|
||||
: null
|
||||
const canSave = !conflictMsg && !validationMsg
|
||||
const maxWaitNum = Number(maxWait)
|
||||
const maxWaitMsg = faceSync === 'smart' && (!Number.isInteger(maxWaitNum) || maxWaitNum < 1 || maxWaitNum > 359)
|
||||
? 'Maximum wait must be 1–359 minutes.'
|
||||
: null
|
||||
const canSave = !conflictMsg && !validationMsg && !maxWaitMsg
|
||||
|
||||
const handleSave = async () => {
|
||||
if (!canSave) return
|
||||
@@ -93,6 +102,8 @@ export default function EditClockSettingsModal({ open, onClose, onSaved, attr, s
|
||||
c2: out2,
|
||||
pulse_duration: runPulse,
|
||||
pause_duration: pauseMs,
|
||||
face_sync_mode: faceSync,
|
||||
...(faceSync === 'smart' ? { smart_max_wait_min: maxWaitNum } : {}),
|
||||
})
|
||||
|
||||
await api.put(`/devices/${id}`, {
|
||||
@@ -102,6 +113,8 @@ export default function EditClockSettingsModal({ open, onClose, onSaved, attr, s
|
||||
...clock,
|
||||
clockOutputs: [out1, out2].filter(o => o > 0),
|
||||
clockTimings: [runPulse, pauseMs],
|
||||
faceSyncMode: faceSync,
|
||||
...(faceSync === 'smart' ? { smartMaxWaitMin: maxWaitNum } : {}),
|
||||
},
|
||||
},
|
||||
})
|
||||
@@ -228,10 +241,42 @@ export default function EditClockSettingsModal({ open, onClose, onSaved, attr, s
|
||||
onChange={setPauseMs}
|
||||
/>
|
||||
|
||||
<div style={{ height: 1, backgroundColor: 'var(--color-border)' }} />
|
||||
|
||||
{/* Face sync policy */}
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-3)' }}>
|
||||
<div>
|
||||
<p style={{ fontSize: 'var(--font-size-base)', fontWeight: 'var(--font-weight-semibold)', color: 'var(--color-text-primary)' }}>
|
||||
Face Ahead of Real Time
|
||||
</p>
|
||||
<p style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-text-muted)', marginTop: 2 }}>
|
||||
The hands only move forward. When they are ahead (e.g. after DST ends), Force runs a full
|
||||
lap to catch up; Smart stops them until real time catches up.
|
||||
</p>
|
||||
</div>
|
||||
<SegmentedControl
|
||||
options={[{ value: 'force', label: 'Force (full lap)' }, { value: 'smart', label: 'Smart (wait)' }]}
|
||||
value={faceSync}
|
||||
onChange={setFaceSync}
|
||||
size="sm"
|
||||
/>
|
||||
{faceSync === 'smart' && (
|
||||
<FormField
|
||||
label="Wait if ahead by at most (minutes)"
|
||||
name="smartMaxWait"
|
||||
type="number"
|
||||
value={maxWait}
|
||||
onChange={e => setMaxWait(e.target.value)}
|
||||
inputProps={{ min: 1, max: 359, step: 1 }}
|
||||
hint="Default 61 covers the DST change. Further ahead than this, the face runs the lap."
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Errors / warnings */}
|
||||
{(conflictMsg || validationMsg) && (
|
||||
{(conflictMsg || validationMsg || maxWaitMsg) && (
|
||||
<p style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-warning)', backgroundColor: 'var(--color-warning-bg)', padding: 'var(--space-2) var(--space-3)', borderRadius: 'var(--radius-sm)' }}>
|
||||
{conflictMsg || validationMsg}
|
||||
{conflictMsg || validationMsg || maxWaitMsg}
|
||||
</p>
|
||||
)}
|
||||
{error && (
|
||||
|
||||
@@ -0,0 +1,309 @@
|
||||
// frontend/src/modals/bellcloud/devices/EditTimezoneModal.jsx
|
||||
// Sets a device's timezone (firmware 3.0.0+, clock.set_timezone). Four modes:
|
||||
// Automatic — pick country → zone from the backend table (rule sent as POSIX), or build a
|
||||
// custom yearly DST rule. DST then switches on the device by itself.
|
||||
// Manual DST — standard offset + DST amount + this season's start/end. Re-entered yearly.
|
||||
// Fixed — constant offset, never switches.
|
||||
// Local only — no timezone at all; the device keeps the local time it is given.
|
||||
// The RTC is untouched; only how the device turns UTC into local time changes.
|
||||
|
||||
import { useEffect, useMemo, useState } from 'react'
|
||||
import Modal from '@/components/ui/Modal'
|
||||
import Button from '@/components/ui/Button'
|
||||
import FormField from '@/components/ui/FormField'
|
||||
import SegmentedControl from '@/components/ui/SegmentedControl'
|
||||
import Spinner from '@/components/ui/Spinner'
|
||||
import { fmtUtcOffset } from '@/lib/formatters'
|
||||
import {
|
||||
TZ_MODES, STD_OFFSET_OPTIONS, DST_AMOUNT_OPTIONS, MONTHS, WEEKS, WEEKDAYS,
|
||||
loadTimezoneTable, findCountryOfZone, buildPosixRule, wallClockToEpoch, epochToWallClock,
|
||||
} from '@/lib/deviceTimezone'
|
||||
|
||||
const DEFAULT_COUNTRY = 'GR'
|
||||
const DEFAULT_RULE = {
|
||||
start: { month: 3, week: 5, weekday: 0, time: '03:00' },
|
||||
end: { month: 10, week: 5, weekday: 0, time: '04:00' },
|
||||
}
|
||||
|
||||
function hint(text) {
|
||||
return (
|
||||
<p style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-text-muted)' }}>{text}</p>
|
||||
)
|
||||
}
|
||||
|
||||
function RuleDateFields({ id, label, value, onChange, timeHint }) {
|
||||
const set = (key, v) => onChange({ ...value, [key]: v })
|
||||
return (
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-2)' }}>
|
||||
<span style={{ fontSize: 'var(--font-size-sm)', fontWeight: 'var(--font-weight-medium)', color: 'var(--color-text-secondary)' }}>
|
||||
{label}
|
||||
</span>
|
||||
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr 1fr', gap: 'var(--space-2)' }}>
|
||||
<FormField label="" name={`${id}-week`} type="select" value={String(value.week)} onChange={e => set('week', Number(e.target.value))}>
|
||||
{WEEKS.map(w => <option key={w.value} value={String(w.value)}>{w.label}</option>)}
|
||||
</FormField>
|
||||
<FormField label="" name={`${id}-weekday`} type="select" value={String(value.weekday)} onChange={e => set('weekday', Number(e.target.value))}>
|
||||
{WEEKDAYS.map((d, i) => <option key={d} value={String(i)}>{d}</option>)}
|
||||
</FormField>
|
||||
<FormField label="" name={`${id}-month`} type="select" value={String(value.month)} onChange={e => set('month', Number(e.target.value))}>
|
||||
{MONTHS.map((m, i) => <option key={m} value={String(i + 1)}>{m}</option>)}
|
||||
</FormField>
|
||||
<FormField label="" name={`${id}-time`} type="time" value={value.time} onChange={e => set('time', e.target.value)} />
|
||||
</div>
|
||||
{hint(timeHint)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default function EditTimezoneModal({ open, onClose, current, sendMqttCommand, onSaved }) {
|
||||
const [table, setTable] = useState(null)
|
||||
const [tableError, setTableError] = useState('')
|
||||
const [mode, setMode] = useState('auto')
|
||||
const [autoSource, setAutoSource] = useState('list') // 'list' | 'custom'
|
||||
const [country, setCountry] = useState(DEFAULT_COUNTRY)
|
||||
const [zoneName, setZoneName] = useState('')
|
||||
const [name, setName] = useState('')
|
||||
const [stdOffset, setStdOffset] = useState(120)
|
||||
const [dstAmount, setDstAmount] = useState(60)
|
||||
const [fixedDst, setFixedDst] = useState(0)
|
||||
const [rule, setRule] = useState(DEFAULT_RULE)
|
||||
const [ruleHasDst, setRuleHasDst] = useState(true)
|
||||
const [dstStart, setDstStart] = useState('')
|
||||
const [dstEnd, setDstEnd] = useState('')
|
||||
const [saving, setSaving] = useState(false)
|
||||
const [error, setError] = useState('')
|
||||
|
||||
// Load the backend table once per session (cached in deviceTimezone.js)
|
||||
useEffect(() => {
|
||||
if (!open || table) return
|
||||
loadTimezoneTable()
|
||||
.then(setTable)
|
||||
.catch(err => setTableError(err.message || 'Could not load the timezone list.'))
|
||||
}, [open, table])
|
||||
|
||||
// Start from what the device reports every time the modal opens
|
||||
useEffect(() => {
|
||||
if (!open) return
|
||||
setError('')
|
||||
const tz = current || {}
|
||||
setMode(tz.mode || 'auto')
|
||||
setName(tz.mode === 'local' ? '' : (tz.name || ''))
|
||||
setStdOffset(tz.std_offset_min ?? 120)
|
||||
setDstAmount(tz.mode === 'manual' && tz.dst_offset_min ? tz.dst_offset_min : 60)
|
||||
setFixedDst(tz.mode === 'fixed' ? (tz.dst_offset_min || 0) : 0)
|
||||
setDstStart(tz.mode === 'manual' ? epochToWallClock(tz.dst_start, tz.std_offset_min) : '')
|
||||
setDstEnd(tz.mode === 'manual' ? epochToWallClock(tz.dst_end, tz.std_offset_min + tz.dst_offset_min) : '')
|
||||
setAutoSource('list')
|
||||
setZoneName(tz.mode === 'auto' ? (tz.name || '') : '')
|
||||
}, [open, current])
|
||||
|
||||
// Once the table is there, select the current zone's country
|
||||
useEffect(() => {
|
||||
if (!table || !open) return
|
||||
const c = findCountryOfZone(table, zoneName)
|
||||
if (c) setCountry(c.code)
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [table, open])
|
||||
|
||||
const countryZones = useMemo(
|
||||
() => table?.countries.find(c => c.code === country)?.zones || [],
|
||||
[table, country],
|
||||
)
|
||||
const selectedZone = countryZones.find(z => z.name === zoneName) || null
|
||||
|
||||
// Picking a country with a single zone picks the zone too
|
||||
const handleCountry = (code) => {
|
||||
setCountry(code)
|
||||
const zones = table?.countries.find(c => c.code === code)?.zones || []
|
||||
setZoneName(zones.length === 1 ? zones[0].name : '')
|
||||
}
|
||||
|
||||
const customPosix = useMemo(
|
||||
() => buildPosixRule({ stdOffsetMin: stdOffset, dstAmountMin: ruleHasDst ? dstAmount : 0, ...rule }),
|
||||
[stdOffset, dstAmount, ruleHasDst, rule],
|
||||
)
|
||||
|
||||
// ── Build the clock.set_timezone contents + validation ────────────────────
|
||||
let contents = null
|
||||
let invalid = '' // shown to the user
|
||||
let incomplete = false // just not filled in yet — Save stays disabled, no message
|
||||
if (mode === 'auto' && autoSource === 'list') {
|
||||
if (selectedZone) contents = { mode: 'auto', name: selectedZone.name, posix: selectedZone.posix }
|
||||
else incomplete = true
|
||||
} else if (mode === 'auto') {
|
||||
contents = { mode: 'auto', name: name.trim() || 'Custom rule', posix: customPosix }
|
||||
} else if (mode === 'manual') {
|
||||
// Start is entered in local standard time, end in local DST time
|
||||
const startWall = wallClockToEpoch(dstStart)
|
||||
const endWall = wallClockToEpoch(dstEnd)
|
||||
if (startWall == null || endWall == null) {
|
||||
incomplete = true
|
||||
} else {
|
||||
const start = startWall - stdOffset * 60
|
||||
const end = endWall - (stdOffset + dstAmount) * 60
|
||||
if (end <= start) invalid = 'DST must end after it starts.'
|
||||
else contents = { mode: 'manual', name: name.trim(), std_offset_min: stdOffset, dst_offset_min: dstAmount, dst_start: start, dst_end: end }
|
||||
}
|
||||
} else if (mode === 'fixed') {
|
||||
contents = { mode: 'fixed', name: name.trim(), std_offset_min: stdOffset, dst_offset_min: fixedDst }
|
||||
} else {
|
||||
contents = { mode: 'local' }
|
||||
}
|
||||
if (contents?.name && contents.name.length > 47) {
|
||||
invalid = 'Name must be at most 47 characters.'
|
||||
contents = null
|
||||
}
|
||||
|
||||
const handleSave = async () => {
|
||||
if (!contents) return
|
||||
setSaving(true)
|
||||
setError('')
|
||||
try {
|
||||
const reply = await sendMqttCommand('clock.set_timezone', contents)
|
||||
onSaved?.(reply?.data || null)
|
||||
onClose()
|
||||
} catch (err) {
|
||||
setError(err.message || 'Failed to set the timezone.')
|
||||
} finally {
|
||||
setSaving(false)
|
||||
}
|
||||
}
|
||||
|
||||
const offsetSelect = (label, fieldName, value, onChange) => (
|
||||
<FormField label={label} name={fieldName} type="select" value={String(value)} onChange={e => onChange(Number(e.target.value))}>
|
||||
{STD_OFFSET_OPTIONS.map(o => <option key={o.value} value={String(o.value)}>{o.label}</option>)}
|
||||
</FormField>
|
||||
)
|
||||
|
||||
const dstAmountSelect = (
|
||||
<FormField label="DST amount" name="dstAmount" type="select" value={String(dstAmount)} onChange={e => setDstAmount(Number(e.target.value))}>
|
||||
{DST_AMOUNT_OPTIONS.map(o => <option key={o.value} value={String(o.value)}>{o.label}</option>)}
|
||||
</FormField>
|
||||
)
|
||||
|
||||
const nameField = (placeholder) => (
|
||||
<FormField label="Name (optional)" name="tzName" value={name} onChange={e => setName(e.target.value)} placeholder={placeholder} />
|
||||
)
|
||||
|
||||
return (
|
||||
<Modal
|
||||
open={open}
|
||||
onClose={onClose}
|
||||
title="Timezone"
|
||||
size="md"
|
||||
footer={
|
||||
<div style={{ display: 'flex', justifyContent: 'flex-end', gap: 'var(--space-3)' }}>
|
||||
<Button variant="ghost" onClick={onClose}>Cancel</Button>
|
||||
<Button variant="primary" loading={saving} disabled={!contents} onClick={handleSave}>Save Timezone</Button>
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-5)' }}>
|
||||
<SegmentedControl options={TZ_MODES} value={mode} onChange={setMode} size="sm" />
|
||||
|
||||
{mode === 'auto' && (
|
||||
<>
|
||||
{hint('The device switches DST by itself every year, following the rules of the chosen timezone.')}
|
||||
<SegmentedControl
|
||||
options={[{ value: 'list', label: 'Choose a timezone' }, { value: 'custom', label: 'Custom yearly rule' }]}
|
||||
value={autoSource}
|
||||
onChange={setAutoSource}
|
||||
size="sm"
|
||||
/>
|
||||
|
||||
{autoSource === 'list' && (
|
||||
tableError ? (
|
||||
<p style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-danger)' }}>{tableError}</p>
|
||||
) : !table ? (
|
||||
<div style={{ display: 'flex', justifyContent: 'center', padding: 'var(--space-4)' }}><Spinner size="md" /></div>
|
||||
) : (
|
||||
<>
|
||||
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 'var(--space-3)' }}>
|
||||
<FormField label="Country" name="tzCountry" type="select" value={country} onChange={e => handleCountry(e.target.value)}>
|
||||
{table.countries.map(c => <option key={c.code} value={c.code}>{c.name}</option>)}
|
||||
</FormField>
|
||||
<FormField label="Timezone" name="tzZone" type="select" value={zoneName} onChange={e => setZoneName(e.target.value)}>
|
||||
<option value="">Choose…</option>
|
||||
{countryZones.map(z => <option key={z.name} value={z.name}>{z.display}</option>)}
|
||||
</FormField>
|
||||
</div>
|
||||
{selectedZone && hint(
|
||||
selectedZone.has_dst
|
||||
? `Standard time ${fmtUtcOffset(selectedZone.std_offset_min)}, DST ${fmtUtcOffset(selectedZone.std_offset_min + selectedZone.dst_offset_min)}. Rules: IANA ${table.tzdata_version}.`
|
||||
: `${fmtUtcOffset(selectedZone.std_offset_min)} all year, no DST. Rules: IANA ${table.tzdata_version}.`,
|
||||
)}
|
||||
{current?.mode === 'auto' && current.posix && !findCountryOfZone(table, current.name) &&
|
||||
hint(`Current custom rule on the device: ${current.posix}`)}
|
||||
</>
|
||||
)
|
||||
)}
|
||||
|
||||
{autoSource === 'custom' && (
|
||||
<>
|
||||
{hint('For places whose DST rule is not in the list. The same rule repeats every year.')}
|
||||
{nameField('e.g. Site time')}
|
||||
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 'var(--space-3)' }}>
|
||||
{offsetSelect('Standard offset', 'ruleStd', stdOffset, setStdOffset)}
|
||||
<FormField label="DST" name="ruleDst" type="select" value={ruleHasDst ? String(dstAmount) : '0'}
|
||||
onChange={e => { const v = Number(e.target.value); setRuleHasDst(v !== 0); if (v) setDstAmount(v) }}>
|
||||
<option value="0">No DST</option>
|
||||
{DST_AMOUNT_OPTIONS.map(o => <option key={o.value} value={String(o.value)}>{o.label}</option>)}
|
||||
</FormField>
|
||||
</div>
|
||||
{ruleHasDst && (
|
||||
<>
|
||||
<RuleDateFields id="ruleStart" label="DST starts" value={rule.start} onChange={start => setRule(r => ({ ...r, start }))}
|
||||
timeHint="Local standard time (before the clocks go forward)." />
|
||||
<RuleDateFields id="ruleEnd" label="DST ends" value={rule.end} onChange={end => setRule(r => ({ ...r, end }))}
|
||||
timeHint="Local summer time (before the clocks go back)." />
|
||||
</>
|
||||
)}
|
||||
<p style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-text-muted)' }}>
|
||||
Rule sent to the device: <span style={{ fontFamily: 'var(--font-family-mono)', color: 'var(--color-text-primary)' }}>{customPosix}</span>
|
||||
</p>
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
|
||||
{mode === 'manual' && (
|
||||
<>
|
||||
{hint('For places with irregular DST dates. Valid for one season — enter next year\'s dates when this one ends (the console will remind you).')}
|
||||
{nameField('e.g. Site time')}
|
||||
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 'var(--space-3)' }}>
|
||||
{offsetSelect('Standard offset', 'manualStd', stdOffset, setStdOffset)}
|
||||
{dstAmountSelect}
|
||||
</div>
|
||||
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 'var(--space-3)' }}>
|
||||
<FormField label="DST starts" name="dstStart" type="datetime-local" value={dstStart} onChange={e => setDstStart(e.target.value)}
|
||||
hint="Local standard time" />
|
||||
<FormField label="DST ends" name="dstEnd" type="datetime-local" value={dstEnd} onChange={e => setDstEnd(e.target.value)}
|
||||
hint="Local summer time" />
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
|
||||
{mode === 'fixed' && (
|
||||
<>
|
||||
{hint('A constant offset that never switches. Automatic NTP still corrects small drift, but never by more than 5 minutes — set the time yourself if it is further off.')}
|
||||
{nameField('e.g. Site time')}
|
||||
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 'var(--space-3)' }}>
|
||||
{offsetSelect('Standard offset', 'fixedStd', stdOffset, setStdOffset)}
|
||||
<FormField label="DST offset now" name="fixedDst" type="select" value={String(fixedDst)} onChange={e => setFixedDst(Number(e.target.value))}>
|
||||
<option value="0">None</option>
|
||||
{DST_AMOUNT_OPTIONS.map(o => <option key={o.value} value={String(o.value)}>{o.label}</option>)}
|
||||
</FormField>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
|
||||
{mode === 'local' && hint('No timezone and no DST: the device keeps exactly the local time you set (use Set Time after saving). NTP is not used in this mode.')}
|
||||
|
||||
{invalid && !incomplete && (
|
||||
<p style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-warning)' }}>{invalid}</p>
|
||||
)}
|
||||
{error && <p style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-danger)' }}>{error}</p>}
|
||||
</div>
|
||||
</Modal>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
// frontend/src/modals/bellcloud/devices/NtpSettingsModal.jsx
|
||||
// NTP settings for a device (firmware 3.1.0+, clock.set_ntp): automatic syncs on/off,
|
||||
// nightly sync time (device local time) and up to 3 servers.
|
||||
|
||||
import { useEffect, useState } from 'react'
|
||||
import Modal from '@/components/ui/Modal'
|
||||
import Button from '@/components/ui/Button'
|
||||
import FormField from '@/components/ui/FormField'
|
||||
import SegmentedControl from '@/components/ui/SegmentedControl'
|
||||
|
||||
const DEFAULT_SERVERS = ['pool.ntp.org', 'time.google.com', 'time.cloudflare.com']
|
||||
|
||||
export default function NtpSettingsModal({ open, onClose, ntp, sendMqttCommand, onSaved }) {
|
||||
const [auto, setAuto] = useState(true)
|
||||
const [syncTime, setSyncTime] = useState('04:30')
|
||||
const [servers, setServers] = useState(['', '', ''])
|
||||
const [saving, setSaving] = useState(false)
|
||||
const [error, setError] = useState('')
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return
|
||||
setError('')
|
||||
setAuto(ntp?.auto ?? true)
|
||||
setSyncTime(ntp?.sync_time || '04:30')
|
||||
const list = ntp?.servers?.length ? ntp.servers : DEFAULT_SERVERS
|
||||
setServers([0, 1, 2].map(i => list[i] || ''))
|
||||
}, [open, ntp])
|
||||
|
||||
const serverList = servers.map(s => s.trim()).filter(Boolean)
|
||||
const badServer = serverList.find(s => s.length > 63 || /\s/.test(s))
|
||||
const invalid =
|
||||
serverList.length === 0 ? 'Enter at least one server.' :
|
||||
badServer ? `Invalid server: ${badServer}` :
|
||||
!/^\d{2}:\d{2}$/.test(syncTime) ? 'Choose a sync time.' : ''
|
||||
|
||||
const handleSave = async () => {
|
||||
if (invalid) return
|
||||
setSaving(true)
|
||||
setError('')
|
||||
try {
|
||||
const reply = await sendMqttCommand('clock.set_ntp', { auto, sync_time: syncTime, servers: serverList })
|
||||
onSaved?.(reply?.data || null)
|
||||
onClose()
|
||||
} catch (err) {
|
||||
setError(err.message || 'Failed to save NTP settings.')
|
||||
} finally {
|
||||
setSaving(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Modal
|
||||
open={open}
|
||||
onClose={onClose}
|
||||
title="NTP Settings"
|
||||
size="sm"
|
||||
footer={
|
||||
<div style={{ display: 'flex', justifyContent: 'flex-end', gap: 'var(--space-3)' }}>
|
||||
<Button variant="ghost" onClick={onClose}>Cancel</Button>
|
||||
<Button variant="primary" loading={saving} disabled={!!invalid} onClick={handleSave}>Save</Button>
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-5)' }}>
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-2)' }}>
|
||||
<span style={{ fontSize: 'var(--font-size-sm)', fontWeight: 'var(--font-weight-medium)', color: 'var(--color-text-secondary)' }}>
|
||||
Automatic sync
|
||||
</span>
|
||||
<SegmentedControl
|
||||
options={[{ value: 'on', label: 'On' }, { value: 'off', label: 'Off' }]}
|
||||
value={auto ? 'on' : 'off'}
|
||||
onChange={v => setAuto(v === 'on')}
|
||||
size="sm"
|
||||
/>
|
||||
<p style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-text-muted)' }}>
|
||||
{auto
|
||||
? 'Nightly sync, plus a sync after connecting while the clock is unconfirmed. At least 3 servers must agree; jumps over 10 minutes wait for a second sync.'
|
||||
: 'The device never syncs by itself. Use Sync Now to correct it.'}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<FormField
|
||||
label="Nightly sync time"
|
||||
name="ntpSyncTime"
|
||||
type="time"
|
||||
value={syncTime}
|
||||
onChange={e => setSyncTime(e.target.value)}
|
||||
hint="Device local time. Default 04:30 — after the usual 01:00–04:00 DST switch hours. Retried hourly for 3 hours if it fails."
|
||||
/>
|
||||
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-3)' }}>
|
||||
{[0, 1, 2].map(i => (
|
||||
<FormField
|
||||
key={i}
|
||||
label={`Server ${i + 1}${i ? ' (optional)' : ''}`}
|
||||
name={`ntpServer${i}`}
|
||||
value={servers[i]}
|
||||
onChange={e => setServers(list => list.map((s, j) => (j === i ? e.target.value : s)))}
|
||||
placeholder={DEFAULT_SERVERS[i]}
|
||||
/>
|
||||
))}
|
||||
<p style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-text-muted)' }}>
|
||||
Needs outbound UDP port 123 from the site network.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{invalid && serverList.length > 0 && (
|
||||
<p style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-warning)' }}>{invalid}</p>
|
||||
)}
|
||||
{error && <p style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-danger)' }}>{error}</p>}
|
||||
</div>
|
||||
</Modal>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
// frontend/src/modals/bellcloud/devices/SetDeviceTimeModal.jsx
|
||||
// Sets a device's clock by hand (firmware 3.0.0+, clock.set_time). Either the current time
|
||||
// from this computer (sent as UTC — the device shows it in its own timezone), or a local
|
||||
// wall-clock time typed in, which the device converts with its timezone. Normally NTP keeps
|
||||
// the time right; this is for sites without internet, or fixed / local-only timezones.
|
||||
|
||||
import { useEffect, useState } from 'react'
|
||||
import Modal from '@/components/ui/Modal'
|
||||
import Button from '@/components/ui/Button'
|
||||
import FormField from '@/components/ui/FormField'
|
||||
import SegmentedControl from '@/components/ui/SegmentedControl'
|
||||
import { fmtUtcOffset } from '@/lib/formatters'
|
||||
import { TZ_MODE_LABELS, epochToWallClock } from '@/lib/deviceTimezone'
|
||||
|
||||
export default function SetDeviceTimeModal({ open, onClose, timezone, ntp, sendMqttCommand, onSaved }) {
|
||||
const [source, setSource] = useState('computer')
|
||||
const [local, setLocal] = useState('')
|
||||
const [saving, setSaving] = useState(false)
|
||||
const [error, setError] = useState('')
|
||||
|
||||
const offset = timezone?.current_offset_min ?? 0
|
||||
const tzLabel = timezone
|
||||
? `${timezone.name || TZ_MODE_LABELS[timezone.mode]} (${fmtUtcOffset(offset)})`
|
||||
: 'the device timezone'
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return
|
||||
setError('')
|
||||
setSource(timezone?.mode === 'local' ? 'manual' : 'computer')
|
||||
setLocal(epochToWallClock(Math.floor(Date.now() / 1000), offset))
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [open])
|
||||
|
||||
const ntpWillCorrect = ntp?.auto && timezone && timezone.mode !== 'local'
|
||||
|
||||
const handleSave = async () => {
|
||||
setSaving(true)
|
||||
setError('')
|
||||
try {
|
||||
const contents = source === 'computer'
|
||||
? { timestamp: Math.floor(Date.now() / 1000) }
|
||||
: { local: local.length === 16 ? `${local}:00` : local }
|
||||
const reply = await sendMqttCommand('clock.set_time', contents)
|
||||
onSaved?.(reply?.data || null)
|
||||
onClose()
|
||||
} catch (err) {
|
||||
setError(err.message || 'Failed to set the time.')
|
||||
} finally {
|
||||
setSaving(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Modal
|
||||
open={open}
|
||||
onClose={onClose}
|
||||
title="Set Device Time"
|
||||
size="sm"
|
||||
footer={
|
||||
<div style={{ display: 'flex', justifyContent: 'flex-end', gap: 'var(--space-3)' }}>
|
||||
<Button variant="ghost" onClick={onClose}>Cancel</Button>
|
||||
<Button variant="primary" loading={saving} disabled={source === 'manual' && !local} onClick={handleSave}>Set Time</Button>
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-5)' }}>
|
||||
<SegmentedControl
|
||||
options={[{ value: 'computer', label: 'From this computer' }, { value: 'manual', label: 'Enter local time' }]}
|
||||
value={source}
|
||||
onChange={setSource}
|
||||
size="sm"
|
||||
/>
|
||||
|
||||
{source === 'computer' ? (
|
||||
<p style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-text-muted)' }}>
|
||||
Sends this computer's current time (as UTC). The device shows it in {tzLabel}.
|
||||
</p>
|
||||
) : (
|
||||
<FormField
|
||||
label="Local time on the device"
|
||||
name="deviceLocalTime"
|
||||
type="datetime-local"
|
||||
value={local}
|
||||
onChange={e => setLocal(e.target.value)}
|
||||
inputProps={{ step: 1 }}
|
||||
hint={`Wall-clock time in ${tzLabel}.`}
|
||||
/>
|
||||
)}
|
||||
|
||||
{ntpWillCorrect && (
|
||||
<p style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-warning)', backgroundColor: 'var(--color-warning-bg)', padding: 'var(--space-2) var(--space-3)', borderRadius: 'var(--radius-sm)' }}>
|
||||
Automatic NTP is on: if this differs from real time, the device corrects it at its next sync
|
||||
{timezone?.mode === 'fixed' ? ' (by up to 5 minutes in fixed mode)' : ''}.
|
||||
</p>
|
||||
)}
|
||||
{error && <p style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-danger)' }}>{error}</p>}
|
||||
</div>
|
||||
</Modal>
|
||||
)
|
||||
}
|
||||
@@ -1,67 +1,118 @@
|
||||
// frontend/src/modals/bellcloud/devices/SyncClockModal.jsx
|
||||
// Placeholder — clock sync UI to be implemented when MQTT sync protocol is defined.
|
||||
// Corrects where the device thinks the clocktower's hands are (clock.set_face).
|
||||
// Flow: pause the clock (clock.pause) so the hands stop while someone reads them, enter what
|
||||
// the face shows, then save (clock.set_face) and resume (clock.resume). The device then moves
|
||||
// the hands to the real time — forward only; with face sync "smart" it waits instead of a full
|
||||
// lap when the face is slightly ahead. Closing without saving resumes the clock.
|
||||
|
||||
import { useEffect, useState } from 'react'
|
||||
import Modal from '@/components/ui/Modal'
|
||||
import Button from '@/components/ui/Button'
|
||||
import Icon from '@/components/ui/Icon'
|
||||
import FormField from '@/components/ui/FormField'
|
||||
|
||||
export default function SyncClockModal({ open, onClose, device }) {
|
||||
const sn = device?.serial_number || device?.device_id
|
||||
const HOURS = Array.from({ length: 12 }, (_, i) => i + 1)
|
||||
const MINUTES = Array.from({ length: 60 }, (_, i) => i)
|
||||
const pad = n => String(n).padStart(2, '0')
|
||||
|
||||
export default function SyncClockModal({ open, onClose, face, sendMqttCommand, onSaved }) {
|
||||
const [paused, setPaused] = useState(false)
|
||||
const [pausing, setPausing] = useState(false)
|
||||
const [hour, setHour] = useState(12)
|
||||
const [minute, setMinute] = useState(0)
|
||||
const [saving, setSaving] = useState(false)
|
||||
const [error, setError] = useState('')
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return
|
||||
setPaused(false)
|
||||
setError('')
|
||||
setHour(face?.clock_hour || 12)
|
||||
setMinute(face?.clock_minute || 0)
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [open])
|
||||
|
||||
const handleClose = async () => {
|
||||
if (paused) {
|
||||
try { await sendMqttCommand('clock.resume') } catch { /* toast already shown */ }
|
||||
}
|
||||
onClose()
|
||||
}
|
||||
|
||||
const handlePause = async () => {
|
||||
setPausing(true)
|
||||
setError('')
|
||||
try {
|
||||
await sendMqttCommand('clock.pause')
|
||||
setPaused(true)
|
||||
} catch (err) {
|
||||
setError(err.message || 'Failed to pause the clock.')
|
||||
} finally {
|
||||
setPausing(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleSave = async () => {
|
||||
setSaving(true)
|
||||
setError('')
|
||||
try {
|
||||
await sendMqttCommand('clock.set_face', { hour, minute })
|
||||
await sendMqttCommand('clock.resume')
|
||||
setPaused(false)
|
||||
onSaved?.()
|
||||
onClose()
|
||||
} catch (err) {
|
||||
setError(err.message || 'Failed to set the clocktower time.')
|
||||
} finally {
|
||||
setSaving(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Modal
|
||||
open={open}
|
||||
onClose={onClose}
|
||||
onClose={handleClose}
|
||||
title="Sync Clocktower"
|
||||
size="sm"
|
||||
persistent={paused}
|
||||
footer={
|
||||
<div style={{ display: 'flex', justifyContent: 'flex-end', gap: 'var(--space-3)' }}>
|
||||
<Button variant="ghost" onClick={onClose}>Close</Button>
|
||||
<Button variant="primary" disabled>
|
||||
Sync (Coming Soon)
|
||||
</Button>
|
||||
<Button variant="ghost" onClick={handleClose}>{paused ? 'Cancel & Resume' : 'Cancel'}</Button>
|
||||
<Button variant="primary" loading={saving} onClick={handleSave}>Save & Resume</Button>
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 'var(--space-5)', padding: 'var(--space-4) 0', textAlign: 'center' }}>
|
||||
<div style={{
|
||||
width: 64,
|
||||
height: 64,
|
||||
borderRadius: 'var(--radius-full)',
|
||||
backgroundColor: 'var(--color-primary-subtle)',
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
}}>
|
||||
<Icon name="refresh" size={28} color="var(--color-primary)" />
|
||||
</div>
|
||||
<div>
|
||||
<p style={{ fontSize: 'var(--font-size-base)', fontWeight: 'var(--font-weight-semibold)', color: 'var(--color-text-primary)', marginBottom: 'var(--space-2)' }}>
|
||||
Clock Synchronisation
|
||||
</p>
|
||||
<p style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-text-muted)', maxWidth: 340 }}>
|
||||
This will send an MQTT command to correct the clocktower's mechanical position
|
||||
if it has drifted from the master time reference.
|
||||
</p>
|
||||
</div>
|
||||
{sn && (
|
||||
<div style={{
|
||||
padding: 'var(--space-3) var(--space-4)',
|
||||
borderRadius: 'var(--radius-md)',
|
||||
backgroundColor: 'var(--color-bg-elevated)',
|
||||
border: '1px solid var(--color-border)',
|
||||
width: '100%',
|
||||
}}>
|
||||
<span style={{ fontSize: 'var(--font-size-xs)', color: 'var(--color-text-muted)', textTransform: 'uppercase', letterSpacing: 'var(--tracking-wide)' }}>
|
||||
Target device
|
||||
</span>
|
||||
<p style={{ fontFamily: 'var(--font-family-mono)', fontSize: 'var(--font-size-sm)', color: 'var(--color-text-primary)', marginTop: 'var(--space-1)' }}>
|
||||
{sn}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
<p style={{ fontSize: 'var(--font-size-xs)', color: 'var(--color-text-muted)', fontStyle: 'italic' }}>
|
||||
Full sync implementation coming soon — MQTT protocol pending.
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-5)' }}>
|
||||
<p style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-text-muted)' }}>
|
||||
The device thinks the clocktower shows{' '}
|
||||
<span style={{ fontFamily: 'var(--font-family-mono)', color: 'var(--color-text-primary)' }}>
|
||||
{face ? `${pad(face.clock_hour)}:${pad(face.clock_minute)}` : '—'}
|
||||
</span>
|
||||
. If the hands show something else, enter what they really show.
|
||||
</p>
|
||||
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 'var(--space-3)' }}>
|
||||
<Button variant="secondary" size="sm" loading={pausing} disabled={paused} onClick={handlePause}>
|
||||
{paused ? 'Clock paused' : 'Pause clock'}
|
||||
</Button>
|
||||
<span style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-text-muted)' }}>
|
||||
Optional — stops the hands while you read them.
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 'var(--space-3)' }}>
|
||||
<FormField label="Hour on the face" name="faceHour" type="select" value={String(hour)} onChange={e => setHour(Number(e.target.value))}>
|
||||
{HOURS.map(h => <option key={h} value={String(h)}>{h}</option>)}
|
||||
</FormField>
|
||||
<FormField label="Minute on the face" name="faceMinute" type="select" value={String(minute)} onChange={e => setMinute(Number(e.target.value))}>
|
||||
{MINUTES.map(m => <option key={m} value={String(m)}>{pad(m)}</option>)}
|
||||
</FormField>
|
||||
</div>
|
||||
|
||||
<p style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-text-muted)' }}>
|
||||
After saving, the hands move forward to the real time. If the face is slightly ahead, the
|
||||
face sync setting decides: Force runs a full lap, Smart waits.
|
||||
</p>
|
||||
{error && <p style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-danger)' }}>{error}</p>}
|
||||
</div>
|
||||
</Modal>
|
||||
)
|
||||
|
||||
@@ -5,7 +5,13 @@ import api from '@/lib/api'
|
||||
import Card from '@/components/ui/Card'
|
||||
import Button from '@/components/ui/Button'
|
||||
import StatusBadge from '@/components/ui/StatusBadge'
|
||||
import { useToast } from '@/components/ui/Toast'
|
||||
import SyncClockModal from '@/modals/bellcloud/devices/SyncClockModal'
|
||||
import EditTimezoneModal from '@/modals/bellcloud/devices/EditTimezoneModal'
|
||||
import SetDeviceTimeModal from '@/modals/bellcloud/devices/SetDeviceTimeModal'
|
||||
import NtpSettingsModal from '@/modals/bellcloud/devices/NtpSettingsModal'
|
||||
import { fmtWallClock, fmtDeviceDateTime, fmtUtcOffset, fmtRelative } from '@/lib/formatters'
|
||||
import { TZ_MODE_LABELS } from '@/lib/deviceTimezone'
|
||||
|
||||
// ─── Helpers ──────────────────────────────────────────────────────────────────
|
||||
|
||||
@@ -44,19 +50,31 @@ function silenceLabel(isOn, from, to) {
|
||||
return 'On'
|
||||
}
|
||||
|
||||
function formatUtcOffset(offsetSec) {
|
||||
if (offsetSec == null) return null
|
||||
const totalMinutes = offsetSec / 60
|
||||
const sign = totalMinutes >= 0 ? '+' : '-'
|
||||
const abs = Math.abs(totalMinutes)
|
||||
const hours = Math.floor(abs / 60)
|
||||
const minutes = abs % 60
|
||||
return minutes === 0 ? `UTC${sign}${hours}` : `UTC${sign}${hours}:${String(minutes).padStart(2, '0')}`
|
||||
// clock.get_ntp last_sync.result → badge (firmware 3.1.0+)
|
||||
const SYNC_RESULTS = {
|
||||
applied: { variant: 'success', label: 'Corrected' },
|
||||
in_sync: { variant: 'success', label: 'In sync' },
|
||||
pending_confirmation: { variant: 'warning', label: 'Awaiting confirmation' },
|
||||
mismatch_not_applied: { variant: 'warning', label: 'Mismatch — not applied' },
|
||||
failed: { variant: 'danger', label: 'Failed' },
|
||||
}
|
||||
|
||||
function fmtDrift(ms) {
|
||||
if (ms == null) return null
|
||||
const abs = Math.abs(ms)
|
||||
const sign = ms < 0 ? '−' : '+'
|
||||
if (abs < 1000) return `${sign}${abs} ms`
|
||||
if (abs < 120000) return `${sign}${(abs / 1000).toFixed(1)} s`
|
||||
return `${sign}${Math.round(abs / 60000)} min`
|
||||
}
|
||||
|
||||
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms))
|
||||
|
||||
// ─── Analog Clock Face ────────────────────────────────────────────────────────
|
||||
|
||||
function AnalogClock({ time, label, variant = 'primary' }) {
|
||||
// `time` is a wall-clock Date read with UTC getters (device time is in the device's timezone,
|
||||
// not the browser's). null = unknown: the face is drawn without hands.
|
||||
function AnalogClock({ time, label, variant = 'primary', showSeconds = true }) {
|
||||
const canvasRef = useRef(null)
|
||||
|
||||
useEffect(() => {
|
||||
@@ -68,9 +86,9 @@ function AnalogClock({ time, label, variant = 'primary' }) {
|
||||
const cy = size / 2
|
||||
const r = size / 2 - 4
|
||||
|
||||
const h = time.getHours() % 12
|
||||
const m = time.getMinutes()
|
||||
const s = time.getSeconds()
|
||||
const h = time ? time.getUTCHours() % 12 : 0
|
||||
const m = time ? time.getUTCMinutes() : 0
|
||||
const s = time && showSeconds ? time.getUTCSeconds() : 0
|
||||
|
||||
const isPrimary = variant === 'primary'
|
||||
const accentColor = isPrimary ? 'rgba(192,193,255,0.9)' : 'rgba(192,193,255,0.35)'
|
||||
@@ -121,6 +139,8 @@ function AnalogClock({ time, label, variant = 'primary' }) {
|
||||
ctx.stroke()
|
||||
}
|
||||
|
||||
if (!time) return
|
||||
|
||||
// Hour hand
|
||||
const hourAngle = ((h + m / 60) / 12) * Math.PI * 2 - Math.PI / 2
|
||||
ctx.beginPath()
|
||||
@@ -142,23 +162,30 @@ function AnalogClock({ time, label, variant = 'primary' }) {
|
||||
ctx.stroke()
|
||||
|
||||
// Second hand
|
||||
const secAngle = (s / 60) * Math.PI * 2 - Math.PI / 2
|
||||
ctx.beginPath()
|
||||
ctx.moveTo(cx, cy)
|
||||
ctx.lineTo(cx + Math.cos(secAngle) * r * 0.82, cy + Math.sin(secAngle) * r * 0.82)
|
||||
ctx.strokeStyle = secondHandColor
|
||||
ctx.lineWidth = 1
|
||||
ctx.lineCap = 'round'
|
||||
ctx.stroke()
|
||||
if (showSeconds) {
|
||||
const secAngle = (s / 60) * Math.PI * 2 - Math.PI / 2
|
||||
ctx.beginPath()
|
||||
ctx.moveTo(cx, cy)
|
||||
ctx.lineTo(cx + Math.cos(secAngle) * r * 0.82, cy + Math.sin(secAngle) * r * 0.82)
|
||||
ctx.strokeStyle = secondHandColor
|
||||
ctx.lineWidth = 1
|
||||
ctx.lineCap = 'round'
|
||||
ctx.stroke()
|
||||
}
|
||||
|
||||
// Center dot
|
||||
ctx.beginPath()
|
||||
ctx.arc(cx, cy, isPrimary ? 4 : 3, 0, Math.PI * 2)
|
||||
ctx.fillStyle = centerDotColor
|
||||
ctx.fill()
|
||||
}, [time, variant])
|
||||
}, [time, variant, showSeconds])
|
||||
|
||||
const digitalTime = `${time.getHours().toString().padStart(2, '0')}:${time.getMinutes().toString().padStart(2, '0')}:${time.getSeconds().toString().padStart(2, '0')}`
|
||||
const pad2 = n => n.toString().padStart(2, '0')
|
||||
const digitalTime = !time
|
||||
? '—'
|
||||
: showSeconds
|
||||
? `${pad2(time.getUTCHours())}:${pad2(time.getUTCMinutes())}:${pad2(time.getUTCSeconds())}`
|
||||
: `${pad2(time.getUTCHours() % 12 || 12)}:${pad2(time.getUTCMinutes())}`
|
||||
|
||||
return (
|
||||
<div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 'var(--space-3)' }}>
|
||||
@@ -275,8 +302,16 @@ export default function ClockTab({
|
||||
loadDevice,
|
||||
reloadDeviceSilent,
|
||||
}) {
|
||||
const { toast } = useToast()
|
||||
const [now, setNow] = useState(new Date())
|
||||
const [showSync, setShowSync] = useState(false)
|
||||
const [showTimezone, setShowTimezone] = useState(false)
|
||||
const [showSetTime, setShowSetTime] = useState(false)
|
||||
const [showNtp, setShowNtp] = useState(false)
|
||||
const [syncingNtp, setSyncingNtp] = useState(false)
|
||||
// Live clock state read from the device (firmware 3.x) — the device is the source of truth
|
||||
// for time, timezone and NTP; none of it is mirrored to the device record.
|
||||
const [live, setLive] = useState({ status: 'loading', time: null, timeAt: 0, tz: null, ntp: null, face: null })
|
||||
const [flashFields, setFlashFields] = useState(false)
|
||||
const [togglingClock, setTogglingClock] = useState(false)
|
||||
|
||||
@@ -335,9 +370,8 @@ export default function ClockTab({
|
||||
trueBacklightOutput !== (clock?.backlightOutput || 0) ||
|
||||
(!!data.backlight && data.backlight_on !== extractTime(clock?.backlightTurnOnTime)) ||
|
||||
(!!data.backlight && data.backlight_off !== extractTime(clock?.backlightTurnOffTime)) ||
|
||||
(data.gmt_offset_sec != null && data.gmt_offset_sec !== clock?.gmtOffsetSec) ||
|
||||
(data.dst_offset_sec != null && data.dst_offset_sec !== clock?.dstOffsetSec) ||
|
||||
(data.ntp_server != null && data.ntp_server !== clock?.ntpServer)
|
||||
(data.face_sync_mode != null && data.face_sync_mode !== (clock?.faceSyncMode || 'force')) ||
|
||||
(data.smart_max_wait_min != null && data.smart_max_wait_min !== (clock?.smartMaxWaitMin ?? 61))
|
||||
|
||||
if (!hasDrift) return
|
||||
|
||||
@@ -363,18 +397,76 @@ export default function ClockTab({
|
||||
backlightOutput: trueBacklightOutput,
|
||||
backlightTurnOnTime: data.backlight_on ? `2000-01-01T${data.backlight_on}:00Z` : '',
|
||||
backlightTurnOffTime: data.backlight_off ? `2000-01-01T${data.backlight_off}:00Z` : '',
|
||||
gmtOffsetSec: data.gmt_offset_sec ?? clock?.gmtOffsetSec,
|
||||
dstOffsetSec: data.dst_offset_sec ?? clock?.dstOffsetSec,
|
||||
ntpServer: data.ntp_server ?? clock?.ntpServer,
|
||||
faceSyncMode: data.face_sync_mode ?? clock?.faceSyncMode ?? 'force',
|
||||
smartMaxWaitMin: data.smart_max_wait_min ?? clock?.smartMaxWaitMin ?? 61,
|
||||
},
|
||||
},
|
||||
}).then(() => reloadDeviceSilent?.())
|
||||
}).catch(() => {
|
||||
// Device offline or didn't reply — keep showing the last-known Firestore values.
|
||||
}).finally(() => {
|
||||
// Replies are matched FIFO (no req_id), so the live reads start only after this one
|
||||
loadLive()
|
||||
})
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [device?.id, device?.device_id])
|
||||
|
||||
// ── Live time / timezone / NTP / face from the device ─────────────────────
|
||||
// Replies are matched FIFO, so these go one after another.
|
||||
const loadLive = async (parts = ['time', 'tz', 'ntp', 'face']) => {
|
||||
if (!sendMqttCommandSilent) return
|
||||
const commands = { time: 'system.get_time', tz: 'clock.get_timezone', ntp: 'clock.get_ntp', face: 'clock.get_face' }
|
||||
const update = {}
|
||||
try {
|
||||
for (const part of parts) {
|
||||
const reply = await sendMqttCommandSilent(commands[part])
|
||||
update[part] = reply?.data || null
|
||||
if (part === 'time') update.timeAt = Date.now()
|
||||
}
|
||||
setLive(l => ({ ...l, ...update, status: 'ok' }))
|
||||
} catch {
|
||||
setLive(l => ({ ...l, ...update, status: l.status === 'ok' ? 'ok' : 'offline' }))
|
||||
}
|
||||
}
|
||||
|
||||
// The face moves a minute at a time — refresh it while the clock runs. Paused while a
|
||||
// modal or Sync Now may be sending commands, so FIFO reply matching can't cross wires.
|
||||
const busy = showSync || showTimezone || showSetTime || showNtp || syncingNtp
|
||||
useEffect(() => {
|
||||
if (!(attr?.hasClock) || live.status !== 'ok' || busy) return
|
||||
const id = setInterval(() => loadLive(['face']), 30000)
|
||||
return () => clearInterval(id)
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [attr?.hasClock, live.status, busy])
|
||||
|
||||
// Sync Now runs on the device in the background (firmware 3.1.0+): poll clock.get_ntp until done
|
||||
const handleSyncNow = async () => {
|
||||
setSyncingNtp(true)
|
||||
try {
|
||||
await sendMqttCommand('clock.sync_ntp')
|
||||
let ntp = null
|
||||
for (let i = 0; i < 10; i++) {
|
||||
await sleep(2000)
|
||||
ntp = (await sendMqttCommandSilent('clock.get_ntp'))?.data
|
||||
if (ntp && !ntp.sync_in_progress) break
|
||||
}
|
||||
setLive(l => ({ ...l, ntp: ntp || l.ntp }))
|
||||
const result = ntp?.last_sync
|
||||
if (!ntp || ntp.sync_in_progress || !result) {
|
||||
toast.warning('NTP sync', 'No result yet — check again in a moment.')
|
||||
} else {
|
||||
const label = SYNC_RESULTS[result.result]?.label || result.result
|
||||
const notify = result.result === 'failed' ? toast.danger : result.result.startsWith('mismatch') ? toast.warning : toast.success
|
||||
notify(`NTP: ${label}`, result.message)
|
||||
}
|
||||
await loadLive(['time'])
|
||||
} catch {
|
||||
// sendMqttCommand already showed the failure toast
|
||||
} finally {
|
||||
setSyncingNtp(false)
|
||||
}
|
||||
}
|
||||
|
||||
// ── Derived values ────────────────────────────────────────────────────────
|
||||
|
||||
const hasClock = attr?.hasClock ?? false
|
||||
@@ -399,9 +491,16 @@ export default function ClockTab({
|
||||
const backlightOnTime = extractTime(clock?.backlightTurnOnTime)
|
||||
const backlightOffTime = extractTime(clock?.backlightTurnOffTime)
|
||||
|
||||
const timezone = formatUtcOffset(clock?.gmtOffsetSec)
|
||||
const ntpServer = clock?.ntpServer || null
|
||||
const dstActive = !!clock?.dstOffsetSec
|
||||
const tz = live.tz
|
||||
const ntp = live.ntp
|
||||
const lastSync = ntp?.last_sync || null
|
||||
const syncBadge = lastSync ? (SYNC_RESULTS[lastSync.result] || { variant: 'neutral', label: lastSync.result }) : null
|
||||
// Device wall clock, ticking locally from the last system.get_time reply
|
||||
const deviceTime = live.time?.rtc_available
|
||||
? new Date(live.time.local_timestamp * 1000 + (now.getTime() - live.timeAt))
|
||||
: null
|
||||
const faceTime = live.face ? new Date(Date.UTC(2000, 0, 1, live.face.clock_hour % 12, live.face.clock_minute)) : null
|
||||
const liveMissing = live.status === 'loading' ? 'Loading…' : 'No reply from the device'
|
||||
|
||||
const alertTypeLabel =
|
||||
alertType === 'single' ? 'Single Fire' :
|
||||
@@ -576,8 +675,8 @@ export default function ClockTab({
|
||||
|
||||
{/* Right — clocks, with equal breathing room on all sides */}
|
||||
<div style={{ display: 'flex', alignItems: 'flex-start', gap: 'var(--space-12)', padding: '0 var(--space-8)' }}>
|
||||
<AnalogClock time={now} label="RTC Time" variant="primary" />
|
||||
<AnalogClock time={now} label="Clocktower" variant="primary" />
|
||||
<AnalogClock time={deviceTime} label="Device Time" variant="primary" />
|
||||
<AnalogClock time={faceTime} label="Clocktower" variant={hasClock ? 'primary' : 'secondary'} showSeconds={false} />
|
||||
</div>
|
||||
|
||||
</div>
|
||||
@@ -695,21 +794,91 @@ export default function ClockTab({
|
||||
</div>
|
||||
</Card>
|
||||
|
||||
{/* Network & Time */}
|
||||
<Card title="Network & Time">
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-2)' }}>
|
||||
<SettingRow label="Timezone" value={timezone || '—'} mono={!!timezone} />
|
||||
<SettingRow label="NTP Server" value={ntpServer || '—'} mono={!!ntpServer} />
|
||||
<SettingRow
|
||||
label="DST"
|
||||
badge={<StatusBadge variant={dstActive ? 'success' : 'neutral'}>{dstActive ? 'Active' : 'Not Active'}</StatusBadge>}
|
||||
/>
|
||||
</div>
|
||||
{canEdit && (
|
||||
<div style={{ marginTop: 'var(--space-4)', paddingTop: 'var(--space-4)', borderTop: '1px solid var(--color-border)' }}>
|
||||
<p style={{ fontSize: 'var(--font-size-xs)', color: 'var(--color-text-muted)' }}>
|
||||
Read-only — reported directly by the device. Editing timezone/NTP settings from the console is not yet supported.
|
||||
</p>
|
||||
{/* Time & Timezone (live from the device) */}
|
||||
<Card
|
||||
title="Time & Timezone"
|
||||
action={canEdit && live.status === 'ok' && (
|
||||
<div style={{ display: 'flex', gap: 'var(--space-2)' }}>
|
||||
<Button variant="ghost" size="sm" onClick={() => setShowSetTime(true)}>Set Time</Button>
|
||||
<Button variant="ghost" size="sm" onClick={() => setShowTimezone(true)}>Edit</Button>
|
||||
</div>
|
||||
)}
|
||||
>
|
||||
{live.status !== 'ok' || !tz ? (
|
||||
<p style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-text-muted)' }}>{liveMissing}</p>
|
||||
) : (
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-2)' }}>
|
||||
<SettingRow label="Local time" value={live.time?.local ? fmtWallClock(live.time.local) : '—'} />
|
||||
<SettingRow label="Timezone" value={tz.name || TZ_MODE_LABELS[tz.mode]} />
|
||||
<SettingRow label="Mode" value={TZ_MODE_LABELS[tz.mode] || tz.mode} />
|
||||
<SettingRow label="UTC offset" value={fmtUtcOffset(tz.current_offset_min)} mono />
|
||||
<SettingRow
|
||||
label="DST"
|
||||
badge={
|
||||
tz.mode === 'local' ? <StatusBadge variant="neutral">Not used</StatusBadge>
|
||||
: tz.dst_schedule_expired ? <StatusBadge variant="warning">Dates expired</StatusBadge>
|
||||
: <StatusBadge variant={tz.dst_active ? 'success' : 'neutral'}>{tz.dst_active ? 'Active' : 'Not active'}</StatusBadge>
|
||||
}
|
||||
/>
|
||||
{tz.next_transition > 0 && (
|
||||
<SettingRow label="Next change" value={fmtDeviceDateTime(tz.next_transition, tz.current_offset_min)} />
|
||||
)}
|
||||
<SettingRow
|
||||
label="Clock source"
|
||||
badge={<StatusBadge variant={live.time?.rtc_synced ? 'success' : 'warning'}>{live.time?.rtc_synced ? 'Synced' : 'Not synced yet'}</StatusBadge>}
|
||||
/>
|
||||
{tz.dst_schedule_expired && (
|
||||
<p style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-warning)', marginTop: 'var(--space-2)' }}>
|
||||
The manual DST dates have passed — enter next season's dates.
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</Card>
|
||||
|
||||
{/* NTP Sync (live from the device) */}
|
||||
<Card
|
||||
title="NTP Sync"
|
||||
action={canEdit && live.status === 'ok' && (
|
||||
<div style={{ display: 'flex', gap: 'var(--space-2)' }}>
|
||||
<Button variant="ghost" size="sm" loading={syncingNtp} disabled={tz?.mode === 'local'} onClick={handleSyncNow}>Sync Now</Button>
|
||||
<Button variant="ghost" size="sm" onClick={() => setShowNtp(true)}>Edit</Button>
|
||||
</div>
|
||||
)}
|
||||
>
|
||||
{live.status !== 'ok' || !ntp ? (
|
||||
<p style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-text-muted)' }}>{liveMissing}</p>
|
||||
) : (
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-2)' }}>
|
||||
<SettingRow
|
||||
label="Automatic"
|
||||
badge={<StatusBadge variant={ntp.auto && tz?.mode !== 'local' ? 'success' : 'neutral'}>
|
||||
{tz?.mode === 'local' ? 'Off (local mode)' : ntp.auto ? `Nightly ${ntp.sync_time}` : 'Off'}
|
||||
</StatusBadge>}
|
||||
/>
|
||||
<SettingRow label="Servers" value={(ntp.servers || []).join(', ') || '—'} mono />
|
||||
<SettingRow
|
||||
label="Last sync"
|
||||
badge={syncBadge ? <StatusBadge variant={syncBadge.variant}>{syncBadge.label}</StatusBadge> : null}
|
||||
value={syncBadge ? undefined : 'None since boot'}
|
||||
/>
|
||||
{lastSync && (
|
||||
<>
|
||||
<SettingRow label="When" value={lastSync.at ? fmtRelative(new Date(lastSync.at * 1000).toISOString()) : '—'} />
|
||||
<SettingRow label="Drift corrected" value={fmtDrift(lastSync.drift_ms) || '—'} mono />
|
||||
<SettingRow label="Servers answered" value={`${lastSync.servers_answered} / ${lastSync.servers_queried}`} />
|
||||
{lastSync.result !== 'applied' && lastSync.result !== 'in_sync' && (
|
||||
<p style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-text-muted)', marginTop: 'var(--space-2)' }}>
|
||||
{lastSync.message}
|
||||
</p>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
{ntp.pending_confirmation && (
|
||||
<p style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-warning)', marginTop: 'var(--space-2)' }}>
|
||||
A large correction is waiting for a second sync to confirm it.
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</Card>
|
||||
@@ -717,7 +886,35 @@ export default function ClockTab({
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<SyncClockModal open={showSync} onClose={() => setShowSync(false)} device={device} />
|
||||
<SyncClockModal
|
||||
open={showSync}
|
||||
onClose={() => setShowSync(false)}
|
||||
face={live.face}
|
||||
sendMqttCommand={sendMqttCommand}
|
||||
onSaved={() => loadLive(['face'])}
|
||||
/>
|
||||
<EditTimezoneModal
|
||||
open={showTimezone}
|
||||
onClose={() => setShowTimezone(false)}
|
||||
current={tz}
|
||||
sendMqttCommand={sendMqttCommand}
|
||||
onSaved={(data) => { setLive(l => ({ ...l, tz: data || l.tz })); loadLive(['time', 'ntp']) }}
|
||||
/>
|
||||
<SetDeviceTimeModal
|
||||
open={showSetTime}
|
||||
onClose={() => setShowSetTime(false)}
|
||||
timezone={tz}
|
||||
ntp={ntp}
|
||||
sendMqttCommand={sendMqttCommand}
|
||||
onSaved={(data) => { if (data) setLive(l => ({ ...l, time: data, timeAt: Date.now() })); loadLive(['tz']) }}
|
||||
/>
|
||||
<NtpSettingsModal
|
||||
open={showNtp}
|
||||
onClose={() => setShowNtp(false)}
|
||||
ntp={ntp}
|
||||
sendMqttCommand={sendMqttCommand}
|
||||
onSaved={(data) => setLive(l => ({ ...l, ntp: data || l.ntp }))}
|
||||
/>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -105,9 +105,9 @@ const NAMESPACES = [
|
||||
{ field: 'url', type: 'string', required: false, notes: 'Download URL, used only when the melody is neither built-in nor on SD. The field is "url" — "download_url" is NOT read by playback.play (that name belongs to files.download). Not sticky: omitted = no download possible for this play.' },
|
||||
{ field: 'speed', type: 'int', required: false, notes: 'ms per beat, 0–65535. Boot default 500. 0 is coerced to 300.' },
|
||||
{ field: 'note_assignments', type: 'int[]', required: false, notes: 'Up to 16 integers, each 0–16. Index = melody note (0-based); value = 1-based BELL channel to ring for that note (0 = silent) — not a relay output. Boot default [1,2,…,16]. A shorter array leaves the remaining entries at their previous values.' },
|
||||
{ field: 'mode', type: 'string', required: false, notes: '"single" | "timed" | "interval" | "infinite" — anything else is rejected. Selects the timing model (see warning). When present, segment_duration and continuous_loop are ignored.' },
|
||||
{ field: 'duration', type: 'int', required: false, notes: 'ms, ≥ 0. Read only when mode is present; must be > 0 for "timed"/"interval". "timed": loop until duration elapses, finish the current loop, stop. "interval": length of each play segment. Ignored for "single"/"infinite".' },
|
||||
{ field: 'pause_duration', type: 'int', required: false, notes: 'ms between segments. Read for mode "interval", or when mode is absent.' },
|
||||
{ field: 'mode', type: 'string', required: false, notes: '"single" | "timed" | "interval" | "infinite" — anything else is rejected. When present, segment_duration and continuous_loop are ignored. "single": play the melody once, start to end, then stop. "timed": loop back-to-back; once duration has passed, finish the current loop and stop. No pauses. "interval": play duration, pause pause_duration, repeat; stop once total_duration has passed since the start, pauses included (0 = never). "infinite": never stops on its own (only playback.stop). With no duration/pause_duration it loops continuously; with both it plays duration, pauses pause_duration, and repeats forever. total_duration is ignored. See the warning for exact timing.' },
|
||||
{ field: 'duration', type: 'int', required: false, notes: 'ms, ≥ 0. Read only when mode is present; must be > 0 for "timed"/"interval". "timed": loop until duration elapses, finish the current loop, stop. "interval": length of each play segment. "infinite": optional segment length; must be sent together with pause_duration (both > 0, or both omitted). Ignored for "single".' },
|
||||
{ field: 'pause_duration', type: 'int', required: false, notes: 'ms of silence between segments, counted from the end of the loop that was playing when the segment ran out. Read for mode "interval" and "infinite", or when mode is absent.' },
|
||||
{ field: 'total_duration', type: 'int', required: false, notes: 'ms overall cap. Read for mode "interval" (0 = forever), or when mode is absent AND continuous_loop is true. With mode absent and continuous_loop false it is IGNORED (overwritten with segment_duration).' },
|
||||
{ field: 'segment_duration', type: 'int', required: false, notes: 'Legacy — read only when mode is absent. With continuous_loop false this is the whole run length (sticky, boot default 15000; 0 = play once). With continuous_loop true it is the segment length.' },
|
||||
{ field: 'continuous_loop', type: 'bool', required: false, notes: 'Legacy — read only when mode is absent. Defaults to false on every command (not sticky).' },
|
||||
@@ -125,14 +125,15 @@ const NAMESPACES = [
|
||||
{ message: 'Invalid total_duration: must be a non-negative integer (ms)', condition: 'Same, for total_duration' },
|
||||
{ message: 'Invalid mode: must be single, timed, interval or infinite', condition: 'Unrecognised mode' },
|
||||
{ message: 'Invalid duration: mode timed and interval require duration > 0', condition: 'mode is timed/interval and duration is missing or 0' },
|
||||
{ message: 'Invalid infinite segments: duration and pause_duration must both be > 0, or both omitted', condition: 'mode is infinite and only one of duration / pause_duration is > 0' },
|
||||
{ message: 'Playback blocked: bell mechanism is disabled (bells.enable)', condition: 'Bells master switch is off (bells.disable)' },
|
||||
{ message: 'Playback blocked: bell overload protection active — wait for the bells to cool', condition: 'Load guard enabled and a bell is over its max load (the guard would force-stop immediately)' },
|
||||
{ message: 'Melody failed to load: file is empty or corrupt', condition: '/melodies/{pid} exists on SD but is empty or has an odd byte count' },
|
||||
{ message: 'Melody not found: not built-in, not on SD card, and no url given', condition: 'Needs a download but no url was sent' },
|
||||
{ message: 'Melody not found locally and this device has no SD card to download it to', condition: 'Needs a download but the build has no SD card / FileManager (agnus)' },
|
||||
],
|
||||
example: '// single — play once and stop\n{ "v": 2, "req_id": "a1", "cmd": "playback.play", "contents": { "pid": "westminster", "speed": 400, "mode": "single" } }\n\n// timed — loop for 2 minutes, finish the loop, stop (downloads first if needed)\n{ "v": 2, "cmd": "playback.play", "contents": { "pid": "ABC123", "url": "https://example.com/ABC123.bin", "mode": "timed", "duration": 120000 } }\n\n// interval — play 15 s, pause 5 s, repeat for 3 min total\n{ "v": 2, "cmd": "playback.play", "contents": { "pid": "ABC123", "mode": "interval", "duration": 15000, "pause_duration": 5000, "total_duration": 180000 } }\n\n// legacy timing (no mode)\n{ "v": 2, "cmd": "playback.play", "contents": { "pid": "ABC123", "segment_duration": 15000, "pause_duration": 5000, "continuous_loop": true } }',
|
||||
warning: 'mode decides which timing fields are read. mode present: duration (+ pause_duration / total_duration for "interval") — segment_duration and continuous_loop are ignored. mode absent (legacy): continuous_loop false → run for segment_duration, total_duration ignored; continuous_loop true → segment_duration segments with pause_duration gaps, stopping after total_duration if given this command, else segment_duration if given, else the previous total_duration (0 = forever). Never mix the two sets expecting both to apply.',
|
||||
example: '// single — play once and stop\n{ "v": 2, "req_id": "a1", "cmd": "playback.play", "contents": { "pid": "westminster", "speed": 400, "mode": "single" } }\n\n// timed — loop for 2 minutes, finish the loop, stop (downloads first if needed)\n{ "v": 2, "cmd": "playback.play", "contents": { "pid": "ABC123", "url": "https://example.com/ABC123.bin", "mode": "timed", "duration": 120000 } }\n\n// interval — play 15 s, pause 5 s, repeat for 3 min total\n{ "v": 2, "cmd": "playback.play", "contents": { "pid": "ABC123", "mode": "interval", "duration": 15000, "pause_duration": 5000, "total_duration": 180000 } }\n\n// infinite — loop until playback.stop\n{ "v": 2, "cmd": "playback.play", "contents": { "pid": "ABC123", "mode": "infinite" } }\n\n// infinite with segments — play 30 s, pause 10 s, forever\n{ "v": 2, "cmd": "playback.play", "contents": { "pid": "ABC123", "mode": "infinite", "duration": 30000, "pause_duration": 10000 } }\n\n// legacy timing (no mode)\n{ "v": 2, "cmd": "playback.play", "contents": { "pid": "ABC123", "segment_duration": 15000, "pause_duration": 5000, "continuous_loop": true } }',
|
||||
warning: 'Exact timing: (1) timing is checked every 500 ms, so every duration / pause / total boundary is hit up to 0.5 s late. (2) A loop is never cut short (only playback.stop and the overload guard do that); when a segment or the run ends mid-loop, the current loop finishes first. (3) At a segment end status/playback goes "paused" straight away while that loop finishes ringing; at the end of a timed/interval run it goes "stopping", then "idle". "single" goes from "playing" directly to "idle". (4) The bells are then silent for the full pause_duration, counted from that loop end, and status goes back to "playing". (5) total_duration counts from the start, pauses included; if it runs out during a pause, playback stops at once. (6) No gap between loops: in every looping mode the next loop starts right after the previous one; the last step\'s beat (speed) is the only spacing (firmware 2.5.1+; older builds waited ~0.5 s between loops when the run had no end time). Which timing fields are read: mode present → duration (+ pause_duration for "infinite", + pause_duration / total_duration for "interval"); segment_duration and continuous_loop are ignored. mode absent (legacy): continuous_loop false → run for segment_duration, total_duration ignored; continuous_loop true → segment_duration segments with pause_duration gaps, stopping after total_duration if given this command, else segment_duration if given, else the previous total_duration (0 = forever). Never mix the two sets expecting both to apply.',
|
||||
},
|
||||
{
|
||||
cmd: 'playback.stop',
|
||||
@@ -373,13 +374,17 @@ const NAMESPACES = [
|
||||
{ field: 'c2', type: 'int', required: false, notes: 'Relay output for clock pulse 2 (1-based). 0 = disabled.' },
|
||||
{ field: 'pulse_duration', type: 'int', required: false, notes: 'Duration of each clock pulse in milliseconds.' },
|
||||
{ field: 'pause_duration', type: 'int', required: false, notes: 'Pause between C1 and C2 pulses in milliseconds.' },
|
||||
{ field: 'face_sync_mode', type: 'string', required: false, notes: 'fw 3.2.0+. "force" (default) or "smart". The face only moves forward: when it is AHEAD of real time (DST fall-back, a correction), force runs it round the dial to catch up; smart stops it until real time catches up, if it is at most smart_max_wait_min ahead (otherwise it runs the lap).' },
|
||||
{ field: 'smart_max_wait_min', type: 'int', required: false, notes: 'fw 3.2.0+. 1-359, default 61 (covers a DST fall-back). Capped below 6 h because a face ahead by N minutes reads the same as one behind by 720 - N.' },
|
||||
],
|
||||
response: '{ "status": "SUCCESS", "type": "clock.set_config", "message": "Clock configuration updated and saved" }',
|
||||
errors: [
|
||||
{ message: 'Provide at least one field: enabled, c1, c2, pulse_duration, pause_duration', condition: 'No known fields present in contents' },
|
||||
{ message: 'Provide at least one field: enabled, c1, c2, pulse_duration, pause_duration, face_sync_mode, smart_max_wait_min', condition: 'No known fields present in contents' },
|
||||
{ message: 'face_sync_mode must be "force" or "smart"', condition: 'Any other value' },
|
||||
{ message: 'smart_max_wait_min must be 1-359', condition: 'Out of range or not an integer' },
|
||||
{ message: 'Settings applied but failed to save to SD', condition: 'SD card write failed after applying values' },
|
||||
],
|
||||
example: '{ "v": 2, "cmd": "clock.set_config", "contents": { "enabled": true, "c1": 5, "c2": 6, "pulse_duration": 100, "pause_duration": 500 } }',
|
||||
example: '{ "v": 2, "cmd": "clock.set_config", "contents": { "enabled": true, "c1": 5, "c2": 6, "pulse_duration": 100, "pause_duration": 500 } }\n\n{ "v": 2, "cmd": "clock.set_config", "contents": { "face_sync_mode": "smart", "smart_max_wait_min": 61 } }',
|
||||
warning: null,
|
||||
},
|
||||
{
|
||||
@@ -412,19 +417,26 @@ const NAMESPACES = [
|
||||
cmd: 'clock.set_time',
|
||||
handler: 'ClockHandler',
|
||||
transports: ['All'],
|
||||
description: 'Set the RTC time directly. timezone_offset and dst_offset are only applied when BOTH are present (they also update the stored timezone); with only one, or neither, timestamp is written to the RTC as-is.',
|
||||
description: 'Set the clock (fw 3.0.0+: the RTC always holds UTC). Send exactly one of timestamp (UTC) or local (wall-clock time, converted to UTC immediately with the timezone being set, or the current one). An optional timezone object is applied in the same step; everything is validated first, so on any error nothing changes. In the repeated hour of a DST fall-back the first (DST) occurrence is used; a local time inside the spring-forward gap is moved forward by the gap.',
|
||||
contents: [
|
||||
{ field: 'timestamp', type: 'int', required: true, notes: 'Unix epoch timestamp (UTC when both offsets are sent; written as-is otherwise)' },
|
||||
{ field: 'timezone_offset', type: 'int', required: false, notes: 'Total UTC offset in seconds incl. DST (e.g. 10800 for UTC+2 with DST). Ignored unless dst_offset is also sent.' },
|
||||
{ field: 'dst_offset', type: 'int', required: false, notes: 'DST offset in seconds. Ignored unless timezone_offset is also sent.' },
|
||||
{ field: 'timestamp', type: 'int', required: false, notes: 'UTC Unix epoch seconds (2024..2099). Exactly one of timestamp / local.' },
|
||||
{ field: 'local', type: 'string', required: false, notes: 'Local wall-clock time "YYYY-MM-DDTHH:MM:SS" (a space instead of T is accepted). Exactly one of timestamp / local. With timezone mode local this IS the device time (offset 0).' },
|
||||
{ field: 'timezone', type: 'object', required: false, notes: 'Timezone object. mode auto: posix (required) + name. mode manual: std_offset_min, dst_offset_min, dst_start, dst_end (all required) + name. mode fixed: std_offset_min (required), dst_offset_min (default 0) + name. mode local: no other fields. Same validation and errors as clock.set_timezone.' },
|
||||
],
|
||||
response: '{ "status": "SUCCESS", "type": "clock.set_time", "message": "RTC time updated successfully" }',
|
||||
response: '{\n "status": "SUCCESS",\n "type": "clock.set_time",\n "data": {\n "rtc_available": true, "rtc_synced": true,\n "utc_timestamp": 1793196300, "local_timestamp": 1793203500,\n "local": "2026-10-28T16:05:00",\n "offset_min": 120, "dst_active": false,\n "tz_mode": "auto", "tz_name": "Europe/Athens",\n "year": 2026, "month": 10, "day": 28, "hour": 16, "minute": 5, "second": 0, "weekday": 3\n }\n}',
|
||||
errors: [
|
||||
{ message: 'Missing required field: timestamp', condition: 'contents.timestamp is absent' },
|
||||
{ message: 'Invalid timestamp value', condition: 'timestamp is 0' },
|
||||
{ message: 'RTC time set but verification failed', condition: 'RTC read-back returned 0 after the write — hardware issue' },
|
||||
{ message: 'Provide exactly one of: timestamp (UTC epoch) or local', condition: 'Both or neither present' },
|
||||
{ message: 'Invalid local time (expected YYYY-MM-DDTHH:MM:SS)', condition: 'Malformed or impossible date (e.g. Feb 29 in a non-leap year), year outside 2000..2099' },
|
||||
{ message: 'Time out of range (2024..2099)', condition: 'Resulting UTC before 2024-01-01 or after 2099' },
|
||||
{ message: 'RTC write failed (read-back mismatch)', condition: 'RTC did not hold the written value (hardware fault)' },
|
||||
{ message: 'Missing required field: mode', condition: 'mode absent' },
|
||||
{ message: 'Invalid mode (expected auto, manual, fixed or local)', condition: 'mode is not one of the four values (lowercase)' },
|
||||
{ message: 'Missing required field: posix', condition: 'mode auto without posix' },
|
||||
{ message: 'Missing required fields for manual: std_offset_min, dst_offset_min, dst_start, dst_end', condition: 'mode manual with any of them missing' },
|
||||
{ message: 'Missing required field: std_offset_min', condition: 'mode fixed without std_offset_min' },
|
||||
{ message: 'Invalid timezone: <reason>', condition: 'Reasons: posix is not a valid POSIX TZ rule | posix too long | name too long | std_offset_min out of range (-720..840) | dst_offset_min must be non-zero, -180..180 | dst_offset_min out of range (-180..180) | dst_end must be after dst_start | dst_start..dst_end spans more than one season' },
|
||||
],
|
||||
example: '{\n "v": 2,\n "cmd": "clock.set_time",\n "contents": { "timestamp": 1740000000, "timezone_offset": 7200, "dst_offset": 3600 }\n}',
|
||||
example: '{\n "v": 2,\n "cmd": "clock.set_time",\n "contents": { "timestamp": 1793145600 }\n}\n\n{\n "v": 2,\n "cmd": "clock.set_time",\n "contents": {\n "local": "2026-10-28T14:05:00",\n "timezone": { "mode": "fixed", "name": "Site time", "std_offset_min": 120, "dst_offset_min": 0 }\n }\n}\n\n{\n "v": 2,\n "cmd": "clock.set_time",\n "contents": { "local": "2026-10-28T14:05:00", "timezone": { "mode": "local" } }\n}',
|
||||
warning: null,
|
||||
},
|
||||
{
|
||||
@@ -450,26 +462,35 @@ const NAMESPACES = [
|
||||
cmd: 'clock.set_timezone',
|
||||
handler: 'ClockHandler',
|
||||
transports: ['All'],
|
||||
description: 'Set timezone independently of RTC time. Does not alter the stored time value — only changes how it is displayed/offset.',
|
||||
description: 'Set the timezone (fw 3.0.0+). The RTC (UTC) is not touched; only the UTC to local conversion changes, so the physical clock, alerts and events follow immediately. Modes: auto = IANA zone + POSIX rule, DST switches every year by itself (the normal case; take the rule from the backend timezone table, never build it by hand: POSIX signs are inverted, EET-2 means UTC+2). manual = std offset + one DST amount active between dst_start and dst_end (one season, re-enter yearly). fixed = constant offsets, never switch. local = offset 0, the device keeps local time as if it were UTC. Offsets are minutes EAST of UTC (UTC+2 = 120, India = 330).',
|
||||
contents: [
|
||||
{ field: 'gmt_offset_sec', type: 'int', required: true, notes: 'GMT offset in seconds (e.g. 7200 for UTC+2)' },
|
||||
{ field: 'dst_offset_sec', type: 'int', required: false, notes: 'DST offset in seconds (e.g. 3600)' },
|
||||
{ field: 'mode', type: 'string', required: true, notes: 'auto | manual | fixed | local (lowercase)' },
|
||||
{ field: 'name', type: 'string', required: false, notes: 'Display name, max 47 chars. For auto use the IANA name, e.g. "Europe/Athens". Forced to "Local" in mode local.' },
|
||||
{ field: 'posix', type: 'string', required: false, notes: 'auto only, required there. POSIX TZ rule, max 63 chars, e.g. "EET-2EEST,M3.5.0/3,M10.5.0/4". DST zones must include start/end rules.' },
|
||||
{ field: 'std_offset_min', type: 'int', required: false, notes: 'manual + fixed (required there). Standard offset in minutes east of UTC, -720..840.' },
|
||||
{ field: 'dst_offset_min', type: 'int', required: false, notes: 'manual: DST amount, required, non-zero, -180..180 (usually 60). fixed: current DST offset, optional, default 0.' },
|
||||
{ field: 'dst_start', type: 'int', required: false, notes: 'manual only, required. UTC epoch when DST starts.' },
|
||||
{ field: 'dst_end', type: 'int', required: false, notes: 'manual only, required. UTC epoch when DST ends; after dst_start, at most ~400 days later.' },
|
||||
],
|
||||
response: '{ "status": "SUCCESS", "type": "clock.set_timezone", "message": "Timezone updated and saved" }',
|
||||
response: '{\n "status": "SUCCESS",\n "type": "clock.set_timezone",\n "data": {\n "mode": "auto", "name": "Europe/Athens",\n "posix": "EET-2EEST,M3.5.0/3,M10.5.0/4",\n "std_offset_min": 120, "dst_offset_min": 60,\n "dst_start": 0, "dst_end": 0,\n "current_offset_min": 120, "dst_active": false,\n "next_transition": 1806195600, "dst_schedule_expired": false\n }\n}',
|
||||
errors: [
|
||||
{ message: 'Missing required field: gmt_offset_sec', condition: 'contents.gmt_offset_sec is absent' },
|
||||
{ message: 'Timezone updated but failed to save to SD', condition: 'SD card write failed' },
|
||||
{ message: 'Missing required field: mode', condition: 'mode absent' },
|
||||
{ message: 'Invalid mode (expected auto, manual, fixed or local)', condition: 'mode is not one of the four values (lowercase)' },
|
||||
{ message: 'Missing required field: posix', condition: 'mode auto without posix' },
|
||||
{ message: 'Missing required fields for manual: std_offset_min, dst_offset_min, dst_start, dst_end', condition: 'mode manual with any of them missing' },
|
||||
{ message: 'Missing required field: std_offset_min', condition: 'mode fixed without std_offset_min' },
|
||||
{ message: 'Invalid timezone: <reason>', condition: 'Reasons: posix is not a valid POSIX TZ rule | posix too long | name too long | std_offset_min out of range (-720..840) | dst_offset_min must be non-zero, -180..180 | dst_offset_min out of range (-180..180) | dst_end must be after dst_start | dst_start..dst_end spans more than one season' },
|
||||
],
|
||||
example: '{ "v": 2, "cmd": "clock.set_timezone", "contents": { "gmt_offset_sec": 7200, "dst_offset_sec": 3600 } }',
|
||||
example: '{\n "v": 2,\n "cmd": "clock.set_timezone",\n "contents": { "mode": "auto", "name": "Australia/Sydney", "posix": "AEST-10AEDT,M10.1.0,M4.1.0/3" }\n}\n\n{\n "v": 2,\n "cmd": "clock.set_timezone",\n "contents": {\n "mode": "manual", "name": "Custom",\n "std_offset_min": 120, "dst_offset_min": 60,\n "dst_start": 1774746000, "dst_end": 1792890000\n }\n}\n\n{ "v": 2, "cmd": "clock.set_timezone", "contents": { "mode": "fixed", "std_offset_min": 330 } }',
|
||||
warning: null,
|
||||
},
|
||||
{
|
||||
cmd: 'clock.get_timezone',
|
||||
handler: 'ClockHandler',
|
||||
transports: ['All'],
|
||||
description: 'Read current timezone settings.',
|
||||
description: 'Read the timezone and its live state. All fields are always present (unused ones are 0 or ""). In auto, std_offset_min / dst_offset_min are derived from the rule. next_transition = UTC epoch of the next offset change (0 if none known). dst_schedule_expired is true only in manual once dst_end has passed (ask the user for next year\'s dates).',
|
||||
contents: null,
|
||||
response: '{\n "status": "SUCCESS",\n "type": "clock.get_timezone",\n "data": {\n "gmt_offset_sec": 7200,\n "dst_offset_sec": 3600,\n "ntp_server": "pool.ntp.org"\n }\n}',
|
||||
response: '{\n "status": "SUCCESS",\n "type": "clock.get_timezone",\n "data": {\n "mode": "auto", "name": "Europe/Athens",\n "posix": "EET-2EEST,M3.5.0/3,M10.5.0/4",\n "std_offset_min": 120, "dst_offset_min": 60,\n "dst_start": 0, "dst_end": 0,\n "current_offset_min": 120, "dst_active": false,\n "next_transition": 1806195600, "dst_schedule_expired": false\n }\n}',
|
||||
errors: [],
|
||||
example: '{ "v": 2, "cmd": "clock.get_timezone" }',
|
||||
warning: null,
|
||||
@@ -478,13 +499,52 @@ const NAMESPACES = [
|
||||
cmd: 'clock.sync_ntp',
|
||||
handler: 'ClockHandler',
|
||||
transports: ['All'],
|
||||
description: 'Run an NTP time sync (blocks up to ~5 s). Always returns SUCCESS — the outcome is only logged.',
|
||||
description: 'Sync now (fw 3.1.0+). Queues a user-initiated NTP session and replies immediately; the session (a few seconds: 5 queries over the configured servers, at least 3 must answer and agree within 1 s) runs on the TimeSync task, never on the network thread. Poll clock.get_ntp until sync_in_progress is false; the outcome is in last_sync. Works even with auto off. Applies a correction of any size at once (automatic syncs hold jumps over 10 min for a second session), except in fixed timezone mode, where differences over 5 min are reported as mismatch_not_applied and never applied.',
|
||||
contents: null,
|
||||
response: '{ "status": "SUCCESS", "type": "clock.sync_ntp", "message": "NTP sync initiated" }',
|
||||
errors: [],
|
||||
response: '{ "status": "SUCCESS", "type": "clock.sync_ntp", "data": { "started": true } }',
|
||||
errors: [
|
||||
{ message: 'NTP is not used in local timezone mode', condition: 'Timezone mode is local' },
|
||||
{ message: 'No network connection', condition: 'Not connected' },
|
||||
{ message: 'Device is in AP mode (no internet)', condition: 'Running its own access point' },
|
||||
{ message: 'A sync is already running - check clock.get_ntp in a few seconds', condition: 'A session is queued or running' },
|
||||
],
|
||||
example: '{ "v": 2, "cmd": "clock.sync_ntp" }',
|
||||
warning: null,
|
||||
},
|
||||
{
|
||||
cmd: 'clock.set_ntp',
|
||||
handler: 'ClockHandler',
|
||||
transports: ['All'],
|
||||
description: 'NTP settings (fw 3.1.0+). Automatic syncs = nightly at sync_time (local time, retried hourly for 3 h if it fails), a few seconds after a network (re)connect while the RTC is not yet synced this boot, every 5 min while the RTC is untrusted, and the confirmation session for large jumps. None of them run in local timezone mode. Replies with the clock.get_ntp payload.',
|
||||
contents: [
|
||||
{ field: 'auto', type: 'bool', required: false, notes: 'Automatic syncs on/off (default true). Off = only clock.sync_ntp. At least one of auto / sync_time / servers.' },
|
||||
{ field: 'sync_time', type: 'string', required: false, notes: 'Nightly sync time "HH:MM", device local time, default "04:30" (outside the usual 01:00-04:00 DST switch hours).' },
|
||||
{ field: 'servers', type: 'string[]', required: false, notes: '1-3 NTP host names, queried round-robin. Default ["pool.ntp.org", "time.google.com", "time.cloudflare.com"]. Needs outbound UDP 123.' },
|
||||
],
|
||||
response: '{\n "status": "SUCCESS",\n "type": "clock.set_ntp",\n "data": {\n "auto": true,\n "sync_time": "04:30", "sync_time_min": 270,\n "servers": ["pool.ntp.org", "time.google.com", "time.cloudflare.com"],\n "rtc_synced": true, "sync_in_progress": false, "pending_confirmation": false,\n "last_sync": {\n "result": "applied", "message": "RTC corrected", "applied": true,\n "servers_answered": 5, "servers_queried": 5,\n "ntp_utc": 1793196300, "drift_ms": 3412,\n "at": 1793196301, "user_initiated": true\n }\n }\n}',
|
||||
errors: [
|
||||
{ message: 'Provide at least one of: auto, sync_time, servers', condition: 'None present' },
|
||||
{ message: 'sync_time must be "HH:MM" (00:00-23:59)', condition: 'Malformed or out of range' },
|
||||
{ message: 'servers must be an array of 1-3 host names', condition: 'Not an array, empty, or more than 3' },
|
||||
{ message: 'Invalid server host name', condition: 'Empty, longer than 63 chars, or contains a space' },
|
||||
{ message: 'Settings busy - try again', condition: 'State lock not available within 1 s (should not happen)' },
|
||||
],
|
||||
example: '{\n "v": 2,\n "cmd": "clock.set_ntp",\n "contents": { "auto": true, "sync_time": "03:15" }\n}',
|
||||
warning: null,
|
||||
},
|
||||
{
|
||||
cmd: 'clock.get_ntp',
|
||||
handler: 'ClockHandler',
|
||||
transports: ['All'],
|
||||
description: 'NTP settings and state (fw 3.1.0+). rtc_synced = the RTC holds real UTC (set by NTP or clock.set_time). last_sync is null until the first session since boot. last_sync.result: applied | in_sync (RTC within 2 s, nothing written) | pending_confirmation (automatic jump over 10 min, waiting for a second session ~15 min later) | mismatch_not_applied (fixed mode, over 5 min off) | failed (message says why). drift_ms = NTP minus RTC before any write; ntp_utc and at are UTC epoch seconds.',
|
||||
contents: null,
|
||||
response: '{\n "status": "SUCCESS",\n "type": "clock.get_ntp",\n "data": {\n "auto": true,\n "sync_time": "04:30", "sync_time_min": 270,\n "servers": ["pool.ntp.org", "time.google.com", "time.cloudflare.com"],\n "rtc_synced": true, "sync_in_progress": false, "pending_confirmation": false,\n "last_sync": {\n "result": "applied", "message": "RTC corrected", "applied": true,\n "servers_answered": 5, "servers_queried": 5,\n "ntp_utc": 1793196300, "drift_ms": 3412,\n "at": 1793196301, "user_initiated": true\n }\n }\n}',
|
||||
errors: [
|
||||
{ message: 'Settings busy - try again', condition: 'State lock not available within 1 s (should not happen)' },
|
||||
],
|
||||
example: '{ "v": 2, "cmd": "clock.get_ntp" }',
|
||||
warning: null,
|
||||
},
|
||||
{
|
||||
cmd: 'clock.enable',
|
||||
handler: 'ClockHandler',
|
||||
@@ -548,9 +608,9 @@ const NAMESPACES = [
|
||||
cmd: 'clock.get_config',
|
||||
handler: 'ClockHandler',
|
||||
transports: ['All'],
|
||||
description: 'Read full clock configuration — outputs, timings, alerts, backlight, silence, enabled state, and timezone. Supersedes clock.get_timezone.',
|
||||
description: 'Read full clock configuration — outputs, timings, alerts, backlight, silence, enabled state, NTP settings and timezone (timezone = the clock.get_timezone object, fw 3.0.0 replaced gmt_offset_sec / dst_offset_sec; ntp = the settings part of clock.get_ntp, fw 3.1.0 replaced ntp_server).',
|
||||
contents: null,
|
||||
response: '{\n "status": "SUCCESS",\n "type": "clock.get_config",\n "data": {\n "enabled": true,\n "c1output": 4, "c2output": 5,\n "pulse_duration": 100, "pause_duration": 500,\n "physical_hour": 10, "physical_minute": 30,\n "next_is_c1": true, "last_sync_time": 1740000000,\n "alert_type": "HOURS", "alert_interval": 1,\n "hour_bell": 5, "half_bell": 255, "quarter_bell": 255,\n "backlight": true, "backlight_output": 6,\n "backlight_on": "07:00", "backlight_off": "22:00",\n "daytime_silence": false, "daytime_on": "00:00", "daytime_off": "00:00",\n "night_silence": true, "night_on": "22:00", "night_off": "07:00",\n "gmt_offset_sec": 7200, "dst_offset_sec": 3600, "ntp_server": "pool.ntp.org"\n }\n}',
|
||||
response: '{\n "status": "SUCCESS",\n "type": "clock.get_config",\n "data": {\n "enabled": true,\n "c1output": 4, "c2output": 5,\n "pulse_duration": 100, "pause_duration": 500,\n "physical_hour": 10, "physical_minute": 30,\n "next_is_c1": true, "last_sync_time": 1740000000,\n "face_sync_mode": "force", "smart_max_wait_min": 61,\n "alert_type": "HOURS", "alert_interval": 1,\n "hour_bell": 5, "half_bell": 255, "quarter_bell": 255,\n "backlight": true, "backlight_output": 6,\n "backlight_on": "07:00", "backlight_off": "22:00",\n "daytime_silence": false, "daytime_on": "00:00", "daytime_off": "00:00",\n "night_silence": true, "night_on": "22:00", "night_off": "07:00",\n "timezone": { ...same object as clock.get_timezone... },\n "ntp": { "auto": true, "sync_time": "04:30", "sync_time_min": 270, "servers": ["pool.ntp.org", "time.google.com", "time.cloudflare.com"] }\n }\n}',
|
||||
errors: [],
|
||||
example: '{ "v": 2, "cmd": "clock.get_config" }',
|
||||
warning: null,
|
||||
@@ -603,9 +663,9 @@ const NAMESPACES = [
|
||||
cmd: 'system.get_time',
|
||||
handler: 'SystemHandler',
|
||||
transports: ['All'],
|
||||
description: 'Get current RTC time in local and UTC, plus individual date/time fields.',
|
||||
description: 'Current time. utc_timestamp is the real instant (the RTC holds UTC since fw 3.0.0). year..second and weekday (0 = Sunday) are LOCAL time; local is the same as an ISO string. local_timestamp is local wall-clock time written as an epoch (UTC + offset), not a real instant. rtc_synced is false until NTP or clock.set_time has written the RTC with fw 3.0.0+ (e.g. right after updating from 2.x).',
|
||||
contents: null,
|
||||
response: '{\n "status": "SUCCESS",\n "type": "system.get_time",\n "data": {\n "local_timestamp": 1740000000,\n "utc_timestamp": 1739993000,\n "rtc_available": true,\n "year": 2025, "month": 2, "day": 20,\n "hour": 10, "minute": 30, "second": 0\n }\n}',
|
||||
response: '{\n "status": "SUCCESS",\n "type": "system.get_time",\n "data": {\n "rtc_available": true, "rtc_synced": true,\n "utc_timestamp": 1793196300, "local_timestamp": 1793203500,\n "local": "2026-10-28T16:05:00",\n "offset_min": 120, "dst_active": false,\n "tz_mode": "auto", "tz_name": "Europe/Athens",\n "year": 2026, "month": 10, "day": 28, "hour": 16, "minute": 5, "second": 0, "weekday": 3\n }\n}',
|
||||
errors: [],
|
||||
example: '{ "v": 2, "cmd": "system.get_time" }',
|
||||
warning: null,
|
||||
@@ -616,7 +676,7 @@ const NAMESPACES = [
|
||||
transports: ['All'],
|
||||
description: 'Full ConfigManager dump — all saved settings grouped by subsystem. Alias: system.get_settings (backward compatible).',
|
||||
contents: null,
|
||||
response: '{\n "status": "SUCCESS",\n "type": "system.get_config",\n "data": {\n "general": {\n "bells_enabled": true, "mqtt_enabled": true,\n "ota_channel": "stable",\n "serial_log": 3, "sd_log": 2, "mqtt_log": 1\n },\n "bell": { "durations": {...}, "outputs": {...} },\n "clock": { ... },\n "time": { "gmtOffsetSec": 7200, "daylightOffsetSec": 3600, ... },\n "network": { "hostname": "...", "useStaticIP": false, ... },\n "mqtt": { "host": "...", "port": 1883, ... }\n }\n}',
|
||||
response: '{\n "status": "SUCCESS",\n "type": "system.get_config",\n "data": {\n "general": {\n "bells_enabled": true, "mqtt_enabled": true,\n "ota_channel": "stable",\n "serial_log": 3, "sd_log": 2, "mqtt_log": 1\n },\n "bell": { "durations": {...}, "outputs": {...} },\n "clock": { ... },\n "time": { "ntp": { "auto": true, "sync_time": "04:30", ... }, "tz": { "mode": "auto", "name": "Europe/Athens", "posix": "EET-2EEST,M3.5.0/3,M10.5.0/4", ... } },\n "network": { "hostname": "...", "useStaticIP": false, ... },\n "mqtt": { "host": "...", "port": 1883, ... }\n }\n}',
|
||||
errors: [
|
||||
{ message: 'Failed to serialize settings', condition: 'Internal JSON serialization error — rare' },
|
||||
],
|
||||
|
||||
Reference in New Issue
Block a user