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 <noreply@anthropic.com>
This commit is contained in:
2026-10-28 21:10:02 +02:00
co-authored by Claude Opus 5.5
parent e4ea43a079
commit cdf5fc79a0
9 changed files with 1072 additions and 101 deletions
+3
View File
@@ -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):
+120
View File
@@ -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)
}
+32
View File
@@ -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&apos;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&apos;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 }))}
/>
</>
)
}