feat(devices): push General/Clock/Bells/Alerts config live over MQTT

Adopts useDeviceCommand across DeviceDetail and its tabs so config
changes (log levels, clock settings, bell outputs, alert thresholds,
backlight, attributes) are sent to the device immediately via
control commands and only persisted to Firestore once the device
acks success, instead of writing Firestore first and hoping the
device eventually picks it up.

- GeneralTab: log-level sliders now call log.set_serial/sd/mqtt
  directly and revert on failure; a background log.get_config +
  network.info pull reconciles Firestore against the device's actual
  state once per mount
- ClockTab, BellsTab, ControlTab, and the Edit* modals: same
  live-command-then-persist pattern
- EditLoggingModal is removed — its job (log level editing) moved
  inline into GeneralTab's sliders, so a modal round-trip is no
  longer needed
- DeviceDetail wires the shared useDeviceCommand connection through
  to each tab and adds a Health tab entry

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
2026-09-21 18:25:30 +03:00
co-authored by Claude Sonnet 5
parent 7c533b9245
commit cc138e3d82
11 changed files with 940 additions and 259 deletions
@@ -28,6 +28,9 @@ const LOG_LEVEL_META = {
const GLASS_BG = 'rgba(28, 32, 38, 0.30)'
const GLASS_BG_INNER = 'rgba(28, 32, 38, 0.40)'
const LOG_CMD = { serial: 'log.set_serial', sd: 'log.set_sd', mqtt: 'log.set_mqtt' }
const LOG_ATTR = { serial: 'serialLogLevel', sd: 'sdLogLevel', mqtt: 'mqttLogLevel' }
// ─── Helpers ──────────────────────────────────────────────────────────────────
function parseCoordinates(coordStr) {
@@ -851,7 +854,9 @@ export default function GeneralTab({
setTags,
onEditLocation,
onEditAttributes,
onEditLogging,
sendMqttCommand,
sendMqttCommandSilent,
reloadDeviceSilent,
}) {
const { toast } = useToast()
const [locationName, setLocationName] = useState(null)
@@ -874,6 +879,56 @@ export default function GeneralTab({
if (Number.isFinite(attr?.mqttLogLevel)) setMqttLevel(attr.mqttLogLevel)
}, [attr?.serialLogLevel, attr?.sdLogLevel, attr?.mqttLogLevel])
// ── Background refresh: pull true log levels + network info from the device ──
// Fires at most once per mount (hasSyncedRef guard). Log levels are reconciled
// against Firestore and silently corrected on drift. Network info is read-only
// and always reflects whatever the device just reported — no drift comparison
// needed since nothing else in the console ever writes it.
const hasSyncedRef = useRef(false)
const [networkInfo, setNetworkInfo] = useState(null)
useEffect(() => {
if (!sendMqttCommandSilent || !device) return
if (hasSyncedRef.current) return
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) => {
setNetworkInfo(reply?.data || null)
}).catch(() => {
// Device offline or didn't reply — Network Info card stays empty/dash.
})
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [device?.id, device?.device_id])
// Nearest place
const coords = useMemo(() => parseCoordinates(device?.device_location_coordinates), [device?.device_location_coordinates])
@@ -886,11 +941,6 @@ export default function GeneralTab({
.catch(() => setLocationName(null))
}, [coords])
const net = attr?.networkSettings || {}
const staticIpAddress = Array.isArray(net.ipAddress)
? net.ipAddress.filter(Boolean).join('.')
: (net.ipAddress || '')
// ── Tag handlers ────────────────────────────────────────────────────────────
const handleAddTag = useCallback(async (tag) => {
@@ -921,34 +971,43 @@ export default function GeneralTab({
}
}, [id, tags, setTags, toast])
// ── Log level save (on blur / edit) ─────────────────────────────────────────
// ── Log level save ────────────────────────────────────────────────────────
// Each slider sends its own log.set_* command to the device first; Firestore
// is only updated once the device confirms SUCCESS. sendMqttCommand already
// shows the blue→green/red toast, so a slider that fails to apply snaps back
// to its last confirmed value instead of drifting from reality.
const logSetters = useMemo(
() => ({ serial: setSerialLevel, sd: setSdLevel, mqtt: setMqttLevel }),
[]
)
const handleSaveLogging = useCallback(async (field, value) => {
if (!canEdit) return
if (!canEdit || !sendMqttCommand) return
const previous = { serial: serialLevel, sd: sdLevel, mqtt: mqttLevel }[field]
logSetters[field](value)
try {
await sendMqttCommand(LOG_CMD[field], { level: value })
await api.put(`/devices/${id}`, {
device_attributes: {
...(attr || {}),
serialLogLevel: field === 'serial' ? value : serialLevel,
sdLogLevel: field === 'sd' ? value : sdLevel,
mqttLogLevel: field === 'mqtt' ? value : mqttLevel,
}
device_attributes: { [LOG_ATTR[field]]: value },
})
toast.success('Saved', 'Log levels updated.')
} catch (err) {
toast.danger('Error', err.message || 'Failed to save log levels.')
} catch {
// sendMqttCommand's toast already reported the failure — revert the slider.
logSetters[field](previous)
}
}, [id, attr, serialLevel, sdLevel, mqttLevel, canEdit, toast])
}, [id, serialLevel, sdLevel, mqttLevel, canEdit, sendMqttCommand, logSetters])
// ── Network fields ───────────────────────────────────────────────────────────
// ── Network fields ─────────────────────────────────────────────────────────
// Populated live from network.info — read-only, reported directly by the device.
const netFields = [
{ label: 'Hostname', value: net.hostname || '—' },
{ label: 'IP Address', value: staticIpAddress || '—' },
{ label: 'Gateway', value: net.gateway || '—' },
{ label: 'DNS', value: net.dns || '—' },
{ label: 'Subnet', value: net.subnet || '—' },
{ label: 'MAC Address', value: net.mac || net.macAddress || '—' },
{ label: 'Hostname', value: networkInfo?.hostname || '—' },
{ label: 'IP Address', value: networkInfo?.ip || '—' },
{ label: 'Gateway', value: networkInfo?.gateway || '—' },
{ label: 'DNS', value: networkInfo?.dns || '—' },
{ label: 'Subnet', value: networkInfo?.subnet || '—' },
{ label: 'MAC Address', value: networkInfo?.mac || '—' },
{ label: 'SSID', value: networkInfo?.ssid || '—' },
{ label: 'Connection', value: networkInfo?.connection_type || '—' },
]
// ── Render ──────────────────────────────────────────────────────────────────
@@ -1013,9 +1072,6 @@ export default function GeneralTab({
<GlassCard
title="Mechanisms"
fullHeight
titleAction={canEdit && (
<EditActionButton onClick={onEditAttributes} />
)}
>
<div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-4)', flex: 1 }}>
@@ -1058,9 +1114,6 @@ export default function GeneralTab({
<GlassCard
title="Log Settings"
fullHeight
titleAction={canEdit && (
<EditActionButton onClick={onEditLogging} />
)}
>
<div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-6)', flex: 1, justifyContent: 'center' }}>
<LogSlider
@@ -1091,9 +1144,6 @@ export default function GeneralTab({
<GlassCard
title="Network Info"
fullHeight
titleAction={canEdit && (
<EditActionButton onClick={onEditAttributes} />
)}
>
<div style={{
display: 'grid',