diff --git a/frontend/src/components/shared/ConfigDriftBanner.jsx b/frontend/src/components/shared/ConfigDriftBanner.jsx new file mode 100644 index 0000000..6e25e8f --- /dev/null +++ b/frontend/src/components/shared/ConfigDriftBanner.jsx @@ -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 ( +
+ {status === 'checking' + ? + : } + + {text} + + {differs && ( + + )} + {status !== 'checking' && ( + + )} +
+ ) +} diff --git a/frontend/src/hooks/useDeviceConfigCheck.js b/frontend/src/hooks/useDeviceConfigCheck.js new file mode 100644 index 0000000..93712ca --- /dev/null +++ b/frontend/src/hooks/useDeviceConfigCheck.js @@ -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 diff --git a/frontend/src/lib/deviceConfigDiff.js b/frontend/src/lib/deviceConfigDiff.js new file mode 100644 index 0000000..4427270 --- /dev/null +++ b/frontend/src/lib/deviceConfigDiff.js @@ -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]) })) +} diff --git a/frontend/src/modals/bellcloud/devices/ConfigConflictModal.jsx b/frontend/src/modals/bellcloud/devices/ConfigConflictModal.jsx new file mode 100644 index 0000000..c71ec05 --- /dev/null +++ b/frontend/src/modals/bellcloud/devices/ConfigConflictModal.jsx @@ -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 ( +
+
+ +
+
+
+ {title} +
+
+ {subtitle} +
+
+
+ ) +} + +function Cell({ label, value, differs, last }) { + return ( +
+ + {label} + + + {value} + +
+ ) +} + +function ColumnFooter({ children, hint }) { + return ( +
+ {children} + + {hint} + +
+ ) +} + +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 ( + {} : onClose} + title={`${title} — Console and device disagree`} + size="lg" + footer={ +
+ + +
+ } + > +
+

+ The settings stored on the device don't match what the console has saved + — + {diffCount} {diffCount === 1 ? 'difference' : 'differences'} + . Choose which version to keep. Nothing changes until you pick one. +

