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."
+ />
+ )}
+
)}
{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 (
+
+ {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')}
+
+ >
+ )}
+
+ {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')}
+
+ >
+ )}
+
+ {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 && (
+
+ {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."
+ />
+
+
+ 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.
-
+ 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.
+
+
+ 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({