Compare commits
19
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
db22abdb7d | ||
|
|
eff9e72681 | ||
|
|
565aca4d56 | ||
|
|
3636556ae7 | ||
|
|
fb35ace0c7 | ||
|
|
da83f2a1cd | ||
|
|
9deff308b6 | ||
|
|
2e3d7ba062 | ||
|
|
5ab87fa9f0 | ||
|
|
62be80c9d8 | ||
|
|
2a6f9697b8 | ||
|
|
fba5110cc0 | ||
|
|
cdf5fc79a0 | ||
|
|
e4ea43a079 | ||
|
|
8837eb1e70 | ||
|
|
d1799bd3b1 | ||
|
|
ca53d2e871 | ||
|
|
65ff2372ca | ||
|
|
c2767ca7e0 |
@@ -375,6 +375,27 @@ lose (or keep) access to the wrong devices.
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
## Firestore Schema v1 (devices)
|
||||||
|
|
||||||
|
The tablet and phone apps (FlutterFlow) and this console share Firestore. The contract
|
||||||
|
is the `bellsystems-schema` repo (`C:\development\bellsystems-schema`, `v1/firestore.schema.json`).
|
||||||
|
One wrongly typed field makes the apps **silently drop the whole device** from the user's list.
|
||||||
|
|
||||||
|
- Every device write goes through `backend/devices/firestore_v1.py` (`to_firestore`), every
|
||||||
|
read through `to_api`. Never write a device dict to Firestore any other way.
|
||||||
|
- Timestamps: ISO 8601 strings in the API, Firestore Timestamps in the DB. Unset = `null`, never `""`.
|
||||||
|
- IP addresses: dotted strings (`"10.0.0.5"`), never octet arrays. The firmware's
|
||||||
|
`network.set_config` MQTT command has its own names (`useStaticIP`, `ip`) — that's the
|
||||||
|
MQTT protocol, not Firestore.
|
||||||
|
- Key spelling is the apps': `bellguardSafetyOn`, `usesStaticIP`, `maintainancePeriod`.
|
||||||
|
- `device_id` and `serial_number` are always equal (decision D1); `serial_number` is canonical.
|
||||||
|
- Hardware identity is `hw_family` / `hw_revision` — the firmware's NVS names (decision D2).
|
||||||
|
`hw_family` is a code (`vesper_plus`), never a label (`"Bell Plus"`). The firmware *catalog*
|
||||||
|
(`/api/firmware/{hw_type}/…`, flash assets) keeps `hw_type` as its variable name — same values.
|
||||||
|
- Check live data with `node tools/audit.js <service-account.json>` in the schema repo.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
## API Client
|
## API Client
|
||||||
|
|
||||||
```js
|
```js
|
||||||
|
|||||||
@@ -39,6 +39,20 @@ bellsystems-admin/
|
|||||||
└── .env
|
└── .env
|
||||||
```
|
```
|
||||||
|
|
||||||
|
## Shared data contract (Firestore schema v1)
|
||||||
|
|
||||||
|
Firestore is shared with the BellSystems tablet and phone apps (FlutterFlow). Device
|
||||||
|
documents must follow the schema in the **bellsystems-schema** repo
|
||||||
|
(`v1/firestore.schema.json`) — one wrongly typed field makes the apps silently hide the
|
||||||
|
device from its users.
|
||||||
|
|
||||||
|
- All device writes go through `backend/devices/firestore_v1.py`.
|
||||||
|
- Adding or changing a shared field: update the schema repo first, then every app and this
|
||||||
|
console in the same release.
|
||||||
|
- Check production data: `node tools/audit.js <service-account.json>` in the schema repo.
|
||||||
|
|
||||||
|
Details: the "Firestore Schema v1" section of `CLAUDE.md`.
|
||||||
|
|
||||||
## Documentation
|
## Documentation
|
||||||
|
|
||||||
See `BellSystems_AdminPanel_Strategy.md` for the full architecture and build plan.
|
See `BellSystems_AdminPanel_Strategy.md` for the full architecture and build plan.
|
||||||
@@ -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")
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,241 @@
|
|||||||
|
"""Device documents <-> Firestore schema v1.
|
||||||
|
|
||||||
|
The contract lives in the bellsystems-schema repo (v1/firestore.schema.json). v1 is
|
||||||
|
the shape the shipped tablet and phone apps read. FlutterFlow parses each document
|
||||||
|
inside safeGet: ONE field of the wrong type makes the app silently drop the whole
|
||||||
|
device from the user's list. So every console write to a device goes through
|
||||||
|
`to_firestore`, and every read goes through `to_api`.
|
||||||
|
|
||||||
|
Rules enforced here (README "rules every writer must follow"):
|
||||||
|
- Timestamps are Firestore Timestamps (datetime). Unset = None, never "".
|
||||||
|
- IP addresses are dotted strings ("10.0.0.5"), never octet arrays.
|
||||||
|
- Exact v1 key spelling: bellguardSafetyOn, usesStaticIP. The misspellings
|
||||||
|
bellGuardSafetyOn / useStaticIP / users_list are converted or dropped.
|
||||||
|
- device_id and serial_number are equal (decision D1); serial_number is canonical.
|
||||||
|
- device_melodies_all items use the MelodyMainItem shape (mainInformation, ...).
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import re
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from google.cloud.firestore_v1 import DocumentReference, GeoPoint
|
||||||
|
|
||||||
|
from shared.exceptions import ValidationError
|
||||||
|
|
||||||
|
# Keys inside device_attributes (and its nested maps) that hold Timestamps.
|
||||||
|
TIMESTAMP_KEYS = {
|
||||||
|
"towerClockTime",
|
||||||
|
"daySilenceFrom", "daySilenceTo",
|
||||||
|
"nightSilenceFrom", "nightSilenceTo",
|
||||||
|
"backlightTurnOnTime", "backlightTurnOffTime",
|
||||||
|
"subscrStart",
|
||||||
|
"warrantyStart", "maintainedOn",
|
||||||
|
}
|
||||||
|
|
||||||
|
IP_KEYS = {"ipAddress", "gateway", "subnet", "dns1", "dns2"}
|
||||||
|
|
||||||
|
# Misspelled key -> v1 key, per nested map. A value of None means "drop".
|
||||||
|
LEGACY_KEYS: dict[str, dict[str, str | None]] = {
|
||||||
|
# hw_type / hw_version: pre-2026-11-08 names; the firmware NVS uses hw_family / hw_revision.
|
||||||
|
"": {"users_list": None, "hw_type": "hw_family", "hw_version": "hw_revision"},
|
||||||
|
"device_attributes": {"bellGuardSafetyOn": "bellguardSafetyOn"},
|
||||||
|
"device_attributes.networkSettings": {"useStaticIP": "usesStaticIP"},
|
||||||
|
}
|
||||||
|
|
||||||
|
# Shape of a melody stored inside a device (MelodyMainItem) vs. a melodies/{id} doc.
|
||||||
|
_MELODY_ITEM_FORBIDDEN = {"information", "default_settings", "url"}
|
||||||
|
|
||||||
|
# Format the console API used to serve before ISO 8601 ("15 January 2026 at 22:01:00 UTC+0000").
|
||||||
|
# Still accepted on write so a browser tab opened before the deploy can't corrupt data.
|
||||||
|
_LEGACY_DISPLAY_FMT = "%d %B %Y at %H:%M:%S UTC%z"
|
||||||
|
|
||||||
|
# Board family code: a BoardType value ("vesper_plus") or a bespoke UID. Never a display
|
||||||
|
# label like "Bell Plus" — the firmware builds its OTA URL from this value.
|
||||||
|
_HW_FAMILY = re.compile(r"^[a-z0-9][a-z0-9_-]*$")
|
||||||
|
|
||||||
|
_IPV4 = re.compile(r"^(25[0-5]|2[0-4]\d|1?\d?\d)(\.(25[0-5]|2[0-4]\d|1?\d?\d)){3}$")
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------- write side
|
||||||
|
|
||||||
|
|
||||||
|
def to_timestamp(value: Any, field: str) -> datetime | None:
|
||||||
|
"""Coerce an API value into a Firestore Timestamp (tz-aware datetime) or None."""
|
||||||
|
if value is None or value == "":
|
||||||
|
return None
|
||||||
|
if isinstance(value, datetime):
|
||||||
|
return value if value.tzinfo else value.replace(tzinfo=timezone.utc)
|
||||||
|
if isinstance(value, str):
|
||||||
|
s = value.strip()
|
||||||
|
try:
|
||||||
|
dt = datetime.fromisoformat(s.replace("Z", "+00:00"))
|
||||||
|
return dt if dt.tzinfo else dt.replace(tzinfo=timezone.utc)
|
||||||
|
except ValueError:
|
||||||
|
pass
|
||||||
|
try:
|
||||||
|
return datetime.strptime(s, _LEGACY_DISPLAY_FMT)
|
||||||
|
except ValueError:
|
||||||
|
pass
|
||||||
|
raise ValidationError(f"{field}: expected an ISO 8601 timestamp or null, got {value!r}")
|
||||||
|
|
||||||
|
|
||||||
|
def to_ipv4(value: Any, field: str) -> str:
|
||||||
|
"""Coerce an API value into a dotted IPv4 string. "" means not set."""
|
||||||
|
if value is None:
|
||||||
|
return ""
|
||||||
|
if isinstance(value, (list, tuple)):
|
||||||
|
parts = [str(p).strip() for p in value if str(p).strip() != ""]
|
||||||
|
if not parts:
|
||||||
|
return ""
|
||||||
|
value = ".".join(parts)
|
||||||
|
if isinstance(value, str):
|
||||||
|
s = value.strip()
|
||||||
|
if s == "" or _IPV4.match(s):
|
||||||
|
return s
|
||||||
|
raise ValidationError(f"{field}: expected a dotted IPv4 address like \"10.0.0.5\", got {value!r}")
|
||||||
|
|
||||||
|
|
||||||
|
def _normalize_map(data: dict, path: str) -> dict:
|
||||||
|
"""Recursively apply key renames, timestamp and IP coercion to one map."""
|
||||||
|
renames = LEGACY_KEYS.get(path, {})
|
||||||
|
out: dict = {}
|
||||||
|
# v1 keys first, so a legacy duplicate never overwrites a correct value
|
||||||
|
# that is also present in the same map.
|
||||||
|
for key in sorted(data, key=lambda k: k in renames):
|
||||||
|
value = data[key]
|
||||||
|
if key in renames:
|
||||||
|
target = renames[key]
|
||||||
|
if target is None or target in out or target in data:
|
||||||
|
continue # drop the legacy key (v1 key present, or field is retired)
|
||||||
|
key = target
|
||||||
|
child = f"{path}.{key}" if path else key
|
||||||
|
if isinstance(value, dict):
|
||||||
|
value = _normalize_map(value, child)
|
||||||
|
elif key in TIMESTAMP_KEYS and path:
|
||||||
|
value = to_timestamp(value, child)
|
||||||
|
elif key in IP_KEYS and path.endswith("networkSettings"):
|
||||||
|
value = to_ipv4(value, child)
|
||||||
|
out[key] = value
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def _user_ref(db, entry) -> DocumentReference:
|
||||||
|
if isinstance(entry, DocumentReference):
|
||||||
|
return entry
|
||||||
|
uid = str(entry).strip().split("/")[-1]
|
||||||
|
if not uid:
|
||||||
|
raise ValidationError(f"user_list: empty entry {entry!r}")
|
||||||
|
return db.collection("users").document(uid)
|
||||||
|
|
||||||
|
|
||||||
|
def _check_melodies(items: Any, db) -> list:
|
||||||
|
if items is None:
|
||||||
|
return []
|
||||||
|
if not isinstance(items, list):
|
||||||
|
raise ValidationError("device_melodies_all: expected a list")
|
||||||
|
out = []
|
||||||
|
for i, item in enumerate(items):
|
||||||
|
if not isinstance(item, dict):
|
||||||
|
raise ValidationError(f"device_melodies_all[{i}]: expected an object")
|
||||||
|
bad = _MELODY_ITEM_FORBIDDEN & item.keys()
|
||||||
|
if bad:
|
||||||
|
raise ValidationError(
|
||||||
|
f"device_melodies_all[{i}]: uses melodies-collection keys {sorted(bad)}; "
|
||||||
|
"device melodies must use mainInformation / defaultSettings / settings / binaryUrl"
|
||||||
|
)
|
||||||
|
ref = item.get("melodyReference")
|
||||||
|
if isinstance(ref, str) and db is not None:
|
||||||
|
item = {**item, "melodyReference": db.collection("melodies").document(ref.split("/")[-1]) if ref else None}
|
||||||
|
out.append(item)
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def to_firestore(data: dict, db=None) -> dict:
|
||||||
|
"""Normalize a (partial) device document for writing to Firestore under v1.
|
||||||
|
|
||||||
|
Raises ValidationError (422) for values that cannot be represented in v1, instead
|
||||||
|
of writing something the apps would choke on.
|
||||||
|
"""
|
||||||
|
out = _normalize_map(data, "")
|
||||||
|
|
||||||
|
# D1: device_id mirrors serial_number. Whichever one is being written, write both.
|
||||||
|
sn, did = out.get("serial_number"), out.get("device_id")
|
||||||
|
if sn and did and sn != did:
|
||||||
|
raise ValidationError(f"device_id ({did}) must equal serial_number ({sn})")
|
||||||
|
if sn or did:
|
||||||
|
out["serial_number"] = out["device_id"] = sn or did
|
||||||
|
|
||||||
|
fam = out.get("hw_family")
|
||||||
|
if fam not in (None, "") and not (isinstance(fam, str) and _HW_FAMILY.match(fam)):
|
||||||
|
raise ValidationError(f"hw_family: expected a board family code like \"vesper_plus\", got {fam!r}")
|
||||||
|
|
||||||
|
if "user_list" in out and db is not None:
|
||||||
|
refs, seen = [], set()
|
||||||
|
for e in out["user_list"] or []:
|
||||||
|
ref = _user_ref(db, e)
|
||||||
|
if ref.id not in seen:
|
||||||
|
seen.add(ref.id)
|
||||||
|
refs.append(ref)
|
||||||
|
out["user_list"] = refs
|
||||||
|
|
||||||
|
if "device_melodies_all" in out:
|
||||||
|
out["device_melodies_all"] = _check_melodies(out["device_melodies_all"], db)
|
||||||
|
|
||||||
|
coords = out.get("device_location_coordinates")
|
||||||
|
if isinstance(coords, dict) and "lat" in coords and "lng" in coords:
|
||||||
|
out["device_location_coordinates"] = GeoPoint(coords["lat"], coords["lng"])
|
||||||
|
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
# ----------------------------------------------------------------- read side
|
||||||
|
|
||||||
|
|
||||||
|
def _api_value(v):
|
||||||
|
if isinstance(v, datetime):
|
||||||
|
dt = v if v.tzinfo else v.replace(tzinfo=timezone.utc)
|
||||||
|
return dt.astimezone(timezone.utc).isoformat().replace("+00:00", "Z")
|
||||||
|
if isinstance(v, GeoPoint):
|
||||||
|
return {"lat": v.latitude, "lng": v.longitude}
|
||||||
|
if isinstance(v, DocumentReference):
|
||||||
|
return v.path
|
||||||
|
if isinstance(v, dict):
|
||||||
|
return {k: _api_value(x) for k, x in v.items()}
|
||||||
|
if isinstance(v, list):
|
||||||
|
return [_api_value(x) for x in v]
|
||||||
|
return v
|
||||||
|
|
||||||
|
|
||||||
|
def to_api(raw: dict) -> dict:
|
||||||
|
"""Firestore device doc -> JSON for the console frontend.
|
||||||
|
|
||||||
|
Timestamps become ISO 8601 UTC strings (round-trip safe with to_timestamp),
|
||||||
|
references become paths, GeoPoints become {lat, lng}. Legacy misspelled keys
|
||||||
|
are folded into their v1 names so the frontend only ever sees v1 names.
|
||||||
|
"""
|
||||||
|
return _api_value(_normalize_read(raw, ""))
|
||||||
|
|
||||||
|
|
||||||
|
def _normalize_read(data: dict, path: str) -> dict:
|
||||||
|
renames = LEGACY_KEYS.get(path, {})
|
||||||
|
out = {}
|
||||||
|
for key in sorted(data, key=lambda k: k in renames):
|
||||||
|
value = data[key]
|
||||||
|
if key in renames:
|
||||||
|
target = renames[key]
|
||||||
|
if target is None or target in data:
|
||||||
|
continue
|
||||||
|
key = target
|
||||||
|
child = f"{path}.{key}" if path else key
|
||||||
|
if isinstance(value, dict):
|
||||||
|
value = _normalize_read(value, child)
|
||||||
|
elif key in TIMESTAMP_KEYS and path and value == "":
|
||||||
|
value = None # stored "" (pre-v1 bug) reads as unset
|
||||||
|
elif key in IP_KEYS and path.endswith("networkSettings") and isinstance(value, list):
|
||||||
|
parts = [str(p) for p in value if str(p) != ""]
|
||||||
|
value = ".".join(parts) if parts else ""
|
||||||
|
out[key] = value
|
||||||
|
return out
|
||||||
+44
-25
@@ -1,7 +1,12 @@
|
|||||||
from pydantic import BaseModel, Field
|
from pydantic import BaseModel, ConfigDict, Field
|
||||||
from typing import Any, Dict, List, Optional
|
from typing import Any, Dict, List, Optional
|
||||||
from enum import Enum
|
from enum import Enum
|
||||||
|
|
||||||
|
# Field names and types follow Firestore schema v1 (bellsystems-schema repo,
|
||||||
|
# v1/firestore.schema.json) — the shape the shipped tablet/phone apps read.
|
||||||
|
# Timestamps travel through the API as ISO 8601 strings and are unset as None
|
||||||
|
# (never ""); devices/firestore_v1.py converts to/from Firestore.
|
||||||
|
|
||||||
|
|
||||||
# --- Enums ---
|
# --- Enums ---
|
||||||
|
|
||||||
@@ -30,12 +35,14 @@ class DeviceTiers(str, Enum):
|
|||||||
|
|
||||||
class DeviceNetworkSettings(BaseModel):
|
class DeviceNetworkSettings(BaseModel):
|
||||||
hostname: str = ""
|
hostname: str = ""
|
||||||
useStaticIP: bool = False
|
usesStaticIP: bool = False
|
||||||
ipAddress: Any = []
|
# Dotted strings ("10.0.0.5"); "" = not set. The firmware's network.set_config
|
||||||
gateway: Any = []
|
# MQTT command uses its own names (useStaticIP / ip) — convert at that boundary.
|
||||||
subnet: Any = []
|
ipAddress: str = ""
|
||||||
dns1: Any = []
|
gateway: str = ""
|
||||||
dns2: Any = []
|
subnet: str = ""
|
||||||
|
dns1: str = ""
|
||||||
|
dns2: str = ""
|
||||||
|
|
||||||
|
|
||||||
class DeviceClockSettings(BaseModel):
|
class DeviceClockSettings(BaseModel):
|
||||||
@@ -49,14 +56,18 @@ class DeviceClockSettings(BaseModel):
|
|||||||
quarterAlertsBell: int = 0
|
quarterAlertsBell: int = 0
|
||||||
isDaySilenceOn: bool = False
|
isDaySilenceOn: bool = False
|
||||||
isNightSilenceOn: bool = False
|
isNightSilenceOn: bool = False
|
||||||
daySilenceFrom: str = ""
|
# Time of day carried in a Timestamp (v1 quirk); only the UTC time part matters.
|
||||||
daySilenceTo: str = ""
|
daySilenceFrom: Optional[str] = None
|
||||||
nightSilenceFrom: str = ""
|
daySilenceTo: Optional[str] = None
|
||||||
nightSilenceTo: str = ""
|
nightSilenceFrom: Optional[str] = None
|
||||||
backlightTurnOnTime: str = ""
|
nightSilenceTo: Optional[str] = None
|
||||||
backlightTurnOffTime: str = ""
|
backlightTurnOnTime: Optional[str] = None
|
||||||
|
backlightTurnOffTime: Optional[str] = None
|
||||||
isBacklightAutomationOn: bool = False
|
isBacklightAutomationOn: bool = False
|
||||||
backlightOutput: int = 0
|
backlightOutput: int = 0
|
||||||
|
# Firmware 3.2.0+ face sync policy (clock.set_config face_sync_mode / smart_max_wait_min)
|
||||||
|
faceSyncMode: str = "force"
|
||||||
|
smartMaxWaitMin: int = 61
|
||||||
|
|
||||||
|
|
||||||
class DeviceAttributes(BaseModel):
|
class DeviceAttributes(BaseModel):
|
||||||
@@ -67,9 +78,9 @@ class DeviceAttributes(BaseModel):
|
|||||||
bellOutputs: List[int] = []
|
bellOutputs: List[int] = []
|
||||||
hammerTimings: List[int] = []
|
hammerTimings: List[int] = []
|
||||||
bellGuardOn: bool = False
|
bellGuardOn: bool = False
|
||||||
bellGuardSafetyOn: bool = False
|
bellguardSafetyOn: bool = False # lower-case g: the exact key the apps read
|
||||||
warningsOn: bool = False
|
warningsOn: bool = False
|
||||||
towerClockTime: str = ""
|
towerClockTime: Optional[str] = None
|
||||||
clockSettings: DeviceClockSettings = DeviceClockSettings()
|
clockSettings: DeviceClockSettings = DeviceClockSettings()
|
||||||
deviceLocale: HelperMelodyTypes = HelperMelodyTypes.all
|
deviceLocale: HelperMelodyTypes = HelperMelodyTypes.all
|
||||||
networkSettings: DeviceNetworkSettings = DeviceNetworkSettings()
|
networkSettings: DeviceNetworkSettings = DeviceNetworkSettings()
|
||||||
@@ -80,7 +91,7 @@ class DeviceAttributes(BaseModel):
|
|||||||
|
|
||||||
class DeviceSubInformation(BaseModel):
|
class DeviceSubInformation(BaseModel):
|
||||||
subscrTier: DeviceTiers = DeviceTiers.basic
|
subscrTier: DeviceTiers = DeviceTiers.basic
|
||||||
subscrStart: str = ""
|
subscrStart: Optional[str] = None
|
||||||
subscrDuration: int = 0
|
subscrDuration: int = 0
|
||||||
maxUsers: int = 0
|
maxUsers: int = 0
|
||||||
maxOutputs: int = 0
|
maxOutputs: int = 0
|
||||||
@@ -92,10 +103,10 @@ class DeviceStatistics(BaseModel):
|
|||||||
perBellStrikes: List[int] = []
|
perBellStrikes: List[int] = []
|
||||||
totalWarningsGiven: int = 0
|
totalWarningsGiven: int = 0
|
||||||
warrantyActive: bool = False
|
warrantyActive: bool = False
|
||||||
warrantyStart: str = ""
|
warrantyStart: Optional[str] = None
|
||||||
warrantyPeriod: int = 0
|
warrantyPeriod: int = 0
|
||||||
maintainedOn: str = ""
|
maintainedOn: Optional[str] = None
|
||||||
maintainancePeriod: int = 0
|
maintainancePeriod: int = 0 # misspelled in v1 on purpose: the apps read this key
|
||||||
|
|
||||||
|
|
||||||
class HealthThresholdTier(BaseModel):
|
class HealthThresholdTier(BaseModel):
|
||||||
@@ -128,13 +139,21 @@ class DeviceHealthSettings(BaseModel):
|
|||||||
|
|
||||||
|
|
||||||
class MelodyMainItem(BaseModel):
|
class MelodyMainItem(BaseModel):
|
||||||
"""Mirrors the Melody schema used in the melodies collection."""
|
"""One melody as stored inside devices.device_melodies_all (v1 MelodyMainItem).
|
||||||
information: dict = {}
|
|
||||||
default_settings: dict = {}
|
NOT the melodies/{id} document shape: the apps read camelCase keys here
|
||||||
type: str = ""
|
(mainInformation / defaultSettings / settings / binaryUrl / melodyReference).
|
||||||
url: str = ""
|
Extra keys are kept so a read-modify-write never drops data.
|
||||||
|
"""
|
||||||
|
model_config = ConfigDict(extra="allow")
|
||||||
|
|
||||||
|
melodyReference: Optional[str] = None # path "melodies/{id}" in the API
|
||||||
uid: str = ""
|
uid: str = ""
|
||||||
pid: str = ""
|
pid: str = ""
|
||||||
|
mainInformation: Dict[str, Any] = {}
|
||||||
|
defaultSettings: Dict[str, Any] = {}
|
||||||
|
settings: Dict[str, Any] = {}
|
||||||
|
binaryUrl: str = ""
|
||||||
|
|
||||||
|
|
||||||
# --- Request / Response schemas ---
|
# --- Request / Response schemas ---
|
||||||
@@ -215,7 +234,7 @@ class DeviceNoteUpdate(BaseModel):
|
|||||||
|
|
||||||
|
|
||||||
class DeviceUserInfo(BaseModel):
|
class DeviceUserInfo(BaseModel):
|
||||||
"""User info resolved from device_users sub-collection or user_list."""
|
"""User info resolved from the device's user_list (role from the device_users mirror)."""
|
||||||
user_id: str = ""
|
user_id: str = ""
|
||||||
display_name: str = ""
|
display_name: str = ""
|
||||||
email: str = ""
|
email: str = ""
|
||||||
|
|||||||
+17
-14
@@ -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")),
|
||||||
@@ -462,13 +462,15 @@ async def add_user_to_device(
|
|||||||
elif isinstance(entry, str):
|
elif isinstance(entry, str):
|
||||||
existing_ids.add(entry.split("/")[-1])
|
existing_ids.add(entry.split("/")[-1])
|
||||||
|
|
||||||
# user_list and the user's device_serials (MQTT ACL lookup) commit together.
|
# user_list, the user's device_serials (MQTT ACL lookup) and the
|
||||||
|
# device_users mirror commit together.
|
||||||
user_ref = fs.collection("users").document(body.user_id)
|
user_ref = fs.collection("users").document(body.user_id)
|
||||||
batch = fs.batch()
|
batch = fs.batch()
|
||||||
if body.user_id not in existing_ids:
|
if body.user_id not in existing_ids:
|
||||||
user_list.append(user_ref)
|
user_list.append(user_ref)
|
||||||
batch.update(device_ref, {"user_list": user_list})
|
batch.update(device_ref, {"user_list": user_list})
|
||||||
users_service.stage_device_serial_link(batch, user_ref, users_service.device_serial_of(data), linked=True)
|
users_service.stage_device_serial_link(batch, user_ref, users_service.device_serial_of(data), linked=True)
|
||||||
|
service.stage_device_users_mirror(batch, device_ref, user_ref, linked=True)
|
||||||
batch.commit()
|
batch.commit()
|
||||||
users_service.invalidate_mqtt_acl_cache(user_doc.to_dict())
|
users_service.invalidate_mqtt_acl_cache(user_doc.to_dict())
|
||||||
|
|
||||||
@@ -512,6 +514,7 @@ async def remove_user_from_device(
|
|||||||
user_doc = user_ref.get()
|
user_doc = user_ref.get()
|
||||||
if user_doc.exists:
|
if user_doc.exists:
|
||||||
users_service.stage_device_serial_link(batch, user_ref, users_service.device_serial_of(data), linked=False)
|
users_service.stage_device_serial_link(batch, user_ref, users_service.device_serial_of(data), linked=False)
|
||||||
|
service.stage_device_users_mirror(batch, device_ref, user_ref, linked=False)
|
||||||
batch.commit()
|
batch.commit()
|
||||||
if user_doc.exists:
|
if user_doc.exists:
|
||||||
users_service.invalidate_mqtt_acl_cache(user_doc.to_dict())
|
users_service.invalidate_mqtt_acl_cache(user_doc.to_dict())
|
||||||
@@ -550,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
|
||||||
|
|||||||
+126
-170
@@ -1,11 +1,12 @@
|
|||||||
import secrets
|
import secrets
|
||||||
import string
|
import string
|
||||||
|
|
||||||
from datetime import datetime
|
from google.cloud.firestore_v1 import DocumentReference
|
||||||
from google.cloud.firestore_v1 import GeoPoint, 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
|
||||||
|
from devices import firestore_v1
|
||||||
from devices.models import DeviceCreate, DeviceUpdate, DeviceInDB
|
from devices.models import DeviceCreate, DeviceUpdate, DeviceInDB
|
||||||
|
|
||||||
COLLECTION = "devices"
|
COLLECTION = "devices"
|
||||||
@@ -14,35 +15,6 @@ COLLECTION = "devices"
|
|||||||
SN_CHARS = string.ascii_uppercase + string.digits
|
SN_CHARS = string.ascii_uppercase + string.digits
|
||||||
SN_SEGMENT_LEN = 4
|
SN_SEGMENT_LEN = 4
|
||||||
|
|
||||||
# Clock/silence/backlight fields stored as Firestore Timestamps (written as datetime)
|
|
||||||
_TIMESTAMP_FIELD_NAMES = {
|
|
||||||
"daySilenceFrom", "daySilenceTo",
|
|
||||||
"nightSilenceFrom", "nightSilenceTo",
|
|
||||||
"backlightTurnOnTime", "backlightTurnOffTime",
|
|
||||||
"subscrStart", "warrantyStart", "maintainedOn",
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
def _restore_timestamps(d: dict) -> dict:
|
|
||||||
"""Recursively convert ISO 8601 strings for known timestamp fields to datetime objects.
|
|
||||||
|
|
||||||
Firestore stores Python datetime objects as native Timestamps, which Flutter
|
|
||||||
reads as DateTime. Plain strings would break the Flutter app.
|
|
||||||
"""
|
|
||||||
result = {}
|
|
||||||
for k, v in d.items():
|
|
||||||
if isinstance(v, dict):
|
|
||||||
result[k] = _restore_timestamps(v)
|
|
||||||
elif isinstance(v, str) and k in _TIMESTAMP_FIELD_NAMES:
|
|
||||||
try:
|
|
||||||
result[k] = datetime.fromisoformat(v.replace("Z", "+00:00"))
|
|
||||||
except ValueError:
|
|
||||||
result[k] = v
|
|
||||||
else:
|
|
||||||
result[k] = v
|
|
||||||
return result
|
|
||||||
|
|
||||||
|
|
||||||
def _generate_serial_number() -> str:
|
def _generate_serial_number() -> str:
|
||||||
"""Generate a unique serial number in the format BS-XXXX-XXXX."""
|
"""Generate a unique serial number in the format BS-XXXX-XXXX."""
|
||||||
seg1 = "".join(secrets.choice(SN_CHARS) for _ in range(SN_SEGMENT_LEN))
|
seg1 = "".join(secrets.choice(SN_CHARS) for _ in range(SN_SEGMENT_LEN))
|
||||||
@@ -67,36 +39,6 @@ def _ensure_unique_serial(db) -> str:
|
|||||||
raise RuntimeError("Could not generate a unique serial number after 100 attempts")
|
raise RuntimeError("Could not generate a unique serial number after 100 attempts")
|
||||||
|
|
||||||
|
|
||||||
def _convert_firestore_value(val):
|
|
||||||
"""Convert Firestore-specific types (Timestamp, GeoPoint, DocumentReference) to strings."""
|
|
||||||
if isinstance(val, datetime):
|
|
||||||
# Firestore DatetimeWithNanoseconds is a datetime subclass
|
|
||||||
return val.strftime("%d %B %Y at %H:%M:%S UTC%z")
|
|
||||||
if isinstance(val, GeoPoint):
|
|
||||||
return {"lat": val.latitude, "lng": val.longitude}
|
|
||||||
if isinstance(val, DocumentReference):
|
|
||||||
# Store the document path (e.g. "users/abc123")
|
|
||||||
return val.path
|
|
||||||
return val
|
|
||||||
|
|
||||||
|
|
||||||
def _sanitize_dict(d: dict) -> dict:
|
|
||||||
"""Recursively convert Firestore-native types in a dict to plain strings."""
|
|
||||||
result = {}
|
|
||||||
for k, v in d.items():
|
|
||||||
if isinstance(v, dict):
|
|
||||||
result[k] = _sanitize_dict(v)
|
|
||||||
elif isinstance(v, list):
|
|
||||||
result[k] = [
|
|
||||||
_sanitize_dict(item) if isinstance(item, dict)
|
|
||||||
else _convert_firestore_value(item)
|
|
||||||
for item in v
|
|
||||||
]
|
|
||||||
else:
|
|
||||||
result[k] = _convert_firestore_value(v)
|
|
||||||
return result
|
|
||||||
|
|
||||||
|
|
||||||
def _auto_upgrade_claimed(doc_ref, data: dict) -> dict:
|
def _auto_upgrade_claimed(doc_ref, data: dict) -> dict:
|
||||||
"""If the device has entries in user_list and isn't already claimed/decommissioned,
|
"""If the device has entries in user_list and isn't already claimed/decommissioned,
|
||||||
upgrade mfg_status to 'claimed' automatically and return the updated data dict."""
|
upgrade mfg_status to 'claimed' automatically and return the updated data dict."""
|
||||||
@@ -118,7 +60,7 @@ def _doc_to_device(doc) -> DeviceInDB:
|
|||||||
"""
|
"""
|
||||||
raw = doc.to_dict()
|
raw = doc.to_dict()
|
||||||
raw = _auto_upgrade_claimed(doc.reference, raw)
|
raw = _auto_upgrade_claimed(doc.reference, raw)
|
||||||
data = _sanitize_dict(raw)
|
data = firestore_v1.to_api(raw)
|
||||||
return DeviceInDB(id=doc.id, **data)
|
return DeviceInDB(id=doc.id, **data)
|
||||||
|
|
||||||
|
|
||||||
@@ -187,22 +129,31 @@ def create_device(data: DeviceCreate) -> DeviceInDB:
|
|||||||
serial_number = _ensure_unique_serial(db)
|
serial_number = _ensure_unique_serial(db)
|
||||||
|
|
||||||
doc_data = data.model_dump()
|
doc_data = data.model_dump()
|
||||||
doc_data["device_id"] = serial_number
|
doc_data["serial_number"] = serial_number # D1: canonical id; to_firestore mirrors it to device_id
|
||||||
|
doc_data.pop("device_id", None)
|
||||||
|
doc_data = firestore_v1.to_firestore(doc_data, db)
|
||||||
|
|
||||||
_, doc_ref = db.collection(COLLECTION).add(doc_data)
|
_, doc_ref = db.collection(COLLECTION).add(doc_data)
|
||||||
|
|
||||||
return DeviceInDB(id=doc_ref.id, **doc_data)
|
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:
|
||||||
@@ -213,44 +164,57 @@ def update_device(device_doc_id: str, data: DeviceUpdate) -> DeviceInDB:
|
|||||||
if not doc.exists:
|
if not doc.exists:
|
||||||
raise NotFoundError("Device")
|
raise NotFoundError("Device")
|
||||||
|
|
||||||
update_data = data.model_dump(exclude_none=True)
|
# Top-level None still means "not sent" (unchanged API behaviour). Inside the
|
||||||
|
# nested maps an explicit null is kept: it clears that field, e.g. a silence
|
||||||
|
# time being switched off — the v1 way to say "unset" (never "").
|
||||||
|
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)
|
||||||
|
|
||||||
# Convert {lat, lng} dict to a Firestore GeoPoint
|
# Nested structs are written field-by-field (dotted paths), so only the
|
||||||
coords = update_data.get("device_location_coordinates")
|
# exact leaves the caller sent are touched. Rewriting the whole parent map
|
||||||
if isinstance(coords, dict) and "lat" in coords and "lng" in coords:
|
# (the old read-merge-write) clobbered sibling fields whenever two writes
|
||||||
update_data["device_location_coordinates"] = GeoPoint(coords["lat"], coords["lng"])
|
# raced, or the FlutterFlow apps wrote in between our read and our write.
|
||||||
|
|
||||||
# Deep-merge nested structs so unmentioned sub-fields are preserved
|
|
||||||
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]:
|
||||||
update_data[key] = _deep_merge(existing[key], update_data[key])
|
update_data.update(_leaf_field_paths(update_data.pop(key), (key,)))
|
||||||
|
|
||||||
update_data = _restore_timestamps(update_data)
|
|
||||||
|
|
||||||
if "user_list" not in update_data:
|
if "user_list" not in update_data:
|
||||||
doc_ref.update(update_data)
|
doc_ref.update(update_data)
|
||||||
else:
|
else:
|
||||||
# A user_list change must also update each affected user's
|
# A user_list change must also update each affected user's
|
||||||
# device_serials (MQTT ACL), in the same atomic batch.
|
# device_serials (MQTT ACL) and the device_users mirror, in the
|
||||||
|
# same atomic batch.
|
||||||
from users import service as users_service
|
from users import service as users_service
|
||||||
|
|
||||||
old_ids = {_user_list_entry_id(e) for e in (existing.get("user_list") or [])} - {""}
|
new_ids = []
|
||||||
new_ids = {_user_list_entry_id(e) for e in update_data["user_list"]} - {""}
|
for e in update_data["user_list"]:
|
||||||
|
uid = user_list_entry_id(e)
|
||||||
|
if uid and uid not in new_ids:
|
||||||
|
new_ids.append(uid)
|
||||||
|
# Stored as DocumentReferences, the format the FlutterFlow app writes.
|
||||||
|
update_data["user_list"] = [db.collection("users").document(uid) for uid in new_ids]
|
||||||
|
|
||||||
|
old_ids = {user_list_entry_id(e) for e in (existing.get("user_list") or [])} - {""}
|
||||||
serial = users_service.device_serial_of(existing)
|
serial = users_service.device_serial_of(existing)
|
||||||
|
mirror = device_users_by_user(doc_ref)
|
||||||
|
|
||||||
batch = db.batch()
|
batch = db.batch()
|
||||||
batch.update(doc_ref, update_data)
|
batch.update(doc_ref, update_data)
|
||||||
touched = []
|
touched = []
|
||||||
for user_id in (old_ids ^ new_ids):
|
for user_id in (old_ids ^ set(new_ids)):
|
||||||
|
linked = user_id in new_ids
|
||||||
user_ref = db.collection("users").document(user_id)
|
user_ref = db.collection("users").document(user_id)
|
||||||
user_doc = user_ref.get()
|
user_doc = user_ref.get()
|
||||||
if not user_doc.exists:
|
if not user_doc.exists:
|
||||||
continue # dangling reference — nothing to sync
|
if not linked:
|
||||||
users_service.stage_device_serial_link(batch, user_ref, serial, linked=user_id in new_ids)
|
stage_device_users_mirror(batch, doc_ref, user_ref, linked=False, existing=mirror)
|
||||||
|
continue # dangling reference — no user doc to sync
|
||||||
|
users_service.stage_device_serial_link(batch, user_ref, serial, linked=linked)
|
||||||
|
stage_device_users_mirror(batch, doc_ref, user_ref, linked=linked, existing=mirror)
|
||||||
touched.append(user_doc.to_dict())
|
touched.append(user_doc.to_dict())
|
||||||
batch.commit()
|
batch.commit()
|
||||||
for user_data in touched:
|
for user_data in touched:
|
||||||
@@ -260,7 +224,7 @@ def update_device(device_doc_id: str, data: DeviceUpdate) -> DeviceInDB:
|
|||||||
return _doc_to_device(updated_doc)
|
return _doc_to_device(updated_doc)
|
||||||
|
|
||||||
|
|
||||||
def _user_list_entry_id(entry) -> str:
|
def user_list_entry_id(entry) -> str:
|
||||||
"""user_list entries are DocumentReferences, "users/{id}" paths or raw doc IDs."""
|
"""user_list entries are DocumentReferences, "users/{id}" paths or raw doc IDs."""
|
||||||
if isinstance(entry, DocumentReference):
|
if isinstance(entry, DocumentReference):
|
||||||
return entry.id
|
return entry.id
|
||||||
@@ -269,11 +233,53 @@ def _user_list_entry_id(entry) -> str:
|
|||||||
return ""
|
return ""
|
||||||
|
|
||||||
|
|
||||||
def get_device_users(device_doc_id: str) -> list[dict]:
|
# ─── device_users sub-collection mirror ──────────────────────────────────────
|
||||||
"""Get users assigned to a device from the device_users sub-collection.
|
# The device's `user_list` field is the single source of truth for who is
|
||||||
|
# assigned to a device. The older `device_users` sub-collection
|
||||||
|
# ({role, user_reference}) is kept as a write-only mirror in case the phone
|
||||||
|
# app still reads it, and is slated for removal. Never read assignments from it.
|
||||||
|
|
||||||
Falls back to the user_list field on the device document if the
|
DEVICE_USERS_SUBCOLLECTION = "device_users"
|
||||||
sub-collection is empty.
|
# Every existing device_users doc (2026-11) has role "admin".
|
||||||
|
DEFAULT_DEVICE_USER_ROLE = "admin"
|
||||||
|
|
||||||
|
|
||||||
|
def device_users_by_user(device_ref) -> dict[str, list]:
|
||||||
|
"""user doc id -> the device_users snapshots that point at that user."""
|
||||||
|
out: dict[str, list] = {}
|
||||||
|
for snap in device_ref.collection(DEVICE_USERS_SUBCOLLECTION).stream():
|
||||||
|
uid = user_list_entry_id((snap.to_dict() or {}).get("user_reference"))
|
||||||
|
if uid:
|
||||||
|
out.setdefault(uid, []).append(snap)
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def stage_device_users_mirror(batch, device_ref, user_ref, linked: bool, existing: dict | None = None) -> None:
|
||||||
|
"""Add (linked=True) or remove the user's device_users mirror doc inside the
|
||||||
|
caller's batch, so it commits together with the `user_list` change.
|
||||||
|
|
||||||
|
`existing` is a pre-fetched device_users_by_user() map, for callers that
|
||||||
|
touch several users of one device.
|
||||||
|
"""
|
||||||
|
if existing is None:
|
||||||
|
existing = device_users_by_user(device_ref)
|
||||||
|
current = existing.get(user_ref.id, [])
|
||||||
|
if linked:
|
||||||
|
if not current:
|
||||||
|
batch.set(device_ref.collection(DEVICE_USERS_SUBCOLLECTION).document(), {
|
||||||
|
"role": DEFAULT_DEVICE_USER_ROLE,
|
||||||
|
"user_reference": user_ref,
|
||||||
|
})
|
||||||
|
else:
|
||||||
|
for snap in current:
|
||||||
|
batch.delete(snap.reference)
|
||||||
|
|
||||||
|
|
||||||
|
def get_device_users(device_doc_id: str) -> list[dict]:
|
||||||
|
"""Users assigned to a device, read from the device's `user_list` field.
|
||||||
|
|
||||||
|
`role` is taken from the device_users mirror when one exists for the user
|
||||||
|
(that's the only place a role is stored); otherwise it is "".
|
||||||
"""
|
"""
|
||||||
db = get_db()
|
db = get_db()
|
||||||
doc_ref = db.collection(COLLECTION).document(device_doc_id)
|
doc_ref = db.collection(COLLECTION).document(device_doc_id)
|
||||||
@@ -281,83 +287,33 @@ def get_device_users(device_doc_id: str) -> list[dict]:
|
|||||||
if not doc.exists:
|
if not doc.exists:
|
||||||
raise NotFoundError("Device")
|
raise NotFoundError("Device")
|
||||||
|
|
||||||
# Try sub-collection first
|
roles = {
|
||||||
sub_docs = list(doc_ref.collection("device_users").stream())
|
uid: (snaps[0].to_dict() or {}).get("role", "")
|
||||||
|
for uid, snaps in device_users_by_user(doc_ref).items()
|
||||||
|
}
|
||||||
|
|
||||||
users = []
|
users = []
|
||||||
|
seen = set()
|
||||||
if sub_docs:
|
for entry in (doc.to_dict() or {}).get("user_list") or []:
|
||||||
for sub_doc in sub_docs:
|
uid = user_list_entry_id(entry)
|
||||||
sub_data = sub_doc.to_dict()
|
if not uid or uid in seen:
|
||||||
role = sub_data.get("role", "")
|
continue
|
||||||
user_ref = sub_data.get("user_reference")
|
seen.add(uid)
|
||||||
|
try:
|
||||||
# Resolve user reference
|
user_doc = db.collection("users").document(uid).get()
|
||||||
user_id = ""
|
except Exception as e:
|
||||||
display_name = ""
|
print(f"[devices] Error resolving user_list entry {uid}: {e}")
|
||||||
email = ""
|
continue
|
||||||
photo_url = ""
|
if not user_doc.exists:
|
||||||
|
continue
|
||||||
if isinstance(user_ref, DocumentReference):
|
user_data = user_doc.to_dict() or {}
|
||||||
try:
|
users.append({
|
||||||
user_doc = user_ref.get()
|
"user_id": user_doc.id,
|
||||||
if user_doc.exists:
|
"display_name": user_data.get("display_name", ""),
|
||||||
user_data = user_doc.to_dict()
|
"email": user_data.get("email", ""),
|
||||||
user_id = user_doc.id
|
"role": roles.get(uid, ""),
|
||||||
display_name = user_data.get("display_name", "")
|
"photo_url": user_data.get("photo_url", ""),
|
||||||
email = user_data.get("email", "")
|
})
|
||||||
photo_url = user_data.get("photo_url", "")
|
|
||||||
except Exception as e:
|
|
||||||
print(f"[devices] Error resolving user reference: {e}")
|
|
||||||
continue
|
|
||||||
elif isinstance(user_ref, str):
|
|
||||||
# String path like "users/abc123"
|
|
||||||
try:
|
|
||||||
ref_doc = db.document(user_ref).get()
|
|
||||||
if ref_doc.exists:
|
|
||||||
user_data = ref_doc.to_dict()
|
|
||||||
user_id = ref_doc.id
|
|
||||||
display_name = user_data.get("display_name", "")
|
|
||||||
email = user_data.get("email", "")
|
|
||||||
photo_url = user_data.get("photo_url", "")
|
|
||||||
except Exception as e:
|
|
||||||
print(f"[devices] Error resolving user path: {e}")
|
|
||||||
continue
|
|
||||||
|
|
||||||
users.append({
|
|
||||||
"user_id": user_id,
|
|
||||||
"display_name": display_name,
|
|
||||||
"email": email,
|
|
||||||
"role": role,
|
|
||||||
"photo_url": photo_url,
|
|
||||||
})
|
|
||||||
else:
|
|
||||||
# Fallback to user_list field
|
|
||||||
device_data = doc.to_dict()
|
|
||||||
user_list = device_data.get("user_list", [])
|
|
||||||
for entry in user_list:
|
|
||||||
try:
|
|
||||||
if isinstance(entry, DocumentReference):
|
|
||||||
user_doc = entry.get()
|
|
||||||
elif isinstance(entry, str) and entry.strip():
|
|
||||||
# Could be a path like "users/abc" or a raw doc ID
|
|
||||||
if "/" in entry:
|
|
||||||
user_doc = db.document(entry).get()
|
|
||||||
else:
|
|
||||||
user_doc = db.collection("users").document(entry).get()
|
|
||||||
else:
|
|
||||||
continue
|
|
||||||
|
|
||||||
if user_doc.exists:
|
|
||||||
user_data = user_doc.to_dict()
|
|
||||||
users.append({
|
|
||||||
"user_id": user_doc.id,
|
|
||||||
"display_name": user_data.get("display_name", ""),
|
|
||||||
"email": user_data.get("email", ""),
|
|
||||||
"role": "",
|
|
||||||
"photo_url": user_data.get("photo_url", ""),
|
|
||||||
})
|
|
||||||
except Exception as e:
|
|
||||||
print(f"[devices] Error resolving user_list entry: {e}")
|
|
||||||
|
|
||||||
return users
|
return users
|
||||||
|
|
||||||
|
|||||||
@@ -29,6 +29,7 @@ from notes.router import router as notes_router
|
|||||||
from tickets.router import router as tickets_router
|
from tickets.router import router as tickets_router
|
||||||
from audit.router import router as audit_router
|
from audit.router import router as audit_router
|
||||||
from search.router import router as search_router
|
from search.router import router as search_router
|
||||||
|
from timezones.router import router as timezones_router
|
||||||
from crm.nextcloud import close_client as close_nextcloud_client, keepalive_ping as nextcloud_keepalive
|
from crm.nextcloud import close_client as close_nextcloud_client, keepalive_ping as nextcloud_keepalive
|
||||||
from crm.mail_accounts import get_mail_accounts
|
from crm.mail_accounts import get_mail_accounts
|
||||||
from mqtt.client import mqtt_manager
|
from mqtt.client import mqtt_manager
|
||||||
@@ -78,6 +79,7 @@ app.include_router(notes_router)
|
|||||||
app.include_router(tickets_router)
|
app.include_router(tickets_router)
|
||||||
app.include_router(audit_router)
|
app.include_router(audit_router)
|
||||||
app.include_router(search_router)
|
app.include_router(search_router)
|
||||||
|
app.include_router(timezones_router)
|
||||||
|
|
||||||
|
|
||||||
async def nextcloud_keepalive_loop():
|
async def nextcloud_keepalive_loop():
|
||||||
@@ -114,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())
|
||||||
|
|||||||
@@ -89,8 +89,8 @@ class DeviceUserSummary(BaseModel):
|
|||||||
class DeviceInventoryItem(BaseModel):
|
class DeviceInventoryItem(BaseModel):
|
||||||
id: str
|
id: str
|
||||||
serial_number: str
|
serial_number: str
|
||||||
hw_type: str
|
hw_family: str # board family code (BoardType value or bespoke UID) = firmware NVS "hw_family"
|
||||||
hw_version: str
|
hw_revision: str # hardware revision, e.g. "1.0" = firmware NVS "hw_revision"
|
||||||
mfg_status: str
|
mfg_status: str
|
||||||
mfg_batch_id: Optional[str] = None
|
mfg_batch_id: Optional[str] = None
|
||||||
created_at: Optional[str] = None
|
created_at: Optional[str] = None
|
||||||
@@ -134,7 +134,7 @@ class CustomerSearchResult(BaseModel):
|
|||||||
|
|
||||||
class RecentActivityItem(BaseModel):
|
class RecentActivityItem(BaseModel):
|
||||||
serial_number: str
|
serial_number: str
|
||||||
hw_type: str
|
hw_family: str
|
||||||
mfg_status: str
|
mfg_status: str
|
||||||
owner: Optional[str] = None
|
owner: Optional[str] = None
|
||||||
updated_at: Optional[str] = None
|
updated_at: Optional[str] = None
|
||||||
|
|||||||
@@ -71,8 +71,8 @@ async def create_batch(
|
|||||||
@router.get("/devices", response_model=DeviceInventoryListResponse)
|
@router.get("/devices", response_model=DeviceInventoryListResponse)
|
||||||
def list_devices(
|
def list_devices(
|
||||||
status: Optional[str] = Query(None),
|
status: Optional[str] = Query(None),
|
||||||
hw_type: Optional[str] = Query(None),
|
hw_family: Optional[str] = Query(None),
|
||||||
hw_types: Optional[list[str]] = Query(None, description="Multi-select board type filter — repeat param, e.g. ?hw_types=vesper&hw_types=chronos"),
|
hw_families: Optional[list[str]] = Query(None, description="Multi-select board family filter — repeat param, e.g. ?hw_families=vesper&hw_families=chronos"),
|
||||||
has_users: Optional[bool] = Query(None, description="Filter by whether the device has any app users assigned"),
|
has_users: Optional[bool] = Query(None, description="Filter by whether the device has any app users assigned"),
|
||||||
search: Optional[str] = Query(None),
|
search: Optional[str] = Query(None),
|
||||||
limit: int = Query(100, ge=1, le=500),
|
limit: int = Query(100, ge=1, le=500),
|
||||||
@@ -81,8 +81,8 @@ def list_devices(
|
|||||||
):
|
):
|
||||||
items = service.list_devices(
|
items = service.list_devices(
|
||||||
status=status,
|
status=status,
|
||||||
hw_type=hw_type,
|
hw_family=hw_family,
|
||||||
hw_types=hw_types,
|
hw_families=hw_families,
|
||||||
has_users=has_users,
|
has_users=has_users,
|
||||||
search=search,
|
search=search,
|
||||||
limit=limit,
|
limit=limit,
|
||||||
@@ -605,7 +605,7 @@ def download_bootloader(
|
|||||||
):
|
):
|
||||||
"""Return the bootloader.bin for this device's hw_type (flashed at 0x1000)."""
|
"""Return the bootloader.bin for this device's hw_type (flashed at 0x1000)."""
|
||||||
item = service.get_device_by_sn(sn)
|
item = service.get_device_by_sn(sn)
|
||||||
hw_type = hw_type_override or item.hw_type
|
hw_type = hw_type_override or item.hw_family
|
||||||
try:
|
try:
|
||||||
data = service.get_flash_asset(hw_type, "bootloader.bin")
|
data = service.get_flash_asset(hw_type, "bootloader.bin")
|
||||||
except NotFoundError as e:
|
except NotFoundError as e:
|
||||||
@@ -625,7 +625,7 @@ def download_partitions(
|
|||||||
):
|
):
|
||||||
"""Return the partitions.bin for this device's hw_type (flashed at 0x8000)."""
|
"""Return the partitions.bin for this device's hw_type (flashed at 0x8000)."""
|
||||||
item = service.get_device_by_sn(sn)
|
item = service.get_device_by_sn(sn)
|
||||||
hw_type = hw_type_override or item.hw_type
|
hw_type = hw_type_override or item.hw_family
|
||||||
try:
|
try:
|
||||||
data = service.get_flash_asset(hw_type, "partitions.bin")
|
data = service.get_flash_asset(hw_type, "partitions.bin")
|
||||||
except NotFoundError as e:
|
except NotFoundError as e:
|
||||||
|
|||||||
@@ -66,8 +66,9 @@ def _doc_to_inventory_item(doc, customer_names: dict | None = None, user_infos:
|
|||||||
return DeviceInventoryItem(
|
return DeviceInventoryItem(
|
||||||
id=doc.id,
|
id=doc.id,
|
||||||
serial_number=data.get("serial_number", ""),
|
serial_number=data.get("serial_number", ""),
|
||||||
hw_type=data.get("hw_type", ""),
|
# hw_type / hw_version: names used before 2026-11-08 (kept as read fallback)
|
||||||
hw_version=data.get("hw_version", ""),
|
hw_family=data.get("hw_family") or data.get("hw_type", ""),
|
||||||
|
hw_revision=data.get("hw_revision") or data.get("hw_version", ""),
|
||||||
mfg_status=data.get("mfg_status", "manufactured"),
|
mfg_status=data.get("mfg_status", "manufactured"),
|
||||||
mfg_batch_id=data.get("mfg_batch_id"),
|
mfg_batch_id=data.get("mfg_batch_id"),
|
||||||
created_at=created_str,
|
created_at=created_str,
|
||||||
@@ -134,8 +135,11 @@ def create_batch(data: BatchCreate) -> BatchResponse:
|
|||||||
|
|
||||||
db.collection(COLLECTION).add({
|
db.collection(COLLECTION).add({
|
||||||
"serial_number": sn,
|
"serial_number": sn,
|
||||||
"hw_type": data.board_type.value,
|
"device_id": sn, # schema v1 / D1: both apps connect over MQTT with device_id
|
||||||
"hw_version": data.board_version,
|
|
||||||
|
# Same names as the firmware NVS keys.
|
||||||
|
"hw_family": data.board_type.value,
|
||||||
|
"hw_revision": data.board_version,
|
||||||
"mfg_status": "manufactured",
|
"mfg_status": "manufactured",
|
||||||
"mfg_batch_id": batch_id,
|
"mfg_batch_id": batch_id,
|
||||||
"created_at": now,
|
"created_at": now,
|
||||||
@@ -168,8 +172,8 @@ def create_batch(data: BatchCreate) -> BatchResponse:
|
|||||||
|
|
||||||
def list_devices(
|
def list_devices(
|
||||||
status: str | None = None,
|
status: str | None = None,
|
||||||
hw_type: str | None = None,
|
hw_family: str | None = None,
|
||||||
hw_types: list[str] | None = None,
|
hw_families: list[str] | None = None,
|
||||||
has_users: bool | None = None,
|
has_users: bool | None = None,
|
||||||
search: str | None = None,
|
search: str | None = None,
|
||||||
limit: int = 100,
|
limit: int = 100,
|
||||||
@@ -180,15 +184,15 @@ def list_devices(
|
|||||||
|
|
||||||
if status:
|
if status:
|
||||||
query = query.where("mfg_status", "==", status)
|
query = query.where("mfg_status", "==", status)
|
||||||
if hw_type:
|
if hw_family:
|
||||||
query = query.where("hw_type", "==", hw_type)
|
query = query.where("hw_family", "==", hw_family)
|
||||||
|
|
||||||
docs = list(query.stream())
|
docs = list(query.stream())
|
||||||
docs_data = [doc.to_dict() or {} for doc in docs]
|
docs_data = [doc.to_dict() or {} for doc in docs]
|
||||||
|
|
||||||
if hw_types:
|
if hw_families:
|
||||||
hw_type_set = set(hw_types)
|
family_set = set(hw_families)
|
||||||
keep = [i for i, d in enumerate(docs_data) if d.get("hw_type") in hw_type_set]
|
keep = [i for i, d in enumerate(docs_data) if d.get("hw_family") in family_set]
|
||||||
docs = [docs[i] for i in keep]
|
docs = [docs[i] for i in keep]
|
||||||
docs_data = [docs_data[i] for i in keep]
|
docs_data = [docs_data[i] for i in keep]
|
||||||
|
|
||||||
@@ -272,8 +276,8 @@ def get_nvs_binary(sn: str, hw_type_override: str | None = None, hw_revision_ove
|
|||||||
item = get_device_by_sn(sn)
|
item = get_device_by_sn(sn)
|
||||||
return generate_nvs_binary(
|
return generate_nvs_binary(
|
||||||
serial_number=item.serial_number,
|
serial_number=item.serial_number,
|
||||||
hw_family=hw_type_override if hw_type_override else item.hw_type,
|
hw_family=hw_type_override if hw_type_override else item.hw_family,
|
||||||
hw_revision=hw_revision_override if hw_revision_override else item.hw_version,
|
hw_revision=hw_revision_override if hw_revision_override else item.hw_revision,
|
||||||
legacy=legacy,
|
legacy=legacy,
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -331,7 +335,7 @@ def assign_device(sn: str, data: DeviceAssign) -> DeviceInventoryItem:
|
|||||||
for item in owned_items
|
for item in owned_items
|
||||||
)
|
)
|
||||||
if not already_assigned:
|
if not already_assigned:
|
||||||
device_name = doc_data.get("device_name") or BOARD_TYPE_LABELS.get(doc_data.get("hw_type", ""), sn)
|
device_name = doc_data.get("device_name") or BOARD_TYPE_LABELS.get(doc_data.get("hw_family") or doc_data.get("hw_type", ""), sn)
|
||||||
owned_items.append({
|
owned_items.append({
|
||||||
"type": "console_device",
|
"type": "console_device",
|
||||||
"console_device": {
|
"console_device": {
|
||||||
@@ -401,7 +405,7 @@ def get_stats() -> ManufacturingStats:
|
|||||||
|
|
||||||
activity_candidates.append(RecentActivityItem(
|
activity_candidates.append(RecentActivityItem(
|
||||||
serial_number=data.get("serial_number", ""),
|
serial_number=data.get("serial_number", ""),
|
||||||
hw_type=data.get("hw_type", ""),
|
hw_family=data.get("hw_family") or data.get("hw_type", ""),
|
||||||
mfg_status=status,
|
mfg_status=status,
|
||||||
owner=data.get("owner"),
|
owner=data.get("owner"),
|
||||||
updated_at=ts_str,
|
updated_at=ts_str,
|
||||||
@@ -561,7 +565,6 @@ def get_firmware_url(sn: str) -> str:
|
|||||||
"""Return the FastAPI download URL for the latest stable firmware for this device's hw_type."""
|
"""Return the FastAPI download URL for the latest stable firmware for this device's hw_type."""
|
||||||
from firmware.service import get_latest
|
from firmware.service import get_latest
|
||||||
item = get_device_by_sn(sn)
|
item = get_device_by_sn(sn)
|
||||||
hw_type = item.hw_type.lower()
|
latest = get_latest(item.hw_family.lower(), "stable")
|
||||||
latest = get_latest(hw_type, "stable")
|
|
||||||
# download_url is a relative path like /api/firmware/vs/stable/1.4.2/firmware.bin
|
# download_url is a relative path like /api/firmware/vs/stable/1.4.2/firmware.bin
|
||||||
return latest.download_url
|
return latest.download_url
|
||||||
|
|||||||
+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,
|
||||||
|
|||||||
@@ -109,9 +109,9 @@ async def validate_serial(serial_number: str):
|
|||||||
device = get_device_by_sn(sn)
|
device = get_device_by_sn(sn)
|
||||||
return SerialValidationResult(
|
return SerialValidationResult(
|
||||||
valid=True,
|
valid=True,
|
||||||
hw_type=device.hw_type,
|
hw_type=device.hw_family,
|
||||||
hw_type_label=HW_TYPE_LABELS.get(device.hw_type, device.hw_type.replace("_", " ").title()),
|
hw_type_label=HW_TYPE_LABELS.get(device.hw_family, device.hw_family.replace("_", " ").title()),
|
||||||
hw_version=device.hw_version,
|
hw_version=device.hw_revision,
|
||||||
)
|
)
|
||||||
except Exception:
|
except Exception:
|
||||||
return SerialValidationResult(valid=False)
|
return SerialValidationResult(valid=False)
|
||||||
|
|||||||
@@ -18,3 +18,5 @@ pdf2image>=1.17.0
|
|||||||
asyncpg==0.30.0
|
asyncpg==0.30.0
|
||||||
sqlalchemy[asyncio]==2.0.36
|
sqlalchemy[asyncio]==2.0.36
|
||||||
alembic==1.14.0
|
alembic==1.14.0
|
||||||
|
# IANA tz database for the device timezone table (timezones/). Bump to pick up new DST rules.
|
||||||
|
tzdata==2026.6
|
||||||
|
|||||||
@@ -0,0 +1,96 @@
|
|||||||
|
"""
|
||||||
|
Make every device's `device_users` sub-collection mirror its `user_list`.
|
||||||
|
|
||||||
|
`user_list` is the source of truth for device assignments. The Console keeps
|
||||||
|
`device_users` ({role, user_reference}) only as a write-only mirror in case the
|
||||||
|
phone app still reads it. Before 2026-11 the Console read `device_users` first
|
||||||
|
and never wrote it, so the two drifted. This script lists the drift and, with
|
||||||
|
--apply, fixes the mirror:
|
||||||
|
|
||||||
|
- users in user_list with no device_users doc -> doc added (role "admin")
|
||||||
|
- device_users docs for users NOT in user_list -> doc deleted
|
||||||
|
|
||||||
|
It never changes `user_list` or `device_serials`. Check the dry-run output
|
||||||
|
first: if a user only appears in device_users and should keep the device,
|
||||||
|
assign them in the Console (Manage tab) before running --apply, or they will be
|
||||||
|
dropped from the mirror. Running it twice is a no-op the second time.
|
||||||
|
|
||||||
|
Run from backend/ (locally or inside the backend container):
|
||||||
|
|
||||||
|
python scripts/sync_device_users_mirror.py # dry run
|
||||||
|
python scripts/sync_device_users_mirror.py --apply # write changes
|
||||||
|
"""
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
import sys
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||||
|
|
||||||
|
from shared.firebase import init_firebase, get_db # noqa: E402
|
||||||
|
from devices.service import ( # noqa: E402
|
||||||
|
DEFAULT_DEVICE_USER_ROLE, DEVICE_USERS_SUBCOLLECTION, device_users_by_user, user_list_entry_id,
|
||||||
|
)
|
||||||
|
|
||||||
|
BATCH_SIZE = 400 # Firestore batch limit is 500 writes
|
||||||
|
|
||||||
|
|
||||||
|
def _label(db, uid: str) -> str:
|
||||||
|
snap = db.collection("users").document(uid).get()
|
||||||
|
if not snap.exists:
|
||||||
|
return f"{uid} (no user doc)"
|
||||||
|
data = snap.to_dict() or {}
|
||||||
|
return f"{uid} ({data.get('display_name') or data.get('email') or '?'})"
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> int:
|
||||||
|
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||||
|
parser.add_argument("--apply", action="store_true", help="write changes (default: dry run)")
|
||||||
|
args = parser.parse_args()
|
||||||
|
|
||||||
|
init_firebase()
|
||||||
|
db = get_db()
|
||||||
|
if db is None:
|
||||||
|
print("[ERROR] Firebase not initialized — check FIREBASE_SERVICE_ACCOUNT_PATH")
|
||||||
|
return 1
|
||||||
|
|
||||||
|
print(f"=== sync device_users mirror — {'APPLY' if args.apply else 'DRY RUN'} ===")
|
||||||
|
writes = [] # (op, ref, data)
|
||||||
|
for dev in db.collection("devices").stream():
|
||||||
|
data = dev.to_dict() or {}
|
||||||
|
wanted = {user_list_entry_id(e) for e in data.get("user_list") or []} - {""}
|
||||||
|
mirror = device_users_by_user(dev.reference)
|
||||||
|
to_add = sorted(u for u in wanted - mirror.keys()
|
||||||
|
if db.collection("users").document(u).get().exists)
|
||||||
|
to_del = sorted(mirror.keys() - wanted)
|
||||||
|
if not to_add and not to_del:
|
||||||
|
continue
|
||||||
|
serial = data.get("serial_number") or data.get("device_id") or "?"
|
||||||
|
print(f"\n{dev.id} {serial} {data.get('device_name') or ''}")
|
||||||
|
for u in to_add:
|
||||||
|
print(f" + add mirror {_label(db, u)}")
|
||||||
|
writes.append(("set", dev.reference.collection(DEVICE_USERS_SUBCOLLECTION).document(), {
|
||||||
|
"role": DEFAULT_DEVICE_USER_ROLE,
|
||||||
|
"user_reference": db.collection("users").document(u),
|
||||||
|
}))
|
||||||
|
for u in to_del:
|
||||||
|
print(f" - remove mirror {_label(db, u)} <- only in device_users, not in user_list")
|
||||||
|
writes.extend(("delete", snap.reference, None) for snap in mirror[u])
|
||||||
|
|
||||||
|
print(f"\n{len(writes)} write(s) needed.")
|
||||||
|
if not args.apply or not writes:
|
||||||
|
if writes:
|
||||||
|
print("Dry run — nothing written. Re-run with --apply to write.")
|
||||||
|
return 0
|
||||||
|
|
||||||
|
for i in range(0, len(writes), BATCH_SIZE):
|
||||||
|
batch = db.batch()
|
||||||
|
for op, ref, payload in writes[i:i + BATCH_SIZE]:
|
||||||
|
batch.set(ref, payload) if op == "set" else batch.delete(ref)
|
||||||
|
batch.commit()
|
||||||
|
print("Done.")
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
sys.exit(main())
|
||||||
@@ -1,16 +1,21 @@
|
|||||||
"""
|
"""
|
||||||
update_device must keep users.device_serials in sync when a PUT changes the
|
Device user assignment: `user_list` is the source of truth. Every write must
|
||||||
device's user_list (the MQTT ACL reads device_serials). Firestore is faked.
|
keep users.device_serials (MQTT ACL) and the device_users sub-collection
|
||||||
|
mirror in sync, and reads must come from user_list only. Firestore is faked.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
import itertools
|
||||||
|
|
||||||
import pytest
|
import pytest
|
||||||
from google.cloud.firestore_v1 import ArrayRemove, ArrayUnion
|
from google.cloud.firestore_v1 import ArrayRemove, ArrayUnion, DocumentReference
|
||||||
|
|
||||||
from devices import service as devices_service
|
from devices import service as devices_service
|
||||||
from devices.models import DeviceUpdate
|
from devices.models import DeviceUpdate
|
||||||
from mqtt import app_users
|
from mqtt import app_users
|
||||||
|
from users import service as users_service
|
||||||
|
|
||||||
SERIAL = "BSVSPR-26C13X-STD01R-X7KQA"
|
SERIAL = "BSVSPR-26C13X-STD01R-X7KQA"
|
||||||
|
MIRROR = "devices/dev1/device_users"
|
||||||
|
|
||||||
|
|
||||||
class _Snap:
|
class _Snap:
|
||||||
@@ -24,9 +29,16 @@ class _Snap:
|
|||||||
return dict(self._data) if self._data is not None else None
|
return dict(self._data) if self._data is not None else None
|
||||||
|
|
||||||
|
|
||||||
class _Ref:
|
class _Ref(DocumentReference):
|
||||||
def __init__(self, db, collection, doc_id):
|
"""A real DocumentReference subclass, so isinstance checks and .id/.path work."""
|
||||||
self._db, self._col, self.id = db, collection, doc_id
|
|
||||||
|
def __init__(self, db, col_path, doc_id):
|
||||||
|
self._db, self._col = db, col_path
|
||||||
|
self._client = db
|
||||||
|
self._path = tuple(col_path.split("/")) + (doc_id,)
|
||||||
|
|
||||||
|
def collection(self, name):
|
||||||
|
return _Collection(self._db, f"{self._col}/{self.id}/{name}")
|
||||||
|
|
||||||
def get(self):
|
def get(self):
|
||||||
return _Snap(self, self._db.docs[self._col].get(self.id))
|
return _Snap(self, self._db.docs[self._col].get(self.id))
|
||||||
@@ -34,32 +46,48 @@ class _Ref:
|
|||||||
def update(self, data):
|
def update(self, data):
|
||||||
self._db.apply(self._col, self.id, data)
|
self._db.apply(self._col, self.id, data)
|
||||||
|
|
||||||
|
def set(self, data):
|
||||||
|
self._db.docs[self._col][self.id] = dict(data)
|
||||||
|
|
||||||
|
def delete(self):
|
||||||
|
self._db.docs[self._col].pop(self.id, None)
|
||||||
|
|
||||||
|
|
||||||
class _Batch:
|
class _Batch:
|
||||||
def __init__(self, db):
|
def __init__(self, db):
|
||||||
self._db, self.ops = db, []
|
self._db, self.ops = db, []
|
||||||
|
|
||||||
def update(self, ref, data):
|
def update(self, ref, data):
|
||||||
self.ops.append((ref, data))
|
self.ops.append(("update", ref, data))
|
||||||
|
|
||||||
|
def set(self, ref, data):
|
||||||
|
self.ops.append(("set", ref, data))
|
||||||
|
|
||||||
|
def delete(self, ref):
|
||||||
|
self.ops.append(("delete", ref, None))
|
||||||
|
|
||||||
def commit(self):
|
def commit(self):
|
||||||
for ref, data in self.ops:
|
for op, ref, data in self.ops:
|
||||||
ref.update(data)
|
getattr(ref, op)(*([data] if data is not None else []))
|
||||||
self._db.commits += 1
|
self._db.commits += 1
|
||||||
|
|
||||||
|
|
||||||
class _Collection:
|
class _Collection:
|
||||||
def __init__(self, db, name):
|
def __init__(self, db, path):
|
||||||
self._db, self._name = db, name
|
self._db, self._path = db, path
|
||||||
|
|
||||||
def document(self, doc_id):
|
def document(self, doc_id=None):
|
||||||
return _Ref(self._db, self._name, doc_id)
|
return _Ref(self._db, self._path, doc_id or f"auto{next(self._db.ids)}")
|
||||||
|
|
||||||
|
def stream(self):
|
||||||
|
return [_Snap(_Ref(self._db, self._path, k), v) for k, v in list(self._db.docs[self._path].items())]
|
||||||
|
|
||||||
|
|
||||||
class FakeDB:
|
class FakeDB:
|
||||||
def __init__(self):
|
def __init__(self):
|
||||||
self.docs = {"devices": {}, "users": {}}
|
self.docs = {"devices": {}, "users": {}, MIRROR: {}}
|
||||||
self.commits = 0
|
self.commits = 0
|
||||||
|
self.ids = itertools.count(1)
|
||||||
|
|
||||||
def collection(self, name):
|
def collection(self, name):
|
||||||
return _Collection(self, name)
|
return _Collection(self, name)
|
||||||
@@ -67,6 +95,10 @@ class FakeDB:
|
|||||||
def batch(self):
|
def batch(self):
|
||||||
return _Batch(self)
|
return _Batch(self)
|
||||||
|
|
||||||
|
def ref(self, path):
|
||||||
|
col, doc_id = path.rsplit("/", 1)
|
||||||
|
return _Ref(self, col, doc_id)
|
||||||
|
|
||||||
def apply(self, col, doc_id, data):
|
def apply(self, col, doc_id, data):
|
||||||
doc = self.docs[col][doc_id]
|
doc = self.docs[col][doc_id]
|
||||||
for key, val in data.items():
|
for key, val in data.items():
|
||||||
@@ -77,38 +109,53 @@ class FakeDB:
|
|||||||
else:
|
else:
|
||||||
doc[key] = val
|
doc[key] = val
|
||||||
|
|
||||||
|
def mirror_user_ids(self):
|
||||||
|
return sorted(d["user_reference"].id for d in self.docs[MIRROR].values())
|
||||||
|
|
||||||
|
def user_list_ids(self, device="dev1"):
|
||||||
|
return [devices_service.user_list_entry_id(e) for e in self.docs["devices"][device]["user_list"]]
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture
|
@pytest.fixture
|
||||||
def db(monkeypatch):
|
def db(monkeypatch):
|
||||||
fake = FakeDB()
|
fake = FakeDB()
|
||||||
fake.docs["devices"]["dev1"] = {
|
fake.docs["devices"]["dev1"] = {
|
||||||
"serial_number": SERIAL, "mfg_status": "claimed", "user_list": ["users/alice", "users/bob"],
|
"serial_number": SERIAL, "mfg_status": "claimed",
|
||||||
|
"user_list": [fake.ref("users/alice"), "users/bob"], # both formats seen in the wild
|
||||||
}
|
}
|
||||||
fake.docs["users"]["alice"] = {"uid": "alice", "device_serials": [SERIAL]}
|
fake.docs[MIRROR]["m1"] = {"role": "admin", "user_reference": fake.ref("users/alice")}
|
||||||
fake.docs["users"]["bob"] = {"uid": "bob", "device_serials": [SERIAL, "OTHER"]}
|
fake.docs["users"]["alice"] = {"uid": "alice", "device_serials": [SERIAL], "display_name": "Alice"}
|
||||||
fake.docs["users"]["carol"] = {"uid": "carol"}
|
fake.docs["users"]["bob"] = {"uid": "bob", "device_serials": [SERIAL, "OTHER"], "display_name": "Bob"}
|
||||||
|
fake.docs["users"]["carol"] = {"uid": "carol", "display_name": "Carol"}
|
||||||
monkeypatch.setattr(devices_service, "get_db", lambda: fake)
|
monkeypatch.setattr(devices_service, "get_db", lambda: fake)
|
||||||
|
monkeypatch.setattr(users_service, "get_db", lambda: fake)
|
||||||
|
monkeypatch.setattr(app_users, "invalidate", lambda uid: None)
|
||||||
return fake
|
return fake
|
||||||
|
|
||||||
|
|
||||||
|
# ── PUT /api/devices/{id} with user_list ─────────────────────────────────────
|
||||||
|
|
||||||
def test_put_user_list_syncs_added_and_removed_users(db, monkeypatch):
|
def test_put_user_list_syncs_added_and_removed_users(db, monkeypatch):
|
||||||
invalidated = []
|
invalidated = []
|
||||||
monkeypatch.setattr(app_users, "invalidate", invalidated.append)
|
monkeypatch.setattr(app_users, "invalidate", invalidated.append)
|
||||||
|
|
||||||
devices_service.update_device("dev1", DeviceUpdate(user_list=["users/alice", "users/carol"]))
|
devices_service.update_device("dev1", DeviceUpdate(user_list=["users/alice", "users/carol"]))
|
||||||
|
|
||||||
assert db.docs["devices"]["dev1"]["user_list"] == ["users/alice", "users/carol"]
|
assert db.user_list_ids() == ["alice", "carol"]
|
||||||
|
assert all(isinstance(e, DocumentReference) for e in db.docs["devices"]["dev1"]["user_list"])
|
||||||
assert db.docs["users"]["alice"]["device_serials"] == [SERIAL] # unchanged
|
assert db.docs["users"]["alice"]["device_serials"] == [SERIAL] # unchanged
|
||||||
assert db.docs["users"]["bob"]["device_serials"] == ["OTHER"] # removed
|
assert db.docs["users"]["bob"]["device_serials"] == ["OTHER"] # removed
|
||||||
assert db.docs["users"]["carol"]["device_serials"] == [SERIAL] # added
|
assert db.docs["users"]["carol"]["device_serials"] == [SERIAL] # added
|
||||||
|
assert db.mirror_user_ids() == ["alice", "carol"] # alice's mirror kept, carol's added
|
||||||
assert sorted(invalidated) == ["bob", "carol"]
|
assert sorted(invalidated) == ["bob", "carol"]
|
||||||
assert db.commits == 1 # one atomic batch
|
assert db.commits == 1 # one atomic batch
|
||||||
|
|
||||||
|
|
||||||
def test_put_user_list_ignores_dangling_user_refs(db):
|
def test_put_user_list_ignores_dangling_user_refs(db):
|
||||||
devices_service.update_device("dev1", DeviceUpdate(user_list=["users/alice", "users/bob", "users/ghost"]))
|
devices_service.update_device("dev1", DeviceUpdate(user_list=["users/alice", "users/bob", "users/ghost"]))
|
||||||
assert db.docs["devices"]["dev1"]["user_list"] == ["users/alice", "users/bob", "users/ghost"]
|
assert db.user_list_ids() == ["alice", "bob", "ghost"]
|
||||||
assert "ghost" not in db.docs["users"]
|
assert "ghost" not in db.docs["users"]
|
||||||
|
assert "ghost" not in db.mirror_user_ids()
|
||||||
|
|
||||||
|
|
||||||
def test_put_without_user_list_does_not_touch_users(db):
|
def test_put_without_user_list_does_not_touch_users(db):
|
||||||
@@ -116,3 +163,45 @@ def test_put_without_user_list_does_not_touch_users(db):
|
|||||||
assert db.docs["devices"]["dev1"]["device_name"] == "Church"
|
assert db.docs["devices"]["dev1"]["device_name"] == "Church"
|
||||||
assert db.commits == 0
|
assert db.commits == 0
|
||||||
assert db.docs["users"]["bob"]["device_serials"] == [SERIAL, "OTHER"]
|
assert db.docs["users"]["bob"]["device_serials"] == [SERIAL, "OTHER"]
|
||||||
|
|
||||||
|
|
||||||
|
# ── Reads come from user_list, not the sub-collection ────────────────────────
|
||||||
|
|
||||||
|
def test_get_device_users_reads_user_list_with_mirror_role(db):
|
||||||
|
# A stale mirror doc for someone NOT in user_list must not show up.
|
||||||
|
db.docs[MIRROR]["stale"] = {"role": "admin", "user_reference": db.ref("users/carol")}
|
||||||
|
|
||||||
|
users = devices_service.get_device_users("dev1")
|
||||||
|
|
||||||
|
assert [(u["user_id"], u["display_name"], u["role"]) for u in users] == [
|
||||||
|
("alice", "Alice", "admin"),
|
||||||
|
("bob", "Bob", ""),
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def test_get_device_users_skips_duplicates_and_missing_users(db):
|
||||||
|
db.docs["devices"]["dev1"]["user_list"] += ["alice", db.ref("users/ghost")]
|
||||||
|
assert [u["user_id"] for u in devices_service.get_device_users("dev1")] == ["alice", "bob"]
|
||||||
|
|
||||||
|
|
||||||
|
# ── Users page: assign / unassign ────────────────────────────────────────────
|
||||||
|
|
||||||
|
def test_assign_device_writes_reference_and_mirror(db):
|
||||||
|
users_service.assign_device("carol", "dev1")
|
||||||
|
assert db.user_list_ids() == ["alice", "bob", "carol"]
|
||||||
|
assert isinstance(db.docs["devices"]["dev1"]["user_list"][-1], DocumentReference)
|
||||||
|
assert db.docs["users"]["carol"]["device_serials"] == [SERIAL]
|
||||||
|
assert db.mirror_user_ids() == ["alice", "carol"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_assign_device_twice_does_not_duplicate(db):
|
||||||
|
users_service.assign_device("alice", "dev1")
|
||||||
|
assert db.user_list_ids() == ["alice", "bob"]
|
||||||
|
assert db.mirror_user_ids() == ["alice"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_unassign_device_removes_any_format_and_mirror(db):
|
||||||
|
users_service.unassign_device("alice", "dev1")
|
||||||
|
assert db.user_list_ids() == ["bob"]
|
||||||
|
assert db.docs["users"]["alice"]["device_serials"] == []
|
||||||
|
assert db.mirror_user_ids() == []
|
||||||
|
|||||||
@@ -0,0 +1,190 @@
|
|||||||
|
"""
|
||||||
|
Device writes must match Firestore schema v1 (bellsystems-schema/v1). One wrongly
|
||||||
|
typed field makes the FlutterFlow apps silently drop the whole device, so these
|
||||||
|
cover the exact shapes found corrupting production data on 2026-11-08.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from google.cloud.firestore_v1 import DocumentReference, GeoPoint
|
||||||
|
|
||||||
|
from devices import firestore_v1 as v1
|
||||||
|
from devices.models import DeviceCreate
|
||||||
|
from shared.exceptions import ValidationError
|
||||||
|
|
||||||
|
|
||||||
|
class _FakeDb:
|
||||||
|
"""Just enough of a Firestore client to build DocumentReferences."""
|
||||||
|
|
||||||
|
def collection(self, name):
|
||||||
|
db = self
|
||||||
|
|
||||||
|
class _Col:
|
||||||
|
def document(self, doc_id):
|
||||||
|
return DocumentReference(name, doc_id, client=db)
|
||||||
|
|
||||||
|
return _Col()
|
||||||
|
|
||||||
|
|
||||||
|
DB = _FakeDb()
|
||||||
|
T = datetime(2026, 1, 15, 22, 1, tzinfo=timezone.utc)
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------- timestamps
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("value", ["", None])
|
||||||
|
def test_unset_timestamp_becomes_null_never_empty_string(value):
|
||||||
|
out = v1.to_firestore({"device_attributes": {"towerClockTime": value,
|
||||||
|
"clockSettings": {"daySilenceFrom": value}}})
|
||||||
|
assert out["device_attributes"]["towerClockTime"] is None
|
||||||
|
assert out["device_attributes"]["clockSettings"]["daySilenceFrom"] is None
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("value", [
|
||||||
|
"2026-01-15T22:01:00Z",
|
||||||
|
"2026-01-15T22:01:00+00:00",
|
||||||
|
"15 January 2026 at 22:01:00 UTC+0000", # the format the API used to serve
|
||||||
|
])
|
||||||
|
def test_timestamp_strings_become_datetimes(value):
|
||||||
|
out = v1.to_firestore({"device_stats": {"maintainedOn": value}})
|
||||||
|
assert out["device_stats"]["maintainedOn"] == T
|
||||||
|
|
||||||
|
|
||||||
|
def test_unparseable_timestamp_is_rejected_not_stored():
|
||||||
|
with pytest.raises(ValidationError):
|
||||||
|
v1.to_firestore({"device_subscription": {"subscrStart": "next tuesday"}})
|
||||||
|
|
||||||
|
|
||||||
|
def test_timestamp_round_trip_is_lossless():
|
||||||
|
stored = {"device_attributes": {"clockSettings": {"nightSilenceTo": T}}}
|
||||||
|
api = v1.to_api(stored)
|
||||||
|
assert api["device_attributes"]["clockSettings"]["nightSilenceTo"] == "2026-01-15T22:01:00Z"
|
||||||
|
again = v1.to_firestore(api)
|
||||||
|
assert again["device_attributes"]["clockSettings"]["nightSilenceTo"] == T
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------- IP addresses
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("value, expected", [
|
||||||
|
(["10", "0", "0", "5"], "10.0.0.5"),
|
||||||
|
([10, 0, 0, 5], "10.0.0.5"),
|
||||||
|
([], ""),
|
||||||
|
("192.168.1.102", "192.168.1.102"),
|
||||||
|
("", ""),
|
||||||
|
])
|
||||||
|
def test_ip_addresses_are_dotted_strings(value, expected):
|
||||||
|
out = v1.to_firestore({"device_attributes": {"networkSettings": {"ipAddress": value}}})
|
||||||
|
assert out["device_attributes"]["networkSettings"]["ipAddress"] == expected
|
||||||
|
|
||||||
|
|
||||||
|
def test_invalid_ip_is_rejected():
|
||||||
|
with pytest.raises(ValidationError):
|
||||||
|
v1.to_firestore({"device_attributes": {"networkSettings": {"gateway": "10.0.0"}}})
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------- key spelling
|
||||||
|
|
||||||
|
def test_legacy_keys_are_renamed():
|
||||||
|
out = v1.to_firestore({"device_attributes": {
|
||||||
|
"bellGuardSafetyOn": True,
|
||||||
|
"networkSettings": {"useStaticIP": True},
|
||||||
|
}})
|
||||||
|
attrs = out["device_attributes"]
|
||||||
|
assert attrs == {"bellguardSafetyOn": True, "networkSettings": {"usesStaticIP": True}}
|
||||||
|
|
||||||
|
|
||||||
|
def test_v1_key_wins_over_legacy_duplicate():
|
||||||
|
out = v1.to_firestore({"device_attributes": {
|
||||||
|
"bellguardSafetyOn": False, "bellGuardSafetyOn": True,
|
||||||
|
"networkSettings": {"usesStaticIP": True, "useStaticIP": False},
|
||||||
|
}})
|
||||||
|
attrs = out["device_attributes"]
|
||||||
|
assert attrs["bellguardSafetyOn"] is False and "bellGuardSafetyOn" not in attrs
|
||||||
|
assert attrs["networkSettings"] == {"usesStaticIP": True}
|
||||||
|
|
||||||
|
|
||||||
|
def test_legacy_hw_names_become_firmware_names():
|
||||||
|
out = v1.to_firestore({"hw_type": "vesper_plus", "hw_version": "1.0"})
|
||||||
|
assert out == {"hw_family": "vesper_plus", "hw_revision": "1.0"}
|
||||||
|
assert v1.to_api({"hw_type": "agnus", "hw_version": "1.0"}) == {"hw_family": "agnus", "hw_revision": "1.0"}
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("label", ["Bell Plus", "Bell Core", "vesper plus"])
|
||||||
|
def test_hw_family_display_labels_are_rejected(label):
|
||||||
|
with pytest.raises(ValidationError):
|
||||||
|
v1.to_firestore({"hw_family": label})
|
||||||
|
|
||||||
|
|
||||||
|
def test_retired_users_list_is_dropped():
|
||||||
|
assert "users_list" not in v1.to_firestore({"users_list": [], "device_name": "x"})
|
||||||
|
|
||||||
|
|
||||||
|
def test_read_folds_legacy_keys_and_repairs_values():
|
||||||
|
api = v1.to_api({"device_attributes": {
|
||||||
|
"bellGuardSafetyOn": True,
|
||||||
|
"towerClockTime": "",
|
||||||
|
"networkSettings": {"useStaticIP": True, "dns1": ["10", "0", "0", "1"]},
|
||||||
|
}})
|
||||||
|
attrs = api["device_attributes"]
|
||||||
|
assert attrs["bellguardSafetyOn"] is True and "bellGuardSafetyOn" not in attrs
|
||||||
|
assert attrs["towerClockTime"] is None
|
||||||
|
assert attrs["networkSettings"] == {"usesStaticIP": True, "dns1": "10.0.0.1"}
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------- identifiers (D1)
|
||||||
|
|
||||||
|
def test_serial_number_is_mirrored_to_device_id():
|
||||||
|
out = v1.to_firestore({"serial_number": "BSVSPR-26C20B-STD10R-2KCDPH"})
|
||||||
|
assert out["device_id"] == out["serial_number"] == "BSVSPR-26C20B-STD10R-2KCDPH"
|
||||||
|
|
||||||
|
|
||||||
|
def test_conflicting_ids_are_rejected():
|
||||||
|
with pytest.raises(ValidationError):
|
||||||
|
v1.to_firestore({"serial_number": "BSVSPR-A", "device_id": "PV25K29BP01R01"})
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------- references
|
||||||
|
|
||||||
|
def test_user_list_entries_become_references():
|
||||||
|
out = v1.to_firestore({"user_list": ["users/alice", "bob", "users/alice"]}, DB)
|
||||||
|
assert [r.path for r in out["user_list"]] == ["users/alice", "users/bob"]
|
||||||
|
assert all(isinstance(r, DocumentReference) for r in out["user_list"])
|
||||||
|
|
||||||
|
|
||||||
|
def test_coordinates_become_geopoint():
|
||||||
|
out = v1.to_firestore({"device_location_coordinates": {"lat": 40.6, "lng": 22.9}})
|
||||||
|
assert isinstance(out["device_location_coordinates"], GeoPoint)
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------- melodies
|
||||||
|
|
||||||
|
def test_device_melody_in_melodies_collection_shape_is_rejected():
|
||||||
|
with pytest.raises(ValidationError):
|
||||||
|
v1.to_firestore({"device_melodies_all": [{"information": {}, "default_settings": {}, "url": "x"}]})
|
||||||
|
|
||||||
|
|
||||||
|
def test_device_melody_reference_becomes_reference():
|
||||||
|
out = v1.to_firestore({"device_melodies_all": [
|
||||||
|
{"melodyReference": "melodies/m1", "mainInformation": {"name": "x"}},
|
||||||
|
]}, DB)
|
||||||
|
ref = out["device_melodies_all"][0]["melodyReference"]
|
||||||
|
assert isinstance(ref, DocumentReference) and ref.path == "melodies/m1"
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------- new devices
|
||||||
|
|
||||||
|
def test_new_device_defaults_are_v1_valid():
|
||||||
|
"""create_device writes DeviceCreate() defaults — they must not break the apps."""
|
||||||
|
doc = v1.to_firestore({**DeviceCreate().model_dump(), "serial_number": "BS-AAAA-BBBB"}, DB)
|
||||||
|
attrs = doc["device_attributes"]
|
||||||
|
for key in ("daySilenceFrom", "daySilenceTo", "nightSilenceFrom", "nightSilenceTo",
|
||||||
|
"backlightTurnOnTime", "backlightTurnOffTime"):
|
||||||
|
assert attrs["clockSettings"][key] is None
|
||||||
|
assert attrs["towerClockTime"] is None
|
||||||
|
assert attrs["networkSettings"]["ipAddress"] == ""
|
||||||
|
assert "useStaticIP" not in attrs["networkSettings"] and "usesStaticIP" in attrs["networkSettings"]
|
||||||
|
assert "bellguardSafetyOn" in attrs and "bellGuardSafetyOn" not in attrs
|
||||||
|
assert doc["device_stats"]["maintainedOn"] is None
|
||||||
|
assert doc["device_subscription"]["subscrStart"] is None
|
||||||
|
assert doc["device_id"] == "BS-AAAA-BBBB"
|
||||||
@@ -0,0 +1,117 @@
|
|||||||
|
"""
|
||||||
|
Timezone table for device clock setup (timezones/). Pure tzdata — no Firestore, no MQTT.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
import tzdata
|
||||||
|
from fastapi import FastAPI
|
||||||
|
from fastapi.testclient import TestClient
|
||||||
|
|
||||||
|
from timezones import service
|
||||||
|
from timezones.router import router
|
||||||
|
|
||||||
|
SUMMER = datetime(2026, 7, 15, 12, tzinfo=timezone.utc)
|
||||||
|
WINTER = datetime(2026, 1, 15, 12, tzinfo=timezone.utc)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("posix, expected", [
|
||||||
|
("EET-2EEST,M3.5.0/3,M10.5.0/4", (120, 60, True)),
|
||||||
|
("EST5EDT,M3.2.0,M11.1.0", (-300, 60, True)),
|
||||||
|
("IST-5:30", (330, 0, False)),
|
||||||
|
("<+0545>-5:45", (345, 0, False)),
|
||||||
|
("<-03>3", (-180, 0, False)),
|
||||||
|
("IST-1GMT0,M10.5.0,M3.5.0/1", (60, -60, True)), # Dublin: negative DST
|
||||||
|
("<+1030>-10:30<+11>-11,M10.1.0,M4.1.0", (630, 30, True)), # Lord Howe: 30 min DST
|
||||||
|
("<+1245>-12:45<+1345>,M9.5.0/2:45,M4.1.0/3:45", (765, 60, True)), # Chatham
|
||||||
|
("IST-2IDT,M3.4.4/26,M10.5.0", (120, 60, True)), # Israel extended hours
|
||||||
|
])
|
||||||
|
def test_posix_offsets(posix, expected):
|
||||||
|
assert service.posix_offsets(posix) == expected
|
||||||
|
|
||||||
|
|
||||||
|
def test_posix_offsets_rejects_garbage():
|
||||||
|
with pytest.raises(ValueError):
|
||||||
|
service.posix_offsets("not a rule")
|
||||||
|
|
||||||
|
|
||||||
|
def test_table_shape_and_version():
|
||||||
|
table = service.get_table(now=WINTER)
|
||||||
|
assert table["tzdata_version"] == tzdata.IANA_VERSION
|
||||||
|
countries = table["countries"]
|
||||||
|
assert len(countries) > 200
|
||||||
|
assert [c["name"] for c in countries] == sorted(c["name"] for c in countries)
|
||||||
|
zone_count = 0
|
||||||
|
for country in countries:
|
||||||
|
assert country["zones"], country["code"]
|
||||||
|
for zone in country["zones"]:
|
||||||
|
zone_count += 1
|
||||||
|
assert zone["posix"] and len(zone["posix"]) < 64 # firmware POSIX_MAX_LEN
|
||||||
|
assert len(zone["name"]) < 48 # firmware NAME_MAX_LEN
|
||||||
|
assert country["code"] in zone["countries"]
|
||||||
|
assert zone_count > 300
|
||||||
|
|
||||||
|
|
||||||
|
def test_greece_and_australia():
|
||||||
|
gr = service.get_table("gr", now=SUMMER)["countries"]
|
||||||
|
assert len(gr) == 1 and gr[0]["name"] == "Greece"
|
||||||
|
athens = gr[0]["zones"][0]
|
||||||
|
assert athens["name"] == "Europe/Athens"
|
||||||
|
assert athens["posix"] == "EET-2EEST,M3.5.0/3,M10.5.0/4"
|
||||||
|
assert (athens["std_offset_min"], athens["dst_offset_min"], athens["has_dst"]) == (120, 60, True)
|
||||||
|
assert athens["current_offset_min"] == 180 and athens["current_dst"] is True
|
||||||
|
assert athens["display"] == "(UTC+03:00) Athens"
|
||||||
|
|
||||||
|
au = {z["name"]: z for z in service.get_table("AU", now=SUMMER)["countries"][0]["zones"]}
|
||||||
|
assert au["Australia/Sydney"]["current_offset_min"] == 600 # southern winter
|
||||||
|
assert au["Australia/Brisbane"]["has_dst"] is False
|
||||||
|
assert au["Australia/Lord_Howe"]["dst_offset_min"] == 30
|
||||||
|
|
||||||
|
|
||||||
|
def test_current_offset_follows_dst():
|
||||||
|
athens = service.get_zone("Europe/Athens", now=WINTER)
|
||||||
|
assert athens["current_offset_min"] == 120 and athens["current_dst"] is False
|
||||||
|
|
||||||
|
|
||||||
|
def test_rule_offsets_match_zoneinfo_once_rules_are_settled():
|
||||||
|
# By 2030 every zone runs on its POSIX footer, so the offset in force must be
|
||||||
|
# either the standard offset or standard + DST from that rule.
|
||||||
|
table = service.get_table()
|
||||||
|
for when in (datetime(2030, 1, 15, 12, tzinfo=timezone.utc), datetime(2030, 7, 15, 12, tzinfo=timezone.utc)):
|
||||||
|
for country in table["countries"]:
|
||||||
|
for zone in country["zones"]:
|
||||||
|
current = service.get_zone(zone["name"], now=when)["current_offset_min"]
|
||||||
|
allowed = {zone["std_offset_min"], zone["std_offset_min"] + zone["dst_offset_min"]}
|
||||||
|
assert current in allowed, (zone["name"], when, current, allowed)
|
||||||
|
|
||||||
|
|
||||||
|
def test_unknown_country_and_zone():
|
||||||
|
assert service.get_table("XX") is None
|
||||||
|
assert service.get_zone("Nowhere/Town") is None
|
||||||
|
assert service.get_zone("../../etc/passwd") is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_alias_not_in_zone_tab_resolves():
|
||||||
|
zone = service.get_zone("Asia/Calcutta")
|
||||||
|
assert zone["posix"] == "IST-5:30" and zone["countries"] == []
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def client():
|
||||||
|
app = FastAPI()
|
||||||
|
app.include_router(router)
|
||||||
|
return TestClient(app)
|
||||||
|
|
||||||
|
|
||||||
|
def test_routes(client):
|
||||||
|
r = client.get("/api/public/timezones", params={"country": "GR"})
|
||||||
|
assert r.status_code == 200
|
||||||
|
assert r.json()["countries"][0]["zones"][0]["name"] == "Europe/Athens"
|
||||||
|
|
||||||
|
assert client.get("/api/public/timezones", params={"country": "XX"}).status_code == 404
|
||||||
|
|
||||||
|
r = client.get("/api/public/timezones/zone", params={"name": "Australia/Sydney"})
|
||||||
|
assert r.status_code == 200 and r.json()["posix"] == "AEST-10AEDT,M10.1.0,M4.1.0/3"
|
||||||
|
|
||||||
|
assert client.get("/api/public/timezones/zone", params={"name": "Nowhere/Town"}).status_code == 404
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
"""
|
||||||
|
Public (no-auth) timezone table for device clock setup — see timezones/service.py.
|
||||||
|
|
||||||
|
Public on purpose: it is IANA data, and the phone app (Firebase auth, MQTT) and the tablet
|
||||||
|
bundle export both need it without console credentials.
|
||||||
|
"""
|
||||||
|
from fastapi import APIRouter, HTTPException, Query
|
||||||
|
|
||||||
|
from timezones import service
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/api/public/timezones", tags=["timezones"])
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("")
|
||||||
|
async def list_timezones(country: str | None = Query(None, description="ISO 3166 alpha-2 code, e.g. GR")):
|
||||||
|
"""All countries with their IANA zones, POSIX rules and current offsets.
|
||||||
|
|
||||||
|
The response is also the file the tablet app bundles (save it as-is; `tzdata_version`
|
||||||
|
tells which IANA release it came from).
|
||||||
|
"""
|
||||||
|
table = service.get_table(country)
|
||||||
|
if table is None:
|
||||||
|
raise HTTPException(status_code=404, detail=f"Unknown country code: {country}")
|
||||||
|
return table
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/zone")
|
||||||
|
async def get_timezone(name: str = Query(..., description="IANA zone name, e.g. Europe/Athens")):
|
||||||
|
"""One zone by IANA name — e.g. to turn a phone's own timezone into a device rule."""
|
||||||
|
zone = service.get_zone(name)
|
||||||
|
if zone is None:
|
||||||
|
raise HTTPException(status_code=404, detail=f"Unknown timezone: {name}")
|
||||||
|
return zone
|
||||||
@@ -0,0 +1,170 @@
|
|||||||
|
"""
|
||||||
|
IANA timezone table for the device clock (firmware 3.0.0+, timezone mode "auto").
|
||||||
|
|
||||||
|
Devices evaluate a POSIX TZ rule string (e.g. "EET-2EEST,M3.5.0/3,M10.5.0/4"), not the
|
||||||
|
IANA database, so whoever sets a device's timezone has to send the rule. This module is the
|
||||||
|
single source of those rules for the console and the phone app (GET /api/public/timezones);
|
||||||
|
the tablet app, which only talks to devices over local WebSocket, bundles a saved copy of
|
||||||
|
the same response.
|
||||||
|
|
||||||
|
Everything comes from the `tzdata` package pinned in requirements.txt (IANA release in
|
||||||
|
`tzdata.IANA_VERSION`): the POSIX rule is the footer of each zone's TZif file, zone →
|
||||||
|
country from zone.tab, country names from iso3166.tab. To pick up new DST rules, bump the
|
||||||
|
pin — nothing is generated or committed by hand.
|
||||||
|
|
||||||
|
The firmware side is project-vesper src/TimeKeeper/TimeZone.cpp; its host tests check that
|
||||||
|
it evaluates every one of these rules the same way as CPython's zoneinfo.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import importlib.resources
|
||||||
|
import re
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
from functools import lru_cache
|
||||||
|
from zoneinfo import ZoneInfo
|
||||||
|
|
||||||
|
import tzdata
|
||||||
|
|
||||||
|
# POSIX TZ: std offset [dst [offset] [,rule]] — only the offsets are needed here.
|
||||||
|
_NAME = r"(?:<[^>]+>|[A-Za-z]{3,})"
|
||||||
|
_OFFSET = r"([+-]?\d{1,3}(?::\d{1,2}){0,2})"
|
||||||
|
_POSIX_RE = re.compile(rf"^{_NAME}{_OFFSET}(?:({_NAME}){_OFFSET}?(?:,.*)?)?$")
|
||||||
|
|
||||||
|
|
||||||
|
def _tzdata_file(name: str):
|
||||||
|
return importlib.resources.files("tzdata.zoneinfo").joinpath(*name.split("/"))
|
||||||
|
|
||||||
|
|
||||||
|
def _hms_to_min(text: str) -> int:
|
||||||
|
sign = -1 if text.startswith("-") else 1
|
||||||
|
parts = [int(p) for p in text.lstrip("+-").split(":")]
|
||||||
|
parts += [0] * (3 - len(parts))
|
||||||
|
return sign * (parts[0] * 60 + parts[1] + (1 if parts[2] >= 30 else 0))
|
||||||
|
|
||||||
|
|
||||||
|
def posix_offsets(posix: str) -> tuple[int, int, bool]:
|
||||||
|
"""(std_offset_min, dst_offset_min, has_dst), east-positive minutes.
|
||||||
|
|
||||||
|
POSIX offsets are west-positive ("EET-2" is UTC+2). dst_offset_min is the DST
|
||||||
|
*amount* (DST total - standard), default one hour, matching the firmware's
|
||||||
|
tz::makeAuto(). It can be negative (Europe/Dublin models winter as negative DST).
|
||||||
|
"""
|
||||||
|
m = _POSIX_RE.match(posix)
|
||||||
|
if not m:
|
||||||
|
raise ValueError(f"unparseable POSIX TZ rule: {posix!r}")
|
||||||
|
std = -_hms_to_min(m.group(1))
|
||||||
|
if not m.group(2):
|
||||||
|
return std, 0, False
|
||||||
|
total = -_hms_to_min(m.group(3)) if m.group(3) else std + 60
|
||||||
|
return std, total - std, True
|
||||||
|
|
||||||
|
|
||||||
|
def posix_rule(name: str) -> str | None:
|
||||||
|
"""POSIX TZ footer of a zone's TZif (v2+) file, or None."""
|
||||||
|
try:
|
||||||
|
data = _tzdata_file(name).read_bytes()
|
||||||
|
except (FileNotFoundError, IsADirectoryError, OSError):
|
||||||
|
return None
|
||||||
|
if not data.startswith(b"TZif") or data[4:5] < b"2":
|
||||||
|
return None
|
||||||
|
footer = data.rstrip(b"\n").rsplit(b"\n", 1)[-1].decode("ascii", "replace")
|
||||||
|
return footer or None
|
||||||
|
|
||||||
|
|
||||||
|
def _format_offset(minutes: int) -> str:
|
||||||
|
sign = "+" if minutes >= 0 else "-"
|
||||||
|
return f"UTC{sign}{abs(minutes) // 60:02d}:{abs(minutes) % 60:02d}"
|
||||||
|
|
||||||
|
|
||||||
|
@lru_cache(maxsize=1)
|
||||||
|
def _static_table() -> tuple[list[dict], dict[str, dict]]:
|
||||||
|
"""Countries (sorted by name) with their zones in zone.tab order, plus a name index.
|
||||||
|
Only the parts that never change at runtime; offsets "now" are added per request."""
|
||||||
|
countries_by_code = {}
|
||||||
|
for line in _tzdata_file("iso3166.tab").read_text(encoding="utf-8").splitlines():
|
||||||
|
if line and not line.startswith("#"):
|
||||||
|
code, name = line.split("\t", 1)
|
||||||
|
countries_by_code[code] = {"code": code, "name": name.strip(), "zones": []}
|
||||||
|
|
||||||
|
zones_by_name: dict[str, dict] = {}
|
||||||
|
for line in _tzdata_file("zone.tab").read_text(encoding="utf-8").splitlines():
|
||||||
|
if not line or line.startswith("#"):
|
||||||
|
continue
|
||||||
|
fields = line.split("\t")
|
||||||
|
code, name = fields[0], fields[2]
|
||||||
|
comment = fields[3].strip() if len(fields) > 3 else ""
|
||||||
|
posix = posix_rule(name)
|
||||||
|
country = countries_by_code.get(code)
|
||||||
|
if not posix or country is None:
|
||||||
|
continue
|
||||||
|
std, dst, has_dst = posix_offsets(posix)
|
||||||
|
zone = zones_by_name.get(name)
|
||||||
|
if zone is None:
|
||||||
|
zone = {
|
||||||
|
"name": name,
|
||||||
|
"city": name.rsplit("/", 1)[-1].replace("_", " "),
|
||||||
|
"comment": comment,
|
||||||
|
"posix": posix,
|
||||||
|
"std_offset_min": std,
|
||||||
|
"dst_offset_min": dst,
|
||||||
|
"has_dst": has_dst,
|
||||||
|
"countries": [],
|
||||||
|
}
|
||||||
|
zones_by_name[name] = zone
|
||||||
|
zone["countries"].append(code)
|
||||||
|
country["zones"].append(zone)
|
||||||
|
|
||||||
|
countries = sorted((c for c in countries_by_code.values() if c["zones"]), key=lambda c: c["name"])
|
||||||
|
return countries, zones_by_name
|
||||||
|
|
||||||
|
|
||||||
|
def _with_current(zone: dict, now: datetime) -> dict:
|
||||||
|
local = now.astimezone(ZoneInfo(zone["name"]))
|
||||||
|
offset = int(local.utcoffset().total_seconds() // 60)
|
||||||
|
out = {k: v for k, v in zone.items() if k != "countries"}
|
||||||
|
out["countries"] = list(zone["countries"])
|
||||||
|
out["current_offset_min"] = offset
|
||||||
|
out["current_dst"] = bool(local.dst())
|
||||||
|
out["display"] = f"({_format_offset(offset)}) {zone['city']}" + (f" — {zone['comment']}" if zone["comment"] else "")
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def tzdata_version() -> str:
|
||||||
|
return tzdata.IANA_VERSION
|
||||||
|
|
||||||
|
|
||||||
|
def get_table(country: str | None = None, now: datetime | None = None) -> dict | None:
|
||||||
|
"""Full table, or one country's (ISO 3166 alpha-2, case-insensitive). None if unknown."""
|
||||||
|
now = now or datetime.now(timezone.utc)
|
||||||
|
countries, _ = _static_table()
|
||||||
|
if country:
|
||||||
|
countries = [c for c in countries if c["code"] == country.upper()]
|
||||||
|
if not countries:
|
||||||
|
return None
|
||||||
|
return {
|
||||||
|
"tzdata_version": tzdata_version(),
|
||||||
|
"generated_at": now.isoformat(timespec="seconds"),
|
||||||
|
"countries": [
|
||||||
|
{"code": c["code"], "name": c["name"], "zones": [_with_current(z, now) for z in c["zones"]]}
|
||||||
|
for c in countries
|
||||||
|
],
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def get_zone(name: str, now: datetime | None = None) -> dict | None:
|
||||||
|
"""One zone. Also resolves IANA names that zone.tab doesn't list (aliases such as
|
||||||
|
"Asia/Calcutta", or "UTC") — phones may report those as their own timezone."""
|
||||||
|
_, zones = _static_table()
|
||||||
|
zone = zones.get(name)
|
||||||
|
if zone is None:
|
||||||
|
posix = posix_rule(name) if re.fullmatch(r"[A-Za-z0-9_+\-]+(/[A-Za-z0-9_+\-]+)*", name) else None
|
||||||
|
if posix is None:
|
||||||
|
return None
|
||||||
|
std, dst, has_dst = posix_offsets(posix)
|
||||||
|
zone = {"name": name, "city": name.rsplit("/", 1)[-1].replace("_", " "), "comment": "",
|
||||||
|
"posix": posix, "std_offset_min": std, "dst_offset_min": dst, "has_dst": has_dst,
|
||||||
|
"countries": []}
|
||||||
|
result = _with_current(zone, now or datetime.now(timezone.utc))
|
||||||
|
result["tzdata_version"] = tzdata_version()
|
||||||
|
return result
|
||||||
+17
-28
@@ -236,29 +236,23 @@ def assign_device(user_doc_id: str, device_doc_id: str) -> UserInDB:
|
|||||||
if not device_doc.exists:
|
if not device_doc.exists:
|
||||||
raise NotFoundError("Device")
|
raise NotFoundError("Device")
|
||||||
|
|
||||||
# Add user path to device's user_list if not already there
|
from devices import service as devices_service
|
||||||
|
|
||||||
|
# Add a user reference to device's user_list if not already there.
|
||||||
|
# Stored as a DocumentReference, the format the FlutterFlow app writes.
|
||||||
device_data = device_doc.to_dict()
|
device_data = device_doc.to_dict()
|
||||||
user_list = device_data.get("user_list", [])
|
user_list = device_data.get("user_list", []) or []
|
||||||
user_path = f"users/{user_doc_id}"
|
already_assigned = any(devices_service.user_list_entry_id(e) == user_doc_id for e in user_list)
|
||||||
|
|
||||||
# Check if already assigned (handle both string paths and DocumentReferences)
|
# Device user_list, the user's device_serials and the device_users mirror
|
||||||
already_assigned = False
|
# are written in one atomic batch. device_serials and the mirror are
|
||||||
for entry in user_list:
|
# re-synced even when already assigned, to heal drift.
|
||||||
if isinstance(entry, DocumentReference):
|
|
||||||
if entry.path == user_path:
|
|
||||||
already_assigned = True
|
|
||||||
break
|
|
||||||
elif entry == user_path:
|
|
||||||
already_assigned = True
|
|
||||||
break
|
|
||||||
|
|
||||||
# Device user_list and the user's device_serials are written in one atomic batch.
|
|
||||||
# device_serials is re-synced even when already assigned, to heal drift.
|
|
||||||
batch = db.batch()
|
batch = db.batch()
|
||||||
if not already_assigned:
|
if not already_assigned:
|
||||||
user_list.append(user_path)
|
user_list.append(user_ref)
|
||||||
batch.update(device_ref, {"user_list": user_list})
|
batch.update(device_ref, {"user_list": user_list})
|
||||||
stage_device_serial_link(batch, user_ref, device_serial_of(device_data), linked=True)
|
stage_device_serial_link(batch, user_ref, device_serial_of(device_data), linked=True)
|
||||||
|
devices_service.stage_device_users_mirror(batch, device_ref, user_ref, linked=True)
|
||||||
batch.commit()
|
batch.commit()
|
||||||
invalidate_mqtt_acl_cache(user_doc.to_dict())
|
invalidate_mqtt_acl_cache(user_doc.to_dict())
|
||||||
|
|
||||||
@@ -281,22 +275,17 @@ def unassign_device(user_doc_id: str, device_doc_id: str) -> UserInDB:
|
|||||||
if not device_doc.exists:
|
if not device_doc.exists:
|
||||||
raise NotFoundError("Device")
|
raise NotFoundError("Device")
|
||||||
|
|
||||||
# Remove user from device's user_list
|
from devices import service as devices_service
|
||||||
device_data = device_doc.to_dict()
|
|
||||||
user_list = device_data.get("user_list", [])
|
|
||||||
user_path = f"users/{user_doc_id}"
|
|
||||||
|
|
||||||
new_list = []
|
# Remove user from device's user_list (any entry format)
|
||||||
for entry in user_list:
|
device_data = device_doc.to_dict()
|
||||||
if isinstance(entry, DocumentReference):
|
user_list = device_data.get("user_list", []) or []
|
||||||
if entry.path != user_path:
|
new_list = [e for e in user_list if devices_service.user_list_entry_id(e) != user_doc_id]
|
||||||
new_list.append(entry)
|
|
||||||
elif entry != user_path:
|
|
||||||
new_list.append(entry)
|
|
||||||
|
|
||||||
batch = db.batch()
|
batch = db.batch()
|
||||||
batch.update(device_ref, {"user_list": new_list})
|
batch.update(device_ref, {"user_list": new_list})
|
||||||
stage_device_serial_link(batch, user_ref, device_serial_of(device_data), linked=False)
|
stage_device_serial_link(batch, user_ref, device_serial_of(device_data), linked=False)
|
||||||
|
devices_service.stage_device_users_mirror(batch, device_ref, user_ref, linked=False)
|
||||||
batch.commit()
|
batch.commit()
|
||||||
invalidate_mqtt_acl_cache(user_doc.to_dict())
|
invalidate_mqtt_acl_cache(user_doc.to_dict())
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,84 @@
|
|||||||
|
# Device timezone table
|
||||||
|
|
||||||
|
Backend module `backend/timezones/` — the list of timezones that the console and the apps offer when
|
||||||
|
setting a device's clock, with the rule each device needs.
|
||||||
|
|
||||||
|
## Why it exists
|
||||||
|
|
||||||
|
Since firmware 3.0.0 the device RTC holds UTC and the device converts to local time itself
|
||||||
|
(project-vesper `src/TimeKeeper/`, catalog F-079). In timezone mode `auto` the device is sent:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{ "mode": "auto", "name": "Europe/Athens", "posix": "EET-2EEST,M3.5.0/3,M10.5.0/4" }
|
||||||
|
```
|
||||||
|
|
||||||
|
`posix` is a POSIX TZ rule: the standard offset, the DST offset and when DST starts/ends every year. The
|
||||||
|
device evaluates it by itself, so DST switches without anyone touching the device. Devices don't carry the
|
||||||
|
IANA database, so whoever sets the timezone (console, phone app, tablet app) must send the rule — and must
|
||||||
|
never build it by hand (POSIX signs are inverted: `EET-2` means UTC+2). This module is where the rule comes
|
||||||
|
from.
|
||||||
|
|
||||||
|
## Source of truth
|
||||||
|
|
||||||
|
The pip package `tzdata` pinned in `backend/requirements.txt` (IANA release reported as `tzdata_version`):
|
||||||
|
|
||||||
|
- POSIX rule = the footer line of each zone's TZif file (the same string the firmware's host tests check
|
||||||
|
against CPython's `zoneinfo` for every zone — project-vesper `test/timezone/`).
|
||||||
|
- Zone → country: `zone.tab`. Country names: `iso3166.tab`.
|
||||||
|
|
||||||
|
Nothing is generated or committed by hand. **To pick up new DST rules** (a country changes or abolishes DST),
|
||||||
|
bump the `tzdata` pin, rebuild the backend, and re-send `clock.set_timezone` to affected devices — devices
|
||||||
|
keep the rule they were given until told otherwise. Re-export the tablet bundle too (below).
|
||||||
|
|
||||||
|
## Endpoints (public, no auth)
|
||||||
|
|
||||||
|
Public on purpose: it is public IANA data, and the phone app (Firebase auth over MQTT) and the tablet bundle
|
||||||
|
export need it without console credentials.
|
||||||
|
|
||||||
|
### `GET /api/public/timezones[?country=GR]`
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"tzdata_version": "2026f",
|
||||||
|
"generated_at": "2026-10-28T14:05:00+00:00",
|
||||||
|
"countries": [
|
||||||
|
{ "code": "GR", "name": "Greece", "zones": [
|
||||||
|
{ "name": "Europe/Athens", "city": "Athens", "comment": "",
|
||||||
|
"posix": "EET-2EEST,M3.5.0/3,M10.5.0/4",
|
||||||
|
"std_offset_min": 120, "dst_offset_min": 60, "has_dst": true,
|
||||||
|
"countries": ["GR"], "current_offset_min": 120, "current_dst": false,
|
||||||
|
"display": "(UTC+02:00) Athens" } ] }
|
||||||
|
]
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
- Countries sorted by name; zones in `zone.tab` order (roughly geographic). Most countries have one zone;
|
||||||
|
pick-country-then-zone UIs can skip the second step for those.
|
||||||
|
- `std_offset_min` / `dst_offset_min`: minutes east of UTC; `dst_offset_min` is the DST **amount** (0 without
|
||||||
|
DST, negative for Europe/Dublin, 30 for Lord Howe). Same values the device reports in `clock.get_timezone`.
|
||||||
|
- `current_offset_min` / `current_dst` / `display` are computed at request time.
|
||||||
|
- A zone used by several countries appears under each, with all of them in `countries`.
|
||||||
|
- `country` filter: ISO 3166 alpha-2, case-insensitive. Unknown → 404.
|
||||||
|
|
||||||
|
### `GET /api/public/timezones/zone?name=Europe/Athens`
|
||||||
|
|
||||||
|
One zone (same fields + `tzdata_version`). Also resolves IANA aliases that `zone.tab` doesn't list
|
||||||
|
(`Asia/Calcutta`, `UTC`, …) with `countries: []` — useful for "use this phone's timezone". Unknown → 404.
|
||||||
|
|
||||||
|
## Tablet app bundle
|
||||||
|
|
||||||
|
The tablet app only talks to devices over local WebSocket, often without internet, so it bundles the table:
|
||||||
|
save the response of `GET /api/public/timezones` as-is (≈ 130 KB) into the app. Ignore the `current_*` and
|
||||||
|
`display` fields there (they were "now" at export time) — compute the current offset on the tablet, or just
|
||||||
|
show `std_offset_min`. Re-export whenever the `tzdata` pin is bumped.
|
||||||
|
|
||||||
|
## Tests
|
||||||
|
|
||||||
|
`backend/tests/test_timezones.py` (pure tzdata, no Firestore/MQTT): POSIX offset parsing incl. negative,
|
||||||
|
half-hour and 45-minute cases; table shape and firmware length limits (name < 48, rule < 64 chars); Greece /
|
||||||
|
Australia spot checks; every zone's offset in 2030 is its standard or standard+DST offset; routes.
|
||||||
|
|
||||||
|
```
|
||||||
|
cd backend
|
||||||
|
python -m pytest tests/test_timezones.py
|
||||||
|
```
|
||||||
@@ -201,11 +201,17 @@ When those lines stop appearing, set `MQTT_ALLOW_LEGACY_PASSWORD=false`.
|
|||||||
Firestore (e.g. a claim flow), it must also update `device_serials` the same way
|
Firestore (e.g. a claim flow), it must also update `device_serials` the same way
|
||||||
(ArrayUnion / ArrayRemove of the serial on the user doc). Otherwise that user
|
(ArrayUnion / ArrayRemove of the serial on the user doc). Otherwise that user
|
||||||
cannot reach the device over MQTT. The app owner will handle this in the app.
|
cannot reach the device over MQTT. The app owner will handle this in the app.
|
||||||
- **The `device_users` subcollection** on devices (older way of recording device users,
|
- **The `device_users` subcollection** on devices (`{role, user_reference}`, the older
|
||||||
read first by `devices.service.get_device_users`) is **intentionally ignored** by
|
way of recording device users) is a **write-only mirror** since 2026-11. `user_list`
|
||||||
the backfill and the MQTT ACL. Left as is by decision.
|
is the only source of truth: the Console reads assignments only from it
|
||||||
- The two Console assignment paths store `user_list` entries in different formats
|
(`devices.service.get_device_users`, which takes just the `role` from the mirror).
|
||||||
(path strings vs DocumentReferences). This predates this work; all readers accept both.
|
Every Console path that edits `user_list` also adds/removes the mirror doc in the
|
||||||
|
same batch (`devices.service.stage_device_users_mirror`). The MQTT ACL and the
|
||||||
|
backfill ignore it. It is kept only in case the phone app still reads it, and is
|
||||||
|
meant to be removed. `scripts/sync_device_users_mirror.py` (dry run by default)
|
||||||
|
fixes drift from before 2026-11.
|
||||||
|
- All Console paths now write `user_list` entries as DocumentReferences (what the app
|
||||||
|
writes). Older data may still hold `"users/{id}"` path strings; all readers accept both.
|
||||||
- ACL denies are logged at INFO, which is not shown by default. Auth denies and
|
- ACL denies are logged at INFO, which is not shown by default. Auth denies and
|
||||||
legacy-password logins are WARNING.
|
legacy-password logins are WARNING.
|
||||||
|
|
||||||
|
|||||||
@@ -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,120 @@
|
|||||||
|
// frontend/src/lib/deviceTimezone.js
|
||||||
|
// Helpers for device clock timezones (firmware 3.0.0+, project-vesper F-079).
|
||||||
|
//
|
||||||
|
// The device RTC holds UTC; a timezone object tells it how to show local time:
|
||||||
|
// { mode: 'auto', name, posix } — DST switches by itself
|
||||||
|
// { mode: 'manual', name, std_offset_min, dst_offset_min, dst_start, dst_end } — one DST season
|
||||||
|
// { mode: 'fixed', name, std_offset_min, dst_offset_min } — never switches
|
||||||
|
// { mode: 'local' } — offset 0, no NTP
|
||||||
|
// Offsets are minutes EAST of UTC. dst_start / dst_end are UTC epoch seconds.
|
||||||
|
// The rule list comes from the backend (GET /api/public/timezones, docs/device-timezones.md).
|
||||||
|
|
||||||
|
import api from '@/lib/api'
|
||||||
|
import { fmtUtcOffset } from '@/lib/formatters'
|
||||||
|
|
||||||
|
export const TZ_MODES = [
|
||||||
|
{ value: 'auto', label: 'Automatic' },
|
||||||
|
{ value: 'manual', label: 'Manual DST' },
|
||||||
|
{ value: 'fixed', label: 'Fixed offset' },
|
||||||
|
{ value: 'local', label: 'Local only' },
|
||||||
|
]
|
||||||
|
|
||||||
|
export const TZ_MODE_LABELS = Object.fromEntries(TZ_MODES.map(m => [m.value, m.label]))
|
||||||
|
|
||||||
|
// UTC-12:00 … UTC+14:00 in 15-minute steps (covers Nepal +5:45, Chatham +12:45)
|
||||||
|
export const STD_OFFSET_OPTIONS = Array.from({ length: (840 + 720) / 15 + 1 }, (_, i) => {
|
||||||
|
const value = -720 + i * 15
|
||||||
|
return { value, label: fmtUtcOffset(value) }
|
||||||
|
})
|
||||||
|
|
||||||
|
export const DST_AMOUNT_OPTIONS = [
|
||||||
|
{ value: 30, label: '+30 min' },
|
||||||
|
{ value: 60, label: '+1 hour' },
|
||||||
|
{ value: 120, label: '+2 hours' },
|
||||||
|
]
|
||||||
|
|
||||||
|
export const MONTHS = ['January', 'February', 'March', 'April', 'May', 'June', 'July',
|
||||||
|
'August', 'September', 'October', 'November', 'December']
|
||||||
|
export const WEEKS = [
|
||||||
|
{ value: 1, label: '1st' }, { value: 2, label: '2nd' }, { value: 3, label: '3rd' },
|
||||||
|
{ value: 4, label: '4th' }, { value: 5, label: 'Last' },
|
||||||
|
]
|
||||||
|
export const WEEKDAYS = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']
|
||||||
|
|
||||||
|
// ── Timezone table (cached for the session) ───────────────────────────────────
|
||||||
|
|
||||||
|
let tablePromise = null
|
||||||
|
|
||||||
|
/** { tzdata_version, countries: [{ code, name, zones: [...] }] } — fetched once. */
|
||||||
|
export function loadTimezoneTable() {
|
||||||
|
if (!tablePromise) {
|
||||||
|
tablePromise = api.get('/public/timezones').catch(err => {
|
||||||
|
tablePromise = null // allow a retry after a failure
|
||||||
|
throw err
|
||||||
|
})
|
||||||
|
}
|
||||||
|
return tablePromise
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The country containing an IANA zone, or null. */
|
||||||
|
export function findCountryOfZone(table, zoneName) {
|
||||||
|
return table?.countries.find(c => c.zones.some(z => z.name === zoneName)) || null
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── POSIX rule builder (custom recurring DST) ─────────────────────────────────
|
||||||
|
|
||||||
|
// POSIX offsets are WEST-positive h[:mm] — the opposite sign of our minutes-east values.
|
||||||
|
function posixOffset(minutesEast) {
|
||||||
|
const west = -minutesEast
|
||||||
|
const sign = west < 0 ? '-' : ''
|
||||||
|
const abs = Math.abs(west)
|
||||||
|
const mm = abs % 60
|
||||||
|
return `${sign}${Math.floor(abs / 60)}${mm ? `:${String(mm).padStart(2, '0')}` : ''}`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Abbreviation for a numeric offset: "<+02>", "<+0545>", "<-03>"
|
||||||
|
function posixName(minutesEast) {
|
||||||
|
const sign = minutesEast < 0 ? '-' : '+'
|
||||||
|
const abs = Math.abs(minutesEast)
|
||||||
|
const mm = abs % 60
|
||||||
|
return `<${sign}${String(Math.floor(abs / 60)).padStart(2, '0')}${mm ? String(mm).padStart(2, '0') : ''}>`
|
||||||
|
}
|
||||||
|
|
||||||
|
// "HH:MM" → "/H" or "/H:MM"
|
||||||
|
function posixTime(hhmm) {
|
||||||
|
const [h, m] = hhmm.split(':').map(Number)
|
||||||
|
return `/${h}${m ? `:${String(m).padStart(2, '0')}` : ''}`
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Builds a POSIX TZ rule for a recurring DST schedule, e.g. std +120, DST +60,
|
||||||
|
* last Sunday of March 03:00 → last Sunday of October 04:00:
|
||||||
|
* "<+02>-2<+03>,M3.5.0/3,M10.5.0/4"
|
||||||
|
* `start.time` is local standard time, `end.time` local DST time (POSIX convention).
|
||||||
|
* dstAmountMin 0 → no DST part.
|
||||||
|
*/
|
||||||
|
export function buildPosixRule({ stdOffsetMin, dstAmountMin, start, end }) {
|
||||||
|
const std = `${posixName(stdOffsetMin)}${posixOffset(stdOffsetMin)}`
|
||||||
|
if (!dstAmountMin) return std
|
||||||
|
const total = stdOffsetMin + dstAmountMin
|
||||||
|
const dst = `${posixName(total)}${dstAmountMin === 60 ? '' : posixOffset(total)}`
|
||||||
|
const date = r => `M${r.month}.${r.week}.${r.weekday}${posixTime(r.time)}`
|
||||||
|
return `${std}${dst},${date(start)},${date(end)}`
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Wall-clock helpers ────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
/** "2026-03-29T03:00[:SS]" → epoch seconds, read as if it were UTC (no browser timezone). */
|
||||||
|
export function wallClockToEpoch(value) {
|
||||||
|
if (!value) return null
|
||||||
|
const ms = Date.parse(`${value.length === 16 ? `${value}:00` : value}Z`)
|
||||||
|
return Number.isNaN(ms) ? null : Math.floor(ms / 1000)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Epoch seconds → "YYYY-MM-DDTHH:MM" wall clock at the given offset (for datetime-local inputs). */
|
||||||
|
export function epochToWallClock(utcSeconds, offsetMin) {
|
||||||
|
if (!utcSeconds) return ''
|
||||||
|
// toISOString() is intentional here: the epoch is already shifted to the device's wall
|
||||||
|
// clock, so reading it back as UTC gives exactly those fields (no browser timezone involved).
|
||||||
|
return new Date((utcSeconds + offsetMin * 60) * 1000).toISOString().slice(0, 16)
|
||||||
|
}
|
||||||
@@ -175,3 +175,35 @@ export function fmtEuro(n) {
|
|||||||
const f = parseFloat(n) || 0
|
const f = parseFloat(n) || 0
|
||||||
return f.toLocaleString('el-GR', { minimumFractionDigits: 2, maximumFractionDigits: 2 }) + ' €'
|
return f.toLocaleString('el-GR', { minimumFractionDigits: 2, maximumFractionDigits: 2 }) + ' €'
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ─── Device wall-clock time ──────────────────────────────────────────────────
|
||||||
|
// A device's local time is in the DEVICE's timezone, not the browser's. These never
|
||||||
|
// convert through the browser timezone: they format wall-clock values as devices report
|
||||||
|
// them (firmware 3.0.0+: "local": "2026-10-28T14:05:00", or a UTC epoch + offset).
|
||||||
|
|
||||||
|
// Formats in UTC so the wall-clock fields come out untouched
|
||||||
|
const WALL_DATETIME = new Intl.DateTimeFormat(LOCALE_LONG, {
|
||||||
|
day: 'numeric', month: 'short', year: 'numeric',
|
||||||
|
hour: '2-digit', minute: '2-digit', hour12: false, timeZone: 'UTC',
|
||||||
|
})
|
||||||
|
|
||||||
|
/** "28 Oct 2026, 14:05" — a device wall-clock string "2026-10-28T14:05:00" */
|
||||||
|
export function fmtWallClock(localIso) {
|
||||||
|
if (!localIso) return '—'
|
||||||
|
const d = safeDate(`${localIso}Z`)
|
||||||
|
return d ? WALL_DATETIME.format(d) : '—'
|
||||||
|
}
|
||||||
|
|
||||||
|
/** "28 Oct 2026, 14:05" — a UTC epoch (seconds) shown in a device's local time */
|
||||||
|
export function fmtDeviceDateTime(utcSeconds, offsetMin) {
|
||||||
|
if (!utcSeconds) return '—'
|
||||||
|
return WALL_DATETIME.format(new Date((utcSeconds + (offsetMin || 0) * 60) * 1000))
|
||||||
|
}
|
||||||
|
|
||||||
|
/** "UTC+02:00" / "UTC-03:30" — minutes east of UTC */
|
||||||
|
export function fmtUtcOffset(minutes) {
|
||||||
|
if (minutes == null) return '—'
|
||||||
|
const sign = minutes >= 0 ? '+' : '-'
|
||||||
|
const abs = Math.abs(minutes)
|
||||||
|
return `UTC${sign}${String(Math.floor(abs / 60)).padStart(2, '0')}:${String(abs % 60).padStart(2, '0')}`
|
||||||
|
}
|
||||||
|
|||||||
@@ -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>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -20,7 +20,7 @@ function extractTime(tsStr) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function timeToIso(hhmm) {
|
function timeToIso(hhmm) {
|
||||||
if (!hhmm) return ''
|
if (!hhmm) return null
|
||||||
return `2000-01-01T${hhmm}:00Z`
|
return `2000-01-01T${hhmm}:00Z`
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -176,18 +176,17 @@ 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),
|
||||||
halfhourAlertsBell: Number(halfBell),
|
halfhourAlertsBell: Number(halfBell),
|
||||||
quarterAlertsBell: Number(quarterBell),
|
quarterAlertsBell: Number(quarterBell),
|
||||||
isDaySilenceOn: isDayOn,
|
isDaySilenceOn: isDayOn,
|
||||||
daySilenceFrom: isDayOn && daySilenceFrom ? timeToIso(daySilenceFrom) : (clock?.daySilenceFrom || ''),
|
daySilenceFrom: isDayOn && daySilenceFrom ? timeToIso(daySilenceFrom) : (clock?.daySilenceFrom ?? null),
|
||||||
daySilenceTo: isDayOn && daySilenceTo ? timeToIso(daySilenceTo) : (clock?.daySilenceTo || ''),
|
daySilenceTo: isDayOn && daySilenceTo ? timeToIso(daySilenceTo) : (clock?.daySilenceTo ?? null),
|
||||||
isNightSilenceOn: isNightOn,
|
isNightSilenceOn: isNightOn,
|
||||||
nightSilenceFrom: isNightOn && nightFrom ? timeToIso(nightFrom) : (clock?.nightSilenceFrom || ''),
|
nightSilenceFrom: isNightOn && nightFrom ? timeToIso(nightFrom) : (clock?.nightSilenceFrom ?? null),
|
||||||
nightSilenceTo: isNightOn && nightTo ? timeToIso(nightTo) : (clock?.nightSilenceTo || ''),
|
nightSilenceTo: isNightOn && nightTo ? timeToIso(nightTo) : (clock?.nightSilenceTo ?? null),
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ const toBool = (v) => v === 'true' || v === true
|
|||||||
|
|
||||||
export default function EditAttributesModal({ open, onClose, onSaved, attr, id }) {
|
export default function EditAttributesModal({ open, onClose, onSaved, attr, id }) {
|
||||||
const [bellGuardOn, setBellGuardOn] = useState(String(attr?.bellGuardOn ?? false))
|
const [bellGuardOn, setBellGuardOn] = useState(String(attr?.bellGuardOn ?? false))
|
||||||
const [bellGuardSafetyOn, setBellGuardSafetyOn] = useState(String(attr?.bellGuardSafetyOn ?? false))
|
const [bellGuardSafetyOn, setBellGuardSafetyOn] = useState(String(attr?.bellguardSafetyOn ?? false))
|
||||||
const [warningsOn, setWarningsOn] = useState(String(attr?.warningsOn ?? false))
|
const [warningsOn, setWarningsOn] = useState(String(attr?.warningsOn ?? false))
|
||||||
const [saving, setSaving] = useState(false)
|
const [saving, setSaving] = useState(false)
|
||||||
const [error, setError] = useState('')
|
const [error, setError] = useState('')
|
||||||
@@ -23,7 +23,7 @@ export default function EditAttributesModal({ open, onClose, onSaved, attr, id }
|
|||||||
device_attributes: {
|
device_attributes: {
|
||||||
bellGuardOn: toBool(bellGuardOn),
|
bellGuardOn: toBool(bellGuardOn),
|
||||||
warningsOn: toBool(warningsOn),
|
warningsOn: toBool(warningsOn),
|
||||||
bellGuardSafetyOn: toBool(bellGuardSafetyOn),
|
bellguardSafetyOn: toBool(bellGuardSafetyOn),
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
await onSaved()
|
await onSaved()
|
||||||
|
|||||||
@@ -17,7 +17,7 @@ function extractTime(tsStr) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function timeToIso(hhmm) {
|
function timeToIso(hhmm) {
|
||||||
if (!hhmm) return ''
|
if (!hhmm) return null
|
||||||
return `2000-01-01T${hhmm}:00Z`
|
return `2000-01-01T${hhmm}:00Z`
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -59,11 +59,10 @@ 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) : '',
|
backlightTurnOnTime: enabled && onTime ? timeToIso(onTime) : null,
|
||||||
backlightTurnOffTime: enabled && offTime ? timeToIso(offTime) : '',
|
backlightTurnOffTime: enabled && offTime ? timeToIso(offTime) : null,
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -1,10 +1,13 @@
|
|||||||
// frontend/src/modals/bellcloud/devices/EditClockSettingsModal.jsx
|
// frontend/src/modals/bellcloud/devices/EditClockSettingsModal.jsx
|
||||||
// Edits: master switch, ODD/EVEN outputs, pulse and pause durations (sliders).
|
// Edits: master switch, ODD/EVEN outputs, pulse and pause durations (sliders), and the
|
||||||
|
// face sync policy (firmware 3.2.0+: force = run a full lap when the face is ahead,
|
||||||
|
// smart = wait if it is at most N minutes ahead).
|
||||||
|
|
||||||
import { useState } from 'react'
|
import { useState } from 'react'
|
||||||
import Modal from '@/components/ui/Modal'
|
import Modal from '@/components/ui/Modal'
|
||||||
import Button from '@/components/ui/Button'
|
import Button from '@/components/ui/Button'
|
||||||
import FormField from '@/components/ui/FormField'
|
import FormField from '@/components/ui/FormField'
|
||||||
|
import SegmentedControl from '@/components/ui/SegmentedControl'
|
||||||
import api from '@/lib/api'
|
import api from '@/lib/api'
|
||||||
|
|
||||||
// Pulse options in milliseconds — shown as sliders with labelled steps
|
// Pulse options in milliseconds — shown as sliders with labelled steps
|
||||||
@@ -68,6 +71,8 @@ export default function EditClockSettingsModal({ open, onClose, onSaved, attr, s
|
|||||||
const [clockOut2, setClockOut2] = useState(String(existingClockOutputs[1] ?? 0))
|
const [clockOut2, setClockOut2] = useState(String(existingClockOutputs[1] ?? 0))
|
||||||
const [runPulse, setRunPulse] = useState(existingTimings[0] || PULSE_STEPS[3]) // default 500ms
|
const [runPulse, setRunPulse] = useState(existingTimings[0] || PULSE_STEPS[3]) // default 500ms
|
||||||
const [pauseMs, setPauseMs] = useState(existingTimings[1] || PAUSE_STEPS[1]) // default 1000ms
|
const [pauseMs, setPauseMs] = useState(existingTimings[1] || PAUSE_STEPS[1]) // default 1000ms
|
||||||
|
const [faceSync, setFaceSync] = useState(clock.faceSyncMode || 'force')
|
||||||
|
const [maxWait, setMaxWait] = useState(String(clock.smartMaxWaitMin ?? 61))
|
||||||
const [saving, setSaving] = useState(false)
|
const [saving, setSaving] = useState(false)
|
||||||
const [error, setError] = useState('')
|
const [error, setError] = useState('')
|
||||||
|
|
||||||
@@ -78,7 +83,11 @@ export default function EditClockSettingsModal({ open, onClose, onSaved, attr, s
|
|||||||
const validationMsg = hasClock && (out1 === 0 || out2 === 0)
|
const validationMsg = hasClock && (out1 === 0 || out2 === 0)
|
||||||
? 'Both outputs must be assigned when the clock is enabled.'
|
? 'Both outputs must be assigned when the clock is enabled.'
|
||||||
: null
|
: null
|
||||||
const canSave = !conflictMsg && !validationMsg
|
const maxWaitNum = Number(maxWait)
|
||||||
|
const maxWaitMsg = faceSync === 'smart' && (!Number.isInteger(maxWaitNum) || maxWaitNum < 1 || maxWaitNum > 359)
|
||||||
|
? 'Maximum wait must be 1–359 minutes.'
|
||||||
|
: null
|
||||||
|
const canSave = !conflictMsg && !validationMsg && !maxWaitMsg
|
||||||
|
|
||||||
const handleSave = async () => {
|
const handleSave = async () => {
|
||||||
if (!canSave) return
|
if (!canSave) return
|
||||||
@@ -93,15 +102,18 @@ export default function EditClockSettingsModal({ open, onClose, onSaved, attr, s
|
|||||||
c2: out2,
|
c2: out2,
|
||||||
pulse_duration: runPulse,
|
pulse_duration: runPulse,
|
||||||
pause_duration: pauseMs,
|
pause_duration: pauseMs,
|
||||||
|
face_sync_mode: faceSync,
|
||||||
|
...(faceSync === 'smart' ? { smart_max_wait_min: maxWaitNum } : {}),
|
||||||
})
|
})
|
||||||
|
|
||||||
await api.put(`/devices/${id}`, {
|
await api.put(`/devices/${id}`, {
|
||||||
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,
|
||||||
|
...(faceSync === 'smart' ? { smartMaxWaitMin: maxWaitNum } : {}),
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
@@ -228,10 +240,42 @@ export default function EditClockSettingsModal({ open, onClose, onSaved, attr, s
|
|||||||
onChange={setPauseMs}
|
onChange={setPauseMs}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
|
<div style={{ height: 1, backgroundColor: 'var(--color-border)' }} />
|
||||||
|
|
||||||
|
{/* Face sync policy */}
|
||||||
|
<div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-3)' }}>
|
||||||
|
<div>
|
||||||
|
<p style={{ fontSize: 'var(--font-size-base)', fontWeight: 'var(--font-weight-semibold)', color: 'var(--color-text-primary)' }}>
|
||||||
|
Face Ahead of Real Time
|
||||||
|
</p>
|
||||||
|
<p style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-text-muted)', marginTop: 2 }}>
|
||||||
|
The hands only move forward. When they are ahead (e.g. after DST ends), Force runs a full
|
||||||
|
lap to catch up; Smart stops them until real time catches up.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<SegmentedControl
|
||||||
|
options={[{ value: 'force', label: 'Force (full lap)' }, { value: 'smart', label: 'Smart (wait)' }]}
|
||||||
|
value={faceSync}
|
||||||
|
onChange={setFaceSync}
|
||||||
|
size="sm"
|
||||||
|
/>
|
||||||
|
{faceSync === 'smart' && (
|
||||||
|
<FormField
|
||||||
|
label="Wait if ahead by at most (minutes)"
|
||||||
|
name="smartMaxWait"
|
||||||
|
type="number"
|
||||||
|
value={maxWait}
|
||||||
|
onChange={e => setMaxWait(e.target.value)}
|
||||||
|
inputProps={{ min: 1, max: 359, step: 1 }}
|
||||||
|
hint="Default 61 covers the DST change. Further ahead than this, the face runs the lap."
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
{/* Errors / warnings */}
|
{/* Errors / warnings */}
|
||||||
{(conflictMsg || validationMsg) && (
|
{(conflictMsg || validationMsg || maxWaitMsg) && (
|
||||||
<p style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-warning)', backgroundColor: 'var(--color-warning-bg)', padding: 'var(--space-2) var(--space-3)', borderRadius: 'var(--radius-sm)' }}>
|
<p style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-warning)', backgroundColor: 'var(--color-warning-bg)', padding: 'var(--space-2) var(--space-3)', borderRadius: 'var(--radius-sm)' }}>
|
||||||
{conflictMsg || validationMsg}
|
{conflictMsg || validationMsg || maxWaitMsg}
|
||||||
</p>
|
</p>
|
||||||
)}
|
)}
|
||||||
{error && (
|
{error && (
|
||||||
|
|||||||
@@ -0,0 +1,309 @@
|
|||||||
|
// frontend/src/modals/bellcloud/devices/EditTimezoneModal.jsx
|
||||||
|
// Sets a device's timezone (firmware 3.0.0+, clock.set_timezone). Four modes:
|
||||||
|
// Automatic — pick country → zone from the backend table (rule sent as POSIX), or build a
|
||||||
|
// custom yearly DST rule. DST then switches on the device by itself.
|
||||||
|
// Manual DST — standard offset + DST amount + this season's start/end. Re-entered yearly.
|
||||||
|
// Fixed — constant offset, never switches.
|
||||||
|
// Local only — no timezone at all; the device keeps the local time it is given.
|
||||||
|
// The RTC is untouched; only how the device turns UTC into local time changes.
|
||||||
|
|
||||||
|
import { useEffect, useMemo, useState } from 'react'
|
||||||
|
import Modal from '@/components/ui/Modal'
|
||||||
|
import Button from '@/components/ui/Button'
|
||||||
|
import FormField from '@/components/ui/FormField'
|
||||||
|
import SegmentedControl from '@/components/ui/SegmentedControl'
|
||||||
|
import Spinner from '@/components/ui/Spinner'
|
||||||
|
import { fmtUtcOffset } from '@/lib/formatters'
|
||||||
|
import {
|
||||||
|
TZ_MODES, STD_OFFSET_OPTIONS, DST_AMOUNT_OPTIONS, MONTHS, WEEKS, WEEKDAYS,
|
||||||
|
loadTimezoneTable, findCountryOfZone, buildPosixRule, wallClockToEpoch, epochToWallClock,
|
||||||
|
} from '@/lib/deviceTimezone'
|
||||||
|
|
||||||
|
const DEFAULT_COUNTRY = 'GR'
|
||||||
|
const DEFAULT_RULE = {
|
||||||
|
start: { month: 3, week: 5, weekday: 0, time: '03:00' },
|
||||||
|
end: { month: 10, week: 5, weekday: 0, time: '04:00' },
|
||||||
|
}
|
||||||
|
|
||||||
|
function hint(text) {
|
||||||
|
return (
|
||||||
|
<p style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-text-muted)' }}>{text}</p>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function RuleDateFields({ id, label, value, onChange, timeHint }) {
|
||||||
|
const set = (key, v) => onChange({ ...value, [key]: v })
|
||||||
|
return (
|
||||||
|
<div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-2)' }}>
|
||||||
|
<span style={{ fontSize: 'var(--font-size-sm)', fontWeight: 'var(--font-weight-medium)', color: 'var(--color-text-secondary)' }}>
|
||||||
|
{label}
|
||||||
|
</span>
|
||||||
|
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr 1fr', gap: 'var(--space-2)' }}>
|
||||||
|
<FormField label="" name={`${id}-week`} type="select" value={String(value.week)} onChange={e => set('week', Number(e.target.value))}>
|
||||||
|
{WEEKS.map(w => <option key={w.value} value={String(w.value)}>{w.label}</option>)}
|
||||||
|
</FormField>
|
||||||
|
<FormField label="" name={`${id}-weekday`} type="select" value={String(value.weekday)} onChange={e => set('weekday', Number(e.target.value))}>
|
||||||
|
{WEEKDAYS.map((d, i) => <option key={d} value={String(i)}>{d}</option>)}
|
||||||
|
</FormField>
|
||||||
|
<FormField label="" name={`${id}-month`} type="select" value={String(value.month)} onChange={e => set('month', Number(e.target.value))}>
|
||||||
|
{MONTHS.map((m, i) => <option key={m} value={String(i + 1)}>{m}</option>)}
|
||||||
|
</FormField>
|
||||||
|
<FormField label="" name={`${id}-time`} type="time" value={value.time} onChange={e => set('time', e.target.value)} />
|
||||||
|
</div>
|
||||||
|
{hint(timeHint)}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function EditTimezoneModal({ open, onClose, current, sendMqttCommand, onSaved }) {
|
||||||
|
const [table, setTable] = useState(null)
|
||||||
|
const [tableError, setTableError] = useState('')
|
||||||
|
const [mode, setMode] = useState('auto')
|
||||||
|
const [autoSource, setAutoSource] = useState('list') // 'list' | 'custom'
|
||||||
|
const [country, setCountry] = useState(DEFAULT_COUNTRY)
|
||||||
|
const [zoneName, setZoneName] = useState('')
|
||||||
|
const [name, setName] = useState('')
|
||||||
|
const [stdOffset, setStdOffset] = useState(120)
|
||||||
|
const [dstAmount, setDstAmount] = useState(60)
|
||||||
|
const [fixedDst, setFixedDst] = useState(0)
|
||||||
|
const [rule, setRule] = useState(DEFAULT_RULE)
|
||||||
|
const [ruleHasDst, setRuleHasDst] = useState(true)
|
||||||
|
const [dstStart, setDstStart] = useState('')
|
||||||
|
const [dstEnd, setDstEnd] = useState('')
|
||||||
|
const [saving, setSaving] = useState(false)
|
||||||
|
const [error, setError] = useState('')
|
||||||
|
|
||||||
|
// Load the backend table once per session (cached in deviceTimezone.js)
|
||||||
|
useEffect(() => {
|
||||||
|
if (!open || table) return
|
||||||
|
loadTimezoneTable()
|
||||||
|
.then(setTable)
|
||||||
|
.catch(err => setTableError(err.message || 'Could not load the timezone list.'))
|
||||||
|
}, [open, table])
|
||||||
|
|
||||||
|
// Start from what the device reports every time the modal opens
|
||||||
|
useEffect(() => {
|
||||||
|
if (!open) return
|
||||||
|
setError('')
|
||||||
|
const tz = current || {}
|
||||||
|
setMode(tz.mode || 'auto')
|
||||||
|
setName(tz.mode === 'local' ? '' : (tz.name || ''))
|
||||||
|
setStdOffset(tz.std_offset_min ?? 120)
|
||||||
|
setDstAmount(tz.mode === 'manual' && tz.dst_offset_min ? tz.dst_offset_min : 60)
|
||||||
|
setFixedDst(tz.mode === 'fixed' ? (tz.dst_offset_min || 0) : 0)
|
||||||
|
setDstStart(tz.mode === 'manual' ? epochToWallClock(tz.dst_start, tz.std_offset_min) : '')
|
||||||
|
setDstEnd(tz.mode === 'manual' ? epochToWallClock(tz.dst_end, tz.std_offset_min + tz.dst_offset_min) : '')
|
||||||
|
setAutoSource('list')
|
||||||
|
setZoneName(tz.mode === 'auto' ? (tz.name || '') : '')
|
||||||
|
}, [open, current])
|
||||||
|
|
||||||
|
// Once the table is there, select the current zone's country
|
||||||
|
useEffect(() => {
|
||||||
|
if (!table || !open) return
|
||||||
|
const c = findCountryOfZone(table, zoneName)
|
||||||
|
if (c) setCountry(c.code)
|
||||||
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
|
}, [table, open])
|
||||||
|
|
||||||
|
const countryZones = useMemo(
|
||||||
|
() => table?.countries.find(c => c.code === country)?.zones || [],
|
||||||
|
[table, country],
|
||||||
|
)
|
||||||
|
const selectedZone = countryZones.find(z => z.name === zoneName) || null
|
||||||
|
|
||||||
|
// Picking a country with a single zone picks the zone too
|
||||||
|
const handleCountry = (code) => {
|
||||||
|
setCountry(code)
|
||||||
|
const zones = table?.countries.find(c => c.code === code)?.zones || []
|
||||||
|
setZoneName(zones.length === 1 ? zones[0].name : '')
|
||||||
|
}
|
||||||
|
|
||||||
|
const customPosix = useMemo(
|
||||||
|
() => buildPosixRule({ stdOffsetMin: stdOffset, dstAmountMin: ruleHasDst ? dstAmount : 0, ...rule }),
|
||||||
|
[stdOffset, dstAmount, ruleHasDst, rule],
|
||||||
|
)
|
||||||
|
|
||||||
|
// ── Build the clock.set_timezone contents + validation ────────────────────
|
||||||
|
let contents = null
|
||||||
|
let invalid = '' // shown to the user
|
||||||
|
let incomplete = false // just not filled in yet — Save stays disabled, no message
|
||||||
|
if (mode === 'auto' && autoSource === 'list') {
|
||||||
|
if (selectedZone) contents = { mode: 'auto', name: selectedZone.name, posix: selectedZone.posix }
|
||||||
|
else incomplete = true
|
||||||
|
} else if (mode === 'auto') {
|
||||||
|
contents = { mode: 'auto', name: name.trim() || 'Custom rule', posix: customPosix }
|
||||||
|
} else if (mode === 'manual') {
|
||||||
|
// Start is entered in local standard time, end in local DST time
|
||||||
|
const startWall = wallClockToEpoch(dstStart)
|
||||||
|
const endWall = wallClockToEpoch(dstEnd)
|
||||||
|
if (startWall == null || endWall == null) {
|
||||||
|
incomplete = true
|
||||||
|
} else {
|
||||||
|
const start = startWall - stdOffset * 60
|
||||||
|
const end = endWall - (stdOffset + dstAmount) * 60
|
||||||
|
if (end <= start) invalid = 'DST must end after it starts.'
|
||||||
|
else contents = { mode: 'manual', name: name.trim(), std_offset_min: stdOffset, dst_offset_min: dstAmount, dst_start: start, dst_end: end }
|
||||||
|
}
|
||||||
|
} else if (mode === 'fixed') {
|
||||||
|
contents = { mode: 'fixed', name: name.trim(), std_offset_min: stdOffset, dst_offset_min: fixedDst }
|
||||||
|
} else {
|
||||||
|
contents = { mode: 'local' }
|
||||||
|
}
|
||||||
|
if (contents?.name && contents.name.length > 47) {
|
||||||
|
invalid = 'Name must be at most 47 characters.'
|
||||||
|
contents = null
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleSave = async () => {
|
||||||
|
if (!contents) return
|
||||||
|
setSaving(true)
|
||||||
|
setError('')
|
||||||
|
try {
|
||||||
|
const reply = await sendMqttCommand('clock.set_timezone', contents)
|
||||||
|
onSaved?.(reply?.data || null)
|
||||||
|
onClose()
|
||||||
|
} catch (err) {
|
||||||
|
setError(err.message || 'Failed to set the timezone.')
|
||||||
|
} finally {
|
||||||
|
setSaving(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const offsetSelect = (label, fieldName, value, onChange) => (
|
||||||
|
<FormField label={label} name={fieldName} type="select" value={String(value)} onChange={e => onChange(Number(e.target.value))}>
|
||||||
|
{STD_OFFSET_OPTIONS.map(o => <option key={o.value} value={String(o.value)}>{o.label}</option>)}
|
||||||
|
</FormField>
|
||||||
|
)
|
||||||
|
|
||||||
|
const dstAmountSelect = (
|
||||||
|
<FormField label="DST amount" name="dstAmount" type="select" value={String(dstAmount)} onChange={e => setDstAmount(Number(e.target.value))}>
|
||||||
|
{DST_AMOUNT_OPTIONS.map(o => <option key={o.value} value={String(o.value)}>{o.label}</option>)}
|
||||||
|
</FormField>
|
||||||
|
)
|
||||||
|
|
||||||
|
const nameField = (placeholder) => (
|
||||||
|
<FormField label="Name (optional)" name="tzName" value={name} onChange={e => setName(e.target.value)} placeholder={placeholder} />
|
||||||
|
)
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Modal
|
||||||
|
open={open}
|
||||||
|
onClose={onClose}
|
||||||
|
title="Timezone"
|
||||||
|
size="md"
|
||||||
|
footer={
|
||||||
|
<div style={{ display: 'flex', justifyContent: 'flex-end', gap: 'var(--space-3)' }}>
|
||||||
|
<Button variant="ghost" onClick={onClose}>Cancel</Button>
|
||||||
|
<Button variant="primary" loading={saving} disabled={!contents} onClick={handleSave}>Save Timezone</Button>
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-5)' }}>
|
||||||
|
<SegmentedControl options={TZ_MODES} value={mode} onChange={setMode} size="sm" />
|
||||||
|
|
||||||
|
{mode === 'auto' && (
|
||||||
|
<>
|
||||||
|
{hint('The device switches DST by itself every year, following the rules of the chosen timezone.')}
|
||||||
|
<SegmentedControl
|
||||||
|
options={[{ value: 'list', label: 'Choose a timezone' }, { value: 'custom', label: 'Custom yearly rule' }]}
|
||||||
|
value={autoSource}
|
||||||
|
onChange={setAutoSource}
|
||||||
|
size="sm"
|
||||||
|
/>
|
||||||
|
|
||||||
|
{autoSource === 'list' && (
|
||||||
|
tableError ? (
|
||||||
|
<p style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-danger)' }}>{tableError}</p>
|
||||||
|
) : !table ? (
|
||||||
|
<div style={{ display: 'flex', justifyContent: 'center', padding: 'var(--space-4)' }}><Spinner size="md" /></div>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 'var(--space-3)' }}>
|
||||||
|
<FormField label="Country" name="tzCountry" type="select" value={country} onChange={e => handleCountry(e.target.value)}>
|
||||||
|
{table.countries.map(c => <option key={c.code} value={c.code}>{c.name}</option>)}
|
||||||
|
</FormField>
|
||||||
|
<FormField label="Timezone" name="tzZone" type="select" value={zoneName} onChange={e => setZoneName(e.target.value)}>
|
||||||
|
<option value="">Choose…</option>
|
||||||
|
{countryZones.map(z => <option key={z.name} value={z.name}>{z.display}</option>)}
|
||||||
|
</FormField>
|
||||||
|
</div>
|
||||||
|
{selectedZone && hint(
|
||||||
|
selectedZone.has_dst
|
||||||
|
? `Standard time ${fmtUtcOffset(selectedZone.std_offset_min)}, DST ${fmtUtcOffset(selectedZone.std_offset_min + selectedZone.dst_offset_min)}. Rules: IANA ${table.tzdata_version}.`
|
||||||
|
: `${fmtUtcOffset(selectedZone.std_offset_min)} all year, no DST. Rules: IANA ${table.tzdata_version}.`,
|
||||||
|
)}
|
||||||
|
{current?.mode === 'auto' && current.posix && !findCountryOfZone(table, current.name) &&
|
||||||
|
hint(`Current custom rule on the device: ${current.posix}`)}
|
||||||
|
</>
|
||||||
|
)
|
||||||
|
)}
|
||||||
|
|
||||||
|
{autoSource === 'custom' && (
|
||||||
|
<>
|
||||||
|
{hint('For places whose DST rule is not in the list. The same rule repeats every year.')}
|
||||||
|
{nameField('e.g. Site time')}
|
||||||
|
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 'var(--space-3)' }}>
|
||||||
|
{offsetSelect('Standard offset', 'ruleStd', stdOffset, setStdOffset)}
|
||||||
|
<FormField label="DST" name="ruleDst" type="select" value={ruleHasDst ? String(dstAmount) : '0'}
|
||||||
|
onChange={e => { const v = Number(e.target.value); setRuleHasDst(v !== 0); if (v) setDstAmount(v) }}>
|
||||||
|
<option value="0">No DST</option>
|
||||||
|
{DST_AMOUNT_OPTIONS.map(o => <option key={o.value} value={String(o.value)}>{o.label}</option>)}
|
||||||
|
</FormField>
|
||||||
|
</div>
|
||||||
|
{ruleHasDst && (
|
||||||
|
<>
|
||||||
|
<RuleDateFields id="ruleStart" label="DST starts" value={rule.start} onChange={start => setRule(r => ({ ...r, start }))}
|
||||||
|
timeHint="Local standard time (before the clocks go forward)." />
|
||||||
|
<RuleDateFields id="ruleEnd" label="DST ends" value={rule.end} onChange={end => setRule(r => ({ ...r, end }))}
|
||||||
|
timeHint="Local summer time (before the clocks go back)." />
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
<p style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-text-muted)' }}>
|
||||||
|
Rule sent to the device: <span style={{ fontFamily: 'var(--font-family-mono)', color: 'var(--color-text-primary)' }}>{customPosix}</span>
|
||||||
|
</p>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{mode === 'manual' && (
|
||||||
|
<>
|
||||||
|
{hint('For places with irregular DST dates. Valid for one season — enter next year\'s dates when this one ends (the console will remind you).')}
|
||||||
|
{nameField('e.g. Site time')}
|
||||||
|
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 'var(--space-3)' }}>
|
||||||
|
{offsetSelect('Standard offset', 'manualStd', stdOffset, setStdOffset)}
|
||||||
|
{dstAmountSelect}
|
||||||
|
</div>
|
||||||
|
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 'var(--space-3)' }}>
|
||||||
|
<FormField label="DST starts" name="dstStart" type="datetime-local" value={dstStart} onChange={e => setDstStart(e.target.value)}
|
||||||
|
hint="Local standard time" />
|
||||||
|
<FormField label="DST ends" name="dstEnd" type="datetime-local" value={dstEnd} onChange={e => setDstEnd(e.target.value)}
|
||||||
|
hint="Local summer time" />
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{mode === 'fixed' && (
|
||||||
|
<>
|
||||||
|
{hint('A constant offset that never switches. Automatic NTP still corrects small drift, but never by more than 5 minutes — set the time yourself if it is further off.')}
|
||||||
|
{nameField('e.g. Site time')}
|
||||||
|
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 'var(--space-3)' }}>
|
||||||
|
{offsetSelect('Standard offset', 'fixedStd', stdOffset, setStdOffset)}
|
||||||
|
<FormField label="DST offset now" name="fixedDst" type="select" value={String(fixedDst)} onChange={e => setFixedDst(Number(e.target.value))}>
|
||||||
|
<option value="0">None</option>
|
||||||
|
{DST_AMOUNT_OPTIONS.map(o => <option key={o.value} value={String(o.value)}>{o.label}</option>)}
|
||||||
|
</FormField>
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{mode === 'local' && hint('No timezone and no DST: the device keeps exactly the local time you set (use Set Time after saving). NTP is not used in this mode.')}
|
||||||
|
|
||||||
|
{invalid && !incomplete && (
|
||||||
|
<p style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-warning)' }}>{invalid}</p>
|
||||||
|
)}
|
||||||
|
{error && <p style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-danger)' }}>{error}</p>}
|
||||||
|
</div>
|
||||||
|
</Modal>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,114 @@
|
|||||||
|
// frontend/src/modals/bellcloud/devices/NtpSettingsModal.jsx
|
||||||
|
// NTP settings for a device (firmware 3.1.0+, clock.set_ntp): automatic syncs on/off,
|
||||||
|
// nightly sync time (device local time) and up to 3 servers.
|
||||||
|
|
||||||
|
import { useEffect, useState } from 'react'
|
||||||
|
import Modal from '@/components/ui/Modal'
|
||||||
|
import Button from '@/components/ui/Button'
|
||||||
|
import FormField from '@/components/ui/FormField'
|
||||||
|
import SegmentedControl from '@/components/ui/SegmentedControl'
|
||||||
|
|
||||||
|
const DEFAULT_SERVERS = ['pool.ntp.org', 'time.google.com', 'time.cloudflare.com']
|
||||||
|
|
||||||
|
export default function NtpSettingsModal({ open, onClose, ntp, sendMqttCommand, onSaved }) {
|
||||||
|
const [auto, setAuto] = useState(true)
|
||||||
|
const [syncTime, setSyncTime] = useState('04:30')
|
||||||
|
const [servers, setServers] = useState(['', '', ''])
|
||||||
|
const [saving, setSaving] = useState(false)
|
||||||
|
const [error, setError] = useState('')
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!open) return
|
||||||
|
setError('')
|
||||||
|
setAuto(ntp?.auto ?? true)
|
||||||
|
setSyncTime(ntp?.sync_time || '04:30')
|
||||||
|
const list = ntp?.servers?.length ? ntp.servers : DEFAULT_SERVERS
|
||||||
|
setServers([0, 1, 2].map(i => list[i] || ''))
|
||||||
|
}, [open, ntp])
|
||||||
|
|
||||||
|
const serverList = servers.map(s => s.trim()).filter(Boolean)
|
||||||
|
const badServer = serverList.find(s => s.length > 63 || /\s/.test(s))
|
||||||
|
const invalid =
|
||||||
|
serverList.length === 0 ? 'Enter at least one server.' :
|
||||||
|
badServer ? `Invalid server: ${badServer}` :
|
||||||
|
!/^\d{2}:\d{2}$/.test(syncTime) ? 'Choose a sync time.' : ''
|
||||||
|
|
||||||
|
const handleSave = async () => {
|
||||||
|
if (invalid) return
|
||||||
|
setSaving(true)
|
||||||
|
setError('')
|
||||||
|
try {
|
||||||
|
const reply = await sendMqttCommand('clock.set_ntp', { auto, sync_time: syncTime, servers: serverList })
|
||||||
|
onSaved?.(reply?.data || null)
|
||||||
|
onClose()
|
||||||
|
} catch (err) {
|
||||||
|
setError(err.message || 'Failed to save NTP settings.')
|
||||||
|
} finally {
|
||||||
|
setSaving(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Modal
|
||||||
|
open={open}
|
||||||
|
onClose={onClose}
|
||||||
|
title="NTP Settings"
|
||||||
|
size="sm"
|
||||||
|
footer={
|
||||||
|
<div style={{ display: 'flex', justifyContent: 'flex-end', gap: 'var(--space-3)' }}>
|
||||||
|
<Button variant="ghost" onClick={onClose}>Cancel</Button>
|
||||||
|
<Button variant="primary" loading={saving} disabled={!!invalid} onClick={handleSave}>Save</Button>
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-5)' }}>
|
||||||
|
<div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-2)' }}>
|
||||||
|
<span style={{ fontSize: 'var(--font-size-sm)', fontWeight: 'var(--font-weight-medium)', color: 'var(--color-text-secondary)' }}>
|
||||||
|
Automatic sync
|
||||||
|
</span>
|
||||||
|
<SegmentedControl
|
||||||
|
options={[{ value: 'on', label: 'On' }, { value: 'off', label: 'Off' }]}
|
||||||
|
value={auto ? 'on' : 'off'}
|
||||||
|
onChange={v => setAuto(v === 'on')}
|
||||||
|
size="sm"
|
||||||
|
/>
|
||||||
|
<p style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-text-muted)' }}>
|
||||||
|
{auto
|
||||||
|
? 'Nightly sync, plus a sync after connecting while the clock is unconfirmed. At least 3 servers must agree; jumps over 10 minutes wait for a second sync.'
|
||||||
|
: 'The device never syncs by itself. Use Sync Now to correct it.'}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<FormField
|
||||||
|
label="Nightly sync time"
|
||||||
|
name="ntpSyncTime"
|
||||||
|
type="time"
|
||||||
|
value={syncTime}
|
||||||
|
onChange={e => setSyncTime(e.target.value)}
|
||||||
|
hint="Device local time. Default 04:30 — after the usual 01:00–04:00 DST switch hours. Retried hourly for 3 hours if it fails."
|
||||||
|
/>
|
||||||
|
|
||||||
|
<div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-3)' }}>
|
||||||
|
{[0, 1, 2].map(i => (
|
||||||
|
<FormField
|
||||||
|
key={i}
|
||||||
|
label={`Server ${i + 1}${i ? ' (optional)' : ''}`}
|
||||||
|
name={`ntpServer${i}`}
|
||||||
|
value={servers[i]}
|
||||||
|
onChange={e => setServers(list => list.map((s, j) => (j === i ? e.target.value : s)))}
|
||||||
|
placeholder={DEFAULT_SERVERS[i]}
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
<p style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-text-muted)' }}>
|
||||||
|
Needs outbound UDP port 123 from the site network.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{invalid && serverList.length > 0 && (
|
||||||
|
<p style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-warning)' }}>{invalid}</p>
|
||||||
|
)}
|
||||||
|
{error && <p style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-danger)' }}>{error}</p>}
|
||||||
|
</div>
|
||||||
|
</Modal>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,100 @@
|
|||||||
|
// frontend/src/modals/bellcloud/devices/SetDeviceTimeModal.jsx
|
||||||
|
// Sets a device's clock by hand (firmware 3.0.0+, clock.set_time). Either the current time
|
||||||
|
// from this computer (sent as UTC — the device shows it in its own timezone), or a local
|
||||||
|
// wall-clock time typed in, which the device converts with its timezone. Normally NTP keeps
|
||||||
|
// the time right; this is for sites without internet, or fixed / local-only timezones.
|
||||||
|
|
||||||
|
import { useEffect, useState } from 'react'
|
||||||
|
import Modal from '@/components/ui/Modal'
|
||||||
|
import Button from '@/components/ui/Button'
|
||||||
|
import FormField from '@/components/ui/FormField'
|
||||||
|
import SegmentedControl from '@/components/ui/SegmentedControl'
|
||||||
|
import { fmtUtcOffset } from '@/lib/formatters'
|
||||||
|
import { TZ_MODE_LABELS, epochToWallClock } from '@/lib/deviceTimezone'
|
||||||
|
|
||||||
|
export default function SetDeviceTimeModal({ open, onClose, timezone, ntp, sendMqttCommand, onSaved }) {
|
||||||
|
const [source, setSource] = useState('computer')
|
||||||
|
const [local, setLocal] = useState('')
|
||||||
|
const [saving, setSaving] = useState(false)
|
||||||
|
const [error, setError] = useState('')
|
||||||
|
|
||||||
|
const offset = timezone?.current_offset_min ?? 0
|
||||||
|
const tzLabel = timezone
|
||||||
|
? `${timezone.name || TZ_MODE_LABELS[timezone.mode]} (${fmtUtcOffset(offset)})`
|
||||||
|
: 'the device timezone'
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!open) return
|
||||||
|
setError('')
|
||||||
|
setSource(timezone?.mode === 'local' ? 'manual' : 'computer')
|
||||||
|
setLocal(epochToWallClock(Math.floor(Date.now() / 1000), offset))
|
||||||
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
|
}, [open])
|
||||||
|
|
||||||
|
const ntpWillCorrect = ntp?.auto && timezone && timezone.mode !== 'local'
|
||||||
|
|
||||||
|
const handleSave = async () => {
|
||||||
|
setSaving(true)
|
||||||
|
setError('')
|
||||||
|
try {
|
||||||
|
const contents = source === 'computer'
|
||||||
|
? { timestamp: Math.floor(Date.now() / 1000) }
|
||||||
|
: { local: local.length === 16 ? `${local}:00` : local }
|
||||||
|
const reply = await sendMqttCommand('clock.set_time', contents)
|
||||||
|
onSaved?.(reply?.data || null)
|
||||||
|
onClose()
|
||||||
|
} catch (err) {
|
||||||
|
setError(err.message || 'Failed to set the time.')
|
||||||
|
} finally {
|
||||||
|
setSaving(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Modal
|
||||||
|
open={open}
|
||||||
|
onClose={onClose}
|
||||||
|
title="Set Device Time"
|
||||||
|
size="sm"
|
||||||
|
footer={
|
||||||
|
<div style={{ display: 'flex', justifyContent: 'flex-end', gap: 'var(--space-3)' }}>
|
||||||
|
<Button variant="ghost" onClick={onClose}>Cancel</Button>
|
||||||
|
<Button variant="primary" loading={saving} disabled={source === 'manual' && !local} onClick={handleSave}>Set Time</Button>
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-5)' }}>
|
||||||
|
<SegmentedControl
|
||||||
|
options={[{ value: 'computer', label: 'From this computer' }, { value: 'manual', label: 'Enter local time' }]}
|
||||||
|
value={source}
|
||||||
|
onChange={setSource}
|
||||||
|
size="sm"
|
||||||
|
/>
|
||||||
|
|
||||||
|
{source === 'computer' ? (
|
||||||
|
<p style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-text-muted)' }}>
|
||||||
|
Sends this computer's current time (as UTC). The device shows it in {tzLabel}.
|
||||||
|
</p>
|
||||||
|
) : (
|
||||||
|
<FormField
|
||||||
|
label="Local time on the device"
|
||||||
|
name="deviceLocalTime"
|
||||||
|
type="datetime-local"
|
||||||
|
value={local}
|
||||||
|
onChange={e => setLocal(e.target.value)}
|
||||||
|
inputProps={{ step: 1 }}
|
||||||
|
hint={`Wall-clock time in ${tzLabel}.`}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{ntpWillCorrect && (
|
||||||
|
<p style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-warning)', backgroundColor: 'var(--color-warning-bg)', padding: 'var(--space-2) var(--space-3)', borderRadius: 'var(--radius-sm)' }}>
|
||||||
|
Automatic NTP is on: if this differs from real time, the device corrects it at its next sync
|
||||||
|
{timezone?.mode === 'fixed' ? ' (by up to 5 minutes in fixed mode)' : ''}.
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
{error && <p style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-danger)' }}>{error}</p>}
|
||||||
|
</div>
|
||||||
|
</Modal>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -1,67 +1,118 @@
|
|||||||
// frontend/src/modals/bellcloud/devices/SyncClockModal.jsx
|
// frontend/src/modals/bellcloud/devices/SyncClockModal.jsx
|
||||||
// Placeholder — clock sync UI to be implemented when MQTT sync protocol is defined.
|
// Corrects where the device thinks the clocktower's hands are (clock.set_face).
|
||||||
|
// Flow: pause the clock (clock.pause) so the hands stop while someone reads them, enter what
|
||||||
|
// the face shows, then save (clock.set_face) and resume (clock.resume). The device then moves
|
||||||
|
// the hands to the real time — forward only; with face sync "smart" it waits instead of a full
|
||||||
|
// lap when the face is slightly ahead. Closing without saving resumes the clock.
|
||||||
|
|
||||||
|
import { useEffect, useState } from 'react'
|
||||||
import Modal from '@/components/ui/Modal'
|
import Modal from '@/components/ui/Modal'
|
||||||
import Button from '@/components/ui/Button'
|
import Button from '@/components/ui/Button'
|
||||||
import Icon from '@/components/ui/Icon'
|
import FormField from '@/components/ui/FormField'
|
||||||
|
|
||||||
export default function SyncClockModal({ open, onClose, device }) {
|
const HOURS = Array.from({ length: 12 }, (_, i) => i + 1)
|
||||||
const sn = device?.serial_number || device?.device_id
|
const MINUTES = Array.from({ length: 60 }, (_, i) => i)
|
||||||
|
const pad = n => String(n).padStart(2, '0')
|
||||||
|
|
||||||
|
export default function SyncClockModal({ open, onClose, face, sendMqttCommand, onSaved }) {
|
||||||
|
const [paused, setPaused] = useState(false)
|
||||||
|
const [pausing, setPausing] = useState(false)
|
||||||
|
const [hour, setHour] = useState(12)
|
||||||
|
const [minute, setMinute] = useState(0)
|
||||||
|
const [saving, setSaving] = useState(false)
|
||||||
|
const [error, setError] = useState('')
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!open) return
|
||||||
|
setPaused(false)
|
||||||
|
setError('')
|
||||||
|
setHour(face?.clock_hour || 12)
|
||||||
|
setMinute(face?.clock_minute || 0)
|
||||||
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
|
}, [open])
|
||||||
|
|
||||||
|
const handleClose = async () => {
|
||||||
|
if (paused) {
|
||||||
|
try { await sendMqttCommand('clock.resume') } catch { /* toast already shown */ }
|
||||||
|
}
|
||||||
|
onClose()
|
||||||
|
}
|
||||||
|
|
||||||
|
const handlePause = async () => {
|
||||||
|
setPausing(true)
|
||||||
|
setError('')
|
||||||
|
try {
|
||||||
|
await sendMqttCommand('clock.pause')
|
||||||
|
setPaused(true)
|
||||||
|
} catch (err) {
|
||||||
|
setError(err.message || 'Failed to pause the clock.')
|
||||||
|
} finally {
|
||||||
|
setPausing(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleSave = async () => {
|
||||||
|
setSaving(true)
|
||||||
|
setError('')
|
||||||
|
try {
|
||||||
|
await sendMqttCommand('clock.set_face', { hour, minute })
|
||||||
|
await sendMqttCommand('clock.resume')
|
||||||
|
setPaused(false)
|
||||||
|
onSaved?.()
|
||||||
|
onClose()
|
||||||
|
} catch (err) {
|
||||||
|
setError(err.message || 'Failed to set the clocktower time.')
|
||||||
|
} finally {
|
||||||
|
setSaving(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Modal
|
<Modal
|
||||||
open={open}
|
open={open}
|
||||||
onClose={onClose}
|
onClose={handleClose}
|
||||||
title="Sync Clocktower"
|
title="Sync Clocktower"
|
||||||
size="sm"
|
size="sm"
|
||||||
|
persistent={paused}
|
||||||
footer={
|
footer={
|
||||||
<div style={{ display: 'flex', justifyContent: 'flex-end', gap: 'var(--space-3)' }}>
|
<div style={{ display: 'flex', justifyContent: 'flex-end', gap: 'var(--space-3)' }}>
|
||||||
<Button variant="ghost" onClick={onClose}>Close</Button>
|
<Button variant="ghost" onClick={handleClose}>{paused ? 'Cancel & Resume' : 'Cancel'}</Button>
|
||||||
<Button variant="primary" disabled>
|
<Button variant="primary" loading={saving} onClick={handleSave}>Save & Resume</Button>
|
||||||
Sync (Coming Soon)
|
|
||||||
</Button>
|
|
||||||
</div>
|
</div>
|
||||||
}
|
}
|
||||||
>
|
>
|
||||||
<div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 'var(--space-5)', padding: 'var(--space-4) 0', textAlign: 'center' }}>
|
<div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-5)' }}>
|
||||||
<div style={{
|
<p style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-text-muted)' }}>
|
||||||
width: 64,
|
The device thinks the clocktower shows{' '}
|
||||||
height: 64,
|
<span style={{ fontFamily: 'var(--font-family-mono)', color: 'var(--color-text-primary)' }}>
|
||||||
borderRadius: 'var(--radius-full)',
|
{face ? `${pad(face.clock_hour)}:${pad(face.clock_minute)}` : '—'}
|
||||||
backgroundColor: 'var(--color-primary-subtle)',
|
</span>
|
||||||
display: 'flex',
|
. If the hands show something else, enter what they really show.
|
||||||
alignItems: 'center',
|
|
||||||
justifyContent: 'center',
|
|
||||||
}}>
|
|
||||||
<Icon name="refresh" size={28} color="var(--color-primary)" />
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<p style={{ fontSize: 'var(--font-size-base)', fontWeight: 'var(--font-weight-semibold)', color: 'var(--color-text-primary)', marginBottom: 'var(--space-2)' }}>
|
|
||||||
Clock Synchronisation
|
|
||||||
</p>
|
|
||||||
<p style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-text-muted)', maxWidth: 340 }}>
|
|
||||||
This will send an MQTT command to correct the clocktower's mechanical position
|
|
||||||
if it has drifted from the master time reference.
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
{sn && (
|
|
||||||
<div style={{
|
|
||||||
padding: 'var(--space-3) var(--space-4)',
|
|
||||||
borderRadius: 'var(--radius-md)',
|
|
||||||
backgroundColor: 'var(--color-bg-elevated)',
|
|
||||||
border: '1px solid var(--color-border)',
|
|
||||||
width: '100%',
|
|
||||||
}}>
|
|
||||||
<span style={{ fontSize: 'var(--font-size-xs)', color: 'var(--color-text-muted)', textTransform: 'uppercase', letterSpacing: 'var(--tracking-wide)' }}>
|
|
||||||
Target device
|
|
||||||
</span>
|
|
||||||
<p style={{ fontFamily: 'var(--font-family-mono)', fontSize: 'var(--font-size-sm)', color: 'var(--color-text-primary)', marginTop: 'var(--space-1)' }}>
|
|
||||||
{sn}
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
<p style={{ fontSize: 'var(--font-size-xs)', color: 'var(--color-text-muted)', fontStyle: 'italic' }}>
|
|
||||||
Full sync implementation coming soon — MQTT protocol pending.
|
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
|
<div style={{ display: 'flex', alignItems: 'center', gap: 'var(--space-3)' }}>
|
||||||
|
<Button variant="secondary" size="sm" loading={pausing} disabled={paused} onClick={handlePause}>
|
||||||
|
{paused ? 'Clock paused' : 'Pause clock'}
|
||||||
|
</Button>
|
||||||
|
<span style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-text-muted)' }}>
|
||||||
|
Optional — stops the hands while you read them.
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 'var(--space-3)' }}>
|
||||||
|
<FormField label="Hour on the face" name="faceHour" type="select" value={String(hour)} onChange={e => setHour(Number(e.target.value))}>
|
||||||
|
{HOURS.map(h => <option key={h} value={String(h)}>{h}</option>)}
|
||||||
|
</FormField>
|
||||||
|
<FormField label="Minute on the face" name="faceMinute" type="select" value={String(minute)} onChange={e => setMinute(Number(e.target.value))}>
|
||||||
|
{MINUTES.map(m => <option key={m} value={String(m)}>{pad(m)}</option>)}
|
||||||
|
</FormField>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<p style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-text-muted)' }}>
|
||||||
|
After saving, the hands move forward to the real time. If the face is slightly ahead, the
|
||||||
|
face sync setting decides: Force runs a full lap, Smart waits.
|
||||||
|
</p>
|
||||||
|
{error && <p style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-danger)' }}>{error}</p>}
|
||||||
</div>
|
</div>
|
||||||
</Modal>
|
</Modal>
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -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>
|
||||||
|
|||||||
@@ -91,7 +91,7 @@ function deepMerge(base, overrides) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function timeToIso(hhmm) {
|
function timeToIso(hhmm) {
|
||||||
if (!hhmm) return ''
|
if (!hhmm) return null
|
||||||
return `2000-01-01T${hhmm}:00Z`
|
return `2000-01-01T${hhmm}:00Z`
|
||||||
}
|
}
|
||||||
function extractTime(tsStr) {
|
function extractTime(tsStr) {
|
||||||
@@ -250,8 +250,8 @@ const TABLE_COLUMNS = [
|
|||||||
render: (d) => friendlyName(d) || <span style={{ color: 'var(--color-text-muted)' }}>—</span>,
|
render: (d) => friendlyName(d) || <span style={{ color: 'var(--color-text-muted)' }}>—</span>,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
key: 'hw_type', label: 'Board Type', sortable: true,
|
key: 'hw_family', label: 'Board Type', sortable: true,
|
||||||
render: (d) => d.hw_type || <span style={{ color: 'var(--color-text-muted)' }}>—</span>,
|
render: (d) => d.hw_family || <span style={{ color: 'var(--color-text-muted)' }}>—</span>,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
key: 'mfg_status', label: 'Status',
|
key: 'mfg_status', label: 'Status',
|
||||||
@@ -301,14 +301,14 @@ function DevicePicker({ onSelect }) {
|
|||||||
}
|
}
|
||||||
if (boardTypes.length > 0) {
|
if (boardTypes.length > 0) {
|
||||||
const boardTypeSet = new Set(boardTypes)
|
const boardTypeSet = new Set(boardTypes)
|
||||||
list = list.filter((d) => boardTypeSet.has(d.hw_type))
|
list = list.filter((d) => boardTypeSet.has(d.hw_family))
|
||||||
}
|
}
|
||||||
const q = search.trim().toLowerCase()
|
const q = search.trim().toLowerCase()
|
||||||
if (q) {
|
if (q) {
|
||||||
list = list.filter((d) => {
|
list = list.filter((d) => {
|
||||||
if ((d.serial_number || '').toLowerCase().includes(q)) return true
|
if ((d.serial_number || '').toLowerCase().includes(q)) return true
|
||||||
if ((friendlyName(d) || '').toLowerCase().includes(q)) return true
|
if ((friendlyName(d) || '').toLowerCase().includes(q)) return true
|
||||||
if ((d.hw_type || '').toLowerCase().includes(q)) return true
|
if ((d.hw_family || '').toLowerCase().includes(q)) return true
|
||||||
if ((d.customer_name || '').toLowerCase().includes(q)) return true
|
if ((d.customer_name || '').toLowerCase().includes(q)) return true
|
||||||
if ((d.users || []).some((u) => (u.display_name || '').toLowerCase().includes(q) || (u.email || '').toLowerCase().includes(q))) return true
|
if ((d.users || []).some((u) => (u.display_name || '').toLowerCase().includes(q) || (u.email || '').toLowerCase().includes(q))) return true
|
||||||
return false
|
return false
|
||||||
@@ -640,7 +640,7 @@ const PlanStep = forwardRef(function PlanStep({ device, onDeviceUpdated }, ref)
|
|||||||
const startIso = startDateStr ? `${startDateStr}T00:00:00Z` : new Date().toISOString()
|
const startIso = startDateStr ? `${startDateStr}T00:00:00Z` : new Date().toISOString()
|
||||||
// PUT /devices/{id} returns the DeviceInDB shape, which doesn't line up
|
// PUT /devices/{id} returns the DeviceInDB shape, which doesn't line up
|
||||||
// field-for-field with the DeviceInventoryItem shape the rest of the wizard
|
// field-for-field with the DeviceInventoryItem shape the rest of the wizard
|
||||||
// uses (e.g. hw_type vs hw_family) — merge in just the two fields Configure
|
// uses — merge in just the two fields Configure
|
||||||
// actually needs rather than replacing the whole device object.
|
// actually needs rather than replacing the whole device object.
|
||||||
const updated = await api.put(`/devices/${device.id}`, {
|
const updated = await api.put(`/devices/${device.id}`, {
|
||||||
device_subscription: {
|
device_subscription: {
|
||||||
@@ -1353,11 +1353,11 @@ function ConfigureStep({ device, onDeviceUpdated, onNext, onBack }) {
|
|||||||
halfhourAlertsBell: Number(alert.halfBell),
|
halfhourAlertsBell: Number(alert.halfBell),
|
||||||
quarterAlertsBell: Number(alert.quarterBell),
|
quarterAlertsBell: Number(alert.quarterBell),
|
||||||
isDaySilenceOn: alert.isDayOn,
|
isDaySilenceOn: alert.isDayOn,
|
||||||
daySilenceFrom: alert.isDayOn && alert.dayFrom ? timeToIso(alert.dayFrom) : (clock.daySilenceFrom || ''),
|
daySilenceFrom: alert.isDayOn && alert.dayFrom ? timeToIso(alert.dayFrom) : (clock.daySilenceFrom ?? null),
|
||||||
daySilenceTo: alert.isDayOn && alert.dayTo ? timeToIso(alert.dayTo) : (clock.daySilenceTo || ''),
|
daySilenceTo: alert.isDayOn && alert.dayTo ? timeToIso(alert.dayTo) : (clock.daySilenceTo ?? null),
|
||||||
isNightSilenceOn: alert.isNightOn,
|
isNightSilenceOn: alert.isNightOn,
|
||||||
nightSilenceFrom: alert.isNightOn && alert.nightFrom ? timeToIso(alert.nightFrom) : (clock.nightSilenceFrom || ''),
|
nightSilenceFrom: alert.isNightOn && alert.nightFrom ? timeToIso(alert.nightFrom) : (clock.nightSilenceFrom ?? null),
|
||||||
nightSilenceTo: alert.isNightOn && alert.nightTo ? timeToIso(alert.nightTo) : (clock.nightSilenceTo || ''),
|
nightSilenceTo: alert.isNightOn && alert.nightTo ? timeToIso(alert.nightTo) : (clock.nightSilenceTo ?? null),
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
@@ -1377,8 +1377,8 @@ function ConfigureStep({ device, onDeviceUpdated, onNext, onBack }) {
|
|||||||
clockSettings: {
|
clockSettings: {
|
||||||
isBacklightAutomationOn: backlight.enabled,
|
isBacklightAutomationOn: backlight.enabled,
|
||||||
backlightOutput: Number(backlight.output),
|
backlightOutput: Number(backlight.output),
|
||||||
backlightTurnOnTime: backlight.enabled && backlight.onTime ? timeToIso(backlight.onTime) : '',
|
backlightTurnOnTime: backlight.enabled && backlight.onTime ? timeToIso(backlight.onTime) : null,
|
||||||
backlightTurnOffTime: backlight.enabled && backlight.offTime ? timeToIso(backlight.offTime) : '',
|
backlightTurnOffTime: backlight.enabled && backlight.offTime ? timeToIso(backlight.offTime) : null,
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
@@ -1975,7 +1975,7 @@ function DeviceWorkspace({ device, onDeviceUpdated, onDone, onChangeDevice }) {
|
|||||||
return (
|
return (
|
||||||
<Card
|
<Card
|
||||||
title={device.serial_number}
|
title={device.serial_number}
|
||||||
subtitle={`${friendlyName(device) || device.hw_type || '—'} · ${device.mfg_status}`}
|
subtitle={`${friendlyName(device) || device.hw_family || '—'} · ${device.mfg_status}`}
|
||||||
action={<Button variant="ghost" size="sm" onClick={onChangeDevice}>Change Device</Button>}
|
action={<Button variant="ghost" size="sm" onClick={onChangeDevice}>Change Device</Button>}
|
||||||
>
|
>
|
||||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-6)' }}>
|
<div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-6)' }}>
|
||||||
|
|||||||
@@ -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,11 +1,21 @@
|
|||||||
// 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'
|
||||||
|
import { useToast } from '@/components/ui/Toast'
|
||||||
import SyncClockModal from '@/modals/bellcloud/devices/SyncClockModal'
|
import SyncClockModal from '@/modals/bellcloud/devices/SyncClockModal'
|
||||||
|
import EditTimezoneModal from '@/modals/bellcloud/devices/EditTimezoneModal'
|
||||||
|
import SetDeviceTimeModal from '@/modals/bellcloud/devices/SetDeviceTimeModal'
|
||||||
|
import NtpSettingsModal from '@/modals/bellcloud/devices/NtpSettingsModal'
|
||||||
|
import { fmtWallClock, fmtDeviceDateTime, fmtUtcOffset, fmtRelative } from '@/lib/formatters'
|
||||||
|
import { TZ_MODE_LABELS } from '@/lib/deviceTimezone'
|
||||||
|
|
||||||
// ─── Helpers ──────────────────────────────────────────────────────────────────
|
// ─── Helpers ──────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
@@ -44,19 +54,31 @@ function silenceLabel(isOn, from, to) {
|
|||||||
return 'On'
|
return 'On'
|
||||||
}
|
}
|
||||||
|
|
||||||
function formatUtcOffset(offsetSec) {
|
// clock.get_ntp last_sync.result → badge (firmware 3.1.0+)
|
||||||
if (offsetSec == null) return null
|
const SYNC_RESULTS = {
|
||||||
const totalMinutes = offsetSec / 60
|
applied: { variant: 'success', label: 'Corrected' },
|
||||||
const sign = totalMinutes >= 0 ? '+' : '-'
|
in_sync: { variant: 'success', label: 'In sync' },
|
||||||
const abs = Math.abs(totalMinutes)
|
pending_confirmation: { variant: 'warning', label: 'Awaiting confirmation' },
|
||||||
const hours = Math.floor(abs / 60)
|
mismatch_not_applied: { variant: 'warning', label: 'Mismatch — not applied' },
|
||||||
const minutes = abs % 60
|
failed: { variant: 'danger', label: 'Failed' },
|
||||||
return minutes === 0 ? `UTC${sign}${hours}` : `UTC${sign}${hours}:${String(minutes).padStart(2, '0')}`
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function fmtDrift(ms) {
|
||||||
|
if (ms == null) return null
|
||||||
|
const abs = Math.abs(ms)
|
||||||
|
const sign = ms < 0 ? '−' : '+'
|
||||||
|
if (abs < 1000) return `${sign}${abs} ms`
|
||||||
|
if (abs < 120000) return `${sign}${(abs / 1000).toFixed(1)} s`
|
||||||
|
return `${sign}${Math.round(abs / 60000)} min`
|
||||||
|
}
|
||||||
|
|
||||||
|
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms))
|
||||||
|
|
||||||
// ─── Analog Clock Face ────────────────────────────────────────────────────────
|
// ─── Analog Clock Face ────────────────────────────────────────────────────────
|
||||||
|
|
||||||
function AnalogClock({ time, label, variant = 'primary' }) {
|
// `time` is a wall-clock Date read with UTC getters (device time is in the device's timezone,
|
||||||
|
// not the browser's). null = unknown: the face is drawn without hands.
|
||||||
|
function AnalogClock({ time, label, variant = 'primary', showSeconds = true }) {
|
||||||
const canvasRef = useRef(null)
|
const canvasRef = useRef(null)
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@@ -68,9 +90,9 @@ function AnalogClock({ time, label, variant = 'primary' }) {
|
|||||||
const cy = size / 2
|
const cy = size / 2
|
||||||
const r = size / 2 - 4
|
const r = size / 2 - 4
|
||||||
|
|
||||||
const h = time.getHours() % 12
|
const h = time ? time.getUTCHours() % 12 : 0
|
||||||
const m = time.getMinutes()
|
const m = time ? time.getUTCMinutes() : 0
|
||||||
const s = time.getSeconds()
|
const s = time && showSeconds ? time.getUTCSeconds() : 0
|
||||||
|
|
||||||
const isPrimary = variant === 'primary'
|
const isPrimary = variant === 'primary'
|
||||||
const accentColor = isPrimary ? 'rgba(192,193,255,0.9)' : 'rgba(192,193,255,0.35)'
|
const accentColor = isPrimary ? 'rgba(192,193,255,0.9)' : 'rgba(192,193,255,0.35)'
|
||||||
@@ -121,6 +143,8 @@ function AnalogClock({ time, label, variant = 'primary' }) {
|
|||||||
ctx.stroke()
|
ctx.stroke()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (!time) return
|
||||||
|
|
||||||
// Hour hand
|
// Hour hand
|
||||||
const hourAngle = ((h + m / 60) / 12) * Math.PI * 2 - Math.PI / 2
|
const hourAngle = ((h + m / 60) / 12) * Math.PI * 2 - Math.PI / 2
|
||||||
ctx.beginPath()
|
ctx.beginPath()
|
||||||
@@ -142,23 +166,30 @@ function AnalogClock({ time, label, variant = 'primary' }) {
|
|||||||
ctx.stroke()
|
ctx.stroke()
|
||||||
|
|
||||||
// Second hand
|
// Second hand
|
||||||
const secAngle = (s / 60) * Math.PI * 2 - Math.PI / 2
|
if (showSeconds) {
|
||||||
ctx.beginPath()
|
const secAngle = (s / 60) * Math.PI * 2 - Math.PI / 2
|
||||||
ctx.moveTo(cx, cy)
|
ctx.beginPath()
|
||||||
ctx.lineTo(cx + Math.cos(secAngle) * r * 0.82, cy + Math.sin(secAngle) * r * 0.82)
|
ctx.moveTo(cx, cy)
|
||||||
ctx.strokeStyle = secondHandColor
|
ctx.lineTo(cx + Math.cos(secAngle) * r * 0.82, cy + Math.sin(secAngle) * r * 0.82)
|
||||||
ctx.lineWidth = 1
|
ctx.strokeStyle = secondHandColor
|
||||||
ctx.lineCap = 'round'
|
ctx.lineWidth = 1
|
||||||
ctx.stroke()
|
ctx.lineCap = 'round'
|
||||||
|
ctx.stroke()
|
||||||
|
}
|
||||||
|
|
||||||
// Center dot
|
// Center dot
|
||||||
ctx.beginPath()
|
ctx.beginPath()
|
||||||
ctx.arc(cx, cy, isPrimary ? 4 : 3, 0, Math.PI * 2)
|
ctx.arc(cx, cy, isPrimary ? 4 : 3, 0, Math.PI * 2)
|
||||||
ctx.fillStyle = centerDotColor
|
ctx.fillStyle = centerDotColor
|
||||||
ctx.fill()
|
ctx.fill()
|
||||||
}, [time, variant])
|
}, [time, variant, showSeconds])
|
||||||
|
|
||||||
const digitalTime = `${time.getHours().toString().padStart(2, '0')}:${time.getMinutes().toString().padStart(2, '0')}:${time.getSeconds().toString().padStart(2, '0')}`
|
const pad2 = n => n.toString().padStart(2, '0')
|
||||||
|
const digitalTime = !time
|
||||||
|
? '—'
|
||||||
|
: showSeconds
|
||||||
|
? `${pad2(time.getUTCHours())}:${pad2(time.getUTCMinutes())}:${pad2(time.getUTCSeconds())}`
|
||||||
|
: `${pad2(time.getUTCHours() % 12 || 12)}:${pad2(time.getUTCMinutes())}`
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 'var(--space-3)' }}>
|
<div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 'var(--space-3)' }}>
|
||||||
@@ -275,8 +306,16 @@ export default function ClockTab({
|
|||||||
loadDevice,
|
loadDevice,
|
||||||
reloadDeviceSilent,
|
reloadDeviceSilent,
|
||||||
}) {
|
}) {
|
||||||
|
const { toast } = useToast()
|
||||||
const [now, setNow] = useState(new Date())
|
const [now, setNow] = useState(new Date())
|
||||||
const [showSync, setShowSync] = useState(false)
|
const [showSync, setShowSync] = useState(false)
|
||||||
|
const [showTimezone, setShowTimezone] = useState(false)
|
||||||
|
const [showSetTime, setShowSetTime] = useState(false)
|
||||||
|
const [showNtp, setShowNtp] = useState(false)
|
||||||
|
const [syncingNtp, setSyncingNtp] = useState(false)
|
||||||
|
// Live clock state read from the device (firmware 3.x) — the device is the source of truth
|
||||||
|
// for time, timezone and NTP; none of it is mirrored to the device record.
|
||||||
|
const [live, setLive] = useState({ status: 'loading', time: null, timeAt: 0, tz: null, ntp: null, face: null })
|
||||||
const [flashFields, setFlashFields] = useState(false)
|
const [flashFields, setFlashFields] = useState(false)
|
||||||
const [togglingClock, setTogglingClock] = useState(false)
|
const [togglingClock, setTogglingClock] = useState(false)
|
||||||
|
|
||||||
@@ -285,96 +324,110 @@ 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.gmt_offset_sec != null && data.gmt_offset_sec !== clock?.gmtOffsetSec) ||
|
|
||||||
(data.dst_offset_sec != null && data.dst_offset_sec !== clock?.dstOffsetSec) ||
|
|
||||||
(data.ntp_server != null && data.ntp_server !== clock?.ntpServer)
|
|
||||||
|
|
||||||
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 || ''),
|
|
||||||
daySilenceTo: data.daytime_off ? `2000-01-01T${data.daytime_off}:00Z` : (clock?.daySilenceTo || ''),
|
|
||||||
isNightSilenceOn: !!data.night_silence,
|
|
||||||
nightSilenceFrom: data.night_on ? `2000-01-01T${data.night_on}:00Z` : (clock?.nightSilenceFrom || ''),
|
|
||||||
nightSilenceTo: data.night_off ? `2000-01-01T${data.night_off}:00Z` : (clock?.nightSilenceTo || ''),
|
|
||||||
isBacklightAutomationOn: !!data.backlight,
|
|
||||||
backlightOutput: trueBacklightOutput,
|
|
||||||
backlightTurnOnTime: data.backlight_on ? `2000-01-01T${data.backlight_on}:00Z` : '',
|
|
||||||
backlightTurnOffTime: data.backlight_off ? `2000-01-01T${data.backlight_off}:00Z` : '',
|
|
||||||
gmtOffsetSec: data.gmt_offset_sec ?? clock?.gmtOffsetSec,
|
|
||||||
dstOffsetSec: data.dst_offset_sec ?? clock?.dstOffsetSec,
|
|
||||||
ntpServer: data.ntp_server ?? clock?.ntpServer,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
}).then(() => reloadDeviceSilent?.())
|
|
||||||
}).catch(() => {
|
|
||||||
// Device offline or didn't reply — keep showing the last-known Firestore values.
|
|
||||||
})
|
|
||||||
// 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 ─────────────────────
|
||||||
|
// Replies are matched FIFO, so these go one after another.
|
||||||
|
const loadLive = async (parts = ['time', 'tz', 'ntp', 'face']) => {
|
||||||
|
if (!sendMqttCommandSilent) return
|
||||||
|
const commands = { time: 'system.get_time', tz: 'clock.get_timezone', ntp: 'clock.get_ntp', face: 'clock.get_face' }
|
||||||
|
const update = {}
|
||||||
|
try {
|
||||||
|
for (const part of parts) {
|
||||||
|
const reply = await sendMqttCommandSilent(commands[part])
|
||||||
|
update[part] = reply?.data || null
|
||||||
|
if (part === 'time') update.timeAt = Date.now()
|
||||||
|
}
|
||||||
|
setLive(l => ({ ...l, ...update, status: 'ok' }))
|
||||||
|
} catch {
|
||||||
|
setLive(l => ({ ...l, ...update, status: l.status === 'ok' ? 'ok' : 'offline' }))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// The face moves a minute at a time — refresh it while the clock runs. Paused while a
|
||||||
|
// modal or Sync Now may be sending commands, so FIFO reply matching can't cross wires.
|
||||||
|
const busy = showSync || showTimezone || showSetTime || showNtp || syncingNtp
|
||||||
|
useEffect(() => {
|
||||||
|
if (!(attr?.hasClock) || live.status !== 'ok' || busy) return
|
||||||
|
const id = setInterval(() => loadLive(['face']), 30000)
|
||||||
|
return () => clearInterval(id)
|
||||||
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
|
}, [attr?.hasClock, live.status, busy])
|
||||||
|
|
||||||
|
// Sync Now runs on the device in the background (firmware 3.1.0+): poll clock.get_ntp until done
|
||||||
|
const handleSyncNow = async () => {
|
||||||
|
setSyncingNtp(true)
|
||||||
|
try {
|
||||||
|
await sendMqttCommand('clock.sync_ntp')
|
||||||
|
let ntp = null
|
||||||
|
for (let i = 0; i < 10; i++) {
|
||||||
|
await sleep(2000)
|
||||||
|
ntp = (await sendMqttCommandSilent('clock.get_ntp'))?.data
|
||||||
|
if (ntp && !ntp.sync_in_progress) break
|
||||||
|
}
|
||||||
|
setLive(l => ({ ...l, ntp: ntp || l.ntp }))
|
||||||
|
const result = ntp?.last_sync
|
||||||
|
if (!ntp || ntp.sync_in_progress || !result) {
|
||||||
|
toast.warning('NTP sync', 'No result yet — check again in a moment.')
|
||||||
|
} else {
|
||||||
|
const label = SYNC_RESULTS[result.result]?.label || result.result
|
||||||
|
const notify = result.result === 'failed' ? toast.danger : result.result.startsWith('mismatch') ? toast.warning : toast.success
|
||||||
|
notify(`NTP: ${label}`, result.message)
|
||||||
|
}
|
||||||
|
await loadLive(['time'])
|
||||||
|
} catch {
|
||||||
|
// sendMqttCommand already showed the failure toast
|
||||||
|
} finally {
|
||||||
|
setSyncingNtp(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// ── Derived values ────────────────────────────────────────────────────────
|
// ── Derived values ────────────────────────────────────────────────────────
|
||||||
|
|
||||||
const hasClock = attr?.hasClock ?? false
|
const hasClock = attr?.hasClock ?? false
|
||||||
@@ -399,9 +452,16 @@ export default function ClockTab({
|
|||||||
const backlightOnTime = extractTime(clock?.backlightTurnOnTime)
|
const backlightOnTime = extractTime(clock?.backlightTurnOnTime)
|
||||||
const backlightOffTime = extractTime(clock?.backlightTurnOffTime)
|
const backlightOffTime = extractTime(clock?.backlightTurnOffTime)
|
||||||
|
|
||||||
const timezone = formatUtcOffset(clock?.gmtOffsetSec)
|
const tz = live.tz
|
||||||
const ntpServer = clock?.ntpServer || null
|
const ntp = live.ntp
|
||||||
const dstActive = !!clock?.dstOffsetSec
|
const lastSync = ntp?.last_sync || null
|
||||||
|
const syncBadge = lastSync ? (SYNC_RESULTS[lastSync.result] || { variant: 'neutral', label: lastSync.result }) : null
|
||||||
|
// Device wall clock, ticking locally from the last system.get_time reply
|
||||||
|
const deviceTime = live.time?.rtc_available
|
||||||
|
? new Date(live.time.local_timestamp * 1000 + (now.getTime() - live.timeAt))
|
||||||
|
: null
|
||||||
|
const faceTime = live.face ? new Date(Date.UTC(2000, 0, 1, live.face.clock_hour % 12, live.face.clock_minute)) : null
|
||||||
|
const liveMissing = live.status === 'loading' ? 'Loading…' : 'No reply from the device'
|
||||||
|
|
||||||
const alertTypeLabel =
|
const alertTypeLabel =
|
||||||
alertType === 'single' ? 'Single Fire' :
|
alertType === 'single' ? 'Single Fire' :
|
||||||
@@ -461,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',
|
||||||
@@ -576,8 +654,8 @@ export default function ClockTab({
|
|||||||
|
|
||||||
{/* Right — clocks, with equal breathing room on all sides */}
|
{/* Right — clocks, with equal breathing room on all sides */}
|
||||||
<div style={{ display: 'flex', alignItems: 'flex-start', gap: 'var(--space-12)', padding: '0 var(--space-8)' }}>
|
<div style={{ display: 'flex', alignItems: 'flex-start', gap: 'var(--space-12)', padding: '0 var(--space-8)' }}>
|
||||||
<AnalogClock time={now} label="RTC Time" variant="primary" />
|
<AnalogClock time={deviceTime} label="Device Time" variant="primary" />
|
||||||
<AnalogClock time={now} label="Clocktower" variant="primary" />
|
<AnalogClock time={faceTime} label="Clocktower" variant={hasClock ? 'primary' : 'secondary'} showSeconds={false} />
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
</div>
|
</div>
|
||||||
@@ -695,21 +773,91 @@ export default function ClockTab({
|
|||||||
</div>
|
</div>
|
||||||
</Card>
|
</Card>
|
||||||
|
|
||||||
{/* Network & Time */}
|
{/* Time & Timezone (live from the device) */}
|
||||||
<Card title="Network & Time">
|
<Card
|
||||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-2)' }}>
|
title="Time & Timezone"
|
||||||
<SettingRow label="Timezone" value={timezone || '—'} mono={!!timezone} />
|
action={canEdit && live.status === 'ok' && (
|
||||||
<SettingRow label="NTP Server" value={ntpServer || '—'} mono={!!ntpServer} />
|
<div style={{ display: 'flex', gap: 'var(--space-2)' }}>
|
||||||
<SettingRow
|
<Button variant="ghost" size="sm" onClick={() => setShowSetTime(true)}>Set Time</Button>
|
||||||
label="DST"
|
<Button variant="ghost" size="sm" onClick={() => setShowTimezone(true)}>Edit</Button>
|
||||||
badge={<StatusBadge variant={dstActive ? 'success' : 'neutral'}>{dstActive ? 'Active' : 'Not Active'}</StatusBadge>}
|
</div>
|
||||||
/>
|
)}
|
||||||
</div>
|
>
|
||||||
{canEdit && (
|
{live.status !== 'ok' || !tz ? (
|
||||||
<div style={{ marginTop: 'var(--space-4)', paddingTop: 'var(--space-4)', borderTop: '1px solid var(--color-border)' }}>
|
<p style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-text-muted)' }}>{liveMissing}</p>
|
||||||
<p style={{ fontSize: 'var(--font-size-xs)', color: 'var(--color-text-muted)' }}>
|
) : (
|
||||||
Read-only — reported directly by the device. Editing timezone/NTP settings from the console is not yet supported.
|
<div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-2)' }}>
|
||||||
</p>
|
<SettingRow label="Local time" value={live.time?.local ? fmtWallClock(live.time.local) : '—'} />
|
||||||
|
<SettingRow label="Timezone" value={tz.name || TZ_MODE_LABELS[tz.mode]} />
|
||||||
|
<SettingRow label="Mode" value={TZ_MODE_LABELS[tz.mode] || tz.mode} />
|
||||||
|
<SettingRow label="UTC offset" value={fmtUtcOffset(tz.current_offset_min)} mono />
|
||||||
|
<SettingRow
|
||||||
|
label="DST"
|
||||||
|
badge={
|
||||||
|
tz.mode === 'local' ? <StatusBadge variant="neutral">Not used</StatusBadge>
|
||||||
|
: tz.dst_schedule_expired ? <StatusBadge variant="warning">Dates expired</StatusBadge>
|
||||||
|
: <StatusBadge variant={tz.dst_active ? 'success' : 'neutral'}>{tz.dst_active ? 'Active' : 'Not active'}</StatusBadge>
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
{tz.next_transition > 0 && (
|
||||||
|
<SettingRow label="Next change" value={fmtDeviceDateTime(tz.next_transition, tz.current_offset_min)} />
|
||||||
|
)}
|
||||||
|
<SettingRow
|
||||||
|
label="Clock source"
|
||||||
|
badge={<StatusBadge variant={live.time?.rtc_synced ? 'success' : 'warning'}>{live.time?.rtc_synced ? 'Synced' : 'Not synced yet'}</StatusBadge>}
|
||||||
|
/>
|
||||||
|
{tz.dst_schedule_expired && (
|
||||||
|
<p style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-warning)', marginTop: 'var(--space-2)' }}>
|
||||||
|
The manual DST dates have passed — enter next season's dates.
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</Card>
|
||||||
|
|
||||||
|
{/* NTP Sync (live from the device) */}
|
||||||
|
<Card
|
||||||
|
title="NTP Sync"
|
||||||
|
action={canEdit && live.status === 'ok' && (
|
||||||
|
<div style={{ display: 'flex', gap: 'var(--space-2)' }}>
|
||||||
|
<Button variant="ghost" size="sm" loading={syncingNtp} disabled={tz?.mode === 'local'} onClick={handleSyncNow}>Sync Now</Button>
|
||||||
|
<Button variant="ghost" size="sm" onClick={() => setShowNtp(true)}>Edit</Button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
{live.status !== 'ok' || !ntp ? (
|
||||||
|
<p style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-text-muted)' }}>{liveMissing}</p>
|
||||||
|
) : (
|
||||||
|
<div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-2)' }}>
|
||||||
|
<SettingRow
|
||||||
|
label="Automatic"
|
||||||
|
badge={<StatusBadge variant={ntp.auto && tz?.mode !== 'local' ? 'success' : 'neutral'}>
|
||||||
|
{tz?.mode === 'local' ? 'Off (local mode)' : ntp.auto ? `Nightly ${ntp.sync_time}` : 'Off'}
|
||||||
|
</StatusBadge>}
|
||||||
|
/>
|
||||||
|
<SettingRow label="Servers" value={(ntp.servers || []).join(', ') || '—'} mono />
|
||||||
|
<SettingRow
|
||||||
|
label="Last sync"
|
||||||
|
badge={syncBadge ? <StatusBadge variant={syncBadge.variant}>{syncBadge.label}</StatusBadge> : null}
|
||||||
|
value={syncBadge ? undefined : 'None since boot'}
|
||||||
|
/>
|
||||||
|
{lastSync && (
|
||||||
|
<>
|
||||||
|
<SettingRow label="When" value={lastSync.at ? fmtRelative(new Date(lastSync.at * 1000).toISOString()) : '—'} />
|
||||||
|
<SettingRow label="Drift corrected" value={fmtDrift(lastSync.drift_ms) || '—'} mono />
|
||||||
|
<SettingRow label="Servers answered" value={`${lastSync.servers_answered} / ${lastSync.servers_queried}`} />
|
||||||
|
{lastSync.result !== 'applied' && lastSync.result !== 'in_sync' && (
|
||||||
|
<p style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-text-muted)', marginTop: 'var(--space-2)' }}>
|
||||||
|
{lastSync.message}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
{ntp.pending_confirmation && (
|
||||||
|
<p style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-warning)', marginTop: 'var(--space-2)' }}>
|
||||||
|
A large correction is waiting for a second sync to confirm it.
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</Card>
|
</Card>
|
||||||
@@ -717,7 +865,35 @@ export default function ClockTab({
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<SyncClockModal open={showSync} onClose={() => setShowSync(false)} device={device} />
|
<SyncClockModal
|
||||||
|
open={showSync}
|
||||||
|
onClose={() => setShowSync(false)}
|
||||||
|
face={live.face}
|
||||||
|
sendMqttCommand={sendMqttCommand}
|
||||||
|
onSaved={() => loadLive(['face'])}
|
||||||
|
/>
|
||||||
|
<EditTimezoneModal
|
||||||
|
open={showTimezone}
|
||||||
|
onClose={() => setShowTimezone(false)}
|
||||||
|
current={tz}
|
||||||
|
sendMqttCommand={sendMqttCommand}
|
||||||
|
onSaved={(data) => { setLive(l => ({ ...l, tz: data || l.tz })); loadLive(['time', 'ntp']) }}
|
||||||
|
/>
|
||||||
|
<SetDeviceTimeModal
|
||||||
|
open={showSetTime}
|
||||||
|
onClose={() => setShowSetTime(false)}
|
||||||
|
timezone={tz}
|
||||||
|
ntp={ntp}
|
||||||
|
sendMqttCommand={sendMqttCommand}
|
||||||
|
onSaved={(data) => { if (data) setLive(l => ({ ...l, time: data, timeAt: Date.now() })); loadLive(['tz']) }}
|
||||||
|
/>
|
||||||
|
<NtpSettingsModal
|
||||||
|
open={showNtp}
|
||||||
|
onClose={() => setShowNtp(false)}
|
||||||
|
ntp={ntp}
|
||||||
|
sendMqttCommand={sendMqttCommand}
|
||||||
|
onSaved={(data) => setLive(l => ({ ...l, ntp: data || l.ntp }))}
|
||||||
|
/>
|
||||||
</>
|
</>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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.
|
||||||
@@ -1170,7 +1176,7 @@ export default function GeneralTab({
|
|||||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-2)', flex: 1, justifyContent: 'center' }}>
|
<div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-2)', flex: 1, justifyContent: 'center' }}>
|
||||||
<SafetyRow label="Bell Guard" description="Automated striking lock" enabled={attr?.bellGuardOn} />
|
<SafetyRow label="Bell Guard" description="Automated striking lock" enabled={attr?.bellGuardOn} />
|
||||||
<SafetyRow label="Warnings" description="Audible system alerts" enabled={attr?.warningsOn} />
|
<SafetyRow label="Warnings" description="Audible system alerts" enabled={attr?.warningsOn} />
|
||||||
<SafetyRow label="Safety" description="Manual override lock" enabled={attr?.bellGuardSafetyOn} />
|
<SafetyRow label="Safety" description="Manual override lock" enabled={attr?.bellguardSafetyOn} />
|
||||||
</div>
|
</div>
|
||||||
</GlassCard>
|
</GlassCard>
|
||||||
</div>
|
</div>
|
||||||
@@ -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; }
|
||||||
|
|||||||
@@ -235,7 +235,7 @@ export default function OverviewTab({
|
|||||||
api.get('/crm/products').catch(() => null),
|
api.get('/crm/products').catch(() => null),
|
||||||
]).then(([mfgItem, productsRes]) => {
|
]).then(([mfgItem, productsRes]) => {
|
||||||
if (mfgItem?.revision) setHwRevision(mfgItem.revision)
|
if (mfgItem?.revision) setHwRevision(mfgItem.revision)
|
||||||
const hwType = mfgItem?.hw_type || ''
|
const hwType = mfgItem?.hw_family || ''
|
||||||
if (!hwType) return
|
if (!hwType) return
|
||||||
const products = productsRes?.products || []
|
const products = productsRes?.products || []
|
||||||
const norm = s => (s || '').toLowerCase().replace(/[^a-z0-9]/g, '')
|
const norm = s => (s || '').toLowerCase().replace(/[^a-z0-9]/g, '')
|
||||||
|
|||||||
@@ -105,9 +105,9 @@ const NAMESPACES = [
|
|||||||
{ field: 'url', type: 'string', required: false, notes: 'Download URL, used only when the melody is neither built-in nor on SD. The field is "url" — "download_url" is NOT read by playback.play (that name belongs to files.download). Not sticky: omitted = no download possible for this play.' },
|
{ field: 'url', type: 'string', required: false, notes: 'Download URL, used only when the melody is neither built-in nor on SD. The field is "url" — "download_url" is NOT read by playback.play (that name belongs to files.download). Not sticky: omitted = no download possible for this play.' },
|
||||||
{ field: 'speed', type: 'int', required: false, notes: 'ms per beat, 0–65535. Boot default 500. 0 is coerced to 300.' },
|
{ field: 'speed', type: 'int', required: false, notes: 'ms per beat, 0–65535. Boot default 500. 0 is coerced to 300.' },
|
||||||
{ field: 'note_assignments', type: 'int[]', required: false, notes: 'Up to 16 integers, each 0–16. Index = melody note (0-based); value = 1-based BELL channel to ring for that note (0 = silent) — not a relay output. Boot default [1,2,…,16]. A shorter array leaves the remaining entries at their previous values.' },
|
{ field: 'note_assignments', type: 'int[]', required: false, notes: 'Up to 16 integers, each 0–16. Index = melody note (0-based); value = 1-based BELL channel to ring for that note (0 = silent) — not a relay output. Boot default [1,2,…,16]. A shorter array leaves the remaining entries at their previous values.' },
|
||||||
{ field: 'mode', type: 'string', required: false, notes: '"single" | "timed" | "interval" | "infinite" — anything else is rejected. Selects the timing model (see warning). When present, segment_duration and continuous_loop are ignored.' },
|
{ field: 'mode', type: 'string', required: false, notes: '"single" | "timed" | "interval" | "infinite" — anything else is rejected. When present, segment_duration and continuous_loop are ignored. "single": play the melody once, start to end, then stop. "timed": loop back-to-back; once duration has passed, finish the current loop and stop. No pauses. "interval": play duration, pause pause_duration, repeat; stop once total_duration has passed since the start, pauses included (0 = never). "infinite": never stops on its own (only playback.stop). With no duration/pause_duration it loops continuously; with both it plays duration, pauses pause_duration, and repeats forever. total_duration is ignored. See the warning for exact timing.' },
|
||||||
{ field: 'duration', type: 'int', required: false, notes: 'ms, ≥ 0. Read only when mode is present; must be > 0 for "timed"/"interval". "timed": loop until duration elapses, finish the current loop, stop. "interval": length of each play segment. Ignored for "single"/"infinite".' },
|
{ field: 'duration', type: 'int', required: false, notes: 'ms, ≥ 0. Read only when mode is present; must be > 0 for "timed"/"interval". "timed": loop until duration elapses, finish the current loop, stop. "interval": length of each play segment. "infinite": optional segment length; must be sent together with pause_duration (both > 0, or both omitted). Ignored for "single".' },
|
||||||
{ field: 'pause_duration', type: 'int', required: false, notes: 'ms between segments. Read for mode "interval", or when mode is absent.' },
|
{ field: 'pause_duration', type: 'int', required: false, notes: 'ms of silence between segments, counted from the end of the loop that was playing when the segment ran out. Read for mode "interval" and "infinite", or when mode is absent.' },
|
||||||
{ field: 'total_duration', type: 'int', required: false, notes: 'ms overall cap. Read for mode "interval" (0 = forever), or when mode is absent AND continuous_loop is true. With mode absent and continuous_loop false it is IGNORED (overwritten with segment_duration).' },
|
{ field: 'total_duration', type: 'int', required: false, notes: 'ms overall cap. Read for mode "interval" (0 = forever), or when mode is absent AND continuous_loop is true. With mode absent and continuous_loop false it is IGNORED (overwritten with segment_duration).' },
|
||||||
{ field: 'segment_duration', type: 'int', required: false, notes: 'Legacy — read only when mode is absent. With continuous_loop false this is the whole run length (sticky, boot default 15000; 0 = play once). With continuous_loop true it is the segment length.' },
|
{ field: 'segment_duration', type: 'int', required: false, notes: 'Legacy — read only when mode is absent. With continuous_loop false this is the whole run length (sticky, boot default 15000; 0 = play once). With continuous_loop true it is the segment length.' },
|
||||||
{ field: 'continuous_loop', type: 'bool', required: false, notes: 'Legacy — read only when mode is absent. Defaults to false on every command (not sticky).' },
|
{ field: 'continuous_loop', type: 'bool', required: false, notes: 'Legacy — read only when mode is absent. Defaults to false on every command (not sticky).' },
|
||||||
@@ -125,14 +125,15 @@ const NAMESPACES = [
|
|||||||
{ message: 'Invalid total_duration: must be a non-negative integer (ms)', condition: 'Same, for total_duration' },
|
{ message: 'Invalid total_duration: must be a non-negative integer (ms)', condition: 'Same, for total_duration' },
|
||||||
{ message: 'Invalid mode: must be single, timed, interval or infinite', condition: 'Unrecognised mode' },
|
{ message: 'Invalid mode: must be single, timed, interval or infinite', condition: 'Unrecognised mode' },
|
||||||
{ message: 'Invalid duration: mode timed and interval require duration > 0', condition: 'mode is timed/interval and duration is missing or 0' },
|
{ message: 'Invalid duration: mode timed and interval require duration > 0', condition: 'mode is timed/interval and duration is missing or 0' },
|
||||||
|
{ message: 'Invalid infinite segments: duration and pause_duration must both be > 0, or both omitted', condition: 'mode is infinite and only one of duration / pause_duration is > 0' },
|
||||||
{ message: 'Playback blocked: bell mechanism is disabled (bells.enable)', condition: 'Bells master switch is off (bells.disable)' },
|
{ message: 'Playback blocked: bell mechanism is disabled (bells.enable)', condition: 'Bells master switch is off (bells.disable)' },
|
||||||
{ message: 'Playback blocked: bell overload protection active — wait for the bells to cool', condition: 'Load guard enabled and a bell is over its max load (the guard would force-stop immediately)' },
|
{ message: 'Playback blocked: bell overload protection active — wait for the bells to cool', condition: 'Load guard enabled and a bell is over its max load (the guard would force-stop immediately)' },
|
||||||
{ message: 'Melody failed to load: file is empty or corrupt', condition: '/melodies/{pid} exists on SD but is empty or has an odd byte count' },
|
{ message: 'Melody failed to load: file is empty or corrupt', condition: '/melodies/{pid} exists on SD but is empty or has an odd byte count' },
|
||||||
{ message: 'Melody not found: not built-in, not on SD card, and no url given', condition: 'Needs a download but no url was sent' },
|
{ message: 'Melody not found: not built-in, not on SD card, and no url given', condition: 'Needs a download but no url was sent' },
|
||||||
{ message: 'Melody not found locally and this device has no SD card to download it to', condition: 'Needs a download but the build has no SD card / FileManager (agnus)' },
|
{ message: 'Melody not found locally and this device has no SD card to download it to', condition: 'Needs a download but the build has no SD card / FileManager (agnus)' },
|
||||||
],
|
],
|
||||||
example: '// single — play once and stop\n{ "v": 2, "req_id": "a1", "cmd": "playback.play", "contents": { "pid": "westminster", "speed": 400, "mode": "single" } }\n\n// timed — loop for 2 minutes, finish the loop, stop (downloads first if needed)\n{ "v": 2, "cmd": "playback.play", "contents": { "pid": "ABC123", "url": "https://example.com/ABC123.bin", "mode": "timed", "duration": 120000 } }\n\n// interval — play 15 s, pause 5 s, repeat for 3 min total\n{ "v": 2, "cmd": "playback.play", "contents": { "pid": "ABC123", "mode": "interval", "duration": 15000, "pause_duration": 5000, "total_duration": 180000 } }\n\n// legacy timing (no mode)\n{ "v": 2, "cmd": "playback.play", "contents": { "pid": "ABC123", "segment_duration": 15000, "pause_duration": 5000, "continuous_loop": true } }',
|
example: '// single — play once and stop\n{ "v": 2, "req_id": "a1", "cmd": "playback.play", "contents": { "pid": "westminster", "speed": 400, "mode": "single" } }\n\n// timed — loop for 2 minutes, finish the loop, stop (downloads first if needed)\n{ "v": 2, "cmd": "playback.play", "contents": { "pid": "ABC123", "url": "https://example.com/ABC123.bin", "mode": "timed", "duration": 120000 } }\n\n// interval — play 15 s, pause 5 s, repeat for 3 min total\n{ "v": 2, "cmd": "playback.play", "contents": { "pid": "ABC123", "mode": "interval", "duration": 15000, "pause_duration": 5000, "total_duration": 180000 } }\n\n// infinite — loop until playback.stop\n{ "v": 2, "cmd": "playback.play", "contents": { "pid": "ABC123", "mode": "infinite" } }\n\n// infinite with segments — play 30 s, pause 10 s, forever\n{ "v": 2, "cmd": "playback.play", "contents": { "pid": "ABC123", "mode": "infinite", "duration": 30000, "pause_duration": 10000 } }\n\n// legacy timing (no mode)\n{ "v": 2, "cmd": "playback.play", "contents": { "pid": "ABC123", "segment_duration": 15000, "pause_duration": 5000, "continuous_loop": true } }',
|
||||||
warning: 'mode decides which timing fields are read. mode present: duration (+ pause_duration / total_duration for "interval") — segment_duration and continuous_loop are ignored. mode absent (legacy): continuous_loop false → run for segment_duration, total_duration ignored; continuous_loop true → segment_duration segments with pause_duration gaps, stopping after total_duration if given this command, else segment_duration if given, else the previous total_duration (0 = forever). Never mix the two sets expecting both to apply.',
|
warning: 'Exact timing: (1) timing is checked every 500 ms, so every duration / pause / total boundary is hit up to 0.5 s late. (2) A loop is never cut short (only playback.stop and the overload guard do that); when a segment or the run ends mid-loop, the current loop finishes first. (3) At a segment end status/playback goes "paused" straight away while that loop finishes ringing; at the end of a timed/interval run it goes "stopping", then "idle". "single" goes from "playing" directly to "idle". (4) The bells are then silent for the full pause_duration, counted from that loop end, and status goes back to "playing". (5) total_duration counts from the start, pauses included; if it runs out during a pause, playback stops at once. (6) No gap between loops: in every looping mode the next loop starts right after the previous one; the last step\'s beat (speed) is the only spacing (firmware 2.5.1+; older builds waited ~0.5 s between loops when the run had no end time). Which timing fields are read: mode present → duration (+ pause_duration for "infinite", + pause_duration / total_duration for "interval"); segment_duration and continuous_loop are ignored. mode absent (legacy): continuous_loop false → run for segment_duration, total_duration ignored; continuous_loop true → segment_duration segments with pause_duration gaps, stopping after total_duration if given this command, else segment_duration if given, else the previous total_duration (0 = forever). Never mix the two sets expecting both to apply.',
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
cmd: 'playback.stop',
|
cmd: 'playback.stop',
|
||||||
@@ -373,13 +374,17 @@ const NAMESPACES = [
|
|||||||
{ field: 'c2', type: 'int', required: false, notes: 'Relay output for clock pulse 2 (1-based). 0 = disabled.' },
|
{ field: 'c2', type: 'int', required: false, notes: 'Relay output for clock pulse 2 (1-based). 0 = disabled.' },
|
||||||
{ field: 'pulse_duration', type: 'int', required: false, notes: 'Duration of each clock pulse in milliseconds.' },
|
{ field: 'pulse_duration', type: 'int', required: false, notes: 'Duration of each clock pulse in milliseconds.' },
|
||||||
{ field: 'pause_duration', type: 'int', required: false, notes: 'Pause between C1 and C2 pulses in milliseconds.' },
|
{ field: 'pause_duration', type: 'int', required: false, notes: 'Pause between C1 and C2 pulses in milliseconds.' },
|
||||||
|
{ field: 'face_sync_mode', type: 'string', required: false, notes: 'fw 3.2.0+. "force" (default) or "smart". The face only moves forward: when it is AHEAD of real time (DST fall-back, a correction), force runs it round the dial to catch up; smart stops it until real time catches up, if it is at most smart_max_wait_min ahead (otherwise it runs the lap).' },
|
||||||
|
{ field: 'smart_max_wait_min', type: 'int', required: false, notes: 'fw 3.2.0+. 1-359, default 61 (covers a DST fall-back). Capped below 6 h because a face ahead by N minutes reads the same as one behind by 720 - N.' },
|
||||||
],
|
],
|
||||||
response: '{ "status": "SUCCESS", "type": "clock.set_config", "message": "Clock configuration updated and saved" }',
|
response: '{ "status": "SUCCESS", "type": "clock.set_config", "message": "Clock configuration updated and saved" }',
|
||||||
errors: [
|
errors: [
|
||||||
{ message: 'Provide at least one field: enabled, c1, c2, pulse_duration, pause_duration', condition: 'No known fields present in contents' },
|
{ message: 'Provide at least one field: enabled, c1, c2, pulse_duration, pause_duration, face_sync_mode, smart_max_wait_min', condition: 'No known fields present in contents' },
|
||||||
|
{ message: 'face_sync_mode must be "force" or "smart"', condition: 'Any other value' },
|
||||||
|
{ message: 'smart_max_wait_min must be 1-359', condition: 'Out of range or not an integer' },
|
||||||
{ message: 'Settings applied but failed to save to SD', condition: 'SD card write failed after applying values' },
|
{ message: 'Settings applied but failed to save to SD', condition: 'SD card write failed after applying values' },
|
||||||
],
|
],
|
||||||
example: '{ "v": 2, "cmd": "clock.set_config", "contents": { "enabled": true, "c1": 5, "c2": 6, "pulse_duration": 100, "pause_duration": 500 } }',
|
example: '{ "v": 2, "cmd": "clock.set_config", "contents": { "enabled": true, "c1": 5, "c2": 6, "pulse_duration": 100, "pause_duration": 500 } }\n\n{ "v": 2, "cmd": "clock.set_config", "contents": { "face_sync_mode": "smart", "smart_max_wait_min": 61 } }',
|
||||||
warning: null,
|
warning: null,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -412,19 +417,26 @@ const NAMESPACES = [
|
|||||||
cmd: 'clock.set_time',
|
cmd: 'clock.set_time',
|
||||||
handler: 'ClockHandler',
|
handler: 'ClockHandler',
|
||||||
transports: ['All'],
|
transports: ['All'],
|
||||||
description: 'Set the RTC time directly. timezone_offset and dst_offset are only applied when BOTH are present (they also update the stored timezone); with only one, or neither, timestamp is written to the RTC as-is.',
|
description: 'Set the clock (fw 3.0.0+: the RTC always holds UTC). Send exactly one of timestamp (UTC) or local (wall-clock time, converted to UTC immediately with the timezone being set, or the current one). An optional timezone object is applied in the same step; everything is validated first, so on any error nothing changes. In the repeated hour of a DST fall-back the first (DST) occurrence is used; a local time inside the spring-forward gap is moved forward by the gap.',
|
||||||
contents: [
|
contents: [
|
||||||
{ field: 'timestamp', type: 'int', required: true, notes: 'Unix epoch timestamp (UTC when both offsets are sent; written as-is otherwise)' },
|
{ field: 'timestamp', type: 'int', required: false, notes: 'UTC Unix epoch seconds (2024..2099). Exactly one of timestamp / local.' },
|
||||||
{ field: 'timezone_offset', type: 'int', required: false, notes: 'Total UTC offset in seconds incl. DST (e.g. 10800 for UTC+2 with DST). Ignored unless dst_offset is also sent.' },
|
{ field: 'local', type: 'string', required: false, notes: 'Local wall-clock time "YYYY-MM-DDTHH:MM:SS" (a space instead of T is accepted). Exactly one of timestamp / local. With timezone mode local this IS the device time (offset 0).' },
|
||||||
{ field: 'dst_offset', type: 'int', required: false, notes: 'DST offset in seconds. Ignored unless timezone_offset is also sent.' },
|
{ field: 'timezone', type: 'object', required: false, notes: 'Timezone object. mode auto: posix (required) + name. mode manual: std_offset_min, dst_offset_min, dst_start, dst_end (all required) + name. mode fixed: std_offset_min (required), dst_offset_min (default 0) + name. mode local: no other fields. Same validation and errors as clock.set_timezone.' },
|
||||||
],
|
],
|
||||||
response: '{ "status": "SUCCESS", "type": "clock.set_time", "message": "RTC time updated successfully" }',
|
response: '{\n "status": "SUCCESS",\n "type": "clock.set_time",\n "data": {\n "rtc_available": true, "rtc_synced": true,\n "utc_timestamp": 1793196300, "local_timestamp": 1793203500,\n "local": "2026-10-28T16:05:00",\n "offset_min": 120, "dst_active": false,\n "tz_mode": "auto", "tz_name": "Europe/Athens",\n "year": 2026, "month": 10, "day": 28, "hour": 16, "minute": 5, "second": 0, "weekday": 3\n }\n}',
|
||||||
errors: [
|
errors: [
|
||||||
{ message: 'Missing required field: timestamp', condition: 'contents.timestamp is absent' },
|
{ message: 'Provide exactly one of: timestamp (UTC epoch) or local', condition: 'Both or neither present' },
|
||||||
{ message: 'Invalid timestamp value', condition: 'timestamp is 0' },
|
{ message: 'Invalid local time (expected YYYY-MM-DDTHH:MM:SS)', condition: 'Malformed or impossible date (e.g. Feb 29 in a non-leap year), year outside 2000..2099' },
|
||||||
{ message: 'RTC time set but verification failed', condition: 'RTC read-back returned 0 after the write — hardware issue' },
|
{ message: 'Time out of range (2024..2099)', condition: 'Resulting UTC before 2024-01-01 or after 2099' },
|
||||||
|
{ message: 'RTC write failed (read-back mismatch)', condition: 'RTC did not hold the written value (hardware fault)' },
|
||||||
|
{ message: 'Missing required field: mode', condition: 'mode absent' },
|
||||||
|
{ message: 'Invalid mode (expected auto, manual, fixed or local)', condition: 'mode is not one of the four values (lowercase)' },
|
||||||
|
{ message: 'Missing required field: posix', condition: 'mode auto without posix' },
|
||||||
|
{ message: 'Missing required fields for manual: std_offset_min, dst_offset_min, dst_start, dst_end', condition: 'mode manual with any of them missing' },
|
||||||
|
{ message: 'Missing required field: std_offset_min', condition: 'mode fixed without std_offset_min' },
|
||||||
|
{ message: 'Invalid timezone: <reason>', condition: 'Reasons: posix is not a valid POSIX TZ rule | posix too long | name too long | std_offset_min out of range (-720..840) | dst_offset_min must be non-zero, -180..180 | dst_offset_min out of range (-180..180) | dst_end must be after dst_start | dst_start..dst_end spans more than one season' },
|
||||||
],
|
],
|
||||||
example: '{\n "v": 2,\n "cmd": "clock.set_time",\n "contents": { "timestamp": 1740000000, "timezone_offset": 7200, "dst_offset": 3600 }\n}',
|
example: '{\n "v": 2,\n "cmd": "clock.set_time",\n "contents": { "timestamp": 1793145600 }\n}\n\n{\n "v": 2,\n "cmd": "clock.set_time",\n "contents": {\n "local": "2026-10-28T14:05:00",\n "timezone": { "mode": "fixed", "name": "Site time", "std_offset_min": 120, "dst_offset_min": 0 }\n }\n}\n\n{\n "v": 2,\n "cmd": "clock.set_time",\n "contents": { "local": "2026-10-28T14:05:00", "timezone": { "mode": "local" } }\n}',
|
||||||
warning: null,
|
warning: null,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -450,26 +462,35 @@ const NAMESPACES = [
|
|||||||
cmd: 'clock.set_timezone',
|
cmd: 'clock.set_timezone',
|
||||||
handler: 'ClockHandler',
|
handler: 'ClockHandler',
|
||||||
transports: ['All'],
|
transports: ['All'],
|
||||||
description: 'Set timezone independently of RTC time. Does not alter the stored time value — only changes how it is displayed/offset.',
|
description: 'Set the timezone (fw 3.0.0+). The RTC (UTC) is not touched; only the UTC to local conversion changes, so the physical clock, alerts and events follow immediately. Modes: auto = IANA zone + POSIX rule, DST switches every year by itself (the normal case; take the rule from the backend timezone table, never build it by hand: POSIX signs are inverted, EET-2 means UTC+2). manual = std offset + one DST amount active between dst_start and dst_end (one season, re-enter yearly). fixed = constant offsets, never switch. local = offset 0, the device keeps local time as if it were UTC. Offsets are minutes EAST of UTC (UTC+2 = 120, India = 330).',
|
||||||
contents: [
|
contents: [
|
||||||
{ field: 'gmt_offset_sec', type: 'int', required: true, notes: 'GMT offset in seconds (e.g. 7200 for UTC+2)' },
|
{ field: 'mode', type: 'string', required: true, notes: 'auto | manual | fixed | local (lowercase)' },
|
||||||
{ field: 'dst_offset_sec', type: 'int', required: false, notes: 'DST offset in seconds (e.g. 3600)' },
|
{ field: 'name', type: 'string', required: false, notes: 'Display name, max 47 chars. For auto use the IANA name, e.g. "Europe/Athens". Forced to "Local" in mode local.' },
|
||||||
|
{ field: 'posix', type: 'string', required: false, notes: 'auto only, required there. POSIX TZ rule, max 63 chars, e.g. "EET-2EEST,M3.5.0/3,M10.5.0/4". DST zones must include start/end rules.' },
|
||||||
|
{ field: 'std_offset_min', type: 'int', required: false, notes: 'manual + fixed (required there). Standard offset in minutes east of UTC, -720..840.' },
|
||||||
|
{ field: 'dst_offset_min', type: 'int', required: false, notes: 'manual: DST amount, required, non-zero, -180..180 (usually 60). fixed: current DST offset, optional, default 0.' },
|
||||||
|
{ field: 'dst_start', type: 'int', required: false, notes: 'manual only, required. UTC epoch when DST starts.' },
|
||||||
|
{ field: 'dst_end', type: 'int', required: false, notes: 'manual only, required. UTC epoch when DST ends; after dst_start, at most ~400 days later.' },
|
||||||
],
|
],
|
||||||
response: '{ "status": "SUCCESS", "type": "clock.set_timezone", "message": "Timezone updated and saved" }',
|
response: '{\n "status": "SUCCESS",\n "type": "clock.set_timezone",\n "data": {\n "mode": "auto", "name": "Europe/Athens",\n "posix": "EET-2EEST,M3.5.0/3,M10.5.0/4",\n "std_offset_min": 120, "dst_offset_min": 60,\n "dst_start": 0, "dst_end": 0,\n "current_offset_min": 120, "dst_active": false,\n "next_transition": 1806195600, "dst_schedule_expired": false\n }\n}',
|
||||||
errors: [
|
errors: [
|
||||||
{ message: 'Missing required field: gmt_offset_sec', condition: 'contents.gmt_offset_sec is absent' },
|
{ message: 'Missing required field: mode', condition: 'mode absent' },
|
||||||
{ message: 'Timezone updated but failed to save to SD', condition: 'SD card write failed' },
|
{ message: 'Invalid mode (expected auto, manual, fixed or local)', condition: 'mode is not one of the four values (lowercase)' },
|
||||||
|
{ message: 'Missing required field: posix', condition: 'mode auto without posix' },
|
||||||
|
{ message: 'Missing required fields for manual: std_offset_min, dst_offset_min, dst_start, dst_end', condition: 'mode manual with any of them missing' },
|
||||||
|
{ message: 'Missing required field: std_offset_min', condition: 'mode fixed without std_offset_min' },
|
||||||
|
{ message: 'Invalid timezone: <reason>', condition: 'Reasons: posix is not a valid POSIX TZ rule | posix too long | name too long | std_offset_min out of range (-720..840) | dst_offset_min must be non-zero, -180..180 | dst_offset_min out of range (-180..180) | dst_end must be after dst_start | dst_start..dst_end spans more than one season' },
|
||||||
],
|
],
|
||||||
example: '{ "v": 2, "cmd": "clock.set_timezone", "contents": { "gmt_offset_sec": 7200, "dst_offset_sec": 3600 } }',
|
example: '{\n "v": 2,\n "cmd": "clock.set_timezone",\n "contents": { "mode": "auto", "name": "Australia/Sydney", "posix": "AEST-10AEDT,M10.1.0,M4.1.0/3" }\n}\n\n{\n "v": 2,\n "cmd": "clock.set_timezone",\n "contents": {\n "mode": "manual", "name": "Custom",\n "std_offset_min": 120, "dst_offset_min": 60,\n "dst_start": 1774746000, "dst_end": 1792890000\n }\n}\n\n{ "v": 2, "cmd": "clock.set_timezone", "contents": { "mode": "fixed", "std_offset_min": 330 } }',
|
||||||
warning: null,
|
warning: null,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
cmd: 'clock.get_timezone',
|
cmd: 'clock.get_timezone',
|
||||||
handler: 'ClockHandler',
|
handler: 'ClockHandler',
|
||||||
transports: ['All'],
|
transports: ['All'],
|
||||||
description: 'Read current timezone settings.',
|
description: 'Read the timezone and its live state. All fields are always present (unused ones are 0 or ""). In auto, std_offset_min / dst_offset_min are derived from the rule. next_transition = UTC epoch of the next offset change (0 if none known). dst_schedule_expired is true only in manual once dst_end has passed (ask the user for next year\'s dates).',
|
||||||
contents: null,
|
contents: null,
|
||||||
response: '{\n "status": "SUCCESS",\n "type": "clock.get_timezone",\n "data": {\n "gmt_offset_sec": 7200,\n "dst_offset_sec": 3600,\n "ntp_server": "pool.ntp.org"\n }\n}',
|
response: '{\n "status": "SUCCESS",\n "type": "clock.get_timezone",\n "data": {\n "mode": "auto", "name": "Europe/Athens",\n "posix": "EET-2EEST,M3.5.0/3,M10.5.0/4",\n "std_offset_min": 120, "dst_offset_min": 60,\n "dst_start": 0, "dst_end": 0,\n "current_offset_min": 120, "dst_active": false,\n "next_transition": 1806195600, "dst_schedule_expired": false\n }\n}',
|
||||||
errors: [],
|
errors: [],
|
||||||
example: '{ "v": 2, "cmd": "clock.get_timezone" }',
|
example: '{ "v": 2, "cmd": "clock.get_timezone" }',
|
||||||
warning: null,
|
warning: null,
|
||||||
@@ -478,13 +499,52 @@ const NAMESPACES = [
|
|||||||
cmd: 'clock.sync_ntp',
|
cmd: 'clock.sync_ntp',
|
||||||
handler: 'ClockHandler',
|
handler: 'ClockHandler',
|
||||||
transports: ['All'],
|
transports: ['All'],
|
||||||
description: 'Run an NTP time sync (blocks up to ~5 s). Always returns SUCCESS — the outcome is only logged.',
|
description: 'Sync now (fw 3.1.0+). Queues a user-initiated NTP session and replies immediately; the session (a few seconds: 5 queries over the configured servers, at least 3 must answer and agree within 1 s) runs on the TimeSync task, never on the network thread. Poll clock.get_ntp until sync_in_progress is false; the outcome is in last_sync. Works even with auto off. Applies a correction of any size at once (automatic syncs hold jumps over 10 min for a second session), except in fixed timezone mode, where differences over 5 min are reported as mismatch_not_applied and never applied.',
|
||||||
contents: null,
|
contents: null,
|
||||||
response: '{ "status": "SUCCESS", "type": "clock.sync_ntp", "message": "NTP sync initiated" }',
|
response: '{ "status": "SUCCESS", "type": "clock.sync_ntp", "data": { "started": true } }',
|
||||||
errors: [],
|
errors: [
|
||||||
|
{ message: 'NTP is not used in local timezone mode', condition: 'Timezone mode is local' },
|
||||||
|
{ message: 'No network connection', condition: 'Not connected' },
|
||||||
|
{ message: 'Device is in AP mode (no internet)', condition: 'Running its own access point' },
|
||||||
|
{ message: 'A sync is already running - check clock.get_ntp in a few seconds', condition: 'A session is queued or running' },
|
||||||
|
],
|
||||||
example: '{ "v": 2, "cmd": "clock.sync_ntp" }',
|
example: '{ "v": 2, "cmd": "clock.sync_ntp" }',
|
||||||
warning: null,
|
warning: null,
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
cmd: 'clock.set_ntp',
|
||||||
|
handler: 'ClockHandler',
|
||||||
|
transports: ['All'],
|
||||||
|
description: 'NTP settings (fw 3.1.0+). Automatic syncs = nightly at sync_time (local time, retried hourly for 3 h if it fails), a few seconds after a network (re)connect while the RTC is not yet synced this boot, every 5 min while the RTC is untrusted, and the confirmation session for large jumps. None of them run in local timezone mode. Replies with the clock.get_ntp payload.',
|
||||||
|
contents: [
|
||||||
|
{ field: 'auto', type: 'bool', required: false, notes: 'Automatic syncs on/off (default true). Off = only clock.sync_ntp. At least one of auto / sync_time / servers.' },
|
||||||
|
{ field: 'sync_time', type: 'string', required: false, notes: 'Nightly sync time "HH:MM", device local time, default "04:30" (outside the usual 01:00-04:00 DST switch hours).' },
|
||||||
|
{ field: 'servers', type: 'string[]', required: false, notes: '1-3 NTP host names, queried round-robin. Default ["pool.ntp.org", "time.google.com", "time.cloudflare.com"]. Needs outbound UDP 123.' },
|
||||||
|
],
|
||||||
|
response: '{\n "status": "SUCCESS",\n "type": "clock.set_ntp",\n "data": {\n "auto": true,\n "sync_time": "04:30", "sync_time_min": 270,\n "servers": ["pool.ntp.org", "time.google.com", "time.cloudflare.com"],\n "rtc_synced": true, "sync_in_progress": false, "pending_confirmation": false,\n "last_sync": {\n "result": "applied", "message": "RTC corrected", "applied": true,\n "servers_answered": 5, "servers_queried": 5,\n "ntp_utc": 1793196300, "drift_ms": 3412,\n "at": 1793196301, "user_initiated": true\n }\n }\n}',
|
||||||
|
errors: [
|
||||||
|
{ message: 'Provide at least one of: auto, sync_time, servers', condition: 'None present' },
|
||||||
|
{ message: 'sync_time must be "HH:MM" (00:00-23:59)', condition: 'Malformed or out of range' },
|
||||||
|
{ message: 'servers must be an array of 1-3 host names', condition: 'Not an array, empty, or more than 3' },
|
||||||
|
{ message: 'Invalid server host name', condition: 'Empty, longer than 63 chars, or contains a space' },
|
||||||
|
{ message: 'Settings busy - try again', condition: 'State lock not available within 1 s (should not happen)' },
|
||||||
|
],
|
||||||
|
example: '{\n "v": 2,\n "cmd": "clock.set_ntp",\n "contents": { "auto": true, "sync_time": "03:15" }\n}',
|
||||||
|
warning: null,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
cmd: 'clock.get_ntp',
|
||||||
|
handler: 'ClockHandler',
|
||||||
|
transports: ['All'],
|
||||||
|
description: 'NTP settings and state (fw 3.1.0+). rtc_synced = the RTC holds real UTC (set by NTP or clock.set_time). last_sync is null until the first session since boot. last_sync.result: applied | in_sync (RTC within 2 s, nothing written) | pending_confirmation (automatic jump over 10 min, waiting for a second session ~15 min later) | mismatch_not_applied (fixed mode, over 5 min off) | failed (message says why). drift_ms = NTP minus RTC before any write; ntp_utc and at are UTC epoch seconds.',
|
||||||
|
contents: null,
|
||||||
|
response: '{\n "status": "SUCCESS",\n "type": "clock.get_ntp",\n "data": {\n "auto": true,\n "sync_time": "04:30", "sync_time_min": 270,\n "servers": ["pool.ntp.org", "time.google.com", "time.cloudflare.com"],\n "rtc_synced": true, "sync_in_progress": false, "pending_confirmation": false,\n "last_sync": {\n "result": "applied", "message": "RTC corrected", "applied": true,\n "servers_answered": 5, "servers_queried": 5,\n "ntp_utc": 1793196300, "drift_ms": 3412,\n "at": 1793196301, "user_initiated": true\n }\n }\n}',
|
||||||
|
errors: [
|
||||||
|
{ message: 'Settings busy - try again', condition: 'State lock not available within 1 s (should not happen)' },
|
||||||
|
],
|
||||||
|
example: '{ "v": 2, "cmd": "clock.get_ntp" }',
|
||||||
|
warning: null,
|
||||||
|
},
|
||||||
{
|
{
|
||||||
cmd: 'clock.enable',
|
cmd: 'clock.enable',
|
||||||
handler: 'ClockHandler',
|
handler: 'ClockHandler',
|
||||||
@@ -548,9 +608,9 @@ const NAMESPACES = [
|
|||||||
cmd: 'clock.get_config',
|
cmd: 'clock.get_config',
|
||||||
handler: 'ClockHandler',
|
handler: 'ClockHandler',
|
||||||
transports: ['All'],
|
transports: ['All'],
|
||||||
description: 'Read full clock configuration — outputs, timings, alerts, backlight, silence, enabled state, and timezone. Supersedes clock.get_timezone.',
|
description: 'Read full clock configuration — outputs, timings, alerts, backlight, silence, enabled state, NTP settings and timezone (timezone = the clock.get_timezone object, fw 3.0.0 replaced gmt_offset_sec / dst_offset_sec; ntp = the settings part of clock.get_ntp, fw 3.1.0 replaced ntp_server).',
|
||||||
contents: null,
|
contents: null,
|
||||||
response: '{\n "status": "SUCCESS",\n "type": "clock.get_config",\n "data": {\n "enabled": true,\n "c1output": 4, "c2output": 5,\n "pulse_duration": 100, "pause_duration": 500,\n "physical_hour": 10, "physical_minute": 30,\n "next_is_c1": true, "last_sync_time": 1740000000,\n "alert_type": "HOURS", "alert_interval": 1,\n "hour_bell": 5, "half_bell": 255, "quarter_bell": 255,\n "backlight": true, "backlight_output": 6,\n "backlight_on": "07:00", "backlight_off": "22:00",\n "daytime_silence": false, "daytime_on": "00:00", "daytime_off": "00:00",\n "night_silence": true, "night_on": "22:00", "night_off": "07:00",\n "gmt_offset_sec": 7200, "dst_offset_sec": 3600, "ntp_server": "pool.ntp.org"\n }\n}',
|
response: '{\n "status": "SUCCESS",\n "type": "clock.get_config",\n "data": {\n "enabled": true,\n "c1output": 4, "c2output": 5,\n "pulse_duration": 100, "pause_duration": 500,\n "physical_hour": 10, "physical_minute": 30,\n "next_is_c1": true, "last_sync_time": 1740000000,\n "face_sync_mode": "force", "smart_max_wait_min": 61,\n "alert_type": "HOURS", "alert_interval": 1,\n "hour_bell": 5, "half_bell": 255, "quarter_bell": 255,\n "backlight": true, "backlight_output": 6,\n "backlight_on": "07:00", "backlight_off": "22:00",\n "daytime_silence": false, "daytime_on": "00:00", "daytime_off": "00:00",\n "night_silence": true, "night_on": "22:00", "night_off": "07:00",\n "timezone": { ...same object as clock.get_timezone... },\n "ntp": { "auto": true, "sync_time": "04:30", "sync_time_min": 270, "servers": ["pool.ntp.org", "time.google.com", "time.cloudflare.com"] }\n }\n}',
|
||||||
errors: [],
|
errors: [],
|
||||||
example: '{ "v": 2, "cmd": "clock.get_config" }',
|
example: '{ "v": 2, "cmd": "clock.get_config" }',
|
||||||
warning: null,
|
warning: null,
|
||||||
@@ -603,9 +663,9 @@ const NAMESPACES = [
|
|||||||
cmd: 'system.get_time',
|
cmd: 'system.get_time',
|
||||||
handler: 'SystemHandler',
|
handler: 'SystemHandler',
|
||||||
transports: ['All'],
|
transports: ['All'],
|
||||||
description: 'Get current RTC time in local and UTC, plus individual date/time fields.',
|
description: 'Current time. utc_timestamp is the real instant (the RTC holds UTC since fw 3.0.0). year..second and weekday (0 = Sunday) are LOCAL time; local is the same as an ISO string. local_timestamp is local wall-clock time written as an epoch (UTC + offset), not a real instant. rtc_synced is false until NTP or clock.set_time has written the RTC with fw 3.0.0+ (e.g. right after updating from 2.x).',
|
||||||
contents: null,
|
contents: null,
|
||||||
response: '{\n "status": "SUCCESS",\n "type": "system.get_time",\n "data": {\n "local_timestamp": 1740000000,\n "utc_timestamp": 1739993000,\n "rtc_available": true,\n "year": 2025, "month": 2, "day": 20,\n "hour": 10, "minute": 30, "second": 0\n }\n}',
|
response: '{\n "status": "SUCCESS",\n "type": "system.get_time",\n "data": {\n "rtc_available": true, "rtc_synced": true,\n "utc_timestamp": 1793196300, "local_timestamp": 1793203500,\n "local": "2026-10-28T16:05:00",\n "offset_min": 120, "dst_active": false,\n "tz_mode": "auto", "tz_name": "Europe/Athens",\n "year": 2026, "month": 10, "day": 28, "hour": 16, "minute": 5, "second": 0, "weekday": 3\n }\n}',
|
||||||
errors: [],
|
errors: [],
|
||||||
example: '{ "v": 2, "cmd": "system.get_time" }',
|
example: '{ "v": 2, "cmd": "system.get_time" }',
|
||||||
warning: null,
|
warning: null,
|
||||||
@@ -616,7 +676,7 @@ const NAMESPACES = [
|
|||||||
transports: ['All'],
|
transports: ['All'],
|
||||||
description: 'Full ConfigManager dump — all saved settings grouped by subsystem. Alias: system.get_settings (backward compatible).',
|
description: 'Full ConfigManager dump — all saved settings grouped by subsystem. Alias: system.get_settings (backward compatible).',
|
||||||
contents: null,
|
contents: null,
|
||||||
response: '{\n "status": "SUCCESS",\n "type": "system.get_config",\n "data": {\n "general": {\n "bells_enabled": true, "mqtt_enabled": true,\n "ota_channel": "stable",\n "serial_log": 3, "sd_log": 2, "mqtt_log": 1\n },\n "bell": { "durations": {...}, "outputs": {...} },\n "clock": { ... },\n "time": { "gmtOffsetSec": 7200, "daylightOffsetSec": 3600, ... },\n "network": { "hostname": "...", "useStaticIP": false, ... },\n "mqtt": { "host": "...", "port": 1883, ... }\n }\n}',
|
response: '{\n "status": "SUCCESS",\n "type": "system.get_config",\n "data": {\n "general": {\n "bells_enabled": true, "mqtt_enabled": true,\n "ota_channel": "stable",\n "serial_log": 3, "sd_log": 2, "mqtt_log": 1\n },\n "bell": { "durations": {...}, "outputs": {...} },\n "clock": { ... },\n "time": { "ntp": { "auto": true, "sync_time": "04:30", ... }, "tz": { "mode": "auto", "name": "Europe/Athens", "posix": "EET-2EEST,M3.5.0/3,M10.5.0/4", ... } },\n "network": { "hostname": "...", "useStaticIP": false, ... },\n "mqtt": { "host": "...", "port": 1883, ... }\n }\n}',
|
||||||
errors: [
|
errors: [
|
||||||
{ message: 'Failed to serialize settings', condition: 'Internal JSON serialization error — rare' },
|
{ message: 'Failed to serialize settings', condition: 'Internal JSON serialization error — rare' },
|
||||||
],
|
],
|
||||||
|
|||||||
@@ -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>
|
||||||
|
|||||||
@@ -154,7 +154,7 @@ export default function DeviceInventory() {
|
|||||||
const params = new URLSearchParams()
|
const params = new URLSearchParams()
|
||||||
if (search) params.set('search', search)
|
if (search) params.set('search', search)
|
||||||
if (statusFilter) params.set('status', statusFilter)
|
if (statusFilter) params.set('status', statusFilter)
|
||||||
if (typeFilter) params.set('hw_type', typeFilter)
|
if (typeFilter) params.set('hw_family', typeFilter)
|
||||||
params.set('limit', '500')
|
params.set('limit', '500')
|
||||||
const data = await api.get(`/manufacturing/devices${params.toString() ? `?${params}` : ''}`)
|
const data = await api.get(`/manufacturing/devices${params.toString() ? `?${params}` : ''}`)
|
||||||
const devs = data.devices || []
|
const devs = data.devices || []
|
||||||
@@ -198,8 +198,8 @@ export default function DeviceInventory() {
|
|||||||
if (!sortKey) return devices
|
if (!sortKey) return devices
|
||||||
return [...devices].sort((a, b) => {
|
return [...devices].sort((a, b) => {
|
||||||
let av, bv
|
let av, bv
|
||||||
if (sortKey === 'type') { av = BOARD_TYPE_LABELS[a.hw_type] || a.hw_type || ''; bv = BOARD_TYPE_LABELS[b.hw_type] || b.hw_type || '' }
|
if (sortKey === 'type') { av = BOARD_TYPE_LABELS[a.hw_family] || a.hw_family || ''; bv = BOARD_TYPE_LABELS[b.hw_family] || b.hw_family || '' }
|
||||||
else if (sortKey === 'version') { av = a.hw_version || ''; bv = b.hw_version || '' }
|
else if (sortKey === 'version') { av = a.hw_revision || ''; bv = b.hw_revision || '' }
|
||||||
else if (sortKey === 'created') { av = a.created_at || ''; bv = b.created_at || '' }
|
else if (sortKey === 'created') { av = a.created_at || ''; bv = b.created_at || '' }
|
||||||
else if (sortKey === 'customer') {
|
else if (sortKey === 'customer') {
|
||||||
const ca = customerMap[a.customer_id]; const cb = customerMap[b.customer_id]
|
const ca = customerMap[a.customer_id]; const cb = customerMap[b.customer_id]
|
||||||
@@ -268,7 +268,7 @@ export default function DeviceInventory() {
|
|||||||
sortable: true,
|
sortable: true,
|
||||||
render: (d) => (
|
render: (d) => (
|
||||||
<span style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-text-secondary)' }}>
|
<span style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-text-secondary)' }}>
|
||||||
{BOARD_TYPE_LABELS[d.hw_type] || d.hw_type}
|
{BOARD_TYPE_LABELS[d.hw_family] || d.hw_family}
|
||||||
</span>
|
</span>
|
||||||
),
|
),
|
||||||
},
|
},
|
||||||
@@ -278,7 +278,7 @@ export default function DeviceInventory() {
|
|||||||
sortable: true,
|
sortable: true,
|
||||||
render: (d) => (
|
render: (d) => (
|
||||||
<span style={{ fontSize: 'var(--font-size-sm)', fontFamily: 'var(--font-family-mono)', color: 'var(--color-text-muted)' }}>
|
<span style={{ fontSize: 'var(--font-size-sm)', fontFamily: 'var(--font-family-mono)', color: 'var(--color-text-muted)' }}>
|
||||||
{formatHwVersion(d.hw_version)}
|
{formatHwVersion(d.hw_revision)}
|
||||||
</span>
|
</span>
|
||||||
),
|
),
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -645,7 +645,7 @@ export default function DeviceInventoryDetail() {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
const boardLabel = BOARD_TYPE_LABELS[device.hw_type] || device.hw_type
|
const boardLabel = BOARD_TYPE_LABELS[device.hw_family] || device.hw_family
|
||||||
const existingUserIds = deviceUsers.map((u) => u.user_id).filter(Boolean)
|
const existingUserIds = deviceUsers.map((u) => u.user_id).filter(Boolean)
|
||||||
|
|
||||||
const editStepMeta = editModalData ? LIFECYCLE[editModalData.stepIndex] : null
|
const editStepMeta = editModalData ? LIFECYCLE[editModalData.stepIndex] : null
|
||||||
@@ -662,7 +662,7 @@ export default function DeviceInventoryDetail() {
|
|||||||
</StatusBadge>
|
</StatusBadge>
|
||||||
</span>
|
</span>
|
||||||
}
|
}
|
||||||
subtitle={`${device.name || device.device_name || '—'} · ${boardLabel} · ${formatHwVersion(device.hw_version)}`}
|
subtitle={`${device.name || device.device_name || '—'} · ${boardLabel} · ${formatHwVersion(device.hw_revision)}`}
|
||||||
>
|
>
|
||||||
{canEdit && (
|
{canEdit && (
|
||||||
<Button variant="secondary" size="md" onClick={() => navigate(`/manufacturing/provision?sn=${sn}`)}>
|
<Button variant="secondary" size="md" onClick={() => navigate(`/manufacturing/provision?sn=${sn}`)}>
|
||||||
@@ -687,7 +687,7 @@ export default function DeviceInventoryDetail() {
|
|||||||
<Field label="Serial Number" value={device.serial_number} mono />
|
<Field label="Serial Number" value={device.serial_number} mono />
|
||||||
<Field label="Batch ID" value={device.batch_id || device.mfg_batch_id} mono />
|
<Field label="Batch ID" value={device.batch_id || device.mfg_batch_id} mono />
|
||||||
<Field label="Hardware Family" value={boardLabel} />
|
<Field label="Hardware Family" value={boardLabel} />
|
||||||
<Field label="HW Version" value={formatHwVersion(device.hw_version)} mono />
|
<Field label="HW Version" value={formatHwVersion(device.hw_revision)} mono />
|
||||||
<Field label="Created At" value={formatDate(device.created_at)} />
|
<Field label="Created At" value={formatDate(device.created_at)} />
|
||||||
<Field label="Device Name" value={device.name || device.device_name} />
|
<Field label="Device Name" value={device.name || device.device_name} />
|
||||||
<div style={{ gridColumn: '1 / -1' }}>
|
<div style={{ gridColumn: '1 / -1' }}>
|
||||||
|
|||||||
@@ -344,7 +344,7 @@ function BespokePickerModal({ open, onConfirm, onClose }) {
|
|||||||
Hardware Family for NVS
|
Hardware Family for NVS
|
||||||
</label>
|
</label>
|
||||||
<p style={{ fontSize: 'var(--font-size-xs)', color: 'var(--color-text-muted)', marginBottom: 'var(--space-2)' }}>
|
<p style={{ fontSize: 'var(--font-size-xs)', color: 'var(--color-text-muted)', marginBottom: 'var(--space-2)' }}>
|
||||||
Written to NVS as <span style={{ fontFamily: 'var(--font-family-mono)' }}>hw_type</span>.
|
Written to NVS as <span style={{ fontFamily: 'var(--font-family-mono)' }}>hw_family</span>.
|
||||||
</p>
|
</p>
|
||||||
<input
|
<input
|
||||||
type="text"
|
type="text"
|
||||||
@@ -508,7 +508,7 @@ function StepSelectDevice({ mode, preloadSn, onSelected, onCreatedSn }) {
|
|||||||
|
|
||||||
// ── Selected confirmation panel ──
|
// ── Selected confirmation panel ──
|
||||||
if (picked) {
|
if (picked) {
|
||||||
const boardInfo = BOARD_TYPE_MAP[picked.hw_type]
|
const boardInfo = BOARD_TYPE_MAP[picked.hw_family]
|
||||||
const pal = BOARD_FAMILY_COLORS[boardInfo?.family || 'vesper']
|
const pal = BOARD_FAMILY_COLORS[boardInfo?.family || 'vesper']
|
||||||
return (
|
return (
|
||||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-4)' }}>
|
<div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-4)' }}>
|
||||||
@@ -516,8 +516,8 @@ function StepSelectDevice({ mode, preloadSn, onSelected, onCreatedSn }) {
|
|||||||
<p style={{ fontSize: 'var(--font-size-xs)', fontWeight: 'var(--font-weight-semibold)', color: pal.selectedText, textTransform: 'uppercase', letterSpacing: 'var(--tracking-wide)', marginBottom: 'var(--space-3)' }}>Device Selected</p>
|
<p style={{ fontSize: 'var(--font-size-xs)', fontWeight: 'var(--font-weight-semibold)', color: pal.selectedText, textTransform: 'uppercase', letterSpacing: 'var(--tracking-wide)', marginBottom: 'var(--space-3)' }}>Device Selected</p>
|
||||||
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 'var(--space-3)' }}>
|
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 'var(--space-3)' }}>
|
||||||
<InfoCell label="Serial Number" value={picked.serial_number} mono />
|
<InfoCell label="Serial Number" value={picked.serial_number} mono />
|
||||||
<InfoCell label="Board Type" value={BOARD_TYPE_LABELS[picked.hw_type] || picked.hw_type} />
|
<InfoCell label="Board Type" value={BOARD_TYPE_LABELS[picked.hw_family] || picked.hw_family} />
|
||||||
<InfoCell label="HW Revision" value={formatHwVersion(picked.hw_version)} />
|
<InfoCell label="HW Revision" value={formatHwVersion(picked.hw_revision)} />
|
||||||
<InfoCell label="Status" value={<StatusBadge variant={STATUS_VARIANT[picked.mfg_status] || 'neutral'}>{picked.mfg_status}</StatusBadge>} />
|
<InfoCell label="Status" value={<StatusBadge variant={STATUS_VARIANT[picked.mfg_status] || 'neutral'}>{picked.mfg_status}</StatusBadge>} />
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -660,8 +660,8 @@ function StepSelectDevice({ mode, preloadSn, onSelected, onCreatedSn }) {
|
|||||||
onMouseLeave={(e) => { e.currentTarget.style.backgroundColor = '' }}
|
onMouseLeave={(e) => { e.currentTarget.style.backgroundColor = '' }}
|
||||||
>
|
>
|
||||||
<td style={{ padding: 'var(--space-3)', fontFamily: 'var(--font-family-mono)', fontSize: 'var(--font-size-sm)', color: 'var(--color-text-primary)' }}>{d.serial_number}</td>
|
<td style={{ padding: 'var(--space-3)', fontFamily: 'var(--font-family-mono)', fontSize: 'var(--font-size-sm)', color: 'var(--color-text-primary)' }}>{d.serial_number}</td>
|
||||||
<td style={{ padding: 'var(--space-3)', fontSize: 'var(--font-size-sm)', color: 'var(--color-text-secondary)' }}>{BOARD_TYPE_LABELS[d.hw_type] || d.hw_type}</td>
|
<td style={{ padding: 'var(--space-3)', fontSize: 'var(--font-size-sm)', color: 'var(--color-text-secondary)' }}>{BOARD_TYPE_LABELS[d.hw_family] || d.hw_family}</td>
|
||||||
<td style={{ padding: 'var(--space-3)', fontFamily: 'var(--font-family-mono)', fontSize: 'var(--font-size-sm)', color: 'var(--color-text-muted)' }}>{formatHwVersion(d.hw_version)}</td>
|
<td style={{ padding: 'var(--space-3)', fontFamily: 'var(--font-family-mono)', fontSize: 'var(--font-size-sm)', color: 'var(--color-text-muted)' }}>{formatHwVersion(d.hw_revision)}</td>
|
||||||
<td style={{ padding: 'var(--space-3)' }}>
|
<td style={{ padding: 'var(--space-3)' }}>
|
||||||
<StatusBadge variant={STATUS_VARIANT[d.mfg_status] || 'neutral'}>{d.mfg_status}</StatusBadge>
|
<StatusBadge variant={STATUS_VARIANT[d.mfg_status] || 'neutral'}>{d.mfg_status}</StatusBadge>
|
||||||
</td>
|
</td>
|
||||||
@@ -888,7 +888,7 @@ function StepFlash({ device, bespokeOverride, onFlashed, serialConn }) {
|
|||||||
|
|
||||||
const webSerialAvailable = typeof navigator !== 'undefined' && 'serial' in navigator
|
const webSerialAvailable = typeof navigator !== 'undefined' && 'serial' in navigator
|
||||||
const busy = connecting || flashing
|
const busy = connecting || flashing
|
||||||
const boardInfo = BOARD_TYPE_MAP[device.hw_type]
|
const boardInfo = BOARD_TYPE_MAP[device.hw_family]
|
||||||
|
|
||||||
const familyPal = BOARD_FAMILY_COLORS[boardInfo?.family || 'vesper']
|
const familyPal = BOARD_FAMILY_COLORS[boardInfo?.family || 'vesper']
|
||||||
const readyToFlash = portConnected && !flashing && !done && log.length === 0
|
const readyToFlash = portConnected && !flashing && !done && log.length === 0
|
||||||
@@ -934,7 +934,7 @@ function StepFlash({ device, bespokeOverride, onFlashed, serialConn }) {
|
|||||||
{bespokeOverride ? (
|
{bespokeOverride ? (
|
||||||
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 'var(--space-3)' }}>
|
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 'var(--space-3)' }}>
|
||||||
<InfoCell label="Serial Number" value={device.serial_number} mono />
|
<InfoCell label="Serial Number" value={device.serial_number} mono />
|
||||||
<InfoCell label="NVS hw_type" value={bespokeOverride.hwFamily} />
|
<InfoCell label="NVS hw_family" value={bespokeOverride.hwFamily} />
|
||||||
<InfoCell label="NVS hw_revision" value="1.0" />
|
<InfoCell label="NVS hw_revision" value="1.0" />
|
||||||
<div>
|
<div>
|
||||||
<p style={{ fontSize: 'var(--font-size-xs)', color: 'var(--color-text-muted)', textTransform: 'uppercase', letterSpacing: 'var(--tracking-wide)', fontWeight: 'var(--font-weight-semibold)', marginBottom: 'var(--space-1)' }}>Firmware</p>
|
<p style={{ fontSize: 'var(--font-size-xs)', color: 'var(--color-text-muted)', textTransform: 'uppercase', letterSpacing: 'var(--tracking-wide)', fontWeight: 'var(--font-weight-semibold)', marginBottom: 'var(--space-1)' }}>Firmware</p>
|
||||||
@@ -956,7 +956,7 @@ function StepFlash({ device, bespokeOverride, onFlashed, serialConn }) {
|
|||||||
Board Type:
|
Board Type:
|
||||||
<span style={{ display: 'inline-block', width: 'var(--space-3)' }} />
|
<span style={{ display: 'inline-block', width: 'var(--space-3)' }} />
|
||||||
<span style={{ fontFamily: 'var(--font-family-mono)', fontSize: 'var(--font-size-md)', fontWeight: 'var(--font-weight-semibold)', color: 'var(--color-primary)' }}>
|
<span style={{ fontFamily: 'var(--font-family-mono)', fontSize: 'var(--font-size-md)', fontWeight: 'var(--font-weight-semibold)', color: 'var(--color-primary)' }}>
|
||||||
{boardInfo?.uiName || boardInfo?.name || device.hw_type}
|
{boardInfo?.uiName || boardInfo?.name || device.hw_family}
|
||||||
</span>
|
</span>
|
||||||
{boardInfo?.codename && (
|
{boardInfo?.codename && (
|
||||||
<span style={{ fontFamily: 'var(--font-family-mono)', color: 'var(--color-text-muted)', fontSize: 'var(--font-size-xs)', marginLeft: 'var(--space-2)' }}>| {boardInfo.codename}</span>
|
<span style={{ fontFamily: 'var(--font-family-mono)', color: 'var(--color-text-muted)', fontSize: 'var(--font-size-xs)', marginLeft: 'var(--space-2)' }}>| {boardInfo.codename}</span>
|
||||||
@@ -967,7 +967,7 @@ function StepFlash({ device, bespokeOverride, onFlashed, serialConn }) {
|
|||||||
Revision:
|
Revision:
|
||||||
<span style={{ display: 'inline-block', width: 'var(--space-3)' }} />
|
<span style={{ display: 'inline-block', width: 'var(--space-3)' }} />
|
||||||
<span style={{ fontFamily: 'var(--font-family-mono)', fontSize: 'var(--font-size-md)', fontWeight: 'var(--font-weight-semibold)', color: 'var(--color-primary)' }}>
|
<span style={{ fontFamily: 'var(--font-family-mono)', fontSize: 'var(--font-size-md)', fontWeight: 'var(--font-weight-semibold)', color: 'var(--color-primary)' }}>
|
||||||
{formatHwVersion(device.hw_version)}
|
{formatHwVersion(device.hw_revision)}
|
||||||
</span>
|
</span>
|
||||||
</p>
|
</p>
|
||||||
</>
|
</>
|
||||||
@@ -1453,11 +1453,11 @@ function StepDone({ device, onProvisionNext, serialConn }) {
|
|||||||
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr' }}>
|
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr' }}>
|
||||||
<div style={{ padding: 'var(--space-4)', borderRight: '1px solid var(--color-border)' }}>
|
<div style={{ padding: 'var(--space-4)', borderRight: '1px solid var(--color-border)' }}>
|
||||||
<p style={{ fontSize: 'var(--font-size-xs)', color: 'var(--color-text-muted)', textTransform: 'uppercase', letterSpacing: 'var(--tracking-wide)', marginBottom: 'var(--space-1)' }}>Board Type</p>
|
<p style={{ fontSize: 'var(--font-size-xs)', color: 'var(--color-text-muted)', textTransform: 'uppercase', letterSpacing: 'var(--tracking-wide)', marginBottom: 'var(--space-1)' }}>Board Type</p>
|
||||||
<p style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-text-primary)' }}>{BOARD_TYPE_LABELS[device?.hw_type] || device?.hw_type}</p>
|
<p style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-text-primary)' }}>{BOARD_TYPE_LABELS[device?.hw_family] || device?.hw_family}</p>
|
||||||
</div>
|
</div>
|
||||||
<div style={{ padding: 'var(--space-4)', display: 'flex', flexDirection: 'column', alignItems: 'flex-end' }}>
|
<div style={{ padding: 'var(--space-4)', display: 'flex', flexDirection: 'column', alignItems: 'flex-end' }}>
|
||||||
<p style={{ fontSize: 'var(--font-size-xs)', color: 'var(--color-text-muted)', textTransform: 'uppercase', letterSpacing: 'var(--tracking-wide)', marginBottom: 'var(--space-1)' }}>HW Version</p>
|
<p style={{ fontSize: 'var(--font-size-xs)', color: 'var(--color-text-muted)', textTransform: 'uppercase', letterSpacing: 'var(--tracking-wide)', marginBottom: 'var(--space-1)' }}>HW Version</p>
|
||||||
<p style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-text-primary)' }}>{formatHwVersion(device?.hw_version)}</p>
|
<p style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-text-primary)' }}>{formatHwVersion(device?.hw_revision)}</p>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
Reference in New Issue
Block a user