Compare commits

..
Author SHA1 Message Date
bonaminandClaude Opus 5.5 db22abdb7d feat(devices): compare console vs device config, let the user pick a side
Bells, Clock and General (log levels) tabs read the device's stored config
on open (read-only) and compare it with what Firestore holds. On mismatch a
banner offers "Compare & resolve": a side-by-side "Saved in Console" vs
"Stored on Device" modal with differing settings highlighted.

- Keep Console version: push saved settings to the device, then re-read
- Keep Device version: write only the differing fields to Firestore
- Nothing is written until the user picks one
- Re-reads the device whenever the saved settings change

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 14:11:18 +02:00
bonaminandClaude Opus 5.5 eff9e72681 fix(devices): stop tabs writing to Firestore on their own
Bells, Clock and General tabs ran a silent "reconcile" on mount that read
the device config and wrote any drift straight to Firestore, with no user
action. Combined with oldest-first ack matching (backend health-check pongs
and other tabs' replies resolved bells.get_config), this wrote 16-item
bellOutputs on load and emptied them on tab switch.

- Remove the auto-write reconciles from Bells/Clock/General tabs
- useDeviceCommand: match acks to commands by payload.type (ping->pong,
  playback.* -> playback), ignore health-check pongs, drop late replies,
  register pending entries before the POST
- update_device: write nested maps as dotted field paths so only the sent
  leaves are touched, never the whole parent map
- Clock modals: stop re-sending the whole clockSettings copy

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 13:15:05 +02:00
13 changed files with 920 additions and 231 deletions
+2 -2
View File
@@ -553,8 +553,8 @@ async def reset_device_stats(
# Firestore device_stats — field-level only. DeviceStatistics mixes true # Firestore device_stats — field-level only. DeviceStatistics mixes true
# counters with warranty/maintenance fields in one object; a blanket # counters with warranty/maintenance fields in one object; a blanket
# clear would destroy warranty data, so only the 4 named counter fields # clear would destroy warranty data, so only the 4 named counter fields
# are ever sent here (deep-merge in service.update_device preserves # are ever sent here (service.update_device writes field paths only, so
# every other key, including warrantyActive/warrantyStart/etc.). # every other key is untouched, including warrantyActive/warrantyStart/etc.).
stats_update = {} stats_update = {}
if body.bell_stats: if body.bell_stats:
stats_update["totalHammerStrikes"] = 0 stats_update["totalHammerStrikes"] = 0
+22 -14
View File
@@ -2,6 +2,7 @@ import secrets
import string import string
from google.cloud.firestore_v1 import DocumentReference from google.cloud.firestore_v1 import DocumentReference
from google.cloud.firestore_v1.field_path import FieldPath
from shared.firebase import get_db from shared.firebase import get_db
from shared.exceptions import NotFoundError from shared.exceptions import NotFoundError
@@ -137,15 +138,22 @@ def create_device(data: DeviceCreate) -> DeviceInDB:
return _doc_to_device(doc_ref.get()) return _doc_to_device(doc_ref.get())
def _deep_merge(base: dict, overrides: dict) -> dict: def _leaf_field_paths(value: dict, prefix: tuple = ()) -> dict:
"""Recursively merge overrides into base, preserving unmentioned nested keys.""" """Flatten a nested map into {firestore field path: leaf value}.
result = dict(base)
for k, v in overrides.items(): Lists and scalars are leaves; a non-empty map is descended into, so writing
if isinstance(v, dict) and isinstance(result.get(k), dict): {"device_attributes": {"hasBells": True}} touches ONLY
result[k] = _deep_merge(result[k], v) device_attributes.hasBells — never the sibling fields of the parent map.
An empty map is kept as a leaf (it explicitly sets that map to {}).
"""
out: dict = {}
for k, v in value.items():
path = prefix + (k,)
if isinstance(v, dict) and v:
out.update(_leaf_field_paths(v, path))
else: else:
result[k] = v out[FieldPath(*path).to_api_repr()] = v
return result return out
def update_device(device_doc_id: str, data: DeviceUpdate) -> DeviceInDB: def update_device(device_doc_id: str, data: DeviceUpdate) -> DeviceInDB:
@@ -162,17 +170,17 @@ def update_device(device_doc_id: str, data: DeviceUpdate) -> DeviceInDB:
sent = data.model_dump(exclude_unset=True) sent = data.model_dump(exclude_unset=True)
update_data = firestore_v1.to_firestore({k: v for k, v in sent.items() if v is not None}, db) update_data = firestore_v1.to_firestore({k: v for k, v in sent.items() if v is not None}, db)
# Deep-merge nested structs so unmentioned sub-fields are preserved, then # Nested structs are written field-by-field (dotted paths), so only the
# normalize the merged map again: that also repairs pre-v1 junk already # exact leaves the caller sent are touched. Rewriting the whole parent map
# stored in the device (""-timestamps, octet-array IPs, misspelled keys). # (the old read-merge-write) clobbered sibling fields whenever two writes
# raced, or the FlutterFlow apps wrote in between our read and our write.
existing = doc.to_dict() existing = doc.to_dict()
nested_keys = ( nested_keys = (
"device_attributes", "device_subscription", "device_stats", "device_health_settings", "device_attributes", "device_subscription", "device_stats", "device_health_settings",
) )
for key in nested_keys: for key in nested_keys:
if key in update_data and isinstance(existing.get(key), dict): if isinstance(update_data.get(key), dict) and update_data[key]:
merged = _deep_merge(existing[key], update_data[key]) update_data.update(_leaf_field_paths(update_data.pop(key), (key,)))
update_data[key] = firestore_v1.to_firestore({key: merged}, db)[key]
if "user_list" not in update_data: if "user_list" not in update_data:
doc_ref.update(update_data) doc_ref.update(update_data)
@@ -0,0 +1,69 @@
// frontend/src/components/shared/ConfigDriftBanner.jsx
// Slim status line telling the user whether the device's stored config matches
// what the console has saved. Read-only: the only action it offers is opening
// the comparison (ConfigConflictModal) or re-reading the device.
//
// Props:
// label — e.g. "Bell configuration"
// status — 'idle' | 'checking' | 'ok' | 'unreachable' (useDeviceConfigCheck)
// diffCount — number of differing settings (when status === 'ok')
// onReview — open the comparison modal
// onRecheck — read the device again
import Button from '@/components/ui/Button'
import Icon from '@/components/ui/Icon'
import Spinner from '@/components/ui/Spinner'
export default function ConfigDriftBanner({ label, status, diffCount = 0, onReview, onRecheck }) {
if (status === 'idle') return null
const differs = status === 'ok' && diffCount > 0
const tone = differs
? { border: 'rgba(251, 191, 36, 0.45)', bg: 'rgba(251, 191, 36, 0.08)', color: 'var(--color-warning)', icon: 'warning' }
: status === 'ok'
? { border: 'var(--color-border)', bg: 'rgba(28, 32, 38, 0.30)', color: 'var(--color-success)', icon: 'check' }
: { border: 'var(--color-border)', bg: 'rgba(28, 32, 38, 0.30)', color: 'var(--color-text-muted)', icon: 'info' }
const text = {
checking: `Checking ${label.toLowerCase()} against the device…`,
unreachable: `Couldn't read ${label.toLowerCase()} from the device — showing saved settings only.`,
ok: differs
? `${label} on the device differs from the saved settings — ${diffCount} ${diffCount === 1 ? 'difference' : 'differences'}.`
: `${label} matches the device.`,
}[status]
return (
<div style={{
display: 'flex',
alignItems: 'center',
gap: 'var(--space-3)',
padding: 'var(--space-2) var(--space-4)',
minHeight: 44,
background: tone.bg,
border: `1px solid ${tone.border}`,
borderRadius: 'var(--radius-lg)',
backdropFilter: 'var(--blur-modal)',
WebkitBackdropFilter: 'var(--blur-modal)',
}}>
{status === 'checking'
? <Spinner size="sm" />
: <Icon name={tone.icon} size={16} color={tone.color} />}
<span style={{
flex: 1,
fontSize: 'var(--font-size-sm)',
color: differs ? 'var(--color-text-primary)' : 'var(--color-text-secondary)',
fontWeight: differs ? 'var(--font-weight-semibold)' : 'var(--font-weight-normal)',
}}>
{text}
</span>
{differs && (
<Button variant="primary" size="sm" onClick={onReview}>Compare &amp; resolve</Button>
)}
{status !== 'checking' && (
<Button variant="ghost" size="sm" icon={<Icon name="refresh" size={13} />} onClick={onRecheck}>
{status === 'unreachable' ? 'Retry' : 'Re-check'}
</Button>
)}
</div>
)
}
+61 -29
View File
@@ -5,8 +5,8 @@
// //
// Device replies arrive on control/ack. They can optionally echo a req_id // Device replies arrive on control/ack. They can optionally echo a req_id
// (see CommandEnvelope.hpp / vesper_mqtt_topic_spec_v2.md), but this hook // (see CommandEnvelope.hpp / vesper_mqtt_topic_spec_v2.md), but this hook
// doesn't send one yet, so in-flight commands are matched FIFO against // doesn't send one yet, so replies are matched to in-flight commands by the
// whichever command is oldest for this device — see the API Reference's wire // command name the device echoes in payload.type (see findPendingFor) — see the API Reference's wire
// envelope: { type: 'control/ack', device_serial, payload: { status, type, message, data } }. // envelope: { type: 'control/ack', device_serial, payload: { status, type, message, data } }.
// //
// Usage: // Usage:
@@ -27,6 +27,28 @@ import api from '@/lib/api'
import { useMqttWebSocket } from '@/hooks/useMqttWebSocket' import { useMqttWebSocket } from '@/hooks/useMqttWebSocket'
import { useToast } from '@/components/ui/Toast' import { useToast } from '@/components/ui/Toast'
// Which in-flight command does a control/ack reply belong to? The device echoes
// the command name in payload.type, with two exceptions: ping → "pong", and
// playback.play / playback.stop → "playback". Handing a reply to the wrong
// command (plain oldest-first) made tabs act on another command's data — e.g.
// a backend health-check pong resolving bells.get_config with no bells.
function findPendingFor(pending, type) {
if (!pending.length) return -1
if (!type) return 0
const exact = pending.findIndex((a) => a.cmd === type)
if (exact !== -1) return exact
// The backend's own health-check pings also reply here — only a console
// ping may take a pong, never any other command.
if (type === 'pong') return pending.findIndex((a) => a.cmd === 'ping')
const family = pending.findIndex((a) => a.cmd.startsWith(`${type}.`))
if (family !== -1) return family
// A dotted type is a v2 command name — if none is pending, it's a late reply
// to one that already timed out. Drop it rather than hand it to another command.
if (type.includes('.')) return -1
// Unrecognized legacy type — fall back to the oldest in-flight command.
return 0
}
export function useDeviceCommand({ deviceSerial, onNonAckMessage, onCommandSent } = {}) { export function useDeviceCommand({ deviceSerial, onNonAckMessage, onCommandSent } = {}) {
const { toast } = useToast() const { toast } = useToast()
const [sendingCmd, setSendingCmd] = useState('') const [sendingCmd, setSendingCmd] = useState('')
@@ -43,8 +65,9 @@ export function useDeviceCommand({ deviceSerial, onNonAckMessage, onCommandSent
return return
} }
const ack = pendingAcksRef.current.shift() // oldest in-flight command const idx = findPendingFor(pendingAcksRef.current, msg.payload?.type)
if (!ack) return if (idx === -1) return
const [ack] = pendingAcksRef.current.splice(idx, 1)
const payload = msg.payload || {} const payload = msg.payload || {}
clearTimeout(ack.timeoutId) clearTimeout(ack.timeoutId)
@@ -73,24 +96,30 @@ export function useDeviceCommand({ deviceSerial, onNonAckMessage, onCommandSent
const toastId = toast.pending(cmd, 'Sent — waiting for reply…') const toastId = toast.pending(cmd, 'Sent — waiting for reply…')
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
api.post(`/mqtt/command/${deviceSerial}`, { cmd, contents }) // Registered before the POST so a reply that beats the HTTP response
.then(() => { // still finds its command.
onCommandSent?.(cmd) const ackEntry = { cmd, toastId, resolve, reject, timeoutId: null }
const ackEntry = { cmd, toastId, resolve, reject, timeoutId: null } const forget = () => {
ackEntry.timeoutId = setTimeout(() => { clearTimeout(ackEntry.timeoutId)
pendingAcksRef.current = pendingAcksRef.current.filter((a) => a !== ackEntry) pendingAcksRef.current = pendingAcksRef.current.filter((a) => a !== ackEntry)
toast.update(toastId, { }
variant: 'warning', ackEntry.timeoutId = setTimeout(() => {
title: 'No reply received', forget()
message: `"${cmd}" was sent but the device did not reply in time.`, toast.update(toastId, {
pending: false, variant: 'warning',
duration: 4000, title: 'No reply received',
}) message: `"${cmd}" was sent but the device did not reply in time.`,
reject(new Error(`"${cmd}" timed out waiting for a reply.`)) pending: false,
}, 5000) duration: 4000,
pendingAcksRef.current.push(ackEntry)
}) })
reject(new Error(`"${cmd}" timed out waiting for a reply.`))
}, 5000)
pendingAcksRef.current.push(ackEntry)
api.post(`/mqtt/command/${deviceSerial}`, { cmd, contents })
.then(() => onCommandSent?.(cmd))
.catch((err) => { .catch((err) => {
forget()
toast.update(toastId, { toast.update(toastId, {
variant: 'danger', variant: 'danger',
title: 'Failed to send', title: 'Failed to send',
@@ -110,16 +139,19 @@ export function useDeviceCommand({ deviceSerial, onNonAckMessage, onCommandSent
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
if (!deviceSerial) { reject(new Error('No device id.')); return } if (!deviceSerial) { reject(new Error('No device id.')); return }
const ackEntry = { cmd, resolve, reject, timeoutId: null }
const forget = () => {
clearTimeout(ackEntry.timeoutId)
pendingAcksRef.current = pendingAcksRef.current.filter((a) => a !== ackEntry)
}
ackEntry.timeoutId = setTimeout(() => {
forget()
reject(new Error(`"${cmd}" timed out waiting for a reply.`))
}, timeoutMs)
pendingAcksRef.current.push(ackEntry)
api.post(`/mqtt/command/${deviceSerial}`, { cmd, contents }) api.post(`/mqtt/command/${deviceSerial}`, { cmd, contents })
.then(() => { .catch((err) => { forget(); reject(err) })
const ackEntry = { cmd, resolve, reject, timeoutId: null }
ackEntry.timeoutId = setTimeout(() => {
pendingAcksRef.current = pendingAcksRef.current.filter((a) => a !== ackEntry)
reject(new Error(`"${cmd}" timed out waiting for a reply.`))
}, timeoutMs)
pendingAcksRef.current.push(ackEntry)
})
.catch(reject)
}) })
}, [deviceSerial]) }, [deviceSerial])
@@ -0,0 +1,51 @@
// frontend/src/hooks/useDeviceConfigCheck.js
// Reads a device's stored config once when a tab opens (and again on demand),
// so the tab can compare it with what the console has saved.
//
// READ-ONLY. This hook never writes anything — when the two disagree, the user
// decides which side to keep (see ConfigConflictModal).
//
// Usage:
// const read = useCallback(() => sendMqttCommandSilent('bells.get_config').then(r => r?.data || {}), [sendMqttCommandSilent])
// const { status, data, recheck } = useDeviceConfigCheck({ enabled: !!sendMqttCommandSilent, read, savedKey })
// status: 'idle' | 'checking' | 'ok' | 'unreachable'
// savedKey: string that changes when the saved settings change — triggers a re-read
import { useState, useCallback, useEffect, useRef } from 'react'
export function useDeviceConfigCheck({ enabled, read, savedKey = '' }) {
const [state, setState] = useState({ status: 'idle', data: null })
const recheck = useCallback(async () => {
setState((s) => ({ status: 'checking', data: s.data }))
try {
const data = await read()
setState({ status: 'ok', data: data || {} })
return data
} catch {
setState({ status: 'unreachable', data: null })
return null
}
}, [read])
// Once per mount — guards against StrictMode's double-invoke.
const startedRef = useRef(false)
useEffect(() => {
if (!enabled || startedRef.current) return
startedRef.current = true
queueMicrotask(recheck)
}, [enabled, recheck])
// When the SAVED side changes (an Edit modal just pushed + saved), the last
// device read is stale — read the device again so the comparison stays true.
const lastKeyRef = useRef(savedKey)
useEffect(() => {
if (lastKeyRef.current === savedKey) return
lastKeyRef.current = savedKey
if (startedRef.current) queueMicrotask(recheck)
}, [savedKey, recheck])
return { ...state, recheck }
}
export default useDeviceConfigCheck
+324
View File
@@ -0,0 +1,324 @@
// frontend/src/lib/deviceConfigDiff.js
// Compares what the console has SAVED (Firestore) against what the device
// actually has STORED (its *.get_config replies), setting by setting.
//
// Every builder returns rows for the ConfigConflictModal:
// { key, label, group, saved, device, differs, patch }
// saved / device — display strings for each side
// differs — true when the two sides really disagree
// patch — device_attributes fragment that makes Firestore match the
// device for THIS row only ("Keep device version")
//
// Nothing here writes anything — callers decide what to do with the rows.
// ─── Shared helpers ───────────────────────────────────────────────────────────
const onOff = (v) => (v ? 'Enabled' : 'Disabled')
function row(key, label, group, savedVal, deviceVal, fmt, patch) {
return {
key,
label,
group,
saved: fmt(savedVal),
device: fmt(deviceVal),
differs: savedVal !== deviceVal,
patch,
}
}
function isPlainObject(v) {
return v !== null && typeof v === 'object' && !Array.isArray(v)
}
/** Merge row patches into one device_attributes object (later rows win per leaf). */
export function mergePatches(rows) {
const out = {}
const merge = (target, src) => {
for (const [k, v] of Object.entries(src)) {
if (isPlainObject(v)) {
if (!isPlainObject(target[k])) target[k] = {}
merge(target[k], v)
} else {
target[k] = v
}
}
}
rows.forEach((r) => r.patch && merge(out, r.patch))
return out
}
// ─── Bells ────────────────────────────────────────────────────────────────────
// 0 and 65535 (the firmware's uint16 "unset") both mean "no output assigned".
const normOutput = (o) => {
const n = Number(o)
return !Number.isFinite(n) || n === 65535 ? 0 : n
}
/**
* The device keeps a fixed set of bell channels (typically 16). Bell index is
* meaningful (melodies map notes to bell numbers), so channels are compared
* index-by-index — never compacted.
*/
export function bellDeviceView(data) {
const outputs = data?.outputs || {}
const durations = data?.durations || {}
const indexes = [...Object.keys(outputs), ...Object.keys(durations)]
.map(Number)
.filter(Number.isInteger)
const channels = indexes.length ? Math.max(...indexes) + 1 : 0
let lastAssigned = -1
for (let i = 0; i < channels; i++) if (normOutput(outputs[i]) > 0) lastAssigned = i
return {
enabled: !!data?.bells_enabled,
channels,
lastAssigned,
output: (i) => normOutput(outputs[i]),
duration: (i) => (durations[i] != null ? Number(durations[i]) : null),
}
}
function bellSaved(attr) {
const outputs = (attr?.bellOutputs || []).map(normOutput)
const timings = attr?.hammerTimings || []
return {
count: outputs.length,
output: (i) => (i < outputs.length ? outputs[i] : 0),
timing: (i) => (timings[i] != null ? Number(timings[i]) : null),
}
}
const bellLabel = (output, ms) =>
output === 0 ? 'Disabled' : `Output ${output} · ${ms != null ? `${ms} ms` : '—'}`
/** How many bell rows to compare: every saved bell + every bell the device has wired. */
export function bellRowCount(attr, data) {
return Math.max(bellSaved(attr).count, bellDeviceView(data).lastAssigned + 1)
}
export function buildBellRows(attr, data) {
const dev = bellDeviceView(data)
const saved = bellSaved(attr)
const count = bellRowCount(attr, data)
// Firestore stores the bells as whole lists, so "keep device" for any bell
// rewrites those lists (and only those) from the device's channels.
const listsPatch = {
totalBells: count,
bellOutputs: Array.from({ length: count }, (_, i) => dev.output(i)),
hammerTimings: Array.from({ length: count }, (_, i) => dev.duration(i) ?? saved.timing(i) ?? 90),
}
const rows = [
row('hasBells', 'Bell Commander', 'commander', !!attr?.hasBells, dev.enabled, onOff, { hasBells: dev.enabled }),
]
for (let i = 0; i < count; i++) {
const so = saved.output(i)
const st = saved.timing(i)
const dout = dev.output(i)
const dt = dev.duration(i)
rows.push({
key: `bell-${i}`,
label: `Bell ${i + 1}`,
group: 'bells',
saved: i < saved.count ? bellLabel(so, st) : 'Not configured',
device: bellLabel(dout, dt),
// Timing only matters for a bell that's actually wired on both sides.
differs: so !== dout || (so > 0 && dout > 0 && st !== dt),
patch: listsPatch,
})
}
return rows
}
/** relay.set_config contents that make the device match the saved bells. */
export function bellPushContents(attr, data) {
const dev = bellDeviceView(data)
const saved = bellSaved(attr)
// relay.set_config is a partial update: every channel past the saved list
// must be sent explicitly as 0, or a stale output stays wired on the device.
const channels = Math.max(dev.channels, saved.count)
const outputs = {}
const durations = {}
for (let i = 0; i < channels; i++) {
outputs[i] = saved.output(i)
const t = saved.timing(i)
if (i < saved.count && Number.isFinite(t)) durations[i] = t
}
return { outputs, durations }
}
// ─── Clock ────────────────────────────────────────────────────────────────────
/** "HH:MM" from a stored timestamp / time string, or null. */
export function extractTime(tsStr) {
if (!tsStr) return null
const d = new Date(
String(tsStr).replace(' at ', ' ').replace('UTC+0000', 'UTC').replace(/UTC\+(\d{4})/, 'UTC')
)
if (!isNaN(d.getTime())) {
return `${d.getUTCHours().toString().padStart(2, '0')}:${d.getUTCMinutes().toString().padStart(2, '0')}`
}
const match = String(tsStr).match(/(\d{1,2}):(\d{2})/)
return match ? `${match[1].padStart(2, '0')}:${match[2]}` : null
}
const timeToIso = (hhmm) => (hhmm ? `2000-01-01T${hhmm}:00Z` : null)
const deviceTime = (v) => (v ? extractTime(v) : null)
const ALERT_FROM_FW = { OFF: 'disabled', SINGLE: 'single', HOURS: 'multi' }
export const ALERT_TO_FW = { disabled: 'OFF', single: 'SINGLE', multi: 'HOURS' }
const ALERT_LABEL = { disabled: 'Disabled', single: 'Single strike', multi: 'Hour indicating' }
const FACE_SYNC_LABEL = { force: 'Force', smart: 'Smart' }
const fwBell = (v) => (v === 255 ? 0 : Number(v) || 0)
export const toFwBell = (n) => (n === 0 ? 255 : n)
const fmtOutput = (o) => (o ? `Output ${o}` : 'None')
const fmtBell = (b) => (b ? `Bell ${b}` : 'None')
const fmtMs = (ms) => (ms ? `${ms} ms` : '—')
const fmtTime = (t) => t || '—'
export function buildClockRows(attr, clock, data) {
const c = clock || {}
const d = data || {}
const rows = []
// ── Clock mechanism (clock.set_config) ──
const devC1 = Number(d.c1output) || 0
const devC2 = Number(d.c2output) || 0
const devPulse = Number(d.pulse_duration) || 0
const devPause = Number(d.pause_duration) || 0
// Positional (odd, even) — never filtered, or an unassigned odd output would
// shift the even one into its slot and the two would never compare equal.
const outputsPatch = { clockSettings: { clockOutputs: [devC1, devC2] } }
const timingsPatch = { clockSettings: { clockTimings: [devPulse, devPause] } }
rows.push(row('hasClock', 'Clock', 'config', !!attr?.hasClock, !!d.enabled, onOff, { hasClock: !!d.enabled }))
rows.push(row('c1', 'Odd output', 'config', Number(c.clockOutputs?.[0]) || 0, devC1, fmtOutput, outputsPatch))
rows.push(row('c2', 'Even output', 'config', Number(c.clockOutputs?.[1]) || 0, devC2, fmtOutput, outputsPatch))
rows.push(row('pulse', 'Run pulse', 'config', Number(c.clockTimings?.[0]) || 0, devPulse, fmtMs, timingsPatch))
rows.push(row('pause', 'Pause', 'config', Number(c.clockTimings?.[1]) || 0, devPause, fmtMs, timingsPatch))
if (d.face_sync_mode != null) {
rows.push(row('faceSync', 'Face sync mode', 'config', c.faceSyncMode || 'force', d.face_sync_mode,
(v) => FACE_SYNC_LABEL[v] || v, { clockSettings: { faceSyncMode: d.face_sync_mode } }))
}
if (d.smart_max_wait_min != null) {
rows.push(row('maxWait', 'Smart sync max wait', 'config', c.smartMaxWaitMin ?? 61, d.smart_max_wait_min,
(v) => `${v} min`, { clockSettings: { smartMaxWaitMin: d.smart_max_wait_min } }))
}
// ── Alerts & silence (clock.set_alerts_config) ──
const savedAlert = c.ringAlerts || 'disabled'
const devAlert = ALERT_FROM_FW[d.alert_type] ?? 'disabled'
rows.push(row('ringAlerts', 'Alerts', 'alerts', savedAlert, devAlert,
(v) => ALERT_LABEL[v] || v, { clockSettings: { ringAlerts: devAlert } }))
if (savedAlert === 'multi' || devAlert === 'multi') {
rows.push(row('ringIntervals', 'Alert tempo', 'alerts', c.ringIntervals ?? null, d.alert_interval ?? null,
fmtMs, { clockSettings: { ringIntervals: d.alert_interval ?? null } }))
}
rows.push(row('hourBell', 'Hour bell', 'alerts', Number(c.hourAlertsBell) || 0, fwBell(d.hour_bell),
fmtBell, { clockSettings: { hourAlertsBell: fwBell(d.hour_bell) } }))
rows.push(row('halfBell', 'Half-hour bell', 'alerts', Number(c.halfhourAlertsBell) || 0, fwBell(d.half_bell),
fmtBell, { clockSettings: { halfhourAlertsBell: fwBell(d.half_bell) } }))
rows.push(row('quarterBell', 'Quarter bell', 'alerts', Number(c.quarterAlertsBell) || 0, fwBell(d.quarter_bell),
fmtBell, { clockSettings: { quarterAlertsBell: fwBell(d.quarter_bell) } }))
const silence = (prefix, label, savedOn, devOn, savedFrom, savedTo, devFrom, devTo, keys) => {
rows.push(row(`${prefix}On`, label, 'alerts', !!savedOn, !!devOn, onOff, { clockSettings: { [keys.on]: !!devOn } }))
// Window times only matter while the silence is on (on either side).
if (savedOn || devOn) {
rows.push(row(`${prefix}From`, `${label} from`, 'alerts', extractTime(savedFrom), deviceTime(devFrom),
fmtTime, { clockSettings: { [keys.from]: timeToIso(deviceTime(devFrom)) } }))
rows.push(row(`${prefix}To`, `${label} until`, 'alerts', extractTime(savedTo), deviceTime(devTo),
fmtTime, { clockSettings: { [keys.to]: timeToIso(deviceTime(devTo)) } }))
}
}
silence('day', 'Day silence', c.isDaySilenceOn, d.daytime_silence, c.daySilenceFrom, c.daySilenceTo,
d.daytime_on, d.daytime_off, { on: 'isDaySilenceOn', from: 'daySilenceFrom', to: 'daySilenceTo' })
silence('night', 'Night silence', c.isNightSilenceOn, d.night_silence, c.nightSilenceFrom, c.nightSilenceTo,
d.night_on, d.night_off, { on: 'isNightSilenceOn', from: 'nightSilenceFrom', to: 'nightSilenceTo' })
// ── Backlight (clock.set_backlight) ──
const savedBl = !!c.isBacklightAutomationOn
const devBl = !!d.backlight
rows.push(row('backlight', 'Backlight automation', 'backlight', savedBl, devBl, onOff,
{ clockSettings: { isBacklightAutomationOn: devBl } }))
rows.push(row('backlightOutput', 'Backlight output', 'backlight', Number(c.backlightOutput) || 0,
fwBell(d.backlight_output), fmtOutput, { clockSettings: { backlightOutput: fwBell(d.backlight_output) } }))
if (savedBl || devBl) {
rows.push(row('backlightOn', 'Backlight on at', 'backlight', extractTime(c.backlightTurnOnTime),
deviceTime(d.backlight_on), fmtTime, { clockSettings: { backlightTurnOnTime: timeToIso(deviceTime(d.backlight_on)) } }))
rows.push(row('backlightOff', 'Backlight off at', 'backlight', extractTime(c.backlightTurnOffTime),
deviceTime(d.backlight_off), fmtTime, { clockSettings: { backlightTurnOffTime: timeToIso(deviceTime(d.backlight_off)) } }))
}
return rows
}
/** The device commands that push the SAVED clock settings, one per differing group. */
export function clockPushCommands(attr, clock, differingGroups) {
const c = clock || {}
const cmds = []
if (differingGroups.has('config')) {
const faceSync = c.faceSyncMode || 'force'
const pulse = Number(c.clockTimings?.[0]) || 0
const pause = Number(c.clockTimings?.[1]) || 0
cmds.push(['clock.set_config', {
enabled: !!attr?.hasClock,
c1: Number(c.clockOutputs?.[0]) || 0,
c2: Number(c.clockOutputs?.[1]) || 0,
...(pulse ? { pulse_duration: pulse } : {}),
...(pause ? { pause_duration: pause } : {}),
face_sync_mode: faceSync,
...(faceSync === 'smart' ? { smart_max_wait_min: c.smartMaxWaitMin ?? 61 } : {}),
}])
}
if (differingGroups.has('alerts')) {
const alert = c.ringAlerts || 'disabled'
const dayOn = !!c.isDaySilenceOn
const nightOn = !!c.isNightSilenceOn
cmds.push(['clock.set_alerts_config', {
alert_type: ALERT_TO_FW[alert],
alert_interval: alert === 'multi' ? c.ringIntervals : undefined,
hour_bell: toFwBell(Number(c.hourAlertsBell) || 0),
half_bell: toFwBell(Number(c.halfhourAlertsBell) || 0),
quarter_bell: toFwBell(Number(c.quarterAlertsBell) || 0),
daytime_silence: dayOn,
daytime_on: dayOn ? extractTime(c.daySilenceFrom) ?? undefined : undefined,
daytime_off: dayOn ? extractTime(c.daySilenceTo) ?? undefined : undefined,
night_silence: nightOn,
night_on: nightOn ? extractTime(c.nightSilenceFrom) ?? undefined : undefined,
night_off: nightOn ? extractTime(c.nightSilenceTo) ?? undefined : undefined,
}])
}
if (differingGroups.has('backlight')) {
const on = !!c.isBacklightAutomationOn
cmds.push(['clock.set_backlight', {
backlight: on,
backlight_output: Number(c.backlightOutput) || 0,
backlight_on: on ? extractTime(c.backlightTurnOnTime) ?? undefined : undefined,
backlight_off: on ? extractTime(c.backlightTurnOffTime) ?? undefined : undefined,
}])
}
return cmds
}
// ─── Log levels ───────────────────────────────────────────────────────────────
const LOG_LEVEL_NAMES = ['Disabled', 'Error', 'Warning', 'Info', 'Debug', 'Verbose']
const fmtLevel = (l) => `${LOG_LEVEL_NAMES[l] ?? l} (${l})`
export const LOG_FIELDS = [
{ key: 'serial', label: 'Serial log', attr: 'serialLogLevel', device: 'serial_level', cmd: 'log.set_serial' },
{ key: 'sd', label: 'SD storage', attr: 'sdLogLevel', device: 'sd_level', cmd: 'log.set_sd' },
{ key: 'mqtt', label: 'MQTT sync', attr: 'mqttLogLevel', device: 'mqtt_level', cmd: 'log.set_mqtt' },
]
export function buildLogRows(attr, data) {
return LOG_FIELDS
.filter((f) => data?.[f.device] != null)
.map((f) => row(f.key, f.label, f.key, Number(attr?.[f.attr] ?? 0), Number(data[f.device]),
fmtLevel, { [f.attr]: Number(data[f.device]) }))
}
@@ -0,0 +1,207 @@
// frontend/src/modals/bellcloud/devices/ConfigConflictModal.jsx
// "Cloud save conflict" for device settings: what the console has saved
// (Firestore) side by side with what the device actually has stored, with the
// differing settings highlighted. The user picks which side to keep:
//
// Keep console version → push the saved settings to the device (MQTT);
// Firestore already holds them, so nothing is written.
// Keep device version → write ONLY the differing fields to Firestore.
//
// Nothing happens until one of the two buttons is pressed.
//
// Props:
// open, onClose
// title — e.g. "Bell configuration"
// rows — from lib/deviceConfigDiff (key, label, saved, device, differs)
// onKeepConsole() — async; push saved → device
// onKeepDevice() — async; write device → Firestore
// canEdit — false hides the two actions (view-only comparison)
import { useState } from 'react'
import Modal from '@/components/ui/Modal'
import Button from '@/components/ui/Button'
import Icon from '@/components/ui/Icon'
const COLUMN_BG = 'rgba(28, 32, 38, 0.40)'
const DIFF_BG = 'rgba(251, 191, 36, 0.10)'
function ColumnHeader({ icon, title, subtitle }) {
return (
<div style={{
background: COLUMN_BG,
borderRadius: 'var(--radius-lg) var(--radius-lg) 0 0',
border: '1px solid var(--color-border)',
borderBottom: 'none',
padding: 'var(--space-4)',
display: 'flex',
alignItems: 'center',
gap: 'var(--space-3)',
}}>
<div style={{
width: 36, height: 36, flexShrink: 0,
borderRadius: 'var(--radius-md)',
background: 'var(--color-bg-elevated)',
display: 'flex', alignItems: 'center', justifyContent: 'center',
}}>
<Icon name={icon} size={18} color="var(--color-text-secondary)" />
</div>
<div style={{ minWidth: 0 }}>
<div style={{ fontSize: 'var(--font-size-base)', fontWeight: 'var(--font-weight-semibold)', color: 'var(--color-text-primary)' }}>
{title}
</div>
<div style={{ fontSize: 'var(--font-size-xs)', color: 'var(--color-text-muted)' }}>
{subtitle}
</div>
</div>
</div>
)
}
function Cell({ label, value, differs, last }) {
return (
<div style={{
background: differs ? DIFF_BG : COLUMN_BG,
borderLeft: `1px solid var(--color-border)`,
borderRight: '1px solid var(--color-border)',
boxShadow: differs ? 'inset 3px 0 0 var(--color-warning)' : 'none',
padding: 'var(--space-2) var(--space-4)',
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
gap: 'var(--space-3)',
minHeight: 40,
borderBottom: last ? 'none' : '1px solid rgba(255,255,255,0.04)',
}}>
<span style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-text-muted)', flexShrink: 0 }}>
{label}
</span>
<span style={{
fontSize: 'var(--font-size-sm)',
fontFamily: 'var(--font-family-mono)',
fontWeight: differs ? 'var(--font-weight-bold)' : 'var(--font-weight-normal)',
color: differs ? 'var(--color-warning)' : 'var(--color-text-secondary)',
textAlign: 'right',
}}>
{value}
</span>
</div>
)
}
function ColumnFooter({ children, hint }) {
return (
<div style={{
background: COLUMN_BG,
borderRadius: '0 0 var(--radius-lg) var(--radius-lg)',
border: '1px solid var(--color-border)',
borderTop: '1px solid var(--color-border)',
padding: 'var(--space-4)',
display: 'flex',
flexDirection: 'column',
gap: 'var(--space-2)',
alignItems: 'stretch',
}}>
{children}
<span style={{ fontSize: 'var(--font-size-xs)', color: 'var(--color-text-muted)', textAlign: 'center' }}>
{hint}
</span>
</div>
)
}
export default function ConfigConflictModal({ open, onClose, title, rows = [], onKeepConsole, onKeepDevice, canEdit = true }) {
const [onlyDiffs, setOnlyDiffs] = useState(true)
const [busy, setBusy] = useState(null) // 'console' | 'device' | null
const [error, setError] = useState('')
const diffCount = rows.filter((r) => r.differs).length
const visible = onlyDiffs ? rows.filter((r) => r.differs) : rows
const run = (which, fn) => async () => {
setBusy(which)
setError('')
try {
await fn()
onClose()
} catch (err) {
// Device rejections already show their own toast; keep the modal open.
setError(err?.message || 'Failed.')
} finally {
setBusy(null)
}
}
return (
<Modal
open={open}
onClose={busy ? () => {} : onClose}
title={`${title} — Console and device disagree`}
size="lg"
footer={
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', width: '100%', gap: 'var(--space-3)' }}>
<label style={{ display: 'flex', alignItems: 'center', gap: 'var(--space-2)', fontSize: 'var(--font-size-sm)', color: 'var(--color-text-secondary)', cursor: 'pointer' }}>
<input type="checkbox" checked={onlyDiffs} onChange={(e) => setOnlyDiffs(e.target.checked)} />
Only show differences
</label>
<Button variant="ghost" onClick={onClose} disabled={!!busy}>Decide later</Button>
</div>
}
>
<div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-4)' }}>
<p style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-text-muted)', margin: 0 }}>
The settings stored on the device don&apos;t match what the console has saved
— <strong style={{ color: 'var(--color-warning)' }}>
{diffCount} {diffCount === 1 ? 'difference' : 'differences'}
</strong>. Choose which version to keep. Nothing changes until you pick one.
</p>
{/* Two columns, rows aligned across them (one shared grid). */}
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', columnGap: 'var(--space-4)' }}>
<ColumnHeader icon="dashboard" title="Saved in Console" subtitle="What the database holds" />
<ColumnHeader icon="devices" title="Stored on Device" subtitle="Read from the device just now" />
{visible.map((r, i) => [
<Cell key={`${r.key}-s`} label={r.label} value={r.saved} differs={r.differs} last={i === visible.length - 1} />,
<Cell key={`${r.key}-d`} label={r.label} value={r.device} differs={r.differs} last={i === visible.length - 1} />,
])}
{canEdit ? (
<>
<ColumnFooter hint="Pushes these settings to the device. The database is already correct.">
<Button
variant="primary"
icon={<Icon name="upload" size={14} />}
loading={busy === 'console'}
disabled={!!busy}
onClick={run('console', onKeepConsole)}
>
Keep Console version
</Button>
</ColumnFooter>
<ColumnFooter hint="Saves only the differing values to the database. The device is not touched.">
<Button
variant="primary"
icon={<Icon name="download" size={14} />}
loading={busy === 'device'}
disabled={!!busy}
onClick={run('device', onKeepDevice)}
>
Keep Device version
</Button>
</ColumnFooter>
</>
) : (
<>
<ColumnFooter hint="You don't have permission to change device settings." />
<ColumnFooter hint="You don't have permission to change device settings." />
</>
)}
</div>
{error && (
<p style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-danger)', margin: 0 }}>{error}</p>
)}
</div>
</Modal>
)
}
@@ -176,7 +176,6 @@ export default function EditAlertsModal({ open, onClose, onSaved, clock, attr, i
await api.put(`/devices/${id}`, { await api.put(`/devices/${id}`, {
device_attributes: { device_attributes: {
clockSettings: { clockSettings: {
...clock,
ringAlerts: alertType, ringAlerts: alertType,
ringIntervals: alertType === 'multi' ? ringIntervals : clock?.ringIntervals, ringIntervals: alertType === 'multi' ? ringIntervals : clock?.ringIntervals,
hourAlertsBell: Number(hourBell), hourAlertsBell: Number(hourBell),
@@ -59,7 +59,6 @@ export default function EditBacklightModal({ open, onClose, onSaved, attr, clock
await api.put(`/devices/${id}`, { await api.put(`/devices/${id}`, {
device_attributes: { device_attributes: {
clockSettings: { clockSettings: {
...clock,
isBacklightAutomationOn: enabled, isBacklightAutomationOn: enabled,
backlightOutput: Number(output), backlightOutput: Number(output),
backlightTurnOnTime: enabled && onTime ? timeToIso(onTime) : null, backlightTurnOnTime: enabled && onTime ? timeToIso(onTime) : null,
@@ -110,7 +110,6 @@ export default function EditClockSettingsModal({ open, onClose, onSaved, attr, s
device_attributes: { device_attributes: {
hasClock, hasClock,
clockSettings: { clockSettings: {
...clock,
clockOutputs: [out1, out2].filter(o => o > 0), clockOutputs: [out1, out2].filter(o => o > 0),
clockTimings: [runPulse, pauseMs], clockTimings: [runPulse, pauseMs],
faceSyncMode: faceSync, faceSyncMode: faceSync,
@@ -2,12 +2,16 @@
// Bell Mechanisms tab — displays Bell Commander/Guard status, connected bell count, // Bell Mechanisms tab — displays Bell Commander/Guard status, connected bell count,
// master switch, and per-bell glass cards with output, timing, size, and strike stats. // master switch, and per-bell glass cards with output, timing, size, and strike stats.
import { useState, useCallback, useEffect, useRef } from 'react' import { useState, useCallback, useMemo } from 'react'
import api from '@/lib/api' import api from '@/lib/api'
import Button from '@/components/ui/Button' import Button from '@/components/ui/Button'
import StatusBadge from '@/components/ui/StatusBadge' import StatusBadge from '@/components/ui/StatusBadge'
import Icon from '@/components/ui/Icon' import Icon from '@/components/ui/Icon'
import ConfirmDialog from '@/components/ui/ConfirmDialog' import ConfirmDialog from '@/components/ui/ConfirmDialog'
import ConfigDriftBanner from '@/components/shared/ConfigDriftBanner'
import ConfigConflictModal from '@/modals/bellcloud/devices/ConfigConflictModal'
import { useDeviceConfigCheck } from '@/hooks/useDeviceConfigCheck'
import { buildBellRows, bellPushContents, mergePatches } from '@/lib/deviceConfigDiff'
import certificationImg from '@/assets/striker-mechanisms/certification.png' import certificationImg from '@/assets/striker-mechanisms/certification.png'
import strikerSize1 from '@/assets/striker-mechanisms/size-1.jpg' import strikerSize1 from '@/assets/striker-mechanisms/size-1.jpg'
@@ -280,75 +284,52 @@ export default function BellsTab({
const [requestingCounters, setRequestingCounters] = useState(false) const [requestingCounters, setRequestingCounters] = useState(false)
const [liveCounters] = useState(null) const [liveCounters] = useState(null)
const [confirmDisable, setConfirmDisable] = useState(false) const [confirmDisable, setConfirmDisable] = useState(false)
const [showConflict, setShowConflict] = useState(false)
// Derived data — shown instantly from Firestore on load, then silently // Shown exactly as saved. This tab never writes on its own — bell settings
// reconciled against the device's true on-device config (see effect below). // are only written by Edit Outputs / the Commander toggle, or by the user
// resolving a console-vs-device conflict below.
const bellOutputs = attr?.bellOutputs || [] const bellOutputs = attr?.bellOutputs || []
const hammerTimings = attr?.hammerTimings || [] const hammerTimings = attr?.hammerTimings || []
const totalBells = attr?.totalBells || 0 const totalBells = attr?.totalBells || 0
const hasBells = attr?.hasBells ?? false const hasBells = attr?.hasBells ?? false
const bellGuardOn = attr?.bellGuardOn ?? false const bellGuardOn = attr?.bellGuardOn ?? false
// ── Background refresh: pull true state from the device right after load ── // ── Console vs device: read the device's stored bell config (read-only) ──
// Fires at most once per mount (hasSyncedRef guard — belt-and-suspenders const readBells = useCallback(
// against StrictMode's double-invoke or any parent re-render retriggering () => sendMqttCommandSilent('bells.get_config').then((r) => r?.data || {}),
// this effect). Reconciles bells_enabled/durations/outputs against Firestore [sendMqttCommandSilent]
// and silently corrects any drift — no toast, this is a quiet sync. )
const hasSyncedRef = useRef(false) const check = useDeviceConfigCheck({
useEffect(() => { enabled: !!sendMqttCommandSilent && !!device,
if (!sendMqttCommandSilent || !device) return read: readBells,
if (hasSyncedRef.current) return savedKey: JSON.stringify([hasBells, bellOutputs, hammerTimings]),
hasSyncedRef.current = true })
const deviceId = device.id || device.device_id const rows = useMemo(
() => (check.status === 'ok' && check.data?.outputs ? buildBellRows(attr, check.data) : []),
[check.status, check.data, attr]
)
const diffRows = rows.filter((r) => r.differs)
sendMqttCommandSilent('bells.get_config').then((reply) => { // Keep Console version: push the saved bells to the device. Firestore already
const data = reply?.data || {} // holds these values, so nothing is written — just re-read to confirm.
const durations = data.durations || {} const keepConsole = async () => {
const outputs = data.outputs || {} if (diffRows.some((r) => r.group === 'bells')) {
const channelCount = Math.max( await sendMqttCommand('relay.set_config', bellPushContents(attr, check.data))
Object.keys(durations).length, }
Object.keys(outputs).length, if (diffRows.some((r) => r.group === 'commander')) {
totalBells, await sendMqttCommand(hasBells ? 'bells.enable' : 'bells.disable')
) }
if (channelCount === 0) return await check.recheck()
}
// Firmware uses both 0 and 65535 (uint16 "unset") as "no output assigned" — // Keep Device version: write ONLY the differing fields to Firestore.
// treat both as disabled so unconfigured channels are never mistaken for const keepDevice = async () => {
// connected bells. await api.put(`/devices/${device.id || device.device_id}`, {
const isDisabledOutput = (o) => !o || o === 65535 device_attributes: mergePatches(diffRows),
// The console's data model assumes bells are a contiguous block starting at
// index 0 (see EditBellOutputsModal / totalBells). The device, however, can
// report enabled channels at any index with gaps in between — so compact
// only the genuinely-connected channels down to a contiguous list, in
// channel order, rather than naively slicing the raw 16-slot arrays.
const connectedIndexes = Array.from({ length: channelCount }, (_, i) => i)
.filter((i) => !isDisabledOutput(Number(outputs[i] ?? 0)))
const trueOutputs = connectedIndexes.map((i) => Number(outputs[i]))
const trueTimings = connectedIndexes.map((i) => Number(durations[i] ?? 0))
const trueEnabled = !!data.bells_enabled
const trueActiveCount = trueOutputs.length
const outputsDiffer = JSON.stringify(trueOutputs) !== JSON.stringify(bellOutputs)
const timingsDiffer = JSON.stringify(trueTimings) !== JSON.stringify(hammerTimings)
const enabledDiffers = trueEnabled !== hasBells
if (!outputsDiffer && !timingsDiffer && !enabledDiffers) return
api.put(`/devices/${deviceId}`, {
device_attributes: {
hasBells: trueEnabled,
totalBells: trueActiveCount,
bellOutputs: trueOutputs,
hammerTimings: trueTimings,
},
}).then(() => reloadDeviceSilent?.())
}).catch(() => {
// Device offline or didn't reply — keep showing the last-known Firestore values.
}) })
// eslint-disable-next-line react-hooks/exhaustive-deps await (reloadDeviceSilent || loadDevice)?.()
}, [device?.id, device?.device_id]) }
// Request strike counters via MQTT // Request strike counters via MQTT
const requestStrikeCounters = useCallback(async () => { const requestStrikeCounters = useCallback(async () => {
@@ -394,6 +375,15 @@ export default function BellsTab({
return ( return (
<div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-6)', width: '100%', maxWidth: 2000, margin: '0 auto' }}> <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-6)', width: '100%', maxWidth: 2000, margin: '0 auto' }}>
{/* ── Console vs device ─────────────────────────────────────────────── */}
<ConfigDriftBanner
label="Bell configuration"
status={check.status}
diffCount={diffRows.length}
onReview={() => setShowConflict(true)}
onRecheck={check.recheck}
/>
{/* ── Status overview bar ───────────────────────────────────────────── */} {/* ── Status overview bar ───────────────────────────────────────────── */}
<div style={{ <div style={{
background: 'rgba(28, 32, 38, 0.30)', background: 'rgba(28, 32, 38, 0.30)',
@@ -559,6 +549,16 @@ export default function BellsTab({
loading={togglingCommander} loading={togglingCommander}
/> />
<ConfigConflictModal
open={showConflict && diffRows.length > 0}
onClose={() => setShowConflict(false)}
title="Bell configuration"
rows={rows}
canEdit={canEdit}
onKeepConsole={keepConsole}
onKeepDevice={keepDevice}
/>
</div> </div>
) )
} }
@@ -1,7 +1,11 @@
// frontend/src/pages/bellcloud/devices/tabs/ClockTab.jsx // frontend/src/pages/bellcloud/devices/tabs/ClockTab.jsx
import { useState, useEffect, useRef } from 'react' import { useState, useEffect, useRef, useCallback, useMemo } from 'react'
import api from '@/lib/api' import api from '@/lib/api'
import ConfigDriftBanner from '@/components/shared/ConfigDriftBanner'
import ConfigConflictModal from '@/modals/bellcloud/devices/ConfigConflictModal'
import { useDeviceConfigCheck } from '@/hooks/useDeviceConfigCheck'
import { buildClockRows, clockPushCommands, mergePatches } from '@/lib/deviceConfigDiff'
import Card from '@/components/ui/Card' import Card from '@/components/ui/Card'
import Button from '@/components/ui/Button' import Button from '@/components/ui/Button'
import StatusBadge from '@/components/ui/StatusBadge' import StatusBadge from '@/components/ui/StatusBadge'
@@ -320,97 +324,54 @@ export default function ClockTab({
return () => clearInterval(id) return () => clearInterval(id)
}, []) }, [])
// ── Background refresh: pull true state from the device right after load ── // ── Live read of time / timezone / NTP / face, once per mount ─────────────
// Fires at most once per mount (hasSyncedRef guard — belt-and-suspenders // Read-only: this tab never writes the device record on its own. Clock
// against StrictMode's double-invoke or any parent re-render retriggering // settings are only written by the Edit modals, after the device confirms.
// this effect). Reconciles enabled/outputs/timings/alerts/backlight/silence const hasLoadedLiveRef = useRef(false)
// against Firestore using semantic (not raw-string) comparison, and silently
// corrects any real drift — no toast.
const hasSyncedRef = useRef(false)
useEffect(() => { useEffect(() => {
if (!sendMqttCommandSilent || !device) return if (!sendMqttCommandSilent || !device) return
if (hasSyncedRef.current) return if (hasLoadedLiveRef.current) return
hasSyncedRef.current = true hasLoadedLiveRef.current = true
const deviceId = device.id || device.device_id loadLive()
sendMqttCommandSilent('clock.get_config').then((reply) => {
const data = reply?.data || {}
if (!data || Object.keys(data).length === 0) return
const trueAlertType = { OFF: 'disabled', SINGLE: 'single', HOURS: 'multi' }[data.alert_type] ?? 'disabled'
const trueHourBell = data.hour_bell === 255 ? 0 : (data.hour_bell || 0)
const trueHalfBell = data.half_bell === 255 ? 0 : (data.half_bell || 0)
const trueQuarterBell = data.quarter_bell === 255 ? 0 : (data.quarter_bell || 0)
const trueC1 = data.c1output || 0
const trueC2 = data.c2output || 0
const truePulse = data.pulse_duration || 0
const truePause = data.pause_duration || 0
const trueBacklightOutput = data.backlight_output === 255 ? 0 : (data.backlight_output || 0)
// Semantic comparison — normalize times to HH:MM via extractTime so format
// differences (timezone suffix, seconds, etc.) never register as false drift.
const hasDrift =
!!data.enabled !== (attr?.hasClock ?? false) ||
trueC1 !== (clock?.clockOutputs?.[0] || 0) ||
trueC2 !== (clock?.clockOutputs?.[1] || 0) ||
truePulse !== (clock?.clockTimings?.[0] || 0) ||
truePause !== (clock?.clockTimings?.[1] || 0) ||
trueAlertType !== (clock?.ringAlerts || 'disabled') ||
(trueAlertType === 'multi' && data.alert_interval !== clock?.ringIntervals) ||
trueHourBell !== (clock?.hourAlertsBell || 0) ||
trueHalfBell !== (clock?.halfhourAlertsBell || 0) ||
trueQuarterBell !== (clock?.quarterAlertsBell || 0) ||
!!data.daytime_silence !== (clock?.isDaySilenceOn ?? false) ||
data.daytime_on !== extractTime(clock?.daySilenceFrom) ||
data.daytime_off !== extractTime(clock?.daySilenceTo) ||
!!data.night_silence !== (clock?.isNightSilenceOn ?? false) ||
data.night_on !== extractTime(clock?.nightSilenceFrom) ||
data.night_off !== extractTime(clock?.nightSilenceTo) ||
!!data.backlight !== (clock?.isBacklightAutomationOn ?? false) ||
trueBacklightOutput !== (clock?.backlightOutput || 0) ||
(!!data.backlight && data.backlight_on !== extractTime(clock?.backlightTurnOnTime)) ||
(!!data.backlight && data.backlight_off !== extractTime(clock?.backlightTurnOffTime)) ||
(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
api.put(`/devices/${deviceId}`, {
device_attributes: {
hasClock: !!data.enabled,
clockSettings: {
...clock,
clockOutputs: [trueC1, trueC2],
clockTimings: [truePulse, truePause],
ringAlerts: trueAlertType,
ringIntervals: data.alert_interval,
hourAlertsBell: trueHourBell,
halfhourAlertsBell: trueHalfBell,
quarterAlertsBell: trueQuarterBell,
isDaySilenceOn: !!data.daytime_silence,
daySilenceFrom: data.daytime_on ? `2000-01-01T${data.daytime_on}:00Z` : (clock?.daySilenceFrom ?? null),
daySilenceTo: data.daytime_off ? `2000-01-01T${data.daytime_off}:00Z` : (clock?.daySilenceTo ?? null),
isNightSilenceOn: !!data.night_silence,
nightSilenceFrom: data.night_on ? `2000-01-01T${data.night_on}:00Z` : (clock?.nightSilenceFrom ?? null),
nightSilenceTo: data.night_off ? `2000-01-01T${data.night_off}:00Z` : (clock?.nightSilenceTo ?? null),
isBacklightAutomationOn: !!data.backlight,
backlightOutput: trueBacklightOutput,
backlightTurnOnTime: data.backlight_on ? `2000-01-01T${data.backlight_on}:00Z` : null,
backlightTurnOffTime: data.backlight_off ? `2000-01-01T${data.backlight_off}:00Z` : null,
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 // eslint-disable-next-line react-hooks/exhaustive-deps
}, [device?.id, device?.device_id]) }, [device?.id, device?.device_id])
// ── Console vs device: read the device's stored clock config (read-only) ──
const [showConflict, setShowConflict] = useState(false)
const readClock = useCallback(
() => sendMqttCommandSilent('clock.get_config').then((r) => r?.data || {}),
[sendMqttCommandSilent]
)
const check = useDeviceConfigCheck({
enabled: !!sendMqttCommandSilent && !!device,
read: readClock,
savedKey: JSON.stringify([attr?.hasClock ?? false, clock || {}]),
})
const rows = useMemo(
() => (check.status === 'ok' && Object.keys(check.data || {}).length
? buildClockRows(attr, clock, check.data)
: []),
[check.status, check.data, attr, clock]
)
const diffRows = rows.filter((r) => r.differs)
// Keep Console version: push only the setting groups that differ.
const keepConsole = async () => {
const groups = new Set(diffRows.map((r) => r.group))
for (const [cmd, contents] of clockPushCommands(attr, clock, groups)) {
await sendMqttCommand(cmd, contents)
}
await check.recheck()
}
// Keep Device version: write ONLY the differing fields to Firestore.
const keepDevice = async () => {
await api.put(`/devices/${device.id || device.device_id}`, {
device_attributes: mergePatches(diffRows),
})
await (reloadDeviceSilent || loadDevice)?.()
}
// ── Live time / timezone / NTP / face from the device ───────────────────── // ── Live time / timezone / NTP / face from the device ─────────────────────
// Replies are matched FIFO, so these go one after another. // Replies are matched FIFO, so these go one after another.
const loadLive = async (parts = ['time', 'tz', 'ntp', 'face']) => { const loadLive = async (parts = ['time', 'tz', 'ntp', 'face']) => {
@@ -560,6 +521,24 @@ export default function ClockTab({
<div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-6)', width: '100%', maxWidth: 2000, margin: '0 auto' }}> <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-6)', width: '100%', maxWidth: 2000, margin: '0 auto' }}>
{/* ── Console vs device ─────────────────────────────────────────────── */}
<ConfigDriftBanner
label="Clock configuration"
status={check.status}
diffCount={diffRows.length}
onReview={() => setShowConflict(true)}
onRecheck={check.recheck}
/>
<ConfigConflictModal
open={showConflict && diffRows.length > 0}
onClose={() => setShowConflict(false)}
title="Clock configuration"
rows={rows}
canEdit={canEdit}
onKeepConsole={keepConsole}
onKeepDevice={keepDevice}
/>
{/* ── Hero ──────────────────────────────────────────────────────────── */} {/* ── Hero ──────────────────────────────────────────────────────────── */}
<div style={{ <div style={{
position: 'relative', position: 'relative',
@@ -10,6 +10,10 @@ import Icon from '@/components/ui/Icon'
import FormField from '@/components/ui/FormField' import FormField from '@/components/ui/FormField'
import Spinner from '@/components/ui/Spinner' import Spinner from '@/components/ui/Spinner'
import { fmtDateTimeMedium } from '@/lib/formatters' import { fmtDateTimeMedium } from '@/lib/formatters'
import ConfigDriftBanner from '@/components/shared/ConfigDriftBanner'
import ConfigConflictModal from '@/modals/bellcloud/devices/ConfigConflictModal'
import { useDeviceConfigCheck } from '@/hooks/useDeviceConfigCheck'
import { buildLogRows, LOG_FIELDS, mergePatches } from '@/lib/deviceConfigDiff'
// ─── Constants ──────────────────────────────────────────────────────────────── // ─── Constants ────────────────────────────────────────────────────────────────
@@ -879,11 +883,10 @@ export default function GeneralTab({
if (Number.isFinite(attr?.mqttLogLevel)) setMqttLevel(attr.mqttLogLevel) if (Number.isFinite(attr?.mqttLogLevel)) setMqttLevel(attr.mqttLogLevel)
}, [attr?.serialLogLevel, attr?.sdLogLevel, attr?.mqttLogLevel]) }, [attr?.serialLogLevel, attr?.sdLogLevel, attr?.mqttLogLevel])
// ── Background refresh: pull true log levels + network info from the device ── // ── Live read of network info + firmware status, once per mount ──────────
// Fires at most once per mount (hasSyncedRef guard). Log levels are reconciled // Read-only display data. This tab never writes the device record on its
// against Firestore and silently corrected on drift. Network info is read-only // own — log levels are only written when the user moves a slider and the
// and always reflects whatever the device just reported — no drift comparison // device confirms (handleSaveLogging).
// needed since nothing else in the console ever writes it.
const hasSyncedRef = useRef(false) const hasSyncedRef = useRef(false)
const [networkInfo, setNetworkInfo] = useState(null) const [networkInfo, setNetworkInfo] = useState(null)
const [firmwareStatus, setFirmwareStatus] = useState(null) const [firmwareStatus, setFirmwareStatus] = useState(null)
@@ -891,36 +894,6 @@ export default function GeneralTab({
if (!sendMqttCommandSilent || !device) return if (!sendMqttCommandSilent || !device) return
if (hasSyncedRef.current) return if (hasSyncedRef.current) return
hasSyncedRef.current = true hasSyncedRef.current = true
const deviceId = device.id || device.device_id
sendMqttCommandSilent('log.get_config').then((reply) => {
const data = reply?.data || {}
const trueSerial = data.serial_level
const trueSd = data.sd_level
const trueMqtt = data.mqtt_level
if (trueSerial == null && trueSd == null && trueMqtt == null) return
const hasDrift =
(trueSerial != null && trueSerial !== (attr?.serialLogLevel ?? 0)) ||
(trueSd != null && trueSd !== (attr?.sdLogLevel ?? 0)) ||
(trueMqtt != null && trueMqtt !== (attr?.mqttLogLevel ?? 0))
if (!hasDrift) return
if (trueSerial != null) setSerialLevel(trueSerial)
if (trueSd != null) setSdLevel(trueSd)
if (trueMqtt != null) setMqttLevel(trueMqtt)
api.put(`/devices/${deviceId}`, {
device_attributes: {
serialLogLevel: trueSerial ?? attr?.serialLogLevel ?? 0,
sdLogLevel: trueSd ?? attr?.sdLogLevel ?? 0,
mqttLogLevel: trueMqtt ?? attr?.mqttLogLevel ?? 0,
},
}).then(() => reloadDeviceSilent?.())
}).catch(() => {
// Device offline or didn't reply — keep showing the last-known Firestore values.
})
sendMqttCommandSilent('network.info').then((reply) => { sendMqttCommandSilent('network.info').then((reply) => {
setNetworkInfo(reply?.data || null) setNetworkInfo(reply?.data || null)
@@ -936,6 +909,38 @@ export default function GeneralTab({
// eslint-disable-next-line react-hooks/exhaustive-deps // eslint-disable-next-line react-hooks/exhaustive-deps
}, [device?.id, device?.device_id]) }, [device?.id, device?.device_id])
// ── Console vs device: read the device's stored log levels (read-only) ──
const [showLogConflict, setShowLogConflict] = useState(false)
const readLogs = useCallback(
() => sendMqttCommandSilent('log.get_config').then((r) => r?.data || {}),
[sendMqttCommandSilent]
)
const logCheck = useDeviceConfigCheck({
enabled: !!sendMqttCommandSilent && !!device,
read: readLogs,
savedKey: JSON.stringify([attr?.serialLogLevel, attr?.sdLogLevel, attr?.mqttLogLevel]),
})
const logRows = useMemo(
() => (logCheck.status === 'ok' ? buildLogRows(attr, logCheck.data) : []),
[logCheck.status, logCheck.data, attr]
)
const logDiffRows = logRows.filter((r) => r.differs)
// Keep Console version: push each differing saved level to the device.
const keepConsoleLogs = async () => {
for (const r of logDiffRows) {
const f = LOG_FIELDS.find((x) => x.key === r.key)
await sendMqttCommand(f.cmd, { level: Number(attr?.[f.attr] ?? 0) })
}
await logCheck.recheck()
}
// Keep Device version: write ONLY the differing levels to Firestore.
const keepDeviceLogs = async () => {
await api.put(`/devices/${id}`, { device_attributes: mergePatches(logDiffRows) })
await reloadDeviceSilent?.()
}
// Nearest place // Nearest place
const coords = useMemo(() => parseCoordinates(device?.device_location_coordinates), [device?.device_location_coordinates]) const coords = useMemo(() => parseCoordinates(device?.device_location_coordinates), [device?.device_location_coordinates])
@@ -997,11 +1002,12 @@ export default function GeneralTab({
await api.put(`/devices/${id}`, { await api.put(`/devices/${id}`, {
device_attributes: { [LOG_ATTR[field]]: value }, device_attributes: { [LOG_ATTR[field]]: value },
}) })
reloadDeviceSilent?.()
} catch { } catch {
// sendMqttCommand's toast already reported the failure — revert the slider. // sendMqttCommand's toast already reported the failure — revert the slider.
logSetters[field](previous) logSetters[field](previous)
} }
}, [id, serialLevel, sdLevel, mqttLevel, canEdit, sendMqttCommand, logSetters]) }, [id, serialLevel, sdLevel, mqttLevel, canEdit, sendMqttCommand, logSetters, reloadDeviceSilent])
// ── Network fields ───────────────────────────────────────────────────────── // ── Network fields ─────────────────────────────────────────────────────────
// Populated live from network.info — read-only, reported directly by the device. // Populated live from network.info — read-only, reported directly by the device.
@@ -1233,6 +1239,22 @@ export default function GeneralTab({
fullHeight fullHeight
> >
<div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-6)', flex: 1, justifyContent: 'center' }}> <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-6)', flex: 1, justifyContent: 'center' }}>
<ConfigDriftBanner
label="Log levels"
status={logCheck.status}
diffCount={logDiffRows.length}
onReview={() => setShowLogConflict(true)}
onRecheck={logCheck.recheck}
/>
<ConfigConflictModal
open={showLogConflict && logDiffRows.length > 0}
onClose={() => setShowLogConflict(false)}
title="Log levels"
rows={logRows}
canEdit={canEdit}
onKeepConsole={keepConsoleLogs}
onKeepDevice={keepDeviceLogs}
/>
<LogSlider <LogSlider
label="Serial Log" label="Serial Log"
level={serialLevel} level={serialLevel}