Compare commits
6
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
db22abdb7d | ||
|
|
eff9e72681 | ||
|
|
565aca4d56 | ||
|
|
3636556ae7 | ||
|
|
fb35ace0c7 | ||
|
|
da83f2a1cd |
@@ -12,6 +12,8 @@ from database.pg_mqtt import (
|
|||||||
get_heartbeats,
|
get_heartbeats,
|
||||||
get_commands,
|
get_commands,
|
||||||
get_latest_heartbeats,
|
get_latest_heartbeats,
|
||||||
|
get_latest_heartbeat,
|
||||||
|
warm_latest_cache,
|
||||||
get_pending_command,
|
get_pending_command,
|
||||||
upsert_alert,
|
upsert_alert,
|
||||||
delete_alert,
|
delete_alert,
|
||||||
@@ -35,6 +37,7 @@ from database.pg_mqtt import (
|
|||||||
insert_report,
|
insert_report,
|
||||||
get_reports,
|
get_reports,
|
||||||
delete_device_logs,
|
delete_device_logs,
|
||||||
|
delete_device_logs_filtered,
|
||||||
delete_device_heartbeats,
|
delete_device_heartbeats,
|
||||||
delete_device_commands,
|
delete_device_commands,
|
||||||
delete_device_alert_events,
|
delete_device_alert_events,
|
||||||
@@ -65,6 +68,8 @@ __all__ = [
|
|||||||
"get_heartbeats",
|
"get_heartbeats",
|
||||||
"get_commands",
|
"get_commands",
|
||||||
"get_latest_heartbeats",
|
"get_latest_heartbeats",
|
||||||
|
"get_latest_heartbeat",
|
||||||
|
"warm_latest_cache",
|
||||||
"get_pending_command",
|
"get_pending_command",
|
||||||
"upsert_alert",
|
"upsert_alert",
|
||||||
"delete_alert",
|
"delete_alert",
|
||||||
@@ -88,6 +93,7 @@ __all__ = [
|
|||||||
"insert_report",
|
"insert_report",
|
||||||
"get_reports",
|
"get_reports",
|
||||||
"delete_device_logs",
|
"delete_device_logs",
|
||||||
|
"delete_device_logs_filtered",
|
||||||
"delete_device_heartbeats",
|
"delete_device_heartbeats",
|
||||||
"delete_device_commands",
|
"delete_device_commands",
|
||||||
"delete_device_alert_events",
|
"delete_device_alert_events",
|
||||||
|
|||||||
@@ -0,0 +1,91 @@
|
|||||||
|
"""In-memory "latest row per device" cache for the fleet-wide status reads.
|
||||||
|
|
||||||
|
Why this exists
|
||||||
|
---------------
|
||||||
|
/mqtt/status (device list + device detail), /mqtt/latest-metrics and the
|
||||||
|
backend ping loop all need "the newest heartbeat / alert event / ping sample /
|
||||||
|
diagnostics report for every device". In Postgres that is a
|
||||||
|
`SELECT DISTINCT ON (device_serial) ... ORDER BY device_serial, ts DESC`,
|
||||||
|
which has to walk the entire history index — heartbeats alone grow by one row
|
||||||
|
per device every 30s and are kept for the full retention window, so each call
|
||||||
|
took seconds and the console showed empty status columns until it finished.
|
||||||
|
|
||||||
|
The MQTT ingest path already sees every new row as it is written, so instead
|
||||||
|
we keep the newest row per device in memory:
|
||||||
|
|
||||||
|
* seed() — one DISTINCT ON query per kind, run once at startup (and lazily
|
||||||
|
on first read if startup warming hasn't finished yet).
|
||||||
|
* put() — called by every insert, keeps whichever row is newer, so rows
|
||||||
|
written while the seed query is still running are never lost.
|
||||||
|
* drop_device() / drop_older_than() — mirror per-device deletes (Reset
|
||||||
|
Stats, Delete Logs) and the retention purge so the cache never
|
||||||
|
shows a row the database no longer has.
|
||||||
|
|
||||||
|
Single process only: the backend runs one uvicorn worker that also owns the
|
||||||
|
MQTT client (see main.py startup), so there is no cross-process staleness.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
|
||||||
|
# kind -> timestamp column used to decide which row is newest
|
||||||
|
TS_FIELD = {
|
||||||
|
"heartbeat": "received_at",
|
||||||
|
"alert_event": "occurred_at",
|
||||||
|
"ping": "sampled_at",
|
||||||
|
"diag": "received_at",
|
||||||
|
}
|
||||||
|
|
||||||
|
_rows: dict[str, dict[str, dict]] = {kind: {} for kind in TS_FIELD}
|
||||||
|
_warm: dict[str, bool] = {kind: False for kind in TS_FIELD}
|
||||||
|
|
||||||
|
|
||||||
|
def _ts(kind: str, row: dict) -> datetime:
|
||||||
|
raw = row.get(TS_FIELD[kind])
|
||||||
|
if isinstance(raw, datetime):
|
||||||
|
return raw if raw.tzinfo else raw.replace(tzinfo=timezone.utc)
|
||||||
|
try:
|
||||||
|
parsed = datetime.fromisoformat(raw)
|
||||||
|
return parsed if parsed.tzinfo else parsed.replace(tzinfo=timezone.utc)
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
return datetime.min.replace(tzinfo=timezone.utc)
|
||||||
|
|
||||||
|
|
||||||
|
def put(kind: str, row: dict) -> None:
|
||||||
|
"""Record a row if it is the newest one seen for its device."""
|
||||||
|
serial = row.get("device_serial")
|
||||||
|
if not serial:
|
||||||
|
return
|
||||||
|
current = _rows[kind].get(serial)
|
||||||
|
if current is None or _ts(kind, row) >= _ts(kind, current):
|
||||||
|
_rows[kind][serial] = row
|
||||||
|
|
||||||
|
|
||||||
|
def seed(kind: str, rows: list[dict]) -> None:
|
||||||
|
for row in rows:
|
||||||
|
put(kind, row)
|
||||||
|
_warm[kind] = True
|
||||||
|
|
||||||
|
|
||||||
|
def is_warm(kind: str) -> bool:
|
||||||
|
return _warm[kind]
|
||||||
|
|
||||||
|
|
||||||
|
def snapshot(kind: str) -> list[dict] | None:
|
||||||
|
"""All cached rows for a kind, or None if the cache isn't seeded yet."""
|
||||||
|
if not _warm[kind]:
|
||||||
|
return None
|
||||||
|
return list(_rows[kind].values())
|
||||||
|
|
||||||
|
|
||||||
|
def get(kind: str, serial: str) -> dict | None:
|
||||||
|
return _rows[kind].get(serial)
|
||||||
|
|
||||||
|
|
||||||
|
def drop_device(kind: str, serial: str) -> None:
|
||||||
|
_rows[kind].pop(serial, None)
|
||||||
|
|
||||||
|
|
||||||
|
def drop_older_than(kind: str, cutoff: datetime) -> None:
|
||||||
|
stale = [s for s, row in _rows[kind].items() if _ts(kind, row) < cutoff]
|
||||||
|
for serial in stale:
|
||||||
|
del _rows[kind][serial]
|
||||||
+133
-47
@@ -17,9 +17,24 @@ from datetime import date, datetime, timedelta, timezone
|
|||||||
from sqlalchemy import text
|
from sqlalchemy import text
|
||||||
from config import settings
|
from config import settings
|
||||||
from database.postgres import AsyncSessionLocal
|
from database.postgres import AsyncSessionLocal
|
||||||
|
from database import latest_cache
|
||||||
|
|
||||||
logger = logging.getLogger("database.pg_mqtt")
|
logger = logging.getLogger("database.pg_mqtt")
|
||||||
|
|
||||||
|
# Column lists shared by the fleet-wide "latest per device" reads and the
|
||||||
|
# RETURNING clause of the matching insert, so a freshly written row lands in
|
||||||
|
# latest_cache with exactly the shape the DISTINCT ON query would return.
|
||||||
|
_HEARTBEAT_COLS = """id, device_serial, device_id, firmware_version, ip_address,
|
||||||
|
gateway, uptime_ms, uptime_display, rssi, free_heap, state, ok,
|
||||||
|
received_at AT TIME ZONE 'UTC' AS received_at"""
|
||||||
|
_ALERT_EVENT_COLS = """id, device_serial, subsystem, state, message,
|
||||||
|
occurred_at AT TIME ZONE 'UTC' AS occurred_at"""
|
||||||
|
_PING_COLS = """id, device_serial, rtt_ms,
|
||||||
|
sampled_at AT TIME ZONE 'UTC' AS sampled_at"""
|
||||||
|
_DIAG_LATEST_COLS = """id, device_serial,
|
||||||
|
cpu_temp_avg, cpu_temp_min, cpu_temp_max, cpu_temp_samples,
|
||||||
|
received_at AT TIME ZONE 'UTC' AS received_at"""
|
||||||
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------------------
|
# ---------------------------------------------------------------------------
|
||||||
# Insert operations
|
# Insert operations
|
||||||
@@ -54,8 +69,7 @@ async def insert_heartbeat(device_serial: str, device_id: str,
|
|||||||
gateway, uptime_ms, uptime_display, rssi, free_heap, state, ok, received_at)
|
gateway, uptime_ms, uptime_display, rssi, free_heap, state, ok, received_at)
|
||||||
VALUES
|
VALUES
|
||||||
(:serial, :device_id, :fw, :ip, :gw, :uptime_ms, :uptime_display, :rssi, :free_heap, :state, :ok, now())
|
(:serial, :device_id, :fw, :ip, :gw, :uptime_ms, :uptime_display, :rssi, :free_heap, :state, :ok, now())
|
||||||
RETURNING id
|
RETURNING """ + _HEARTBEAT_COLS),
|
||||||
"""),
|
|
||||||
{
|
{
|
||||||
"serial": device_serial,
|
"serial": device_serial,
|
||||||
"device_id": device_id,
|
"device_id": device_id,
|
||||||
@@ -70,9 +84,10 @@ async def insert_heartbeat(device_serial: str, device_id: str,
|
|||||||
"ok": ok,
|
"ok": ok,
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
row = result.fetchone()
|
row = result.mappings().fetchone()
|
||||||
await session.commit()
|
await session.commit()
|
||||||
return row[0]
|
latest_cache.put("heartbeat", _row_to_dict(row))
|
||||||
|
return row["id"]
|
||||||
|
|
||||||
|
|
||||||
async def insert_command(device_serial: str, command_name: str,
|
async def insert_command(device_serial: str, command_name: str,
|
||||||
@@ -259,20 +274,41 @@ async def get_commands(device_serial: str, limit: int = 100,
|
|||||||
|
|
||||||
|
|
||||||
async def get_latest_heartbeats() -> list:
|
async def get_latest_heartbeats() -> list:
|
||||||
|
"""Newest heartbeat per device — served from latest_cache once seeded."""
|
||||||
|
cached = latest_cache.snapshot("heartbeat")
|
||||||
|
if cached is not None:
|
||||||
|
return cached
|
||||||
async with AsyncSessionLocal() as session:
|
async with AsyncSessionLocal() as session:
|
||||||
rows_result = await session.execute(
|
rows_result = await session.execute(
|
||||||
text("""
|
text(f"""
|
||||||
SELECT DISTINCT ON (device_serial)
|
SELECT DISTINCT ON (device_serial) {_HEARTBEAT_COLS}
|
||||||
id, device_serial, device_id, firmware_version, ip_address,
|
|
||||||
gateway, uptime_ms, uptime_display, rssi, free_heap, state, ok,
|
|
||||||
received_at AT TIME ZONE 'UTC' AS received_at
|
|
||||||
FROM heartbeats
|
FROM heartbeats
|
||||||
ORDER BY device_serial, received_at DESC
|
ORDER BY device_serial, received_at DESC
|
||||||
""")
|
""")
|
||||||
)
|
)
|
||||||
rows = rows_result.mappings().all()
|
rows = [_row_to_dict(r) for r in rows_result.mappings().all()]
|
||||||
|
latest_cache.seed("heartbeat", rows)
|
||||||
|
return latest_cache.snapshot("heartbeat")
|
||||||
|
|
||||||
return [_row_to_dict(r) for r in rows]
|
|
||||||
|
async def get_latest_heartbeat(device_serial: str) -> dict | None:
|
||||||
|
"""Newest heartbeat for one device. Cache first; otherwise a single
|
||||||
|
indexed lookup (idx_heartbeats_serial_time), never the fleet-wide scan."""
|
||||||
|
if latest_cache.is_warm("heartbeat"):
|
||||||
|
return latest_cache.get("heartbeat", device_serial)
|
||||||
|
async with AsyncSessionLocal() as session:
|
||||||
|
result = await session.execute(
|
||||||
|
text(f"""
|
||||||
|
SELECT {_HEARTBEAT_COLS}
|
||||||
|
FROM heartbeats
|
||||||
|
WHERE device_serial = :serial
|
||||||
|
ORDER BY received_at DESC
|
||||||
|
LIMIT 1
|
||||||
|
"""),
|
||||||
|
{"serial": device_serial},
|
||||||
|
)
|
||||||
|
row = result.mappings().fetchone()
|
||||||
|
return _row_to_dict(row) if row else None
|
||||||
|
|
||||||
|
|
||||||
async def get_pending_command(device_serial: str) -> dict | None:
|
async def get_pending_command(device_serial: str) -> dict | None:
|
||||||
@@ -361,31 +397,35 @@ async def get_alerts(device_serial: str) -> list:
|
|||||||
async def insert_alert_event(device_serial: str, subsystem: str, state: str,
|
async def insert_alert_event(device_serial: str, subsystem: str, state: str,
|
||||||
message: str | None = None):
|
message: str | None = None):
|
||||||
async with AsyncSessionLocal() as session:
|
async with AsyncSessionLocal() as session:
|
||||||
await session.execute(
|
result = await session.execute(
|
||||||
text("""
|
text("""
|
||||||
INSERT INTO device_alert_events (device_serial, subsystem, state, message, occurred_at)
|
INSERT INTO device_alert_events (device_serial, subsystem, state, message, occurred_at)
|
||||||
VALUES (:serial, :subsystem, :state, :message, now())
|
VALUES (:serial, :subsystem, :state, :message, now())
|
||||||
"""),
|
RETURNING """ + _ALERT_EVENT_COLS),
|
||||||
{"serial": device_serial, "subsystem": subsystem, "state": state, "message": message},
|
{"serial": device_serial, "subsystem": subsystem, "state": state, "message": message},
|
||||||
)
|
)
|
||||||
|
row = result.mappings().fetchone()
|
||||||
await session.commit()
|
await session.commit()
|
||||||
|
latest_cache.put("alert_event", _row_to_dict(row))
|
||||||
|
|
||||||
|
|
||||||
async def get_latest_alert_events() -> list:
|
async def get_latest_alert_events() -> list:
|
||||||
"""Most recent alert event per device, across all devices — one row each."""
|
"""Most recent alert event per device, across all devices — one row each.
|
||||||
|
Served from latest_cache once seeded."""
|
||||||
|
cached = latest_cache.snapshot("alert_event")
|
||||||
|
if cached is not None:
|
||||||
|
return cached
|
||||||
async with AsyncSessionLocal() as session:
|
async with AsyncSessionLocal() as session:
|
||||||
result = await session.execute(
|
result = await session.execute(
|
||||||
text("""
|
text(f"""
|
||||||
SELECT DISTINCT ON (device_serial)
|
SELECT DISTINCT ON (device_serial) {_ALERT_EVENT_COLS}
|
||||||
id, device_serial, subsystem, state, message,
|
|
||||||
occurred_at AT TIME ZONE 'UTC' AS occurred_at
|
|
||||||
FROM device_alert_events
|
FROM device_alert_events
|
||||||
ORDER BY device_serial, occurred_at DESC
|
ORDER BY device_serial, occurred_at DESC
|
||||||
""")
|
""")
|
||||||
)
|
)
|
||||||
rows = result.mappings().all()
|
rows = [_row_to_dict(r) for r in result.mappings().all()]
|
||||||
|
latest_cache.seed("alert_event", rows)
|
||||||
return [_row_to_dict(r) for r in rows]
|
return latest_cache.snapshot("alert_event")
|
||||||
|
|
||||||
|
|
||||||
async def get_alert_events(device_serial: str, limit: int = 100,
|
async def get_alert_events(device_serial: str, limit: int = 100,
|
||||||
@@ -415,6 +455,8 @@ async def get_alert_events(device_serial: str, limit: int = 100,
|
|||||||
|
|
||||||
|
|
||||||
async def get_latest_alert_event(device_serial: str) -> dict | None:
|
async def get_latest_alert_event(device_serial: str) -> dict | None:
|
||||||
|
if latest_cache.is_warm("alert_event"):
|
||||||
|
return latest_cache.get("alert_event", device_serial)
|
||||||
async with AsyncSessionLocal() as session:
|
async with AsyncSessionLocal() as session:
|
||||||
result = await session.execute(
|
result = await session.execute(
|
||||||
text("""
|
text("""
|
||||||
@@ -718,13 +760,13 @@ async def insert_ping_sample(device_serial: str, rtt_ms: int) -> int:
|
|||||||
text("""
|
text("""
|
||||||
INSERT INTO device_ping_samples (device_serial, rtt_ms, sampled_at)
|
INSERT INTO device_ping_samples (device_serial, rtt_ms, sampled_at)
|
||||||
VALUES (:serial, :rtt_ms, now())
|
VALUES (:serial, :rtt_ms, now())
|
||||||
RETURNING id
|
RETURNING """ + _PING_COLS),
|
||||||
"""),
|
|
||||||
{"serial": device_serial, "rtt_ms": rtt_ms},
|
{"serial": device_serial, "rtt_ms": rtt_ms},
|
||||||
)
|
)
|
||||||
row = result.fetchone()
|
row = result.mappings().fetchone()
|
||||||
await session.commit()
|
await session.commit()
|
||||||
return row[0]
|
latest_cache.put("ping", _row_to_dict(row))
|
||||||
|
return row["id"]
|
||||||
|
|
||||||
|
|
||||||
async def get_ping_samples(device_serial: str, limit: int = 200, offset: int = 0,
|
async def get_ping_samples(device_serial: str, limit: int = 200, offset: int = 0,
|
||||||
@@ -759,19 +801,20 @@ async def get_ping_samples(device_serial: str, limit: int = 200, offset: int = 0
|
|||||||
async def get_latest_ping_samples() -> list:
|
async def get_latest_ping_samples() -> list:
|
||||||
# Fleet-wide "last known" ping RTT for DeviceList — same DISTINCT ON
|
# Fleet-wide "last known" ping RTT for DeviceList — same DISTINCT ON
|
||||||
# pattern as get_latest_heartbeats(); devices with no RTC never appear.
|
# pattern as get_latest_heartbeats(); devices with no RTC never appear.
|
||||||
|
cached = latest_cache.snapshot("ping")
|
||||||
|
if cached is not None:
|
||||||
|
return cached
|
||||||
async with AsyncSessionLocal() as session:
|
async with AsyncSessionLocal() as session:
|
||||||
rows_result = await session.execute(
|
rows_result = await session.execute(
|
||||||
text("""
|
text(f"""
|
||||||
SELECT DISTINCT ON (device_serial)
|
SELECT DISTINCT ON (device_serial) {_PING_COLS}
|
||||||
id, device_serial, rtt_ms,
|
|
||||||
sampled_at AT TIME ZONE 'UTC' AS sampled_at
|
|
||||||
FROM device_ping_samples
|
FROM device_ping_samples
|
||||||
ORDER BY device_serial, sampled_at DESC
|
ORDER BY device_serial, sampled_at DESC
|
||||||
""")
|
""")
|
||||||
)
|
)
|
||||||
rows = rows_result.mappings().all()
|
rows = [_row_to_dict(r) for r in rows_result.mappings().all()]
|
||||||
|
latest_cache.seed("ping", rows)
|
||||||
return [_row_to_dict(r) for r in rows]
|
return latest_cache.snapshot("ping")
|
||||||
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------------------
|
# ---------------------------------------------------------------------------
|
||||||
@@ -817,8 +860,7 @@ async def insert_diagnostics_report(
|
|||||||
:ota_current_version, :ota_update_available, :ota_available_version,
|
:ota_current_version, :ota_update_available, :ota_available_version,
|
||||||
:ota_last_check_uptime_ms, :ota_last_error,
|
:ota_last_check_uptime_ms, :ota_last_error,
|
||||||
:stack_high_water, :bell_strikes, :bell_loads, :cooling_active, now())
|
:stack_high_water, :bell_strikes, :bell_loads, :cooling_active, now())
|
||||||
RETURNING id
|
RETURNING """ + _DIAG_LATEST_COLS),
|
||||||
"""),
|
|
||||||
{
|
{
|
||||||
"serial": device_serial,
|
"serial": device_serial,
|
||||||
"cpu_temp_avg": cpu_temp_avg,
|
"cpu_temp_avg": cpu_temp_avg,
|
||||||
@@ -839,9 +881,10 @@ async def insert_diagnostics_report(
|
|||||||
"cooling_active": cooling_active,
|
"cooling_active": cooling_active,
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
row = result.fetchone()
|
row = result.mappings().fetchone()
|
||||||
await session.commit()
|
await session.commit()
|
||||||
return row[0]
|
latest_cache.put("diag", _row_to_dict(row))
|
||||||
|
return row["id"]
|
||||||
|
|
||||||
|
|
||||||
async def get_diagnostics_reports(device_serial: str, limit: int = 200, offset: int = 0,
|
async def get_diagnostics_reports(device_serial: str, limit: int = 200, offset: int = 0,
|
||||||
@@ -904,20 +947,57 @@ async def get_latest_diagnostics_report(device_serial: str) -> dict | None:
|
|||||||
async def get_latest_diagnostics_reports() -> list:
|
async def get_latest_diagnostics_reports() -> list:
|
||||||
# Fleet-wide "last known" CPU temp for DeviceList — one DISTINCT ON query
|
# Fleet-wide "last known" CPU temp for DeviceList — one DISTINCT ON query
|
||||||
# instead of N per-device round trips, same pattern as get_latest_heartbeats().
|
# instead of N per-device round trips, same pattern as get_latest_heartbeats().
|
||||||
|
cached = latest_cache.snapshot("diag")
|
||||||
|
if cached is not None:
|
||||||
|
return cached
|
||||||
async with AsyncSessionLocal() as session:
|
async with AsyncSessionLocal() as session:
|
||||||
rows_result = await session.execute(
|
rows_result = await session.execute(
|
||||||
text("""
|
text(f"""
|
||||||
SELECT DISTINCT ON (device_serial)
|
SELECT DISTINCT ON (device_serial) {_DIAG_LATEST_COLS}
|
||||||
id, device_serial,
|
|
||||||
cpu_temp_avg, cpu_temp_min, cpu_temp_max, cpu_temp_samples,
|
|
||||||
received_at AT TIME ZONE 'UTC' AS received_at
|
|
||||||
FROM device_diagnostics_reports
|
FROM device_diagnostics_reports
|
||||||
ORDER BY device_serial, received_at DESC
|
ORDER BY device_serial, received_at DESC
|
||||||
""")
|
""")
|
||||||
)
|
)
|
||||||
rows = rows_result.mappings().all()
|
rows = [_row_to_dict(r) for r in rows_result.mappings().all()]
|
||||||
|
latest_cache.seed("diag", rows)
|
||||||
|
return latest_cache.snapshot("diag")
|
||||||
|
|
||||||
return [_row_to_dict(r) for r in rows]
|
|
||||||
|
async def warm_latest_cache() -> None:
|
||||||
|
"""Seed latest_cache at startup so the first /mqtt/status after a restart
|
||||||
|
is already instant. Each kind is independent — one failing (e.g. a table
|
||||||
|
missing on a fresh DB) doesn't stop the others; that kind just seeds
|
||||||
|
lazily on its first read instead."""
|
||||||
|
for loader in (get_latest_heartbeats, get_latest_alert_events,
|
||||||
|
get_latest_ping_samples, get_latest_diagnostics_reports):
|
||||||
|
try:
|
||||||
|
await loader()
|
||||||
|
except Exception as e:
|
||||||
|
logger.warning(f"latest_cache warm-up: {loader.__name__} failed: {e}")
|
||||||
|
|
||||||
|
|
||||||
|
async def delete_device_logs_filtered(device_serial: str,
|
||||||
|
sources: list[str] | None = None,
|
||||||
|
levels: list[str] | None = None,
|
||||||
|
until: datetime | None = None) -> int:
|
||||||
|
"""Delete one device's console-stored log rows, optionally narrowed to
|
||||||
|
some sources (log / info), some levels (INFO / WARN / ERROR) and rows at
|
||||||
|
or before `until`. No filters = every log row for the device."""
|
||||||
|
where = "device_serial = :serial"
|
||||||
|
params: dict = {"serial": device_serial}
|
||||||
|
if sources:
|
||||||
|
where += " AND source = ANY(:sources)"
|
||||||
|
params["sources"] = list(sources)
|
||||||
|
if levels:
|
||||||
|
where += " AND level = ANY(:levels)"
|
||||||
|
params["levels"] = list(levels)
|
||||||
|
if until is not None:
|
||||||
|
where += " AND received_at <= :until"
|
||||||
|
params["until"] = until
|
||||||
|
async with AsyncSessionLocal() as session:
|
||||||
|
result = await session.execute(text(f"DELETE FROM device_logs WHERE {where}"), params)
|
||||||
|
await session.commit()
|
||||||
|
return result.rowcount
|
||||||
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------------------
|
# ---------------------------------------------------------------------------
|
||||||
@@ -947,7 +1027,8 @@ async def delete_device_heartbeats(device_serial: str) -> int:
|
|||||||
{"serial": device_serial},
|
{"serial": device_serial},
|
||||||
)
|
)
|
||||||
await session.commit()
|
await session.commit()
|
||||||
return result.rowcount
|
latest_cache.drop_device("heartbeat", device_serial)
|
||||||
|
return result.rowcount
|
||||||
|
|
||||||
|
|
||||||
async def delete_device_commands(device_serial: str) -> int:
|
async def delete_device_commands(device_serial: str) -> int:
|
||||||
@@ -967,7 +1048,8 @@ async def delete_device_alert_events(device_serial: str) -> int:
|
|||||||
{"serial": device_serial},
|
{"serial": device_serial},
|
||||||
)
|
)
|
||||||
await session.commit()
|
await session.commit()
|
||||||
return result.rowcount
|
latest_cache.drop_device("alert_event", device_serial)
|
||||||
|
return result.rowcount
|
||||||
|
|
||||||
|
|
||||||
async def delete_device_current_alerts(device_serial: str) -> int:
|
async def delete_device_current_alerts(device_serial: str) -> int:
|
||||||
@@ -1000,7 +1082,8 @@ async def delete_device_ping_samples(device_serial: str) -> int:
|
|||||||
{"serial": device_serial},
|
{"serial": device_serial},
|
||||||
)
|
)
|
||||||
await session.commit()
|
await session.commit()
|
||||||
return result.rowcount
|
latest_cache.drop_device("ping", device_serial)
|
||||||
|
return result.rowcount
|
||||||
|
|
||||||
|
|
||||||
async def delete_device_diagnostics_reports(device_serial: str) -> int:
|
async def delete_device_diagnostics_reports(device_serial: str) -> int:
|
||||||
@@ -1010,7 +1093,8 @@ async def delete_device_diagnostics_reports(device_serial: str) -> int:
|
|||||||
{"serial": device_serial},
|
{"serial": device_serial},
|
||||||
)
|
)
|
||||||
await session.commit()
|
await session.commit()
|
||||||
return result.rowcount
|
latest_cache.drop_device("diag", device_serial)
|
||||||
|
return result.rowcount
|
||||||
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------------------
|
# ---------------------------------------------------------------------------
|
||||||
@@ -1190,6 +1274,8 @@ async def purge_old_data(retention_days: int | None = None):
|
|||||||
{"cutoff": cutoff},
|
{"cutoff": cutoff},
|
||||||
)
|
)
|
||||||
await session.commit()
|
await session.commit()
|
||||||
|
for kind in ("heartbeat", "ping", "diag"):
|
||||||
|
latest_cache.drop_older_than(kind, cutoff)
|
||||||
logger.info(f"Purged heartbeats, commands, ping samples, diagnostics reports, and device reports older than {days} days")
|
logger.info(f"Purged heartbeats, commands, ping samples, diagnostics reports, and device reports older than {days} days")
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
+13
-13
@@ -27,7 +27,7 @@ CRM_COLLECTION = "crm_customers"
|
|||||||
|
|
||||||
|
|
||||||
@router.get("", response_model=DeviceListResponse)
|
@router.get("", response_model=DeviceListResponse)
|
||||||
async def list_devices(
|
def list_devices(
|
||||||
search: Optional[str] = Query(None),
|
search: Optional[str] = Query(None),
|
||||||
online: Optional[bool] = Query(None),
|
online: Optional[bool] = Query(None),
|
||||||
tier: Optional[str] = Query(None),
|
tier: Optional[str] = Query(None),
|
||||||
@@ -42,7 +42,7 @@ async def list_devices(
|
|||||||
|
|
||||||
|
|
||||||
@router.get("/{device_id}", response_model=DeviceInDB)
|
@router.get("/{device_id}", response_model=DeviceInDB)
|
||||||
async def get_device(
|
def get_device(
|
||||||
device_id: str,
|
device_id: str,
|
||||||
_user: TokenPayload = Depends(require_permission("devices", "view")),
|
_user: TokenPayload = Depends(require_permission("devices", "view")),
|
||||||
):
|
):
|
||||||
@@ -50,7 +50,7 @@ async def get_device(
|
|||||||
|
|
||||||
|
|
||||||
@router.get("/{device_id}/users", response_model=DeviceUsersResponse)
|
@router.get("/{device_id}/users", response_model=DeviceUsersResponse)
|
||||||
async def get_device_users(
|
def get_device_users(
|
||||||
device_id: str,
|
device_id: str,
|
||||||
_user: TokenPayload = Depends(require_permission("devices", "view")),
|
_user: TokenPayload = Depends(require_permission("devices", "view")),
|
||||||
):
|
):
|
||||||
@@ -119,7 +119,7 @@ async def get_device_alerts(
|
|||||||
# ─────────────────────────────────────────────────────────────────────────────
|
# ─────────────────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
@router.get("/{device_id}/notes")
|
@router.get("/{device_id}/notes")
|
||||||
async def list_device_notes(
|
def list_device_notes(
|
||||||
device_id: str,
|
device_id: str,
|
||||||
_user: TokenPayload = Depends(require_permission("devices", "view")),
|
_user: TokenPayload = Depends(require_permission("devices", "view")),
|
||||||
):
|
):
|
||||||
@@ -139,7 +139,7 @@ async def list_device_notes(
|
|||||||
|
|
||||||
|
|
||||||
@router.post("/{device_id}/notes", status_code=201)
|
@router.post("/{device_id}/notes", status_code=201)
|
||||||
async def create_device_note(
|
def create_device_note(
|
||||||
device_id: str,
|
device_id: str,
|
||||||
body: DeviceNoteCreate,
|
body: DeviceNoteCreate,
|
||||||
_user: TokenPayload = Depends(require_permission("devices", "edit")),
|
_user: TokenPayload = Depends(require_permission("devices", "edit")),
|
||||||
@@ -163,7 +163,7 @@ async def create_device_note(
|
|||||||
|
|
||||||
|
|
||||||
@router.put("/{device_id}/notes/{note_id}")
|
@router.put("/{device_id}/notes/{note_id}")
|
||||||
async def update_device_note(
|
def update_device_note(
|
||||||
device_id: str,
|
device_id: str,
|
||||||
note_id: str,
|
note_id: str,
|
||||||
body: DeviceNoteUpdate,
|
body: DeviceNoteUpdate,
|
||||||
@@ -187,7 +187,7 @@ async def update_device_note(
|
|||||||
|
|
||||||
|
|
||||||
@router.delete("/{device_id}/notes/{note_id}", status_code=204)
|
@router.delete("/{device_id}/notes/{note_id}", status_code=204)
|
||||||
async def delete_device_note(
|
def delete_device_note(
|
||||||
device_id: str,
|
device_id: str,
|
||||||
note_id: str,
|
note_id: str,
|
||||||
_user: TokenPayload = Depends(require_permission("devices", "edit")),
|
_user: TokenPayload = Depends(require_permission("devices", "edit")),
|
||||||
@@ -210,7 +210,7 @@ class TagsUpdate(BaseModel):
|
|||||||
|
|
||||||
|
|
||||||
@router.put("/{device_id}/tags", response_model=DeviceInDB)
|
@router.put("/{device_id}/tags", response_model=DeviceInDB)
|
||||||
async def update_device_tags(
|
def update_device_tags(
|
||||||
device_id: str,
|
device_id: str,
|
||||||
body: TagsUpdate,
|
body: TagsUpdate,
|
||||||
_user: TokenPayload = Depends(require_permission("devices", "edit")),
|
_user: TokenPayload = Depends(require_permission("devices", "edit")),
|
||||||
@@ -236,7 +236,7 @@ class AssignCustomerBody(BaseModel):
|
|||||||
|
|
||||||
|
|
||||||
@router.get("/{device_id}/customer-search")
|
@router.get("/{device_id}/customer-search")
|
||||||
async def search_customers_for_device(
|
def search_customers_for_device(
|
||||||
device_id: str,
|
device_id: str,
|
||||||
q: str = Query(""),
|
q: str = Query(""),
|
||||||
_user: TokenPayload = Depends(require_permission("devices", "view")),
|
_user: TokenPayload = Depends(require_permission("devices", "view")),
|
||||||
@@ -357,7 +357,7 @@ async def unassign_device_from_customer(
|
|||||||
# ─────────────────────────────────────────────────────────────────────────────
|
# ─────────────────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
@router.get("/{device_id}/customer")
|
@router.get("/{device_id}/customer")
|
||||||
async def get_device_customer(
|
def get_device_customer(
|
||||||
device_id: str,
|
device_id: str,
|
||||||
_user: TokenPayload = Depends(require_permission("devices", "view")),
|
_user: TokenPayload = Depends(require_permission("devices", "view")),
|
||||||
):
|
):
|
||||||
@@ -399,7 +399,7 @@ class UserSearchResult(BaseModel):
|
|||||||
|
|
||||||
|
|
||||||
@router.get("/{device_id}/user-search")
|
@router.get("/{device_id}/user-search")
|
||||||
async def search_users_for_device(
|
def search_users_for_device(
|
||||||
device_id: str,
|
device_id: str,
|
||||||
q: str = Query(""),
|
q: str = Query(""),
|
||||||
_user: TokenPayload = Depends(require_permission("devices", "view")),
|
_user: TokenPayload = Depends(require_permission("devices", "view")),
|
||||||
@@ -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)
|
||||||
|
|||||||
@@ -116,6 +116,10 @@ async def startup():
|
|||||||
await sqlite_init_db()
|
await sqlite_init_db()
|
||||||
await melody_service.migrate_from_firestore()
|
await melody_service.migrate_from_firestore()
|
||||||
mqtt_manager.start(asyncio.get_event_loop())
|
mqtt_manager.start(asyncio.get_event_loop())
|
||||||
|
# Seed the in-memory latest-status cache in the background so the first
|
||||||
|
# device list / detail load after a restart doesn't pay for the slow
|
||||||
|
# fleet-wide DISTINCT ON scans (see database/latest_cache.py).
|
||||||
|
asyncio.create_task(db.warm_latest_cache())
|
||||||
asyncio.create_task(db.partition_manager_loop())
|
asyncio.create_task(db.partition_manager_loop())
|
||||||
asyncio.create_task(db.purge_loop())
|
asyncio.create_task(db.purge_loop())
|
||||||
asyncio.create_task(mqtt_manager.ping_loop())
|
asyncio.create_task(mqtt_manager.ping_loop())
|
||||||
|
|||||||
+63
-22
@@ -1,4 +1,5 @@
|
|||||||
from fastapi import APIRouter, Depends, Query, WebSocket, WebSocketDisconnect
|
from fastapi import APIRouter, Depends, HTTPException, Query, WebSocket, WebSocketDisconnect
|
||||||
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
from typing import Optional, List
|
from typing import Optional, List
|
||||||
from auth.models import TokenPayload
|
from auth.models import TokenPayload
|
||||||
from auth.dependencies import require_permission
|
from auth.dependencies import require_permission
|
||||||
@@ -15,45 +16,60 @@ from mqtt.crash_groups import group_crashes
|
|||||||
from mqtt.client import mqtt_manager
|
from mqtt.client import mqtt_manager
|
||||||
from mqtt import presence
|
from mqtt import presence
|
||||||
import database as db
|
import database as db
|
||||||
|
from database.postgres import get_pg_session
|
||||||
|
from shared.audit import log_action
|
||||||
from datetime import datetime, timezone
|
from datetime import datetime, timezone
|
||||||
|
|
||||||
router = APIRouter(prefix="/api/mqtt", tags=["mqtt"])
|
router = APIRouter(prefix="/api/mqtt", tags=["mqtt"])
|
||||||
|
|
||||||
|
|
||||||
|
def _device_status(hb: dict, alert_event: dict | None, now: datetime) -> DeviceMqttStatus:
|
||||||
|
try:
|
||||||
|
received = datetime.fromisoformat(hb["received_at"])
|
||||||
|
if received.tzinfo is None:
|
||||||
|
received = received.replace(tzinfo=timezone.utc)
|
||||||
|
seconds_ago = int((now - received).total_seconds())
|
||||||
|
except (ValueError, TypeError):
|
||||||
|
seconds_ago = 9999
|
||||||
|
return DeviceMqttStatus(
|
||||||
|
device_serial=hb["device_serial"],
|
||||||
|
online=seconds_ago < 90 and not presence.is_marked_offline(hb["device_serial"]),
|
||||||
|
last_heartbeat=HeartbeatEntry(**hb),
|
||||||
|
seconds_since_heartbeat=seconds_ago,
|
||||||
|
last_alert_event=AlertEventEntry(**alert_event) if alert_event else None,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
@router.get("/status", response_model=MqttStatusResponse)
|
@router.get("/status", response_model=MqttStatusResponse)
|
||||||
async def get_all_device_status(
|
async def get_all_device_status(
|
||||||
_user: TokenPayload = Depends(require_permission("mqtt", "view")),
|
_user: TokenPayload = Depends(require_permission("mqtt", "view")),
|
||||||
):
|
):
|
||||||
|
# Both reads come from database/latest_cache.py (kept current by the MQTT
|
||||||
|
# ingest), so this answers instantly instead of scanning history tables.
|
||||||
heartbeats = await db.get_latest_heartbeats()
|
heartbeats = await db.get_latest_heartbeats()
|
||||||
alert_events = await db.get_latest_alert_events()
|
alert_events = await db.get_latest_alert_events()
|
||||||
alert_by_serial = {a["device_serial"]: a for a in alert_events}
|
alert_by_serial = {a["device_serial"]: a for a in alert_events}
|
||||||
now = datetime.now(timezone.utc)
|
now = datetime.now(timezone.utc)
|
||||||
devices = []
|
|
||||||
for hb in heartbeats:
|
|
||||||
received_str = hb["received_at"]
|
|
||||||
try:
|
|
||||||
received = datetime.fromisoformat(received_str)
|
|
||||||
if received.tzinfo is None:
|
|
||||||
received = received.replace(tzinfo=timezone.utc)
|
|
||||||
seconds_ago = int((now - received).total_seconds())
|
|
||||||
except (ValueError, TypeError):
|
|
||||||
seconds_ago = 9999
|
|
||||||
|
|
||||||
alert_event = alert_by_serial.get(hb["device_serial"])
|
|
||||||
|
|
||||||
devices.append(DeviceMqttStatus(
|
|
||||||
device_serial=hb["device_serial"],
|
|
||||||
online=seconds_ago < 90 and not presence.is_marked_offline(hb["device_serial"]),
|
|
||||||
last_heartbeat=HeartbeatEntry(**hb),
|
|
||||||
seconds_since_heartbeat=seconds_ago,
|
|
||||||
last_alert_event=AlertEventEntry(**alert_event) if alert_event else None,
|
|
||||||
))
|
|
||||||
return MqttStatusResponse(
|
return MqttStatusResponse(
|
||||||
devices=devices,
|
devices=[_device_status(hb, alert_by_serial.get(hb["device_serial"]), now) for hb in heartbeats],
|
||||||
broker_connected=mqtt_manager.connected,
|
broker_connected=mqtt_manager.connected,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/status/{device_serial}", response_model=Optional[DeviceMqttStatus])
|
||||||
|
async def get_device_status(
|
||||||
|
device_serial: str,
|
||||||
|
_user: TokenPayload = Depends(require_permission("mqtt", "view")),
|
||||||
|
):
|
||||||
|
"""One device's live status — what DeviceDetail needs, without shipping
|
||||||
|
the whole fleet. null when the device has never sent a heartbeat."""
|
||||||
|
hb = await db.get_latest_heartbeat(device_serial)
|
||||||
|
if not hb:
|
||||||
|
return None
|
||||||
|
alert_event = await db.get_latest_alert_event(device_serial)
|
||||||
|
return _device_status(hb, alert_event, datetime.now(timezone.utc))
|
||||||
|
|
||||||
|
|
||||||
@router.get("/latest-metrics", response_model=LatestMetricsResponse)
|
@router.get("/latest-metrics", response_model=LatestMetricsResponse)
|
||||||
async def get_latest_metrics(
|
async def get_latest_metrics(
|
||||||
_user: TokenPayload = Depends(require_permission("mqtt", "view")),
|
_user: TokenPayload = Depends(require_permission("mqtt", "view")),
|
||||||
@@ -123,6 +139,31 @@ async def get_device_logs(
|
|||||||
return LogListResponse(logs=logs, total=total)
|
return LogListResponse(logs=logs, total=total)
|
||||||
|
|
||||||
|
|
||||||
|
@router.delete("/logs/{device_serial}")
|
||||||
|
async def delete_device_logs(
|
||||||
|
device_serial: str,
|
||||||
|
source: Optional[List[str]] = Query(None, description="Only these sources: log, info. Repeat param for several. Omit for all."),
|
||||||
|
level: Optional[List[str]] = Query(None, description="Only these levels: INFO, WARN, ERROR. Repeat param for several. Omit for all."),
|
||||||
|
until: Optional[datetime] = Query(None, description="Only rows at/before this ISO timestamp"),
|
||||||
|
_user: TokenPayload = Depends(require_permission("devices", "edit")),
|
||||||
|
pg: AsyncSession = Depends(get_pg_session),
|
||||||
|
):
|
||||||
|
"""Delete console-stored log rows for one device (Health tab → Logs →
|
||||||
|
Delete Logs). Narrowed by source/level/time when given. Heartbeats,
|
||||||
|
alert history and commands are cleared through the existing
|
||||||
|
POST /api/devices/{id}/reset-stats instead."""
|
||||||
|
bad_sources = [s for s in (source or []) if s not in ("log", "info")]
|
||||||
|
bad_levels = [l for l in (level or []) if l not in ("INFO", "WARN", "ERROR")]
|
||||||
|
if bad_sources or bad_levels:
|
||||||
|
raise HTTPException(status_code=400, detail=f"Invalid filter: {bad_sources + bad_levels}")
|
||||||
|
deleted = await db.delete_device_logs_filtered(device_serial, sources=source, levels=level, until=until)
|
||||||
|
await log_action(pg, _user.sub, _user.name or _user.email, "DELETE", "device_logs",
|
||||||
|
device_serial, device_serial,
|
||||||
|
meta={"sources": source, "levels": level,
|
||||||
|
"until": until.isoformat() if until else None, "deleted": deleted})
|
||||||
|
return {"deleted": deleted}
|
||||||
|
|
||||||
|
|
||||||
@router.get("/heartbeats/{device_serial}", response_model=HeartbeatListResponse)
|
@router.get("/heartbeats/{device_serial}", response_model=HeartbeatListResponse)
|
||||||
async def get_device_heartbeats(
|
async def get_device_heartbeats(
|
||||||
device_serial: str,
|
device_serial: str,
|
||||||
|
|||||||
@@ -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 (
|
||||||
|
<div style={{
|
||||||
|
display: 'flex',
|
||||||
|
alignItems: 'center',
|
||||||
|
gap: 'var(--space-3)',
|
||||||
|
padding: 'var(--space-2) var(--space-4)',
|
||||||
|
minHeight: 44,
|
||||||
|
background: tone.bg,
|
||||||
|
border: `1px solid ${tone.border}`,
|
||||||
|
borderRadius: 'var(--radius-lg)',
|
||||||
|
backdropFilter: 'var(--blur-modal)',
|
||||||
|
WebkitBackdropFilter: 'var(--blur-modal)',
|
||||||
|
}}>
|
||||||
|
{status === 'checking'
|
||||||
|
? <Spinner size="sm" />
|
||||||
|
: <Icon name={tone.icon} size={16} color={tone.color} />}
|
||||||
|
<span style={{
|
||||||
|
flex: 1,
|
||||||
|
fontSize: 'var(--font-size-sm)',
|
||||||
|
color: differs ? 'var(--color-text-primary)' : 'var(--color-text-secondary)',
|
||||||
|
fontWeight: differs ? 'var(--font-weight-semibold)' : 'var(--font-weight-normal)',
|
||||||
|
}}>
|
||||||
|
{text}
|
||||||
|
</span>
|
||||||
|
{differs && (
|
||||||
|
<Button variant="primary" size="sm" onClick={onReview}>Compare & resolve</Button>
|
||||||
|
)}
|
||||||
|
{status !== 'checking' && (
|
||||||
|
<Button variant="ghost" size="sm" icon={<Icon name="refresh" size={13} />} onClick={onRecheck}>
|
||||||
|
{status === 'unreachable' ? 'Retry' : 'Re-check'}
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -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])
|
||||||
|
|
||||||
|
|||||||
@@ -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
|
||||||
@@ -0,0 +1,113 @@
|
|||||||
|
// frontend/src/lib/deviceCache.js
|
||||||
|
// Last-known device data for stale-while-revalidate rendering.
|
||||||
|
//
|
||||||
|
// DeviceList and DeviceDetail paint instantly from whatever was fetched last
|
||||||
|
// (in this tab, or earlier in this browser session), then revalidate in the
|
||||||
|
// background and swap in fresh data silently. The backend's MQTT ingest keeps
|
||||||
|
// status current every ~30s, so the cached copy is almost always right; the
|
||||||
|
// background fetch just confirms it.
|
||||||
|
//
|
||||||
|
// Kept in memory (survives in-app navigation) and mirrored to sessionStorage
|
||||||
|
// (survives a page reload in the same tab). Storage can be unavailable or
|
||||||
|
// full — every access is wrapped so the cache silently degrades to memory-only.
|
||||||
|
|
||||||
|
const STORAGE_KEY = 'bs.deviceCache.v1'
|
||||||
|
|
||||||
|
function load() {
|
||||||
|
try {
|
||||||
|
const raw = sessionStorage.getItem(STORAGE_KEY)
|
||||||
|
if (raw) return JSON.parse(raw)
|
||||||
|
} catch { /* unavailable / corrupt — start empty */ }
|
||||||
|
return {}
|
||||||
|
}
|
||||||
|
|
||||||
|
const state = {
|
||||||
|
devicesByQuery: {}, // list query string -> devices[]
|
||||||
|
deviceById: {}, // firestore doc id -> device
|
||||||
|
statusMap: null, // serial -> /mqtt/status entry
|
||||||
|
diagMap: null, // serial -> latest diagnostics (list columns)
|
||||||
|
pingMap: null, // serial -> latest ping sample (list columns)
|
||||||
|
healthByKey: {}, // `${sn}|${rangeKey}` -> Health overview datasets
|
||||||
|
...load(),
|
||||||
|
}
|
||||||
|
|
||||||
|
let persistTimer = null
|
||||||
|
function persist() {
|
||||||
|
// Coalesce bursts (e.g. a heartbeat per device) into one write.
|
||||||
|
if (persistTimer) return
|
||||||
|
persistTimer = setTimeout(() => {
|
||||||
|
persistTimer = null
|
||||||
|
try {
|
||||||
|
// Health datasets can be thousands of rows — memory only.
|
||||||
|
const { healthByKey, ...rest } = state
|
||||||
|
sessionStorage.setItem(STORAGE_KEY, JSON.stringify(rest))
|
||||||
|
} catch { /* quota / unavailable — memory cache still works */ }
|
||||||
|
}, 500)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Device list ──────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
export function getCachedDevices(query) {
|
||||||
|
return state.devicesByQuery[query] || null
|
||||||
|
}
|
||||||
|
|
||||||
|
export function setCachedDevices(query, devices) {
|
||||||
|
state.devicesByQuery[query] = devices
|
||||||
|
for (const d of devices) if (d?.id) state.deviceById[d.id] = d
|
||||||
|
persist()
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Single device ────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
export function getCachedDevice(id) {
|
||||||
|
return state.deviceById[id] || null
|
||||||
|
}
|
||||||
|
|
||||||
|
export function setCachedDevice(device) {
|
||||||
|
if (!device?.id) return
|
||||||
|
state.deviceById[device.id] = device
|
||||||
|
persist()
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── MQTT status ──────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
export function getCachedStatusMap() {
|
||||||
|
return state.statusMap
|
||||||
|
}
|
||||||
|
|
||||||
|
export function setCachedStatusMap(map) {
|
||||||
|
state.statusMap = map
|
||||||
|
persist()
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getCachedStatus(serial) {
|
||||||
|
return (serial && state.statusMap?.[serial]) || null
|
||||||
|
}
|
||||||
|
|
||||||
|
export function setCachedStatus(serial, status) {
|
||||||
|
if (!serial) return
|
||||||
|
state.statusMap = { ...(state.statusMap || {}), [serial]: status }
|
||||||
|
persist()
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Latest metrics (list columns) ────────────────────────────────────────────
|
||||||
|
|
||||||
|
export function getCachedMetrics() {
|
||||||
|
return { diagMap: state.diagMap, pingMap: state.pingMap }
|
||||||
|
}
|
||||||
|
|
||||||
|
export function setCachedMetrics(diagMap, pingMap) {
|
||||||
|
state.diagMap = diagMap
|
||||||
|
state.pingMap = pingMap
|
||||||
|
persist()
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Health overview datasets ─────────────────────────────────────────────────
|
||||||
|
|
||||||
|
export function getCachedHealth(key) {
|
||||||
|
return state.healthByKey[key] || null
|
||||||
|
}
|
||||||
|
|
||||||
|
export function setCachedHealth(key, data) {
|
||||||
|
state.healthByKey[key] = data
|
||||||
|
}
|
||||||
@@ -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]) }))
|
||||||
|
}
|
||||||
@@ -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 (
|
||||||
|
<div style={{
|
||||||
|
background: COLUMN_BG,
|
||||||
|
borderRadius: 'var(--radius-lg) var(--radius-lg) 0 0',
|
||||||
|
border: '1px solid var(--color-border)',
|
||||||
|
borderBottom: 'none',
|
||||||
|
padding: 'var(--space-4)',
|
||||||
|
display: 'flex',
|
||||||
|
alignItems: 'center',
|
||||||
|
gap: 'var(--space-3)',
|
||||||
|
}}>
|
||||||
|
<div style={{
|
||||||
|
width: 36, height: 36, flexShrink: 0,
|
||||||
|
borderRadius: 'var(--radius-md)',
|
||||||
|
background: 'var(--color-bg-elevated)',
|
||||||
|
display: 'flex', alignItems: 'center', justifyContent: 'center',
|
||||||
|
}}>
|
||||||
|
<Icon name={icon} size={18} color="var(--color-text-secondary)" />
|
||||||
|
</div>
|
||||||
|
<div style={{ minWidth: 0 }}>
|
||||||
|
<div style={{ fontSize: 'var(--font-size-base)', fontWeight: 'var(--font-weight-semibold)', color: 'var(--color-text-primary)' }}>
|
||||||
|
{title}
|
||||||
|
</div>
|
||||||
|
<div style={{ fontSize: 'var(--font-size-xs)', color: 'var(--color-text-muted)' }}>
|
||||||
|
{subtitle}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function Cell({ label, value, differs, last }) {
|
||||||
|
return (
|
||||||
|
<div style={{
|
||||||
|
background: differs ? DIFF_BG : COLUMN_BG,
|
||||||
|
borderLeft: `1px solid var(--color-border)`,
|
||||||
|
borderRight: '1px solid var(--color-border)',
|
||||||
|
boxShadow: differs ? 'inset 3px 0 0 var(--color-warning)' : 'none',
|
||||||
|
padding: 'var(--space-2) var(--space-4)',
|
||||||
|
display: 'flex',
|
||||||
|
justifyContent: 'space-between',
|
||||||
|
alignItems: 'center',
|
||||||
|
gap: 'var(--space-3)',
|
||||||
|
minHeight: 40,
|
||||||
|
borderBottom: last ? 'none' : '1px solid rgba(255,255,255,0.04)',
|
||||||
|
}}>
|
||||||
|
<span style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-text-muted)', flexShrink: 0 }}>
|
||||||
|
{label}
|
||||||
|
</span>
|
||||||
|
<span style={{
|
||||||
|
fontSize: 'var(--font-size-sm)',
|
||||||
|
fontFamily: 'var(--font-family-mono)',
|
||||||
|
fontWeight: differs ? 'var(--font-weight-bold)' : 'var(--font-weight-normal)',
|
||||||
|
color: differs ? 'var(--color-warning)' : 'var(--color-text-secondary)',
|
||||||
|
textAlign: 'right',
|
||||||
|
}}>
|
||||||
|
{value}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function ColumnFooter({ children, hint }) {
|
||||||
|
return (
|
||||||
|
<div style={{
|
||||||
|
background: COLUMN_BG,
|
||||||
|
borderRadius: '0 0 var(--radius-lg) var(--radius-lg)',
|
||||||
|
border: '1px solid var(--color-border)',
|
||||||
|
borderTop: '1px solid var(--color-border)',
|
||||||
|
padding: 'var(--space-4)',
|
||||||
|
display: 'flex',
|
||||||
|
flexDirection: 'column',
|
||||||
|
gap: 'var(--space-2)',
|
||||||
|
alignItems: 'stretch',
|
||||||
|
}}>
|
||||||
|
{children}
|
||||||
|
<span style={{ fontSize: 'var(--font-size-xs)', color: 'var(--color-text-muted)', textAlign: 'center' }}>
|
||||||
|
{hint}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
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 (
|
||||||
|
<Modal
|
||||||
|
open={open}
|
||||||
|
onClose={busy ? () => {} : onClose}
|
||||||
|
title={`${title} — Console and device disagree`}
|
||||||
|
size="lg"
|
||||||
|
footer={
|
||||||
|
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', width: '100%', gap: 'var(--space-3)' }}>
|
||||||
|
<label style={{ display: 'flex', alignItems: 'center', gap: 'var(--space-2)', fontSize: 'var(--font-size-sm)', color: 'var(--color-text-secondary)', cursor: 'pointer' }}>
|
||||||
|
<input type="checkbox" checked={onlyDiffs} onChange={(e) => setOnlyDiffs(e.target.checked)} />
|
||||||
|
Only show differences
|
||||||
|
</label>
|
||||||
|
<Button variant="ghost" onClick={onClose} disabled={!!busy}>Decide later</Button>
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-4)' }}>
|
||||||
|
<p style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-text-muted)', margin: 0 }}>
|
||||||
|
The settings stored on the device don't match what the console has saved
|
||||||
|
— <strong style={{ color: 'var(--color-warning)' }}>
|
||||||
|
{diffCount} {diffCount === 1 ? 'difference' : 'differences'}
|
||||||
|
</strong>. Choose which version to keep. Nothing changes until you pick one.
|
||||||
|
</p>
|
||||||
|
|
||||||
|
{/* Two columns, rows aligned across them (one shared grid). */}
|
||||||
|
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', columnGap: 'var(--space-4)' }}>
|
||||||
|
<ColumnHeader icon="dashboard" title="Saved in Console" subtitle="What the database holds" />
|
||||||
|
<ColumnHeader icon="devices" title="Stored on Device" subtitle="Read from the device just now" />
|
||||||
|
|
||||||
|
{visible.map((r, i) => [
|
||||||
|
<Cell key={`${r.key}-s`} label={r.label} value={r.saved} differs={r.differs} last={i === visible.length - 1} />,
|
||||||
|
<Cell key={`${r.key}-d`} label={r.label} value={r.device} differs={r.differs} last={i === visible.length - 1} />,
|
||||||
|
])}
|
||||||
|
|
||||||
|
{canEdit ? (
|
||||||
|
<>
|
||||||
|
<ColumnFooter hint="Pushes these settings to the device. The database is already correct.">
|
||||||
|
<Button
|
||||||
|
variant="primary"
|
||||||
|
icon={<Icon name="upload" size={14} />}
|
||||||
|
loading={busy === 'console'}
|
||||||
|
disabled={!!busy}
|
||||||
|
onClick={run('console', onKeepConsole)}
|
||||||
|
>
|
||||||
|
Keep Console version
|
||||||
|
</Button>
|
||||||
|
</ColumnFooter>
|
||||||
|
<ColumnFooter hint="Saves only the differing values to the database. The device is not touched.">
|
||||||
|
<Button
|
||||||
|
variant="primary"
|
||||||
|
icon={<Icon name="download" size={14} />}
|
||||||
|
loading={busy === 'device'}
|
||||||
|
disabled={!!busy}
|
||||||
|
onClick={run('device', onKeepDevice)}
|
||||||
|
>
|
||||||
|
Keep Device version
|
||||||
|
</Button>
|
||||||
|
</ColumnFooter>
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<ColumnFooter hint="You don't have permission to change device settings." />
|
||||||
|
<ColumnFooter hint="You don't have permission to change device settings." />
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{error && (
|
||||||
|
<p style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-danger)', margin: 0 }}>{error}</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</Modal>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,175 @@
|
|||||||
|
// frontend/src/modals/bellcloud/devices/DeleteDeviceLogsModal.jsx
|
||||||
|
// Health tab → Logs → "Delete Logs…". Permanently deletes console-stored log
|
||||||
|
// history for one device, filtered by log type (and by level for the text
|
||||||
|
// channels). Unlike ResetStatsModal this never touches the device itself,
|
||||||
|
// Firestore stats, boot history or ping/diagnostics data — just the log
|
||||||
|
// channels shown in the Logs explorer.
|
||||||
|
//
|
||||||
|
// Device Logs / Info → DELETE /mqtt/logs/{serial}?source=…&level=…
|
||||||
|
// Alerts / Heartbeats / Commands → POST /devices/{id}/reset-stats (existing)
|
||||||
|
|
||||||
|
import { useState } from 'react'
|
||||||
|
import Modal from '@/components/ui/Modal'
|
||||||
|
import Button from '@/components/ui/Button'
|
||||||
|
import PressHoldButton from '@/components/ui/PressHoldButton'
|
||||||
|
import Icon from '@/components/ui/Icon'
|
||||||
|
import api from '@/lib/api'
|
||||||
|
import { useToast } from '@/components/ui/Toast'
|
||||||
|
|
||||||
|
const TYPES = [
|
||||||
|
{ key: 'log', label: 'Device Logs', description: 'Debug log lines the firmware streams over MQTT.', leveled: true },
|
||||||
|
{ key: 'info', label: 'Info events', description: 'System info events (playback started, config changes, …).', leveled: true },
|
||||||
|
{ key: 'alert_history', label: 'Alert history', description: 'Past alert transitions. Current active alerts are kept.' },
|
||||||
|
{ key: 'heartbeats', label: 'Heartbeats', description: 'Heartbeat history — also empties the RSSI and free-heap charts on Overview.' },
|
||||||
|
{ key: 'commands', label: 'Commands', description: 'Sent-command history (also shown in the Control tab).' },
|
||||||
|
]
|
||||||
|
|
||||||
|
const LEVELS = ['INFO', 'WARN', 'ERROR']
|
||||||
|
|
||||||
|
function CheckRow({ label, description, checked, onChange, disabled }) {
|
||||||
|
return (
|
||||||
|
<label style={{
|
||||||
|
display: 'flex', alignItems: 'flex-start', gap: 'var(--space-3)',
|
||||||
|
padding: 'var(--space-2) 0', cursor: disabled ? 'default' : 'pointer',
|
||||||
|
opacity: disabled ? 0.5 : 1,
|
||||||
|
}}>
|
||||||
|
<input
|
||||||
|
type="checkbox"
|
||||||
|
checked={checked}
|
||||||
|
onChange={onChange}
|
||||||
|
disabled={disabled}
|
||||||
|
style={{ accentColor: 'var(--color-danger)', flexShrink: 0, marginTop: 3 }}
|
||||||
|
/>
|
||||||
|
<div style={{ flex: 1, minWidth: 0 }}>
|
||||||
|
<p style={{ fontSize: 'var(--font-size-sm)', fontWeight: 'var(--font-weight-medium)', color: 'var(--color-text-primary)' }}>
|
||||||
|
{label}
|
||||||
|
</p>
|
||||||
|
{description && (
|
||||||
|
<p style={{ fontSize: 'var(--font-size-xs)', color: 'var(--color-text-muted)', marginTop: 2 }}>
|
||||||
|
{description}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</label>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function DeleteDeviceLogsModal({ open, onClose, onDeleted, deviceId, serial }) {
|
||||||
|
const { toast } = useToast()
|
||||||
|
const [types, setTypes] = useState({ log: true, info: true, alert_history: false, heartbeats: false, commands: false })
|
||||||
|
const [levels, setLevels] = useState({ INFO: true, WARN: true, ERROR: true })
|
||||||
|
const [running, setRunning] = useState(false)
|
||||||
|
|
||||||
|
const textSources = ['log', 'info'].filter(k => types[k])
|
||||||
|
const selectedLevels = LEVELS.filter(l => levels[l])
|
||||||
|
const allLevels = selectedLevels.length === LEVELS.length
|
||||||
|
const tableKeys = ['alert_history', 'heartbeats', 'commands'].filter(k => types[k])
|
||||||
|
const canRun = (textSources.length > 0 && selectedLevels.length > 0) || tableKeys.length > 0
|
||||||
|
|
||||||
|
const handleClose = () => { if (!running) onClose() }
|
||||||
|
|
||||||
|
const run = async () => {
|
||||||
|
setRunning(true)
|
||||||
|
const done = []
|
||||||
|
const failed = []
|
||||||
|
if (textSources.length > 0 && selectedLevels.length > 0) {
|
||||||
|
const params = new URLSearchParams()
|
||||||
|
textSources.forEach(s => params.append('source', s))
|
||||||
|
if (!allLevels) selectedLevels.forEach(l => params.append('level', l))
|
||||||
|
try {
|
||||||
|
const res = await api.delete(`/mqtt/logs/${encodeURIComponent(serial)}?${params}`)
|
||||||
|
done.push(`${res?.deleted ?? 0} log line(s)`)
|
||||||
|
} catch (err) {
|
||||||
|
failed.push(`logs: ${err.message || 'failed'}`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (tableKeys.length > 0) {
|
||||||
|
const body = Object.fromEntries(tableKeys.map(k => [k, true]))
|
||||||
|
try {
|
||||||
|
const res = await api.post(`/devices/${deviceId}/reset-stats`, body)
|
||||||
|
for (const k of tableKeys) {
|
||||||
|
const label = TYPES.find(t => t.key === k).label.toLowerCase()
|
||||||
|
done.push(`${res?.[k] ?? 0} ${label}`)
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
failed.push(`${tableKeys.join(', ')}: ${err.message || 'failed'}`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
setRunning(false)
|
||||||
|
if (failed.length === 0) {
|
||||||
|
toast.success('Logs deleted', `Removed ${done.join(', ')}.`)
|
||||||
|
} else {
|
||||||
|
toast.danger('Delete incomplete', failed.join(' · '))
|
||||||
|
}
|
||||||
|
onDeleted?.()
|
||||||
|
onClose()
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Modal open={open} onClose={handleClose} title="Delete Device Logs" size="md" persistent={running}>
|
||||||
|
<div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-5)' }}>
|
||||||
|
<div style={{
|
||||||
|
display: 'flex', alignItems: 'flex-start', gap: 'var(--space-2)',
|
||||||
|
padding: 'var(--space-3) var(--space-4)', borderRadius: 'var(--radius-md)',
|
||||||
|
backgroundColor: 'var(--color-danger-bg)', border: '1px solid var(--color-danger)',
|
||||||
|
fontSize: 'var(--font-size-sm)', color: 'var(--color-danger)',
|
||||||
|
}}>
|
||||||
|
<Icon name="warning" size={16} color="var(--color-danger)" style={{ flexShrink: 0, marginTop: 1 }} />
|
||||||
|
<span>
|
||||||
|
Permanently deletes the selected history for <strong>{serial}</strong> from the console database. The device's own SD-card logs are not affected. <strong>This cannot be undone.</strong>
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<span style={{ fontSize: 'var(--font-size-xs)', fontWeight: 'var(--font-weight-semibold)', color: 'var(--color-text-muted)', letterSpacing: 'var(--tracking-wide)', textTransform: 'uppercase' }}>
|
||||||
|
Log types
|
||||||
|
</span>
|
||||||
|
<div style={{ borderTop: '1px solid var(--color-border)', marginTop: 'var(--space-2)' }}>
|
||||||
|
{TYPES.map(t => (
|
||||||
|
<CheckRow
|
||||||
|
key={t.key}
|
||||||
|
label={t.label}
|
||||||
|
description={t.description}
|
||||||
|
checked={!!types[t.key]}
|
||||||
|
onChange={() => setTypes(prev => ({ ...prev, [t.key]: !prev[t.key] }))}
|
||||||
|
disabled={running}
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{textSources.length > 0 && (
|
||||||
|
<div>
|
||||||
|
<span style={{ fontSize: 'var(--font-size-xs)', fontWeight: 'var(--font-weight-semibold)', color: 'var(--color-text-muted)', letterSpacing: 'var(--tracking-wide)', textTransform: 'uppercase' }}>
|
||||||
|
Levels (Device Logs & Info)
|
||||||
|
</span>
|
||||||
|
<div style={{ display: 'flex', gap: 'var(--space-6)', borderTop: '1px solid var(--color-border)', marginTop: 'var(--space-2)', flexWrap: 'wrap' }}>
|
||||||
|
{LEVELS.map(l => (
|
||||||
|
<CheckRow
|
||||||
|
key={l}
|
||||||
|
label={l}
|
||||||
|
checked={!!levels[l]}
|
||||||
|
onChange={() => setLevels(prev => ({ ...prev, [l]: !prev[l] }))}
|
||||||
|
disabled={running}
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<div style={{ display: 'flex', justifyContent: 'flex-end', gap: 'var(--space-3)', paddingTop: 'var(--space-2)', borderTop: '1px solid var(--color-border)', flexWrap: 'wrap' }}>
|
||||||
|
<Button variant="ghost" onClick={handleClose} disabled={running}>Cancel</Button>
|
||||||
|
<PressHoldButton
|
||||||
|
variant="danger"
|
||||||
|
holdMs={2000}
|
||||||
|
disabled={running || !canRun}
|
||||||
|
holdingLabel="Keep holding to delete…"
|
||||||
|
onConfirm={run}
|
||||||
|
>
|
||||||
|
{running ? 'Deleting…' : 'Hold to Delete'}
|
||||||
|
</PressHoldButton>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</Modal>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -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,
|
||||||
|
|||||||
@@ -1,9 +1,10 @@
|
|||||||
// frontend/src/pages/bellcloud/devices/DeviceDetail.jsx
|
// frontend/src/pages/bellcloud/devices/DeviceDetail.jsx
|
||||||
// Parent shell — data fetching, tab routing, modals. Tab content lives in tabs/
|
// Parent shell — data fetching, tab routing, modals. Tab content lives in tabs/
|
||||||
|
|
||||||
import { useState, useEffect, useCallback } from 'react'
|
import { useState, useEffect, useCallback, useRef } from 'react'
|
||||||
import { useParams, useNavigate, useSearchParams } from 'react-router-dom'
|
import { useParams, useNavigate, useSearchParams } from 'react-router-dom'
|
||||||
import api from '@/lib/api'
|
import api from '@/lib/api'
|
||||||
|
import { getCachedDevice, setCachedDevice, getCachedStatus, setCachedStatus } from '@/lib/deviceCache'
|
||||||
import { useAuth } from '@/hooks/useAuth'
|
import { useAuth } from '@/hooks/useAuth'
|
||||||
import { useToast } from '@/components/ui/Toast'
|
import { useToast } from '@/components/ui/Toast'
|
||||||
import { useDeviceCommand } from '@/hooks/useDeviceCommand'
|
import { useDeviceCommand } from '@/hooks/useDeviceCommand'
|
||||||
@@ -73,10 +74,19 @@ export default function DeviceDetail() {
|
|||||||
const canEdit = hasPermission('devices', 'edit')
|
const canEdit = hasPermission('devices', 'edit')
|
||||||
|
|
||||||
// ── State ──────────────────────────────────────────────────────────────────
|
// ── State ──────────────────────────────────────────────────────────────────
|
||||||
const [device, setDevice] = useState(null)
|
// Seeded from the last-known cache (lib/deviceCache — filled by DeviceList
|
||||||
const [loading, setLoading] = useState(true)
|
// and by earlier visits) so the page renders instantly; loadDevice() then
|
||||||
|
// revalidates in the background and `refreshing` drives the Syncing hint.
|
||||||
|
const [device, setDevice] = useState(() => getCachedDevice(id))
|
||||||
|
const [loading, setLoading] = useState(() => !getCachedDevice(id))
|
||||||
|
const [refreshing, setRefreshing] = useState(false)
|
||||||
const [error, setError] = useState('')
|
const [error, setError] = useState('')
|
||||||
const [mqttStatus, setMqttStatus] = useState(null)
|
const [mqttStatus, setMqttStatus] = useState(() => {
|
||||||
|
const d = getCachedDevice(id)
|
||||||
|
return getCachedStatus(d?.serial_number || d?.device_id)
|
||||||
|
})
|
||||||
|
const deviceRef = useRef(device)
|
||||||
|
deviceRef.current = device
|
||||||
const [activeTab, setActiveTab] = useState(() => resolveInitialTab(searchParams))
|
const [activeTab, setActiveTab] = useState(() => resolveInitialTab(searchParams))
|
||||||
|
|
||||||
const [deviceUsers, setDeviceUsers] = useState([])
|
const [deviceUsers, setDeviceUsers] = useState([])
|
||||||
@@ -84,8 +94,11 @@ export default function DeviceDetail() {
|
|||||||
const [ownerCustomer, setOwnerCustomer] = useState(null)
|
const [ownerCustomer, setOwnerCustomer] = useState(null)
|
||||||
const [assigningCustomer, setAssigningCustomer] = useState(false)
|
const [assigningCustomer, setAssigningCustomer] = useState(false)
|
||||||
|
|
||||||
const [tags, setTags] = useState([])
|
const [tags, setTags] = useState(() => {
|
||||||
const [staffNotes, setStaffNotes] = useState('')
|
const t = getCachedDevice(id)?.tags
|
||||||
|
return Array.isArray(t) ? t : []
|
||||||
|
})
|
||||||
|
const [staffNotes, setStaffNotes] = useState(() => getCachedDevice(id)?.staffNotes || '')
|
||||||
|
|
||||||
const [showDelete, setShowDelete] = useState(false)
|
const [showDelete, setShowDelete] = useState(false)
|
||||||
const [deleting, setDeleting] = useState(false)
|
const [deleting, setDeleting] = useState(false)
|
||||||
@@ -108,8 +121,29 @@ export default function DeviceDetail() {
|
|||||||
// ── Data fetching ──────────────────────────────────────────────────────────
|
// ── Data fetching ──────────────────────────────────────────────────────────
|
||||||
|
|
||||||
const loadDevice = useCallback(async () => {
|
const loadDevice = useCallback(async () => {
|
||||||
setLoading(true)
|
// Already showing this device (e.g. reload after a modal save) → refresh
|
||||||
|
// in place. Navigated here → seed from cache if we have it. Only a device
|
||||||
|
// we've never seen shows the full-page spinner.
|
||||||
|
const current = deviceRef.current?.id === id ? deviceRef.current : null
|
||||||
|
const seed = current || getCachedDevice(id)
|
||||||
|
if (!current) {
|
||||||
|
setDevice(seed)
|
||||||
|
setMqttStatus(seed ? getCachedStatus(seed.serial_number || seed.device_id) : null)
|
||||||
|
if (seed?.staffNotes) setStaffNotes(seed.staffNotes)
|
||||||
|
if (Array.isArray(seed?.tags)) setTags(seed.tags)
|
||||||
|
}
|
||||||
|
setLoading(!seed)
|
||||||
|
setRefreshing(true)
|
||||||
setError('')
|
setError('')
|
||||||
|
|
||||||
|
// Live status for just this device. Started right away when the serial
|
||||||
|
// is already known, in parallel with the device fetch.
|
||||||
|
const fetchStatus = sn => api.get(`/mqtt/status/${encodeURIComponent(sn)}`)
|
||||||
|
.then(st => setMqttStatus(st || null))
|
||||||
|
.catch(() => {})
|
||||||
|
const seedSn = seed?.serial_number || seed?.device_id
|
||||||
|
const statusPromise = seedSn ? fetchStatus(seedSn) : null
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const d = await api.get(`/devices/${id}`)
|
const d = await api.get(`/devices/${id}`)
|
||||||
setDevice(d)
|
setDevice(d)
|
||||||
@@ -118,14 +152,8 @@ export default function DeviceDetail() {
|
|||||||
setLoading(false)
|
setLoading(false)
|
||||||
|
|
||||||
const sn = d.serial_number || d.device_id
|
const sn = d.serial_number || d.device_id
|
||||||
if (sn) {
|
const statusDone = statusPromise || (sn ? fetchStatus(sn) : Promise.resolve())
|
||||||
api.get('/mqtt/status').then(mqttData => {
|
statusDone.finally(() => setRefreshing(false))
|
||||||
if (mqttData?.devices) {
|
|
||||||
const match = mqttData.devices.find(s => s.device_serial === sn)
|
|
||||||
setMqttStatus(match || null)
|
|
||||||
}
|
|
||||||
}).catch(() => {})
|
|
||||||
}
|
|
||||||
|
|
||||||
if (d.customer_id) {
|
if (d.customer_id) {
|
||||||
api.get(`/devices/${id}/customer`).then(res => {
|
api.get(`/devices/${id}/customer`).then(res => {
|
||||||
@@ -141,8 +169,10 @@ export default function DeviceDetail() {
|
|||||||
}).catch(() => setDeviceUsers([])).finally(() => setUsersLoading(false))
|
}).catch(() => setDeviceUsers([])).finally(() => setUsersLoading(false))
|
||||||
|
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
setError(err.message || 'Failed to load device.')
|
// Cached data on screen → keep it and stay quiet; otherwise show the error.
|
||||||
|
if (!seed) setError(err.message || 'Failed to load device.')
|
||||||
setLoading(false)
|
setLoading(false)
|
||||||
|
setRefreshing(false)
|
||||||
}
|
}
|
||||||
}, [id])
|
}, [id])
|
||||||
|
|
||||||
@@ -187,6 +217,11 @@ export default function DeviceDetail() {
|
|||||||
|
|
||||||
const deviceSerial = device?.serial_number || device?.device_id
|
const deviceSerial = device?.serial_number || device?.device_id
|
||||||
|
|
||||||
|
// Write-through: every device / status change (fresh fetch, modal save,
|
||||||
|
// live heartbeat) updates the cache the next visit will paint from.
|
||||||
|
useEffect(() => { if (device) setCachedDevice(device) }, [device])
|
||||||
|
useEffect(() => { if (deviceSerial && mqttStatus) setCachedStatus(deviceSerial, mqttStatus) }, [deviceSerial, mqttStatus])
|
||||||
|
|
||||||
const handleNonAckMessage = useCallback((msg) => {
|
const handleNonAckMessage = useCallback((msg) => {
|
||||||
// Live heartbeat — updates the online dot/RSSI without polling. The device
|
// Live heartbeat — updates the online dot/RSSI without polling. The device
|
||||||
// publishes one every ~30s; we just reflect whatever lands here instead of
|
// publishes one every ~30s; we just reflect whatever lands here instead of
|
||||||
@@ -418,6 +453,16 @@ export default function DeviceDetail() {
|
|||||||
</span>
|
</span>
|
||||||
}
|
}
|
||||||
>
|
>
|
||||||
|
{refreshing && (
|
||||||
|
<span
|
||||||
|
role="status"
|
||||||
|
title="Fetching fresh data — showing last-known values meanwhile"
|
||||||
|
style={{ display: 'inline-flex', alignItems: 'center', gap: 'var(--space-2)', color: 'var(--color-text-muted)', fontSize: 'var(--font-size-xs)' }}
|
||||||
|
>
|
||||||
|
<Spinner size="sm" />
|
||||||
|
Syncing…
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
<Button variant="ghost" onClick={() => sendMqttCommand('ping')}>
|
<Button variant="ghost" onClick={() => sendMqttCommand('ping')}>
|
||||||
Ping Now
|
Ping Now
|
||||||
</Button>
|
</Button>
|
||||||
|
|||||||
@@ -1,8 +1,13 @@
|
|||||||
// frontend/src/pages/devices/DeviceList.jsx
|
// frontend/src/pages/devices/DeviceList.jsx
|
||||||
|
|
||||||
import { useState, useEffect, useCallback } from 'react'
|
import { useState, useEffect, useCallback, useRef } from 'react'
|
||||||
import { useNavigate } from 'react-router-dom'
|
import { useNavigate } from 'react-router-dom'
|
||||||
import api from '@/lib/api'
|
import api from '@/lib/api'
|
||||||
|
import {
|
||||||
|
getCachedDevices, setCachedDevices,
|
||||||
|
getCachedStatusMap, setCachedStatusMap,
|
||||||
|
getCachedMetrics, setCachedMetrics,
|
||||||
|
} from '@/lib/deviceCache'
|
||||||
import { useAuth } from '@/hooks/useAuth'
|
import { useAuth } from '@/hooks/useAuth'
|
||||||
import { useMqttWebSocket } from '@/hooks/useMqttWebSocket'
|
import { useMqttWebSocket } from '@/hooks/useMqttWebSocket'
|
||||||
import PageHeader from '@/components/ui/PageHeader'
|
import PageHeader from '@/components/ui/PageHeader'
|
||||||
@@ -14,6 +19,7 @@ import Pagination from '@/components/ui/Pagination'
|
|||||||
import SearchBar from '@/components/ui/SearchBar'
|
import SearchBar from '@/components/ui/SearchBar'
|
||||||
import RowActions from '@/components/ui/RowActions'
|
import RowActions from '@/components/ui/RowActions'
|
||||||
import Icon from '@/components/ui/Icon'
|
import Icon from '@/components/ui/Icon'
|
||||||
|
import Spinner from '@/components/ui/Spinner'
|
||||||
import SegmentedControl from '@/components/ui/SegmentedControl'
|
import SegmentedControl from '@/components/ui/SegmentedControl'
|
||||||
import DeleteDeviceModal from '@/modals/bellcloud/devices/DeleteDeviceModal'
|
import DeleteDeviceModal from '@/modals/bellcloud/devices/DeleteDeviceModal'
|
||||||
import DeviceFiltersModal from '@/modals/bellcloud/devices/DeviceFiltersModal'
|
import DeviceFiltersModal from '@/modals/bellcloud/devices/DeviceFiltersModal'
|
||||||
@@ -301,14 +307,18 @@ export default function DeviceList() {
|
|||||||
const { hasPermission } = useAuth()
|
const { hasPermission } = useAuth()
|
||||||
const canEdit = hasPermission('devices', 'edit')
|
const canEdit = hasPermission('devices', 'edit')
|
||||||
|
|
||||||
// Data
|
// Data — seeded from the last-known cache so the table paints instantly;
|
||||||
const [devices, setDevices] = useState([])
|
// fetchDevices() then revalidates in the background (see lib/deviceCache).
|
||||||
const [loading, setLoading] = useState(true)
|
// The cache key '' matches the initial (unfiltered) query below.
|
||||||
|
const [devices, setDevices] = useState(() => getCachedDevices('') || [])
|
||||||
|
const [loading, setLoading] = useState(() => !getCachedDevices(''))
|
||||||
|
const [refreshing, setRefreshing] = useState(false)
|
||||||
const [error, setError] = useState('')
|
const [error, setError] = useState('')
|
||||||
const [mqttStatusMap, setMqttStatusMap] = useState({})
|
const [mqttStatusMap, setMqttStatusMap] = useState(() => getCachedStatusMap() || {})
|
||||||
const [mqttLoaded, setMqttLoaded] = useState(false)
|
const [mqttLoaded, setMqttLoaded] = useState(() => !!getCachedStatusMap())
|
||||||
const [latestDiagMap, setLatestDiagMap] = useState({})
|
const [latestDiagMap, setLatestDiagMap] = useState(() => getCachedMetrics().diagMap || {})
|
||||||
const [latestPingMap, setLatestPingMap] = useState({})
|
const [latestPingMap, setLatestPingMap] = useState(() => getCachedMetrics().pingMap || {})
|
||||||
|
const fetchSeq = useRef(0)
|
||||||
|
|
||||||
// Server-side filters
|
// Server-side filters
|
||||||
const [search, setSearch] = useState('')
|
const [search, setSearch] = useState('')
|
||||||
@@ -377,49 +387,71 @@ export default function DeviceList() {
|
|||||||
}, [])
|
}, [])
|
||||||
|
|
||||||
// ── Fetch devices ──────────────────────────────────────────────────────────
|
// ── Fetch devices ──────────────────────────────────────────────────────────
|
||||||
|
// Stale-while-revalidate: if this exact query was fetched before, show it
|
||||||
|
// immediately and refresh silently; only a never-seen query shows the
|
||||||
|
// table's loading state. Status + metrics are fetched in parallel with the
|
||||||
|
// device list (not after it) — they're served from the backend's in-memory
|
||||||
|
// latest-status cache and come back fast.
|
||||||
const fetchDevices = useCallback(async () => {
|
const fetchDevices = useCallback(async () => {
|
||||||
setLoading(true)
|
const seq = ++fetchSeq.current
|
||||||
setMqttLoaded(false)
|
const params = new URLSearchParams()
|
||||||
setError('')
|
if (search) params.set('search', search)
|
||||||
try {
|
if (onlineFilter === 'true') params.set('online', 'true')
|
||||||
const params = new URLSearchParams()
|
if (onlineFilter === 'false') params.set('online', 'false')
|
||||||
if (search) params.set('search', search)
|
if (tierFilter) params.set('tier', tierFilter)
|
||||||
if (onlineFilter === 'true') params.set('online', 'true')
|
// Note: online filter is server-side — we pass it as a query param but
|
||||||
if (onlineFilter === 'false') params.set('online', 'false')
|
// the server returns ALL devices when the param is absent, so we also
|
||||||
if (tierFilter) params.set('tier', tierFilter)
|
// apply a client-side guard to ensure ONLINE-only actually filters.
|
||||||
// Note: online filter is server-side — we pass it as a query param but
|
const qs = params.toString()
|
||||||
// the server returns ALL devices when the param is absent, so we also
|
|
||||||
// apply a client-side guard to ensure ONLINE-only actually filters.
|
const cached = getCachedDevices(qs)
|
||||||
const qs = params.toString()
|
if (cached) {
|
||||||
const data = await api.get(`/devices${qs ? `?${qs}` : ''}`)
|
setDevices(cached)
|
||||||
setDevices(data.devices ?? [])
|
|
||||||
api.get('/mqtt/status').then((mqttData) => {
|
|
||||||
if (mqttData?.devices) {
|
|
||||||
const map = {}
|
|
||||||
for (const s of mqttData.devices) map[s.device_serial] = s
|
|
||||||
setMqttStatusMap(map)
|
|
||||||
}
|
|
||||||
setMqttLoaded(true)
|
|
||||||
}).catch(() => { setMqttLoaded(true) })
|
|
||||||
// Last-known CPU temp + ping RTT — one extra request, fleet-wide,
|
|
||||||
// reading whatever the background MQTT ingestion already stored.
|
|
||||||
// Never triggers a live poll of any device.
|
|
||||||
api.get('/mqtt/latest-metrics').then((metrics) => {
|
|
||||||
if (metrics?.diagnostics) {
|
|
||||||
const dMap = {}
|
|
||||||
for (const d of metrics.diagnostics) dMap[d.device_serial] = d
|
|
||||||
setLatestDiagMap(dMap)
|
|
||||||
}
|
|
||||||
if (metrics?.pings) {
|
|
||||||
const pMap = {}
|
|
||||||
for (const p of metrics.pings) pMap[p.device_serial] = p
|
|
||||||
setLatestPingMap(pMap)
|
|
||||||
}
|
|
||||||
}).catch(() => { /* optional columns — non-fatal if unavailable */ })
|
|
||||||
} catch (err) {
|
|
||||||
setError(err.message || 'Failed to load devices.')
|
|
||||||
} finally {
|
|
||||||
setLoading(false)
|
setLoading(false)
|
||||||
|
} else {
|
||||||
|
setLoading(true)
|
||||||
|
}
|
||||||
|
setRefreshing(true)
|
||||||
|
setError('')
|
||||||
|
|
||||||
|
api.get('/mqtt/status').then((mqttData) => {
|
||||||
|
if (mqttData?.devices) {
|
||||||
|
const map = {}
|
||||||
|
for (const s of mqttData.devices) map[s.device_serial] = s
|
||||||
|
setMqttStatusMap(map)
|
||||||
|
setCachedStatusMap(map)
|
||||||
|
}
|
||||||
|
setMqttLoaded(true)
|
||||||
|
}).catch(() => { setMqttLoaded(true) })
|
||||||
|
|
||||||
|
// Last-known CPU temp + ping RTT — one extra request, fleet-wide,
|
||||||
|
// reading whatever the background MQTT ingestion already stored.
|
||||||
|
// Never triggers a live poll of any device.
|
||||||
|
api.get('/mqtt/latest-metrics').then((metrics) => {
|
||||||
|
const dMap = {}
|
||||||
|
for (const d of metrics?.diagnostics || []) dMap[d.device_serial] = d
|
||||||
|
const pMap = {}
|
||||||
|
for (const p of metrics?.pings || []) pMap[p.device_serial] = p
|
||||||
|
setLatestDiagMap(dMap)
|
||||||
|
setLatestPingMap(pMap)
|
||||||
|
setCachedMetrics(dMap, pMap)
|
||||||
|
}).catch(() => { /* optional columns — non-fatal if unavailable */ })
|
||||||
|
|
||||||
|
try {
|
||||||
|
const data = await api.get(`/devices${qs ? `?${qs}` : ''}`)
|
||||||
|
const list = data.devices ?? []
|
||||||
|
setCachedDevices(qs, list)
|
||||||
|
// Typing in the search box fires several fetches — only the newest
|
||||||
|
// one may update the table, or an older slow response could win.
|
||||||
|
if (seq === fetchSeq.current) setDevices(list)
|
||||||
|
} catch (err) {
|
||||||
|
// With cached rows on screen a failed revalidation stays silent.
|
||||||
|
if (seq === fetchSeq.current && !cached) setError(err.message || 'Failed to load devices.')
|
||||||
|
} finally {
|
||||||
|
if (seq === fetchSeq.current) {
|
||||||
|
setLoading(false)
|
||||||
|
setRefreshing(false)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}, [search, onlineFilter, tierFilter])
|
}, [search, onlineFilter, tierFilter])
|
||||||
|
|
||||||
@@ -473,6 +505,12 @@ export default function DeviceList() {
|
|||||||
},
|
},
|
||||||
})
|
})
|
||||||
|
|
||||||
|
// Keep the cache in step with live heartbeats, so the next visit (or the
|
||||||
|
// detail page) starts from the freshest status this tab has seen.
|
||||||
|
useEffect(() => {
|
||||||
|
if (mqttLoaded) setCachedStatusMap(mqttStatusMap)
|
||||||
|
}, [mqttStatusMap, mqttLoaded])
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
setPage(1)
|
setPage(1)
|
||||||
}, [search, onlineFilter, tierFilter, subscrStatusFilter, warrantyStatusFilter, hasClockFilter, hasBellsFilter])
|
}, [search, onlineFilter, tierFilter, subscrStatusFilter, warrantyStatusFilter, hasClockFilter, hasBellsFilter])
|
||||||
@@ -713,6 +751,16 @@ export default function DeviceList() {
|
|||||||
: undefined
|
: undefined
|
||||||
}
|
}
|
||||||
>
|
>
|
||||||
|
{refreshing && !loading && (
|
||||||
|
<span
|
||||||
|
role="status"
|
||||||
|
title="Fetching fresh data — showing last-known values meanwhile"
|
||||||
|
style={{ display: 'inline-flex', alignItems: 'center', gap: 'var(--space-2)', color: 'var(--color-text-muted)', fontSize: 'var(--font-size-xs)' }}
|
||||||
|
>
|
||||||
|
<Spinner size="sm" />
|
||||||
|
Syncing…
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
<Button variant="secondary" icon={<Icon name="warning" size={14} />} onClick={() => navigate('/devices/crashes')}>
|
<Button variant="secondary" icon={<Icon name="warning" size={14} />} onClick={() => navigate('/devices/crashes')}>
|
||||||
Crash Report
|
Crash Report
|
||||||
</Button>
|
</Button>
|
||||||
|
|||||||
@@ -2,12 +2,16 @@
|
|||||||
// 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, useMemo } 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'
|
||||||
import Icon from '@/components/ui/Icon'
|
import Icon from '@/components/ui/Icon'
|
||||||
import ConfirmDialog from '@/components/ui/ConfirmDialog'
|
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 certificationImg from '@/assets/striker-mechanisms/certification.png'
|
||||||
import strikerSize1 from '@/assets/striker-mechanisms/size-1.jpg'
|
import strikerSize1 from '@/assets/striker-mechanisms/size-1.jpg'
|
||||||
@@ -280,75 +284,52 @@ export default function BellsTab({
|
|||||||
const [requestingCounters, setRequestingCounters] = useState(false)
|
const [requestingCounters, setRequestingCounters] = useState(false)
|
||||||
const [liveCounters] = useState(null)
|
const [liveCounters] = useState(null)
|
||||||
const [confirmDisable, setConfirmDisable] = useState(false)
|
const [confirmDisable, setConfirmDisable] = useState(false)
|
||||||
|
const [showConflict, setShowConflict] = 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, or by the user
|
||||||
|
// resolving a console-vs-device conflict below.
|
||||||
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 ──
|
// ── Console vs device: read the device's stored bell config (read-only) ──
|
||||||
// Fires at most once per mount (hasSyncedRef guard — belt-and-suspenders
|
const readBells = useCallback(
|
||||||
// against StrictMode's double-invoke or any parent re-render retriggering
|
() => sendMqttCommandSilent('bells.get_config').then((r) => r?.data || {}),
|
||||||
// this effect). Reconciles bells_enabled/durations/outputs against Firestore
|
[sendMqttCommandSilent]
|
||||||
// and silently corrects any drift — no toast, this is a quiet sync.
|
)
|
||||||
const hasSyncedRef = useRef(false)
|
const check = useDeviceConfigCheck({
|
||||||
useEffect(() => {
|
enabled: !!sendMqttCommandSilent && !!device,
|
||||||
if (!sendMqttCommandSilent || !device) return
|
read: readBells,
|
||||||
if (hasSyncedRef.current) return
|
savedKey: JSON.stringify([hasBells, bellOutputs, hammerTimings]),
|
||||||
hasSyncedRef.current = true
|
})
|
||||||
const deviceId = device.id || device.device_id
|
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)
|
||||||
|
|
||||||
sendMqttCommandSilent('bells.get_config').then((reply) => {
|
// Keep Console version: push the saved bells to the device. Firestore already
|
||||||
const data = reply?.data || {}
|
// holds these values, so nothing is written — just re-read to confirm.
|
||||||
const durations = data.durations || {}
|
const keepConsole = async () => {
|
||||||
const outputs = data.outputs || {}
|
if (diffRows.some((r) => r.group === 'bells')) {
|
||||||
const channelCount = Math.max(
|
await sendMqttCommand('relay.set_config', bellPushContents(attr, check.data))
|
||||||
Object.keys(durations).length,
|
}
|
||||||
Object.keys(outputs).length,
|
if (diffRows.some((r) => r.group === 'commander')) {
|
||||||
totalBells,
|
await sendMqttCommand(hasBells ? 'bells.enable' : 'bells.disable')
|
||||||
)
|
}
|
||||||
if (channelCount === 0) return
|
await check.recheck()
|
||||||
|
}
|
||||||
|
|
||||||
// Firmware uses both 0 and 65535 (uint16 "unset") as "no output assigned" —
|
// Keep Device version: write ONLY the differing fields to Firestore.
|
||||||
// treat both as disabled so unconfigured channels are never mistaken for
|
const keepDevice = async () => {
|
||||||
// connected bells.
|
await api.put(`/devices/${device.id || device.device_id}`, {
|
||||||
const isDisabledOutput = (o) => !o || o === 65535
|
device_attributes: mergePatches(diffRows),
|
||||||
|
|
||||||
// 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
|
await (reloadDeviceSilent || loadDevice)?.()
|
||||||
}, [device?.id, device?.device_id])
|
}
|
||||||
|
|
||||||
// Request strike counters via MQTT
|
// Request strike counters via MQTT
|
||||||
const requestStrikeCounters = useCallback(async () => {
|
const requestStrikeCounters = useCallback(async () => {
|
||||||
@@ -394,6 +375,15 @@ export default function BellsTab({
|
|||||||
return (
|
return (
|
||||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-6)', width: '100%', maxWidth: 2000, margin: '0 auto' }}>
|
<div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-6)', width: '100%', maxWidth: 2000, margin: '0 auto' }}>
|
||||||
|
|
||||||
|
{/* ── Console vs device ─────────────────────────────────────────────── */}
|
||||||
|
<ConfigDriftBanner
|
||||||
|
label="Bell configuration"
|
||||||
|
status={check.status}
|
||||||
|
diffCount={diffRows.length}
|
||||||
|
onReview={() => setShowConflict(true)}
|
||||||
|
onRecheck={check.recheck}
|
||||||
|
/>
|
||||||
|
|
||||||
{/* ── Status overview bar ───────────────────────────────────────────── */}
|
{/* ── Status overview bar ───────────────────────────────────────────── */}
|
||||||
<div style={{
|
<div style={{
|
||||||
background: 'rgba(28, 32, 38, 0.30)',
|
background: 'rgba(28, 32, 38, 0.30)',
|
||||||
@@ -559,6 +549,16 @@ export default function BellsTab({
|
|||||||
loading={togglingCommander}
|
loading={togglingCommander}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
|
<ConfigConflictModal
|
||||||
|
open={showConflict && diffRows.length > 0}
|
||||||
|
onClose={() => setShowConflict(false)}
|
||||||
|
title="Bell configuration"
|
||||||
|
rows={rows}
|
||||||
|
canEdit={canEdit}
|
||||||
|
onKeepConsole={keepConsole}
|
||||||
|
onKeepDevice={keepDevice}
|
||||||
|
/>
|
||||||
|
|
||||||
</div>
|
</div>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,7 +1,11 @@
|
|||||||
// frontend/src/pages/bellcloud/devices/tabs/ClockTab.jsx
|
// 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 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 Card from '@/components/ui/Card'
|
||||||
import Button from '@/components/ui/Button'
|
import Button from '@/components/ui/Button'
|
||||||
import StatusBadge from '@/components/ui/StatusBadge'
|
import StatusBadge from '@/components/ui/StatusBadge'
|
||||||
@@ -320,97 +324,54 @@ 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])
|
||||||
|
|
||||||
|
// ── 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 ─────────────────────
|
// ── Live time / timezone / NTP / face from the device ─────────────────────
|
||||||
// Replies are matched FIFO, so these go one after another.
|
// Replies are matched FIFO, so these go one after another.
|
||||||
const loadLive = async (parts = ['time', 'tz', 'ntp', 'face']) => {
|
const loadLive = async (parts = ['time', 'tz', 'ntp', 'face']) => {
|
||||||
@@ -560,6 +521,24 @@ export default function ClockTab({
|
|||||||
|
|
||||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-6)', width: '100%', maxWidth: 2000, margin: '0 auto' }}>
|
<div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-6)', width: '100%', maxWidth: 2000, margin: '0 auto' }}>
|
||||||
|
|
||||||
|
{/* ── Console vs device ─────────────────────────────────────────────── */}
|
||||||
|
<ConfigDriftBanner
|
||||||
|
label="Clock configuration"
|
||||||
|
status={check.status}
|
||||||
|
diffCount={diffRows.length}
|
||||||
|
onReview={() => setShowConflict(true)}
|
||||||
|
onRecheck={check.recheck}
|
||||||
|
/>
|
||||||
|
<ConfigConflictModal
|
||||||
|
open={showConflict && diffRows.length > 0}
|
||||||
|
onClose={() => setShowConflict(false)}
|
||||||
|
title="Clock configuration"
|
||||||
|
rows={rows}
|
||||||
|
canEdit={canEdit}
|
||||||
|
onKeepConsole={keepConsole}
|
||||||
|
onKeepDevice={keepDevice}
|
||||||
|
/>
|
||||||
|
|
||||||
{/* ── Hero ──────────────────────────────────────────────────────────── */}
|
{/* ── Hero ──────────────────────────────────────────────────────────── */}
|
||||||
<div style={{
|
<div style={{
|
||||||
position: 'relative',
|
position: 'relative',
|
||||||
|
|||||||
@@ -10,6 +10,10 @@ import Icon from '@/components/ui/Icon'
|
|||||||
import FormField from '@/components/ui/FormField'
|
import FormField from '@/components/ui/FormField'
|
||||||
import Spinner from '@/components/ui/Spinner'
|
import Spinner from '@/components/ui/Spinner'
|
||||||
import { fmtDateTimeMedium } from '@/lib/formatters'
|
import { fmtDateTimeMedium } from '@/lib/formatters'
|
||||||
|
import ConfigDriftBanner from '@/components/shared/ConfigDriftBanner'
|
||||||
|
import ConfigConflictModal from '@/modals/bellcloud/devices/ConfigConflictModal'
|
||||||
|
import { useDeviceConfigCheck } from '@/hooks/useDeviceConfigCheck'
|
||||||
|
import { buildLogRows, LOG_FIELDS, mergePatches } from '@/lib/deviceConfigDiff'
|
||||||
|
|
||||||
// ─── Constants ────────────────────────────────────────────────────────────────
|
// ─── Constants ────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
@@ -879,11 +883,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 +894,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)
|
||||||
@@ -936,6 +909,38 @@ export default function GeneralTab({
|
|||||||
// 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])
|
||||||
|
|
||||||
|
// ── Console vs device: read the device's stored log levels (read-only) ──
|
||||||
|
const [showLogConflict, setShowLogConflict] = useState(false)
|
||||||
|
const readLogs = useCallback(
|
||||||
|
() => 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
|
// Nearest place
|
||||||
const coords = useMemo(() => parseCoordinates(device?.device_location_coordinates), [device?.device_location_coordinates])
|
const coords = useMemo(() => parseCoordinates(device?.device_location_coordinates), [device?.device_location_coordinates])
|
||||||
|
|
||||||
@@ -997,11 +1002,12 @@ export default function GeneralTab({
|
|||||||
await api.put(`/devices/${id}`, {
|
await api.put(`/devices/${id}`, {
|
||||||
device_attributes: { [LOG_ATTR[field]]: value },
|
device_attributes: { [LOG_ATTR[field]]: value },
|
||||||
})
|
})
|
||||||
|
reloadDeviceSilent?.()
|
||||||
} catch {
|
} catch {
|
||||||
// sendMqttCommand's toast already reported the failure — revert the slider.
|
// sendMqttCommand's toast already reported the failure — revert the slider.
|
||||||
logSetters[field](previous)
|
logSetters[field](previous)
|
||||||
}
|
}
|
||||||
}, [id, serialLevel, sdLevel, mqttLevel, canEdit, sendMqttCommand, logSetters])
|
}, [id, serialLevel, sdLevel, mqttLevel, canEdit, sendMqttCommand, logSetters, reloadDeviceSilent])
|
||||||
|
|
||||||
// ── Network fields ─────────────────────────────────────────────────────────
|
// ── Network fields ─────────────────────────────────────────────────────────
|
||||||
// Populated live from network.info — read-only, reported directly by the device.
|
// Populated live from network.info — read-only, reported directly by the device.
|
||||||
@@ -1233,6 +1239,22 @@ export default function GeneralTab({
|
|||||||
fullHeight
|
fullHeight
|
||||||
>
|
>
|
||||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-6)', flex: 1, justifyContent: 'center' }}>
|
<div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-6)', flex: 1, justifyContent: 'center' }}>
|
||||||
|
<ConfigDriftBanner
|
||||||
|
label="Log levels"
|
||||||
|
status={logCheck.status}
|
||||||
|
diffCount={logDiffRows.length}
|
||||||
|
onReview={() => setShowLogConflict(true)}
|
||||||
|
onRecheck={logCheck.recheck}
|
||||||
|
/>
|
||||||
|
<ConfigConflictModal
|
||||||
|
open={showLogConflict && logDiffRows.length > 0}
|
||||||
|
onClose={() => setShowLogConflict(false)}
|
||||||
|
title="Log levels"
|
||||||
|
rows={logRows}
|
||||||
|
canEdit={canEdit}
|
||||||
|
onKeepConsole={keepConsoleLogs}
|
||||||
|
onKeepDevice={keepDeviceLogs}
|
||||||
|
/>
|
||||||
<LogSlider
|
<LogSlider
|
||||||
label="Serial Log"
|
label="Serial Log"
|
||||||
level={serialLevel}
|
level={serialLevel}
|
||||||
|
|||||||
@@ -10,6 +10,7 @@
|
|||||||
|
|
||||||
import { useState, useEffect, useCallback, useMemo } from 'react'
|
import { useState, useEffect, useCallback, useMemo } from 'react'
|
||||||
import api from '@/lib/api'
|
import api from '@/lib/api'
|
||||||
|
import { getCachedHealth, setCachedHealth } from '@/lib/deviceCache'
|
||||||
import Card from '@/components/ui/Card'
|
import Card from '@/components/ui/Card'
|
||||||
import StatusBadge from '@/components/ui/StatusBadge'
|
import StatusBadge from '@/components/ui/StatusBadge'
|
||||||
import Spinner from '@/components/ui/Spinner'
|
import Spinner from '@/components/ui/Spinner'
|
||||||
@@ -292,18 +293,42 @@ function StatusIcon({ status }) {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ─── Firmware version + OTA badge ──────────────────────────────────────────
|
||||||
|
// The running version comes from the latest HEARTBEAT (every 30s, and pushed
|
||||||
|
// live over the WebSocket), not the diagnostics report. Diagnostics arrive
|
||||||
|
// only every 5 minutes — the first one 5 min after boot — and this tab
|
||||||
|
// doesn't re-fetch them while open, so right after an OTA the report still
|
||||||
|
// described the old firmware and the tile lagged behind. Both carry the same
|
||||||
|
// compiled FW_VERSION on the device, so the heartbeat is simply fresher.
|
||||||
|
// The OTA "update available" flag only exists in diagnostics, so it's shown
|
||||||
|
// only when that report describes the firmware that is running now.
|
||||||
|
|
||||||
|
const normFw = v => (v ? String(v).trim().replace(/^v/i, '') : '')
|
||||||
|
|
||||||
|
function firmwareSummary(mqttStatus, latestDiag) {
|
||||||
|
const hbFw = normFw(mqttStatus?.last_heartbeat?.firmware_version)
|
||||||
|
const diagFw = normFw(latestDiag?.ota_current_version)
|
||||||
|
const current = hbFw || diagFw
|
||||||
|
if (!latestDiag) return { current, badge: null }
|
||||||
|
if (!hbFw || !diagFw || hbFw === diagFw) {
|
||||||
|
return {
|
||||||
|
current,
|
||||||
|
badge: latestDiag.ota_update_available
|
||||||
|
? { variant: 'warning', label: 'update available' }
|
||||||
|
: { variant: 'success', label: 'up to date' },
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Firmware changed since the last report. If it moved to the version that
|
||||||
|
// report said was available, the update has been applied.
|
||||||
|
if (normFw(latestDiag.ota_available_version) === hbFw) {
|
||||||
|
return { current, badge: { variant: 'success', label: 'up to date' } }
|
||||||
|
}
|
||||||
|
return { current, badge: { variant: 'neutral', label: 'OTA status pending' } }
|
||||||
|
}
|
||||||
|
|
||||||
// ─── Health overview sub-tab (stats + charts + boot history) ───────────────
|
// ─── Health overview sub-tab (stats + charts + boot history) ───────────────
|
||||||
|
|
||||||
function HealthOverview({ sn, mqttStatus, range, offlineTimeoutSec, healthSettings, isOnline, sendMqttCommand }) {
|
function HealthOverview({ sn, mqttStatus, range, offlineTimeoutSec, healthSettings, isOnline, sendMqttCommand }) {
|
||||||
const [bootEvents, setBootEvents] = useState([])
|
|
||||||
const [heartbeats, setHeartbeats] = useState([])
|
|
||||||
const [pingSamples, setPingSamples] = useState([])
|
|
||||||
const [diagReports, setDiagReports] = useState([])
|
|
||||||
const [loading, setLoading] = useState(true)
|
|
||||||
const [error, setError] = useState('')
|
|
||||||
const [expandedId, setExpandedId] = useState(null)
|
|
||||||
const [syncing, setSyncing] = useState(false)
|
|
||||||
|
|
||||||
const rangeParams = useMemo(() => {
|
const rangeParams = useMemo(() => {
|
||||||
const p = new URLSearchParams()
|
const p = new URLSearchParams()
|
||||||
if (range.since) p.set('since', range.since.toISOString())
|
if (range.since) p.set('since', range.since.toISOString())
|
||||||
@@ -311,9 +336,33 @@ function HealthOverview({ sn, mqttStatus, range, offlineTimeoutSec, healthSettin
|
|||||||
return p.toString()
|
return p.toString()
|
||||||
}, [range])
|
}, [range])
|
||||||
|
|
||||||
|
// Cache key: presets are relative ("last 7d"), so key them by name — the
|
||||||
|
// exact `since` timestamp shifts on every resolve. Custom ranges are exact.
|
||||||
|
const cacheKey = `${sn}|${range.key === 'custom' ? rangeParams : range.key}`
|
||||||
|
|
||||||
|
const [bootEvents, setBootEvents] = useState(() => getCachedHealth(cacheKey)?.bootEvents || [])
|
||||||
|
const [heartbeats, setHeartbeats] = useState(() => getCachedHealth(cacheKey)?.heartbeats || [])
|
||||||
|
const [pingSamples, setPingSamples] = useState(() => getCachedHealth(cacheKey)?.pingSamples || [])
|
||||||
|
const [diagReports, setDiagReports] = useState(() => getCachedHealth(cacheKey)?.diagReports || [])
|
||||||
|
const [loading, setLoading] = useState(() => !getCachedHealth(cacheKey))
|
||||||
|
const [error, setError] = useState('')
|
||||||
|
const [expandedId, setExpandedId] = useState(null)
|
||||||
|
const [syncing, setSyncing] = useState(false)
|
||||||
|
|
||||||
|
// Stale-while-revalidate: last-known datasets for this device + range
|
||||||
|
// render immediately; the full-section spinner only shows on a cold load.
|
||||||
const load = useCallback(async () => {
|
const load = useCallback(async () => {
|
||||||
if (!sn) return
|
if (!sn) return
|
||||||
setLoading(true)
|
const prior = getCachedHealth(cacheKey)
|
||||||
|
if (prior) {
|
||||||
|
setBootEvents(prior.bootEvents)
|
||||||
|
setHeartbeats(prior.heartbeats)
|
||||||
|
setPingSamples(prior.pingSamples)
|
||||||
|
setDiagReports(prior.diagReports)
|
||||||
|
setLoading(false)
|
||||||
|
} else {
|
||||||
|
setLoading(true)
|
||||||
|
}
|
||||||
setError('')
|
setError('')
|
||||||
try {
|
try {
|
||||||
const suffix = rangeParams ? `&${rangeParams}` : ''
|
const suffix = rangeParams ? `&${rangeParams}` : ''
|
||||||
@@ -323,16 +372,23 @@ function HealthOverview({ sn, mqttStatus, range, offlineTimeoutSec, healthSettin
|
|||||||
api.get(`/mqtt/ping-samples/${sn}?limit=5000${suffix}`),
|
api.get(`/mqtt/ping-samples/${sn}?limit=5000${suffix}`),
|
||||||
api.get(`/mqtt/diagnostics-reports/${sn}?limit=5000${suffix}`),
|
api.get(`/mqtt/diagnostics-reports/${sn}?limit=5000${suffix}`),
|
||||||
])
|
])
|
||||||
setBootEvents(bootRes.events || [])
|
const next = {
|
||||||
setHeartbeats(hbRes.heartbeats || [])
|
bootEvents: bootRes.events || [],
|
||||||
setPingSamples(pingRes.samples || [])
|
heartbeats: hbRes.heartbeats || [],
|
||||||
setDiagReports(diagRes.reports || [])
|
pingSamples: pingRes.samples || [],
|
||||||
|
diagReports: diagRes.reports || [],
|
||||||
|
}
|
||||||
|
setCachedHealth(cacheKey, next)
|
||||||
|
setBootEvents(next.bootEvents)
|
||||||
|
setHeartbeats(next.heartbeats)
|
||||||
|
setPingSamples(next.pingSamples)
|
||||||
|
setDiagReports(next.diagReports)
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
setError(err.message || 'Failed to load device health data.')
|
if (!prior) setError(err.message || 'Failed to load device health data.')
|
||||||
} finally {
|
} finally {
|
||||||
setLoading(false)
|
setLoading(false)
|
||||||
}
|
}
|
||||||
}, [sn, rangeParams])
|
}, [sn, rangeParams, cacheKey])
|
||||||
|
|
||||||
useEffect(() => { load() }, [load])
|
useEffect(() => { load() }, [load])
|
||||||
|
|
||||||
@@ -371,6 +427,7 @@ function HealthOverview({ sn, mqttStatus, range, offlineTimeoutSec, healthSettin
|
|||||||
|
|
||||||
const latestBoot = bootEvents[0] || null
|
const latestBoot = bootEvents[0] || null
|
||||||
const latestDiag = diagReports[0] || null
|
const latestDiag = diagReports[0] || null
|
||||||
|
const fw = firmwareSummary(mqttStatus, latestDiag)
|
||||||
const restartsInRange = bootEvents.length
|
const restartsInRange = bootEvents.length
|
||||||
const rangeLabelShort = range.key === 'all' ? 'all-time' : (
|
const rangeLabelShort = range.key === 'all' ? 'all-time' : (
|
||||||
range.key === 'custom' ? 'custom range' :
|
range.key === 'custom' ? 'custom range' :
|
||||||
@@ -513,13 +570,11 @@ function HealthOverview({ sn, mqttStatus, range, offlineTimeoutSec, healthSettin
|
|||||||
/>
|
/>
|
||||||
<MetricTile label="Firmware / OTA">
|
<MetricTile label="Firmware / OTA">
|
||||||
<span style={{ fontFamily: 'var(--font-family-mono)', fontSize: '1rem', fontWeight: 'var(--font-weight-semibold)', color: 'var(--color-text-primary)' }}>
|
<span style={{ fontFamily: 'var(--font-family-mono)', fontSize: '1rem', fontWeight: 'var(--font-weight-semibold)', color: 'var(--color-text-primary)' }}>
|
||||||
{latestDiag?.ota_current_version ? `v${latestDiag.ota_current_version}` : '—'}
|
{fw.current ? `v${fw.current}` : '—'}
|
||||||
</span>
|
</span>
|
||||||
{latestDiag && (
|
{fw.badge && (
|
||||||
<div style={{ marginTop: 2 }}>
|
<div style={{ marginTop: 2 }}>
|
||||||
<StatusBadge variant={latestDiag.ota_update_available ? 'warning' : 'success'} size="sm">
|
<StatusBadge variant={fw.badge.variant} size="sm">{fw.badge.label}</StatusBadge>
|
||||||
{latestDiag.ota_update_available ? 'update available' : 'up to date'}
|
|
||||||
</StatusBadge>
|
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</MetricTile>
|
</MetricTile>
|
||||||
@@ -911,7 +966,7 @@ function useHeaderStatus(sn, healthSettings, mqttStatus) {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
export default function HealthTab({ device, sn, mqttStatus, isOnline, sendMqttCommand }) {
|
export default function HealthTab({ device, sn, mqttStatus, isOnline, sendMqttCommand, canEdit }) {
|
||||||
const [subTab, setSubTab] = useState('overview')
|
const [subTab, setSubTab] = useState('overview')
|
||||||
const [range, setRange] = useState(() => resolveRange('7d'))
|
const [range, setRange] = useState(() => resolveRange('7d'))
|
||||||
// Local override after a successful save, so the Settings form and offline-
|
// Local override after a successful save, so the Settings form and offline-
|
||||||
@@ -951,7 +1006,7 @@ export default function HealthTab({ device, sn, mqttStatus, isOnline, sendMqttCo
|
|||||||
{subTab === 'overview' && (
|
{subTab === 'overview' && (
|
||||||
<HealthOverview sn={sn} mqttStatus={mqttStatus} range={range} offlineTimeoutSec={offlineTimeoutSec} healthSettings={healthSettings} isOnline={isOnline} sendMqttCommand={sendMqttCommand} />
|
<HealthOverview sn={sn} mqttStatus={mqttStatus} range={range} offlineTimeoutSec={offlineTimeoutSec} healthSettings={healthSettings} isOnline={isOnline} sendMqttCommand={sendMqttCommand} />
|
||||||
)}
|
)}
|
||||||
{subTab === 'logs' && <LogsTab sn={sn} range={range} />}
|
{subTab === 'logs' && <LogsTab sn={sn} range={range} deviceId={device?.id} canEdit={canEdit} />}
|
||||||
{subTab === 'settings' && (
|
{subTab === 'settings' && (
|
||||||
<HealthSettings deviceId={device?.id} settings={healthSettings} onSaved={setSavedOverride} />
|
<HealthSettings deviceId={device?.id} settings={healthSettings} onSaved={setSavedOverride} />
|
||||||
)}
|
)}
|
||||||
|
|||||||
@@ -7,9 +7,15 @@ import api from '@/lib/api'
|
|||||||
import Spinner from '@/components/ui/Spinner'
|
import Spinner from '@/components/ui/Spinner'
|
||||||
import StatusBadge from '@/components/ui/StatusBadge'
|
import StatusBadge from '@/components/ui/StatusBadge'
|
||||||
import Pagination from '@/components/ui/Pagination'
|
import Pagination from '@/components/ui/Pagination'
|
||||||
import { fmtDateTimeMedium, fmtRelative, fmtLogTimestamp } from '@/lib/formatters'
|
import Button from '@/components/ui/Button'
|
||||||
|
import Icon from '@/components/ui/Icon'
|
||||||
|
import DeleteDeviceLogsModal from '@/modals/bellcloud/devices/DeleteDeviceLogsModal'
|
||||||
|
import { fmtDateTimeMedium, fmtRelative, fmtLogTimestamp, fmtTime24 } from '@/lib/formatters'
|
||||||
import { useMqttWebSocket } from '@/hooks/useMqttWebSocket'
|
import { useMqttWebSocket } from '@/hooks/useMqttWebSocket'
|
||||||
|
|
||||||
|
// Rows timestamped before the "Clear view" point are hidden (view-only).
|
||||||
|
const afterClear = (clearedAt, ts) => !clearedAt || (ts && new Date(ts) >= clearedAt)
|
||||||
|
|
||||||
// ─── Glass surface tokens (match Overview / Control tab aesthetic) ────────────
|
// ─── Glass surface tokens (match Overview / Control tab aesthetic) ────────────
|
||||||
|
|
||||||
const GLASS = 'rgba(28, 32, 38, 0.30)'
|
const GLASS = 'rgba(28, 32, 38, 0.30)'
|
||||||
@@ -474,7 +480,7 @@ function TextLogPanel({ sn, source, liveTypes, channel, onChannelChange, range }
|
|||||||
|
|
||||||
// ─── Unified feed (Device Logs + Info + Alerts merged, chronological) ────────
|
// ─── Unified feed (Device Logs + Info + Alerts merged, chronological) ────────
|
||||||
|
|
||||||
function UnifiedPanel({ sn, channel, onChannelChange, range }) {
|
function UnifiedPanel({ sn, channel, onChannelChange, range, clearedAt }) {
|
||||||
const [logRows, setLogRows] = useState([])
|
const [logRows, setLogRows] = useState([])
|
||||||
const [alertRows, setAlertRows] = useState([])
|
const [alertRows, setAlertRows] = useState([])
|
||||||
const [initialLoading, setInitialLoading] = useState(true)
|
const [initialLoading, setInitialLoading] = useState(true)
|
||||||
@@ -559,11 +565,13 @@ function UnifiedPanel({ sn, channel, onChannelChange, range }) {
|
|||||||
|
|
||||||
const merged = useMemo(() => {
|
const merged = useMemo(() => {
|
||||||
const logEntries = logRows.map(l => ({ _kind: 'log', source: l.source || 'log', ...l }))
|
const logEntries = logRows.map(l => ({ _kind: 'log', source: l.source || 'log', ...l }))
|
||||||
const alertEntries = alertRows.map(a => ({ _kind: 'alert', source: 'alert', ...a, received_at: a.occurred_at }))
|
const alertEntries = alertRows
|
||||||
|
.filter(a => afterClear(clearedAt, a.occurred_at))
|
||||||
|
.map(a => ({ _kind: 'alert', source: 'alert', ...a, received_at: a.occurred_at }))
|
||||||
const combined = [...logEntries, ...alertEntries]
|
const combined = [...logEntries, ...alertEntries]
|
||||||
combined.sort((a, b) => new Date(b.received_at) - new Date(a.received_at))
|
combined.sort((a, b) => new Date(b.received_at) - new Date(a.received_at))
|
||||||
return combined
|
return combined
|
||||||
}, [logRows, alertRows])
|
}, [logRows, alertRows, clearedAt])
|
||||||
|
|
||||||
const liveFiltered = liveRows.filter(l => {
|
const liveFiltered = liveRows.filter(l => {
|
||||||
if (l._kind === 'alert') return true
|
if (l._kind === 'alert') return true
|
||||||
@@ -678,8 +686,9 @@ function UnifiedPanel({ sn, channel, onChannelChange, range }) {
|
|||||||
|
|
||||||
// ─── Alerts history panel ─────────────────────────────────────────────────────
|
// ─── Alerts history panel ─────────────────────────────────────────────────────
|
||||||
|
|
||||||
function AlertsPanel({ sn, channel, onChannelChange }) {
|
function AlertsPanel({ sn, channel, onChannelChange, clearedAt }) {
|
||||||
const [rows, setRows] = useState([])
|
const [allRows, setRows] = useState([])
|
||||||
|
const rows = allRows.filter(r => afterClear(clearedAt, r.occurred_at))
|
||||||
const [total, setTotal] = useState(0)
|
const [total, setTotal] = useState(0)
|
||||||
const [initialLoading, setInitialLoading] = useState(true)
|
const [initialLoading, setInitialLoading] = useState(true)
|
||||||
const [page, setPage] = useState(1)
|
const [page, setPage] = useState(1)
|
||||||
@@ -750,7 +759,7 @@ function AlertsPanel({ sn, channel, onChannelChange }) {
|
|||||||
</tbody>
|
</tbody>
|
||||||
</table>
|
</table>
|
||||||
</div>
|
</div>
|
||||||
{total > PAGE_SIZE && (
|
{total > PAGE_SIZE && !clearedAt && (
|
||||||
<div style={{ padding: 'var(--space-4) var(--space-5)', borderTop: '1px solid var(--color-border)' }}>
|
<div style={{ padding: 'var(--space-4) var(--space-5)', borderTop: '1px solid var(--color-border)' }}>
|
||||||
<Pagination page={page} pageSize={PAGE_SIZE} total={total} onPageChange={setPage} />
|
<Pagination page={page} pageSize={PAGE_SIZE} total={total} onPageChange={setPage} />
|
||||||
</div>
|
</div>
|
||||||
@@ -761,8 +770,9 @@ function AlertsPanel({ sn, channel, onChannelChange }) {
|
|||||||
|
|
||||||
// ─── Heartbeats panel ─────────────────────────────────────────────────────────
|
// ─── Heartbeats panel ─────────────────────────────────────────────────────────
|
||||||
|
|
||||||
function HeartbeatsPanel({ sn, channel, onChannelChange }) {
|
function HeartbeatsPanel({ sn, channel, onChannelChange, clearedAt }) {
|
||||||
const [rows, setRows] = useState([])
|
const [allRows, setRows] = useState([])
|
||||||
|
const rows = allRows.filter(r => afterClear(clearedAt, r.received_at))
|
||||||
const [total, setTotal] = useState(0)
|
const [total, setTotal] = useState(0)
|
||||||
const [initialLoading, setInitialLoading] = useState(true)
|
const [initialLoading, setInitialLoading] = useState(true)
|
||||||
const [page, setPage] = useState(1)
|
const [page, setPage] = useState(1)
|
||||||
@@ -835,7 +845,7 @@ function HeartbeatsPanel({ sn, channel, onChannelChange }) {
|
|||||||
</tbody>
|
</tbody>
|
||||||
</table>
|
</table>
|
||||||
</div>
|
</div>
|
||||||
{total > PAGE_SIZE && (
|
{total > PAGE_SIZE && !clearedAt && (
|
||||||
<div style={{ padding: 'var(--space-4) var(--space-5)', borderTop: '1px solid var(--color-border)' }}>
|
<div style={{ padding: 'var(--space-4) var(--space-5)', borderTop: '1px solid var(--color-border)' }}>
|
||||||
<Pagination page={page} pageSize={PAGE_SIZE} total={total} onPageChange={setPage} />
|
<Pagination page={page} pageSize={PAGE_SIZE} total={total} onPageChange={setPage} />
|
||||||
</div>
|
</div>
|
||||||
@@ -853,8 +863,9 @@ const COMMAND_STATUS_VARIANT = {
|
|||||||
timeout: 'danger',
|
timeout: 'danger',
|
||||||
}
|
}
|
||||||
|
|
||||||
function CommandsPanel({ sn, channel, onChannelChange }) {
|
function CommandsPanel({ sn, channel, onChannelChange, clearedAt }) {
|
||||||
const [rows, setRows] = useState([])
|
const [allRows, setRows] = useState([])
|
||||||
|
const rows = allRows.filter(r => afterClear(clearedAt, r.sent_at))
|
||||||
const [total, setTotal] = useState(0)
|
const [total, setTotal] = useState(0)
|
||||||
const [initialLoading, setInitialLoading] = useState(true)
|
const [initialLoading, setInitialLoading] = useState(true)
|
||||||
const [page, setPage] = useState(1)
|
const [page, setPage] = useState(1)
|
||||||
@@ -924,7 +935,7 @@ function CommandsPanel({ sn, channel, onChannelChange }) {
|
|||||||
</tbody>
|
</tbody>
|
||||||
</table>
|
</table>
|
||||||
</div>
|
</div>
|
||||||
{total > PAGE_SIZE && (
|
{total > PAGE_SIZE && !clearedAt && (
|
||||||
<div style={{ padding: 'var(--space-4) var(--space-5)', borderTop: '1px solid var(--color-border)' }}>
|
<div style={{ padding: 'var(--space-4) var(--space-5)', borderTop: '1px solid var(--color-border)' }}>
|
||||||
<Pagination page={page} pageSize={PAGE_SIZE} total={total} onPageChange={setPage} />
|
<Pagination page={page} pageSize={PAGE_SIZE} total={total} onPageChange={setPage} />
|
||||||
</div>
|
</div>
|
||||||
@@ -935,31 +946,87 @@ function CommandsPanel({ sn, channel, onChannelChange }) {
|
|||||||
|
|
||||||
// ─── LogsTab ──────────────────────────────────────────────────────────────────
|
// ─── LogsTab ──────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
export default function LogsTab({ sn, range }) {
|
export default function LogsTab({ sn, range, deviceId, canEdit }) {
|
||||||
const [channel, setChannel] = useState('unified')
|
const [channel, setChannel] = useState('unified')
|
||||||
|
// "Clear" is view-only: hide everything received before this moment so
|
||||||
|
// only fresh entries show. Nothing is deleted — "Show all" brings it back.
|
||||||
|
const [clearedAt, setClearedAt] = useState(null)
|
||||||
|
// Bumped on clear / show-all / delete to remount the active panel, which
|
||||||
|
// drops its buffered live rows and refetches from scratch.
|
||||||
|
const [viewEpoch, setViewEpoch] = useState(0)
|
||||||
|
const [showDelete, setShowDelete] = useState(false)
|
||||||
|
|
||||||
|
// Text-log channels filter server-side: the clear point simply becomes the
|
||||||
|
// range's lower bound (whichever is later).
|
||||||
|
const effectiveRange = useMemo(() => {
|
||||||
|
if (!clearedAt) return range
|
||||||
|
const since = range?.since && range.since > clearedAt ? range.since : clearedAt
|
||||||
|
return { ...range, since }
|
||||||
|
}, [range, clearedAt])
|
||||||
|
|
||||||
|
const clearView = () => { setClearedAt(new Date()); setViewEpoch(e => e + 1) }
|
||||||
|
const showAll = () => { setClearedAt(null); setViewEpoch(e => e + 1) }
|
||||||
|
|
||||||
|
const panelKey = `${channel}-${viewEpoch}`
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-6)', width: '100%', maxWidth: 2000, margin: '0 auto' }}>
|
<div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-4)', width: '100%', maxWidth: 2000, margin: '0 auto' }}>
|
||||||
|
{sn && (
|
||||||
|
<div style={{ display: 'flex', alignItems: 'center', gap: 'var(--space-3)', flexWrap: 'wrap' }}>
|
||||||
|
{clearedAt ? (
|
||||||
|
<span style={{ fontSize: 'var(--font-size-xs)', color: 'var(--color-text-muted)' }}>
|
||||||
|
View cleared at <span style={{ fontFamily: 'var(--font-family-mono)', color: 'var(--color-text-secondary)' }}>{fmtTime24(clearedAt)}</span> — showing only newer entries.
|
||||||
|
</span>
|
||||||
|
) : (
|
||||||
|
<span style={{ fontSize: 'var(--font-size-xs)', color: 'var(--color-text-muted)' }}>
|
||||||
|
Clear the view to watch only fresh entries. Nothing is deleted.
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
<div style={{ flex: 1 }} />
|
||||||
|
{clearedAt && (
|
||||||
|
<Button variant="ghost" size="sm" onClick={showAll}>Show all</Button>
|
||||||
|
)}
|
||||||
|
<Button variant="secondary" size="sm" icon={<Icon name="refresh" size={13} />} onClick={clearView}>
|
||||||
|
{clearedAt ? 'Clear again' : 'Clear view'}
|
||||||
|
</Button>
|
||||||
|
{canEdit && deviceId && (
|
||||||
|
<Button variant="danger" size="sm" icon={<Icon name="delete" size={13} />} onClick={() => setShowDelete(true)}>
|
||||||
|
Delete logs…
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
<GlassCard style={{ overflow: 'hidden' }}>
|
<GlassCard style={{ overflow: 'hidden' }}>
|
||||||
{!sn ? (
|
{!sn ? (
|
||||||
<div style={{ padding: 'var(--space-8)', textAlign: 'center', color: 'var(--color-text-muted)', fontSize: 'var(--font-size-sm)', fontStyle: 'italic' }}>
|
<div style={{ padding: 'var(--space-8)', textAlign: 'center', color: 'var(--color-text-muted)', fontSize: 'var(--font-size-sm)', fontStyle: 'italic' }}>
|
||||||
No serial number available for this device.
|
No serial number available for this device.
|
||||||
</div>
|
</div>
|
||||||
) : channel === 'unified' ? (
|
) : channel === 'unified' ? (
|
||||||
<UnifiedPanel sn={sn} channel={channel} onChannelChange={setChannel} range={range} />
|
<UnifiedPanel key={panelKey} sn={sn} channel={channel} onChannelChange={setChannel} range={effectiveRange} clearedAt={clearedAt} />
|
||||||
) : channel === 'log' ? (
|
) : channel === 'log' ? (
|
||||||
<TextLogPanel sn={sn} source="log" liveTypes={['system/logs']} channel={channel} onChannelChange={setChannel} range={range} />
|
<TextLogPanel key={panelKey} sn={sn} source="log" liveTypes={['system/logs']} channel={channel} onChannelChange={setChannel} range={effectiveRange} />
|
||||||
) : channel === 'info' ? (
|
) : channel === 'info' ? (
|
||||||
<TextLogPanel sn={sn} source="info" liveTypes={['system/info']} channel={channel} onChannelChange={setChannel} range={range} />
|
<TextLogPanel key={panelKey} sn={sn} source="info" liveTypes={['system/info']} channel={channel} onChannelChange={setChannel} range={effectiveRange} />
|
||||||
) : channel === 'alerts' ? (
|
) : channel === 'alerts' ? (
|
||||||
<AlertsPanel sn={sn} channel={channel} onChannelChange={setChannel} />
|
<AlertsPanel key={panelKey} sn={sn} channel={channel} onChannelChange={setChannel} clearedAt={clearedAt} />
|
||||||
) : channel === 'heartbeats' ? (
|
) : channel === 'heartbeats' ? (
|
||||||
<HeartbeatsPanel sn={sn} channel={channel} onChannelChange={setChannel} />
|
<HeartbeatsPanel key={panelKey} sn={sn} channel={channel} onChannelChange={setChannel} clearedAt={clearedAt} />
|
||||||
) : (
|
) : (
|
||||||
<CommandsPanel sn={sn} channel={channel} onChannelChange={setChannel} />
|
<CommandsPanel key={panelKey} sn={sn} channel={channel} onChannelChange={setChannel} clearedAt={clearedAt} />
|
||||||
)}
|
)}
|
||||||
</GlassCard>
|
</GlassCard>
|
||||||
|
|
||||||
|
{canEdit && deviceId && (
|
||||||
|
<DeleteDeviceLogsModal
|
||||||
|
open={showDelete}
|
||||||
|
onClose={() => setShowDelete(false)}
|
||||||
|
onDeleted={() => setViewEpoch(e => e + 1)}
|
||||||
|
deviceId={deviceId}
|
||||||
|
serial={sn}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
|
||||||
<style>{`
|
<style>{`
|
||||||
@keyframes logstab-pulse {
|
@keyframes logstab-pulse {
|
||||||
0%, 100% { opacity: 1; }
|
0%, 100% { opacity: 1; }
|
||||||
|
|||||||
@@ -117,6 +117,28 @@ function FirmwareFormModal({ initial, onClose, onSaved }) {
|
|||||||
const [error, setError] = useState('')
|
const [error, setError] = useState('')
|
||||||
const fileInputRef = useRef(null)
|
const fileInputRef = useRef(null)
|
||||||
const elfInputRef = useRef(null)
|
const elfInputRef = useRef(null)
|
||||||
|
// Min FW on a new upload defaults to whatever the previous release for the
|
||||||
|
// same board carried — an upgrade-chain floor rarely changes between
|
||||||
|
// releases. Re-derived when board/channel change, until the user edits it.
|
||||||
|
const minFwTouched = useRef(false)
|
||||||
|
const [minFwSource, setMinFwSource] = useState(null) // release the default came from
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (isEdit || minFwTouched.current) return
|
||||||
|
if (hwType === 'bespoke' && !bespokeUid.trim()) return
|
||||||
|
let cancelled = false
|
||||||
|
api.get(`/firmware?hw_type=${encodeURIComponent(hwType)}`).then(data => {
|
||||||
|
if (cancelled || minFwTouched.current) return
|
||||||
|
// Newest first (backend sorts by uploaded_at desc). Prefer the same
|
||||||
|
// channel; fall back to the board's newest release on any channel.
|
||||||
|
const pool = (data?.firmware || []).filter(fw =>
|
||||||
|
hwType !== 'bespoke' || fw.bespoke_uid === bespokeUid.trim())
|
||||||
|
const prev = pool.find(fw => fw.channel === channel) || pool[0] || null
|
||||||
|
setMinFw(prev?.min_fw_version || '')
|
||||||
|
setMinFwSource(prev?.min_fw_version ? prev : null)
|
||||||
|
}).catch(() => { /* no default — field just stays empty */ })
|
||||||
|
return () => { cancelled = true }
|
||||||
|
}, [isEdit, hwType, channel, bespokeUid])
|
||||||
|
|
||||||
const handleSubmit = async (e) => {
|
const handleSubmit = async (e) => {
|
||||||
e.preventDefault()
|
e.preventDefault()
|
||||||
@@ -198,7 +220,10 @@ function FirmwareFormModal({ initial, onClose, onSaved }) {
|
|||||||
{CHANNELS.map((c) => <option key={c} value={c}>{c}</option>)}
|
{CHANNELS.map((c) => <option key={c} value={c}>{c}</option>)}
|
||||||
</FormField>
|
</FormField>
|
||||||
<FormField label="Version" name="version" value={version} onChange={(e) => setVersion(e.target.value)} placeholder="1.5" required />
|
<FormField label="Version" name="version" value={version} onChange={(e) => setVersion(e.target.value)} placeholder="1.5" required />
|
||||||
<FormField label="Min FW" name="min_fw" value={minFw} onChange={(e) => setMinFw(e.target.value)} placeholder="e.g. 1.2" />
|
<FormField label="Min FW" name="min_fw" value={minFw}
|
||||||
|
onChange={(e) => { minFwTouched.current = true; setMinFwSource(null); setMinFw(e.target.value) }}
|
||||||
|
placeholder="e.g. 1.2"
|
||||||
|
hint={minFwSource ? `From v${minFwSource.version} (${minFwSource.channel})` : undefined} />
|
||||||
</div>
|
</div>
|
||||||
<div>
|
<div>
|
||||||
<p style={{ fontSize: 'var(--font-size-xs)', fontWeight: 'var(--font-weight-medium)', color: 'var(--color-text-muted)', marginBottom: 'var(--space-2)' }}>Update Type</p>
|
<p style={{ fontSize: 'var(--font-size-xs)', fontWeight: 'var(--font-weight-medium)', color: 'var(--color-text-muted)', marginBottom: 'var(--space-2)' }}>Update Type</p>
|
||||||
|
|||||||
Reference in New Issue
Block a user