+ + {/* Two columns, rows aligned across them (one shared grid). */} +
+ + + + {visible.map((r, i) => [ + , + , + ])} + + {canEdit ? ( + <> + + + + + + + + ) : ( + <> + + + + )} +
+ + {error && ( +

{error}

+ )} +
+
+ ) +} diff --git a/frontend/src/pages/bellcloud/devices/tabs/BellsTab.jsx b/frontend/src/pages/bellcloud/devices/tabs/BellsTab.jsx index bd182fa..749c1ef 100644 --- a/frontend/src/pages/bellcloud/devices/tabs/BellsTab.jsx +++ b/frontend/src/pages/bellcloud/devices/tabs/BellsTab.jsx @@ -2,12 +2,16 @@ // 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. -import { useState, useCallback } from 'react' +import { useState, useCallback, useMemo } from 'react' import api from '@/lib/api' import Button from '@/components/ui/Button' import StatusBadge from '@/components/ui/StatusBadge' import Icon from '@/components/ui/Icon' 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 strikerSize1 from '@/assets/striker-mechanisms/size-1.jpg' @@ -271,23 +275,62 @@ export default function BellsTab({ attr, canEdit, loadDevice, + reloadDeviceSilent, sendMqttCommand, + sendMqttCommandSilent, onEditBellOutputs, }) { const [togglingCommander, setTogglingCommander] = useState(false) const [requestingCounters, setRequestingCounters] = useState(false) const [liveCounters] = useState(null) const [confirmDisable, setConfirmDisable] = useState(false) + const [showConflict, setShowConflict] = useState(false) // Shown exactly as saved. This tab never writes on its own — bell settings - // are only written by Edit Outputs / the Commander toggle, after the device - // confirms the change. + // 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 hammerTimings = attr?.hammerTimings || [] const totalBells = attr?.totalBells || 0 const hasBells = attr?.hasBells ?? false const bellGuardOn = attr?.bellGuardOn ?? false + // ── Console vs device: read the device's stored bell config (read-only) ── + const readBells = useCallback( + () => sendMqttCommandSilent('bells.get_config').then((r) => r?.data || {}), + [sendMqttCommandSilent] + ) + const check = useDeviceConfigCheck({ + enabled: !!sendMqttCommandSilent && !!device, + read: readBells, + savedKey: JSON.stringify([hasBells, bellOutputs, hammerTimings]), + }) + 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) + + // Keep Console version: push the saved bells to the device. Firestore already + // holds these values, so nothing is written — just re-read to confirm. + const keepConsole = async () => { + if (diffRows.some((r) => r.group === 'bells')) { + await sendMqttCommand('relay.set_config', bellPushContents(attr, check.data)) + } + if (diffRows.some((r) => r.group === 'commander')) { + await sendMqttCommand(hasBells ? 'bells.enable' : 'bells.disable') + } + 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)?.() + } + // Request strike counters via MQTT const requestStrikeCounters = useCallback(async () => { if (!sendMqttCommand) return @@ -332,6 +375,15 @@ export default function BellsTab({ return (
+ {/* ── Console vs device ─────────────────────────────────────────────── */} + setShowConflict(true)} + onRecheck={check.recheck} + /> + {/* ── Status overview bar ───────────────────────────────────────────── */}
+ 0} + onClose={() => setShowConflict(false)} + title="Bell configuration" + rows={rows} + canEdit={canEdit} + onKeepConsole={keepConsole} + onKeepDevice={keepDevice} + /> +
) } diff --git a/frontend/src/pages/bellcloud/devices/tabs/ClockTab.jsx b/frontend/src/pages/bellcloud/devices/tabs/ClockTab.jsx index 86ae4d4..81e4876 100644 --- a/frontend/src/pages/bellcloud/devices/tabs/ClockTab.jsx +++ b/frontend/src/pages/bellcloud/devices/tabs/ClockTab.jsx @@ -1,7 +1,11 @@ // 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 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 Button from '@/components/ui/Button' import StatusBadge from '@/components/ui/StatusBadge' @@ -300,6 +304,7 @@ export default function ClockTab({ sendMqttCommand, sendMqttCommandSilent, loadDevice, + reloadDeviceSilent, }) { const { toast } = useToast() const [now, setNow] = useState(new Date()) @@ -331,6 +336,42 @@ export default function ClockTab({ // eslint-disable-next-line react-hooks/exhaustive-deps }, [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 ───────────────────── // Replies are matched FIFO, so these go one after another. const loadLive = async (parts = ['time', 'tz', 'ntp', 'face']) => { @@ -480,6 +521,24 @@ export default function ClockTab({
+ {/* ── Console vs device ─────────────────────────────────────────────── */} + setShowConflict(true)} + onRecheck={check.recheck} + /> + 0} + onClose={() => setShowConflict(false)} + title="Clock configuration" + rows={rows} + canEdit={canEdit} + onKeepConsole={keepConsole} + onKeepDevice={keepDevice} + /> + {/* ── Hero ──────────────────────────────────────────────────────────── */}
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 const coords = useMemo(() => parseCoordinates(device?.device_location_coordinates), [device?.device_location_coordinates]) @@ -965,11 +1002,12 @@ export default function GeneralTab({ await api.put(`/devices/${id}`, { device_attributes: { [LOG_ATTR[field]]: value }, }) + reloadDeviceSilent?.() } catch { // sendMqttCommand's toast already reported the failure — revert the slider. logSetters[field](previous) } - }, [id, serialLevel, sdLevel, mqttLevel, canEdit, sendMqttCommand, logSetters]) + }, [id, serialLevel, sdLevel, mqttLevel, canEdit, sendMqttCommand, logSetters, reloadDeviceSilent]) // ── Network fields ───────────────────────────────────────────────────────── // Populated live from network.info — read-only, reported directly by the device. @@ -1201,6 +1239,22 @@ export default function GeneralTab({ fullHeight >
+ setShowLogConflict(true)} + onRecheck={logCheck.recheck} + /> + 0} + onClose={() => setShowLogConflict(false)} + title="Log levels" + rows={logRows} + canEdit={canEdit} + onKeepConsole={keepConsoleLogs} + onKeepDevice={keepDeviceLogs} + />