Files
bellsystems-cp/frontend/src/modals/bellcloud/devices/EditClockSettingsModal.jsx
T
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

288 lines
11 KiB
React
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// frontend/src/modals/bellcloud/devices/EditClockSettingsModal.jsx
// Edits: master switch, ODD/EVEN outputs, pulse and pause durations (sliders), and the
// face sync policy (firmware 3.2.0+: force = run a full lap when the face is ahead,
// smart = wait if it is at most N minutes ahead).
import { useState } from 'react'
import Modal from '@/components/ui/Modal'
import Button from '@/components/ui/Button'
import FormField from '@/components/ui/FormField'
import SegmentedControl from '@/components/ui/SegmentedControl'
import api from '@/lib/api'
// Pulse options in milliseconds — shown as sliders with labelled steps
const PULSE_STEPS = [200, 300, 400, 500, 600, 800, 1000, 1200, 1500, 2000]
const PAUSE_STEPS = [500, 1000, 1500, 2000, 3000, 4000, 5000]
function msLabel(ms) {
if (!ms) return '—'
return ms >= 1000 ? `${(ms / 1000).toFixed(1)}s` : `${ms}ms`
}
// Slider that snaps to a fixed array of allowed values
function StepSlider({ steps, value, onChange, label }) {
const idx = steps.indexOf(value)
const currentIdx = idx >= 0 ? idx : 0
return (
<div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-2)' }}>
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
<span style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-text-muted)', fontWeight: 'var(--font-weight-medium)' }}>
{label}
</span>
<span style={{
fontFamily: 'var(--font-family-display)',
fontSize: 'var(--font-size-xl)',
fontWeight: 'var(--font-weight-bold)',
letterSpacing: 'var(--tracking-tight)',
color: 'var(--color-primary)',
lineHeight: 1,
}}>
{msLabel(steps[currentIdx])}
</span>
</div>
<input
type="range"
min={0}
max={steps.length - 1}
step={1}
value={currentIdx}
onChange={e => onChange(steps[Number(e.target.value)])}
style={{ width: '100%', accentColor: 'var(--color-primary)', cursor: 'pointer' }}
/>
<div style={{ display: 'flex', justifyContent: 'space-between' }}>
<span style={{ fontSize: 'var(--font-size-xs)', color: 'var(--color-text-muted)' }}>{msLabel(steps[0])}</span>
<span style={{ fontSize: 'var(--font-size-xs)', color: 'var(--color-text-muted)' }}>{msLabel(steps[steps.length - 1])}</span>
</div>
</div>
)
}
export default function EditClockSettingsModal({ open, onClose, onSaved, attr, sub, id, sendMqttCommand }) {
const clock = attr?.clockSettings || {}
const maxOutputs = sub?.maxOutputs || 8
const bellOutputsUsed = (attr?.bellOutputs || []).filter(o => o > 0)
const existingClockOutputs = clock.clockOutputs || []
const existingTimings = clock.clockTimings || []
const [hasClock, setHasClock] = useState(attr?.hasClock ?? false)
const [clockOut1, setClockOut1] = useState(String(existingClockOutputs[0] ?? 0))
const [clockOut2, setClockOut2] = useState(String(existingClockOutputs[1] ?? 0))
const [runPulse, setRunPulse] = useState(existingTimings[0] || PULSE_STEPS[3]) // default 500ms
const [pauseMs, setPauseMs] = useState(existingTimings[1] || PAUSE_STEPS[1]) // default 1000ms
const [faceSync, setFaceSync] = useState(clock.faceSyncMode || 'force')
const [maxWait, setMaxWait] = useState(String(clock.smartMaxWaitMin ?? 61))
const [saving, setSaving] = useState(false)
const [error, setError] = useState('')
const out1 = Number(clockOut1)
const out2 = Number(clockOut2)
const conflictMsg = out1 > 0 && out1 === out2 ? 'ODD and EVEN outputs cannot be the same.' : null
const validationMsg = hasClock && (out1 === 0 || out2 === 0)
? 'Both outputs must be assigned when the clock is enabled.'
: null
const maxWaitNum = Number(maxWait)
const maxWaitMsg = faceSync === 'smart' && (!Number.isInteger(maxWaitNum) || maxWaitNum < 1 || maxWaitNum > 359)
? 'Maximum wait must be 1–359 minutes.'
: null
const canSave = !conflictMsg && !validationMsg && !maxWaitMsg
const handleSave = async () => {
if (!canSave) return
setSaving(true)
setError('')
try {
// Push to the device first — clock.set_config batches enable/outputs/timings
// into one round trip. Firestore is only written once the device confirms.
await sendMqttCommand('clock.set_config', {
enabled: hasClock,
c1: out1,
c2: out2,
pulse_duration: runPulse,
pause_duration: pauseMs,
face_sync_mode: faceSync,
...(faceSync === 'smart' ? { smart_max_wait_min: maxWaitNum } : {}),
})
await api.put(`/devices/${id}`, {
device_attributes: {
hasClock,
clockSettings: {
clockOutputs: [out1, out2].filter(o => o > 0),
clockTimings: [runPulse, pauseMs],
faceSyncMode: faceSync,
...(faceSync === 'smart' ? { smartMaxWaitMin: maxWaitNum } : {}),
},
},
})
await onSaved()
onClose()
} catch (err) {
// sendMqttCommand already surfaced a failure toast if the device rejected it.
setError(err.message || 'Failed to save.')
} finally {
setSaving(false)
}
}
const outputOptions = Array.from({ length: maxOutputs }, (_, j) => {
const out = j + 1
return { out, isBell: bellOutputsUsed.includes(out) }
})
return (
<Modal
open={open}
onClose={onClose}
title="Clock Settings"
size="sm"
footer={
<div style={{ display: 'flex', justifyContent: 'flex-end', gap: 'var(--space-3)' }}>
<Button variant="ghost" onClick={onClose}>Cancel</Button>
<Button variant="primary" loading={saving} disabled={!canSave} onClick={handleSave}>
Save Settings
</Button>
</div>
}
>
<div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-5)' }}>
{/* Master switch */}
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
<div>
<p style={{ fontSize: 'var(--font-size-base)', fontWeight: 'var(--font-weight-semibold)', color: 'var(--color-text-primary)' }}>
Clock Controller
</p>
<p style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-text-muted)', marginTop: 2 }}>
Enable or disable the clock mechanism entirely
</p>
</div>
<button
type="button"
role="switch"
aria-checked={hasClock}
onClick={() => setHasClock(v => !v)}
style={{
position: 'relative',
width: 44,
height: 24,
borderRadius: 'var(--radius-full)',
backgroundColor: hasClock ? 'var(--color-success)' : 'var(--color-bg-island)',
border: `1px solid ${hasClock ? 'var(--color-success)' : 'var(--color-border-strong)'}`,
cursor: 'pointer',
flexShrink: 0,
padding: 0,
transition: 'background-color 0.2s, border-color 0.2s',
}}
>
<div style={{
position: 'absolute',
top: 3,
left: hasClock ? 21 : 3,
width: 16,
height: 16,
borderRadius: 'var(--radius-full)',
backgroundColor: hasClock ? 'var(--color-text-inverse)' : 'var(--color-text-muted)',
transition: 'left 0.2s',
}} />
</button>
</div>
<div style={{ height: 1, backgroundColor: 'var(--color-border)' }} />
{/* Outputs */}
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 'var(--space-3)' }}>
<FormField
label="ODD Output"
name="clockOut1"
type="select"
value={clockOut1}
onChange={e => setClockOut1(e.target.value)}
>
<option value="0">Disconnected</option>
{outputOptions.map(({ out, isBell }) => (
<option key={out} value={String(out)}>
Output {out}{isBell ? ' (Bell)' : ''}
</option>
))}
</FormField>
<FormField
label="EVEN Output"
name="clockOut2"
type="select"
value={clockOut2}
onChange={e => setClockOut2(e.target.value)}
>
<option value="0">Disconnected</option>
{outputOptions.map(({ out, isBell }) => (
<option key={out} value={String(out)}>
Output {out}{isBell ? ' (Bell)' : ''}
</option>
))}
</FormField>
</div>
<div style={{ height: 1, backgroundColor: 'var(--color-border)' }} />
{/* Sliders */}
<StepSlider
label="Pulse Duration"
steps={PULSE_STEPS}
value={runPulse}
onChange={setRunPulse}
/>
<StepSlider
label="Pause Duration"
steps={PAUSE_STEPS}
value={pauseMs}
onChange={setPauseMs}
/>
<div style={{ height: 1, backgroundColor: 'var(--color-border)' }} />
{/* Face sync policy */}
<div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-3)' }}>
<div>
<p style={{ fontSize: 'var(--font-size-base)', fontWeight: 'var(--font-weight-semibold)', color: 'var(--color-text-primary)' }}>
Face Ahead of Real Time
</p>
<p style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-text-muted)', marginTop: 2 }}>
The hands only move forward. When they are ahead (e.g. after DST ends), Force runs a full
lap to catch up; Smart stops them until real time catches up.
</p>
</div>
<SegmentedControl
options={[{ value: 'force', label: 'Force (full lap)' }, { value: 'smart', label: 'Smart (wait)' }]}
value={faceSync}
onChange={setFaceSync}
size="sm"
/>
{faceSync === 'smart' && (
<FormField
label="Wait if ahead by at most (minutes)"
name="smartMaxWait"
type="number"
value={maxWait}
onChange={e => setMaxWait(e.target.value)}
inputProps={{ min: 1, max: 359, step: 1 }}
hint="Default 61 covers the DST change. Further ahead than this, the face runs the lap."
/>
)}
</div>
{/* Errors / warnings */}
{(conflictMsg || validationMsg || maxWaitMsg) && (
<p style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-warning)', backgroundColor: 'var(--color-warning-bg)', padding: 'var(--space-2) var(--space-3)', borderRadius: 'var(--radius-sm)' }}>
{conflictMsg || validationMsg || maxWaitMsg}
</p>
)}
{error && (
<p style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-danger)' }}>{error}</p>
)}
</div>
</Modal>
)
}