From cdf5fc79a0a0e2829436961435a3c326b74774b5 Mon Sep 17 00:00:00 2001 From: bonamin Date: Wed, 28 Oct 2026 21:10:02 +0200 Subject: [PATCH] feat(clock): timezone, NTP, set-time and clocktower sync in the device Clock tab Console side of the firmware 3.x TimeKeeper overhaul (project-vesper F-079/F-081/F-083). The Clock tab's "Network & Time" card was read-only and showed fields the firmware no longer reports, and both analog clocks drew the browser's own time. - Time & Timezone card: device local time, zone, mode, UTC offset, DST state (incl. expired manual dates), next change, RTC synced. Read live from the device (system.get_time, clock.get_timezone) - the device is the source of truth for time settings; nothing about them is mirrored to Firestore. - EditTimezoneModal: Automatic (country -> zone from the backend timezone table, or a custom yearly rule built into a POSIX string), Manual DST (std offset, amount, this season's start/end), Fixed, Local only. - SetDeviceTimeModal: this computer's UTC time, or a typed local time. - NTP Sync card + NtpSettingsModal: automatic on/off, nightly time, servers, last result/drift; Sync Now queues clock.sync_ntp and polls clock.get_ntp. - SyncClockModal (was a placeholder): pause, enter what the face shows, clock.set_face + resume. - EditClockSettingsModal: face sync policy force/smart + max wait; mirrored as clockSettings.faceSyncMode / smartMaxWaitMin (added to the backend model, which silently dropped unknown keys - the old gmtOffsetSec/ntpServer mirror never persisted, so those dead drift checks are removed). - Device Time / Clocktower clocks now show the device's wall clock and the real face position (refreshed every 30 s while the clock runs). Live reads are chained after the existing clock.get_config drift check and face polling pauses while a modal or Sync Now is sending, because device replies are matched FIFO without a request id. Stage 5 of project-vesper docs/features/timekeeper-overhaul.md. Co-Authored-By: Claude Opus 5.5 --- backend/devices/models.py | 3 + frontend/src/lib/deviceTimezone.js | 120 +++++++ frontend/src/lib/formatters.js | 32 ++ .../devices/EditClockSettingsModal.jsx | 53 ++- .../bellcloud/devices/EditTimezoneModal.jsx | 309 ++++++++++++++++++ .../bellcloud/devices/NtpSettingsModal.jsx | 114 +++++++ .../bellcloud/devices/SetDeviceTimeModal.jsx | 100 ++++++ .../bellcloud/devices/SyncClockModal.jsx | 147 ++++++--- .../pages/bellcloud/devices/tabs/ClockTab.jsx | 295 ++++++++++++++--- 9 files changed, 1072 insertions(+), 101 deletions(-) create mode 100644 frontend/src/lib/deviceTimezone.js create mode 100644 frontend/src/modals/bellcloud/devices/EditTimezoneModal.jsx create mode 100644 frontend/src/modals/bellcloud/devices/NtpSettingsModal.jsx create mode 100644 frontend/src/modals/bellcloud/devices/SetDeviceTimeModal.jsx diff --git a/backend/devices/models.py b/backend/devices/models.py index 951e874..6341da6 100644 --- a/backend/devices/models.py +++ b/backend/devices/models.py @@ -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): diff --git a/frontend/src/lib/deviceTimezone.js b/frontend/src/lib/deviceTimezone.js new file mode 100644 index 0000000..49205e8 --- /dev/null +++ b/frontend/src/lib/deviceTimezone.js @@ -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) +} diff --git a/frontend/src/lib/formatters.js b/frontend/src/lib/formatters.js index 7dbb7b9..a522d4d 100644 --- a/frontend/src/lib/formatters.js +++ b/frontend/src/lib/formatters.js @@ -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')}` +} diff --git a/frontend/src/modals/bellcloud/devices/EditClockSettingsModal.jsx b/frontend/src/modals/bellcloud/devices/EditClockSettingsModal.jsx index 3f1c869..7f9dfd8 100644 --- a/frontend/src/modals/bellcloud/devices/EditClockSettingsModal.jsx +++ b/frontend/src/modals/bellcloud/devices/EditClockSettingsModal.jsx @@ -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} /> +
+ + {/* Face sync policy */} +
+
+

+ Face Ahead of Real Time +

+

+ 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. +

+
+ + {faceSync === 'smart' && ( + 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." + /> + )} +
+ {/* Errors / warnings */} - {(conflictMsg || validationMsg) && ( + {(conflictMsg || validationMsg || maxWaitMsg) && (

- {conflictMsg || validationMsg} + {conflictMsg || validationMsg || maxWaitMsg}

)} {error && ( diff --git a/frontend/src/modals/bellcloud/devices/EditTimezoneModal.jsx b/frontend/src/modals/bellcloud/devices/EditTimezoneModal.jsx new file mode 100644 index 0000000..721ccad --- /dev/null +++ b/frontend/src/modals/bellcloud/devices/EditTimezoneModal.jsx @@ -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 ( +

{text}

+ ) +} + +function RuleDateFields({ id, label, value, onChange, timeHint }) { + const set = (key, v) => onChange({ ...value, [key]: v }) + return ( +
+ + {label} + +
+ set('week', Number(e.target.value))}> + {WEEKS.map(w => )} + + set('weekday', Number(e.target.value))}> + {WEEKDAYS.map((d, i) => )} + + set('month', Number(e.target.value))}> + {MONTHS.map((m, i) => )} + + set('time', e.target.value)} /> +
+ {hint(timeHint)} +
+ ) +} + +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) => ( + onChange(Number(e.target.value))}> + {STD_OFFSET_OPTIONS.map(o => )} + + ) + + const dstAmountSelect = ( + setDstAmount(Number(e.target.value))}> + {DST_AMOUNT_OPTIONS.map(o => )} + + ) + + const nameField = (placeholder) => ( + setName(e.target.value)} placeholder={placeholder} /> + ) + + return ( + + + +
+ } + > +
+ + + {mode === 'auto' && ( + <> + {hint('The device switches DST by itself every year, following the rules of the chosen timezone.')} + + + {autoSource === 'list' && ( + tableError ? ( +

{tableError}

+ ) : !table ? ( +
+ ) : ( + <> +
+ handleCountry(e.target.value)}> + {table.countries.map(c => )} + + setZoneName(e.target.value)}> + + {countryZones.map(z => )} + +
+ {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')} +
+ {offsetSelect('Standard offset', 'ruleStd', stdOffset, setStdOffset)} + { const v = Number(e.target.value); setRuleHasDst(v !== 0); if (v) setDstAmount(v) }}> + + {DST_AMOUNT_OPTIONS.map(o => )} + +
+ {ruleHasDst && ( + <> + setRule(r => ({ ...r, start }))} + timeHint="Local standard time (before the clocks go forward)." /> + setRule(r => ({ ...r, end }))} + timeHint="Local summer time (before the clocks go back)." /> + + )} +

+ Rule sent to the device: {customPosix} +

+ + )} + + )} + + {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')} +
+ {offsetSelect('Standard offset', 'manualStd', stdOffset, setStdOffset)} + {dstAmountSelect} +
+
+ setDstStart(e.target.value)} + hint="Local standard time" /> + setDstEnd(e.target.value)} + hint="Local summer time" /> +
+ + )} + + {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')} +
+ {offsetSelect('Standard offset', 'fixedStd', stdOffset, setStdOffset)} + setFixedDst(Number(e.target.value))}> + + {DST_AMOUNT_OPTIONS.map(o => )} + +
+ + )} + + {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 && ( +

{invalid}

+ )} + {error &&

{error}

} +
+ + ) +} diff --git a/frontend/src/modals/bellcloud/devices/NtpSettingsModal.jsx b/frontend/src/modals/bellcloud/devices/NtpSettingsModal.jsx new file mode 100644 index 0000000..8843bc9 --- /dev/null +++ b/frontend/src/modals/bellcloud/devices/NtpSettingsModal.jsx @@ -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 ( + + + + + } + > +
+
+ + Automatic sync + + setAuto(v === 'on')} + size="sm" + /> +

+ {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.'} +

+
+ + 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." + /> + +
+ {[0, 1, 2].map(i => ( + setServers(list => list.map((s, j) => (j === i ? e.target.value : s)))} + placeholder={DEFAULT_SERVERS[i]} + /> + ))} +

+ Needs outbound UDP port 123 from the site network. +

+
+ + {invalid && serverList.length > 0 && ( +

{invalid}

+ )} + {error &&

{error}

} +
+
+ ) +} diff --git a/frontend/src/modals/bellcloud/devices/SetDeviceTimeModal.jsx b/frontend/src/modals/bellcloud/devices/SetDeviceTimeModal.jsx new file mode 100644 index 0000000..acc84d1 --- /dev/null +++ b/frontend/src/modals/bellcloud/devices/SetDeviceTimeModal.jsx @@ -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 ( + + + + + } + > +
+ + + {source === 'computer' ? ( +

+ Sends this computer's current time (as UTC). The device shows it in {tzLabel}. +

+ ) : ( + setLocal(e.target.value)} + inputProps={{ step: 1 }} + hint={`Wall-clock time in ${tzLabel}.`} + /> + )} + + {ntpWillCorrect && ( +

+ 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)' : ''}. +

+ )} + {error &&

{error}

} +
+
+ ) +} diff --git a/frontend/src/modals/bellcloud/devices/SyncClockModal.jsx b/frontend/src/modals/bellcloud/devices/SyncClockModal.jsx index 1235c77..e6e1e4f 100644 --- a/frontend/src/modals/bellcloud/devices/SyncClockModal.jsx +++ b/frontend/src/modals/bellcloud/devices/SyncClockModal.jsx @@ -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 ( - - + + } > -
-
- -
-
-

- Clock Synchronisation -

-

- This will send an MQTT command to correct the clocktower's mechanical position - if it has drifted from the master time reference. -

-
- {sn && ( -
- - Target device - -

- {sn} -

-
- )} -

- Full sync implementation coming soon — MQTT protocol pending. +

+

+ The device thinks the clocktower shows{' '} + + {face ? `${pad(face.clock_hour)}:${pad(face.clock_minute)}` : '—'} + + . If the hands show something else, enter what they really show.

+ +
+ + + Optional — stops the hands while you read them. + +
+ +
+ setHour(Number(e.target.value))}> + {HOURS.map(h => )} + + setMinute(Number(e.target.value))}> + {MINUTES.map(m => )} + +
+ +

+ 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. +

+ {error &&

{error}

}
) diff --git a/frontend/src/pages/bellcloud/devices/tabs/ClockTab.jsx b/frontend/src/pages/bellcloud/devices/tabs/ClockTab.jsx index ba3903d..13d4d97 100644 --- a/frontend/src/pages/bellcloud/devices/tabs/ClockTab.jsx +++ b/frontend/src/pages/bellcloud/devices/tabs/ClockTab.jsx @@ -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 (
@@ -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 */}
- - + +
@@ -695,21 +794,91 @@ export default function ClockTab({
- {/* Network & Time */} - -
- - - {dstActive ? 'Active' : 'Not Active'}} - /> -
- {canEdit && ( -
-

- Read-only — reported directly by the device. Editing timezone/NTP settings from the console is not yet supported. -

+ {/* Time & Timezone (live from the device) */} + + + +
+ )} + > + {live.status !== 'ok' || !tz ? ( +

{liveMissing}

+ ) : ( +
+ + + + + Not used + : tz.dst_schedule_expired ? Dates expired + : {tz.dst_active ? 'Active' : 'Not active'} + } + /> + {tz.next_transition > 0 && ( + + )} + {live.time?.rtc_synced ? 'Synced' : 'Not synced yet'}} + /> + {tz.dst_schedule_expired && ( +

+ The manual DST dates have passed — enter next season's dates. +

+ )} +
+ )} +
+ + {/* NTP Sync (live from the device) */} + + + + + )} + > + {live.status !== 'ok' || !ntp ? ( +

{liveMissing}

+ ) : ( +
+ + {tz?.mode === 'local' ? 'Off (local mode)' : ntp.auto ? `Nightly ${ntp.sync_time}` : 'Off'} + } + /> + + {syncBadge.label} : null} + value={syncBadge ? undefined : 'None since boot'} + /> + {lastSync && ( + <> + + + + {lastSync.result !== 'applied' && lastSync.result !== 'in_sync' && ( +

+ {lastSync.message} +

+ )} + + )} + {ntp.pending_confirmation && ( +

+ A large correction is waiting for a second sync to confirm it. +

+ )}
)}
@@ -717,7 +886,35 @@ export default function ClockTab({ - setShowSync(false)} device={device} /> + setShowSync(false)} + face={live.face} + sendMqttCommand={sendMqttCommand} + onSaved={() => loadLive(['face'])} + /> + setShowTimezone(false)} + current={tz} + sendMqttCommand={sendMqttCommand} + onSaved={(data) => { setLive(l => ({ ...l, tz: data || l.tz })); loadLive(['time', 'ntp']) }} + /> + setShowSetTime(false)} + timezone={tz} + ntp={ntp} + sendMqttCommand={sendMqttCommand} + onSaved={(data) => { if (data) setLive(l => ({ ...l, time: data, timeAt: Date.now() })); loadLive(['tz']) }} + /> + setShowNtp(false)} + ntp={ntp} + sendMqttCommand={sendMqttCommand} + onSaved={(data) => setLive(l => ({ ...l, ntp: data || l.ntp }))} + /> ) }