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>
This commit is contained in:
@@ -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
@@ -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)
|
||||||
|
|||||||
@@ -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])
|
||||||
|
|
||||||
|
|||||||
@@ -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,7 +2,7 @@
|
|||||||
// 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 } 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'
|
||||||
@@ -271,9 +271,7 @@ export default function BellsTab({
|
|||||||
attr,
|
attr,
|
||||||
canEdit,
|
canEdit,
|
||||||
loadDevice,
|
loadDevice,
|
||||||
reloadDeviceSilent,
|
|
||||||
sendMqttCommand,
|
sendMqttCommand,
|
||||||
sendMqttCommandSilent,
|
|
||||||
onEditBellOutputs,
|
onEditBellOutputs,
|
||||||
}) {
|
}) {
|
||||||
const [togglingCommander, setTogglingCommander] = useState(false)
|
const [togglingCommander, setTogglingCommander] = useState(false)
|
||||||
@@ -281,75 +279,15 @@ export default function BellsTab({
|
|||||||
const [liveCounters] = useState(null)
|
const [liveCounters] = useState(null)
|
||||||
const [confirmDisable, setConfirmDisable] = useState(false)
|
const [confirmDisable, setConfirmDisable] = 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, after the device
|
||||||
|
// confirms the change.
|
||||||
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 ──
|
|
||||||
// Fires at most once per mount (hasSyncedRef guard — belt-and-suspenders
|
|
||||||
// against StrictMode's double-invoke or any parent re-render retriggering
|
|
||||||
// this effect). Reconciles bells_enabled/durations/outputs against Firestore
|
|
||||||
// and silently corrects any drift — no toast, this is a quiet sync.
|
|
||||||
const hasSyncedRef = useRef(false)
|
|
||||||
useEffect(() => {
|
|
||||||
if (!sendMqttCommandSilent || !device) return
|
|
||||||
if (hasSyncedRef.current) return
|
|
||||||
hasSyncedRef.current = true
|
|
||||||
const deviceId = device.id || device.device_id
|
|
||||||
|
|
||||||
sendMqttCommandSilent('bells.get_config').then((reply) => {
|
|
||||||
const data = reply?.data || {}
|
|
||||||
const durations = data.durations || {}
|
|
||||||
const outputs = data.outputs || {}
|
|
||||||
const channelCount = Math.max(
|
|
||||||
Object.keys(durations).length,
|
|
||||||
Object.keys(outputs).length,
|
|
||||||
totalBells,
|
|
||||||
)
|
|
||||||
if (channelCount === 0) return
|
|
||||||
|
|
||||||
// Firmware uses both 0 and 65535 (uint16 "unset") as "no output assigned" —
|
|
||||||
// treat both as disabled so unconfigured channels are never mistaken for
|
|
||||||
// connected bells.
|
|
||||||
const isDisabledOutput = (o) => !o || o === 65535
|
|
||||||
|
|
||||||
// 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
|
|
||||||
}, [device?.id, device?.device_id])
|
|
||||||
|
|
||||||
// Request strike counters via MQTT
|
// Request strike counters via MQTT
|
||||||
const requestStrikeCounters = useCallback(async () => {
|
const requestStrikeCounters = useCallback(async () => {
|
||||||
if (!sendMqttCommand) return
|
if (!sendMqttCommand) return
|
||||||
|
|||||||
@@ -300,7 +300,6 @@ export default function ClockTab({
|
|||||||
sendMqttCommand,
|
sendMqttCommand,
|
||||||
sendMqttCommandSilent,
|
sendMqttCommandSilent,
|
||||||
loadDevice,
|
loadDevice,
|
||||||
reloadDeviceSilent,
|
|
||||||
}) {
|
}) {
|
||||||
const { toast } = useToast()
|
const { toast } = useToast()
|
||||||
const [now, setNow] = useState(new Date())
|
const [now, setNow] = useState(new Date())
|
||||||
@@ -320,94 +319,15 @@ 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])
|
||||||
|
|
||||||
|
|||||||
@@ -856,7 +856,6 @@ export default function GeneralTab({
|
|||||||
onEditAttributes,
|
onEditAttributes,
|
||||||
sendMqttCommand,
|
sendMqttCommand,
|
||||||
sendMqttCommandSilent,
|
sendMqttCommandSilent,
|
||||||
reloadDeviceSilent,
|
|
||||||
}) {
|
}) {
|
||||||
const { toast } = useToast()
|
const { toast } = useToast()
|
||||||
const [locationName, setLocationName] = useState(null)
|
const [locationName, setLocationName] = useState(null)
|
||||||
@@ -879,11 +878,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 +889,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)
|
||||||
|
|||||||
Reference in New Issue
Block a user