{enabled ? 'Armed' : 'Disarmed'}
)
}
// ─── Log Slider ───────────────────────────────────────────────────────────────
function LogSlider({ label, level, onChange, canEdit, color }) {
const meta = getLogLevelMeta(level)
const safeLevel = Number.isFinite(level) ? Number(level) : 0
// Build CSS gradient for the track — filled up to thumb position
const pct = (safeLevel / (LOG_LEVELS.length - 1)) * 100
const trackBg = `linear-gradient(90deg, ${color} 0%, ${color} ${pct}%, rgba(28,32,38,0.70) ${pct}%, rgba(28,32,38,0.70) 100%)`
return (
{label}
{meta ? meta.label : '—'}
onChange(Number(e.target.value)) : undefined}
style={{
background: trackBg,
opacity: canEdit ? 1 : 0.6,
// thumb color via CSS custom property on inline style — works in Safari
'--thumb-color': color,
}}
/>
{/* tick marks — padding-inline of 7px (half thumb width) aligns ticks with thumb centre */}
)
}
// ─── GeneralTab ───────────────────────────────────────────────────────────────
export default function GeneralTab({
device,
canEdit,
attr,
tags,
setTags,
onEditLocation,
onEditAttributes,
sendMqttCommand,
sendMqttCommandSilent,
reloadDeviceSilent,
}) {
const { toast } = useToast()
const [locationName, setLocationName] = useState(null)
const [savingTags, setSavingTags] = useState(false)
// Logging level state — local editable copies for sliders
const [serialLevel, setSerialLevel] = useState(attr?.serialLogLevel ?? 0)
const [sdLevel, setSdLevel] = useState(attr?.sdLogLevel ?? 0)
const [mqttLevel, setMqttLevel] = useState(attr?.mqttLogLevel ?? 0)
const id = device?.id || device?.device_id
// Inject CSS keyframes + slider styles
useEffect(() => { ensureKeyframes() }, [])
// Keep slider state in sync if attr changes
useEffect(() => {
if (Number.isFinite(attr?.serialLogLevel)) setSerialLevel(attr.serialLogLevel)
if (Number.isFinite(attr?.sdLogLevel)) setSdLevel(attr.sdLogLevel)
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)
const [firmwareStatus, setFirmwareStatus] = 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.
})
sendMqttCommandSilent('firmware.status').then((reply) => {
setFirmwareStatus(reply?.data || null)
}).catch(() => {
// Device offline or didn't reply — Firmware 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])
useEffect(() => {
if (!coords) return
setLocationName(null)
fetch(`https://nominatim.openstreetmap.org/reverse?lat=${coords.lat}&lon=${coords.lng}&format=json`)
.then(r => r.json())
.then(data => setLocationName(getNearestPlaceLabel(data) || null))
.catch(() => setLocationName(null))
}, [coords])
// ── Tag handlers ────────────────────────────────────────────────────────────
const handleAddTag = useCallback(async (tag) => {
const trimmed = tag.trim()
if (!trimmed || tags.includes(trimmed)) return
const next = [...tags, trimmed]
setSavingTags(true)
try {
await api.put(`/devices/${id}/tags`, { tags: next })
setTags(next)
} catch (err) {
toast.danger('Error', err.message || 'Failed to add tag.')
} finally {
setSavingTags(false)
}
}, [id, tags, setTags, toast])
const handleRemoveTag = useCallback(async (tag) => {
const next = tags.filter(t => t !== tag)
setSavingTags(true)
try {
await api.put(`/devices/${id}/tags`, { tags: next })
setTags(next)
} catch (err) {
toast.danger('Error', err.message || 'Failed to remove tag.')
} finally {
setSavingTags(false)
}
}, [id, tags, setTags, toast])
// ── 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 || !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: { [LOG_ATTR[field]]: value },
})
} catch {
// sendMqttCommand's toast already reported the failure — revert the slider.
logSetters[field](previous)
}
}, [id, serialLevel, sdLevel, mqttLevel, canEdit, sendMqttCommand, logSetters])
// ── Network fields ─────────────────────────────────────────────────────────
// Populated live from network.info — read-only, reported directly by the device.
const netFields = [
{ 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 ──────────────────────────────────────────────────────────────────
return (
{/* ════════════════════════════════════════════════════════════════════
ROW 0 — Firmware (full width, short)
════════════════════════════════════════════════════════════════════ */}
{(() => {
// The firmware reports the literal string "Unknown" (not null/absent) for
// backup_version when no second OTA slot has ever been flashed — guard
// against that sentinel so it doesn't render as "vUnknown".
const backupKnown = firmwareStatus?.backup_version && firmwareStatus.backup_version !== 'Unknown'
const items = [
{
label: 'Version',
content: (