Compare commits

...
Author SHA1 Message Date
bonaminandClaude Opus 5.5 db22abdb7d feat(devices): compare console vs device config, let the user pick a side
Bells, Clock and General (log levels) tabs read the device's stored config
on open (read-only) and compare it with what Firestore holds. On mismatch a
banner offers "Compare & resolve": a side-by-side "Saved in Console" vs
"Stored on Device" modal with differing settings highlighted.

- Keep Console version: push saved settings to the device, then re-read
- Keep Device version: write only the differing fields to Firestore
- Nothing is written until the user picks one
- Re-reads the device whenever the saved settings change

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 14:11:18 +02:00
bonaminandClaude Opus 5.5 eff9e72681 fix(devices): stop tabs writing to Firestore on their own
Bells, Clock and General tabs ran a silent "reconcile" on mount that read
the device config and wrote any drift straight to Firestore, with no user
action. Combined with oldest-first ack matching (backend health-check pongs
and other tabs' replies resolved bells.get_config), this wrote 16-item
bellOutputs on load and emptied them on tab switch.

- Remove the auto-write reconciles from Bells/Clock/General tabs
- useDeviceCommand: match acks to commands by payload.type (ping->pong,
  playback.* -> playback), ignore health-check pongs, drop late replies,
  register pending entries before the POST
- update_device: write nested maps as dotted field paths so only the sent
  leaves are touched, never the whole parent map
- Clock modals: stop re-sending the whole clockSettings copy

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 13:15:05 +02:00
bonaminandClaude Opus 5.5 565aca4d56 feat(firmware): pre-fill Min FW on upload from the previous release
A new release almost always keeps the previous release's upgrade-chain
floor, so the upload form now defaults Min FW to the newest existing
release for the same board (same channel preferred, any channel as
fallback; bespoke matched by UID). Empty when no previous release set one.
It re-derives when board/channel change until the user edits the field,
and a hint shows which release the value came from. Edit mode unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 21:34:38 +02:00
bonaminandClaude Opus 5.5 3636556ae7 feat(devices): clear log view and delete logs from the Health tab
Health → Logs gets two actions above the log explorer:

- Clear view (view-only): hides everything received before now so only
  fresh entries show. Text channels use it as the server-side `since`
  bound; alerts/heartbeats/commands filter client-side. "Show all" undoes
  it; nothing is deleted.
- Delete logs… (devices:edit): DeleteDeviceLogsModal permanently deletes
  selected history by type — Device Logs and Info (optionally only some
  levels) via DELETE /mqtt/logs/{serial}, and alert history / heartbeats /
  commands via the existing reset-stats endpoint. Press-and-hold confirm,
  like Reset Stats. Device SD-card logs are untouched.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 21:34:38 +02:00
bonaminandClaude Opus 5.5 fb35ace0c7 feat(devices): paint list/detail from last-known data, revalidate silently
The device list and detail page showed empty status columns/fields until
every request finished. They now render instantly from the last-known data
and refresh in the background, with a small "Syncing…" spinner in the page
header while fresh data is in flight.

- lib/deviceCache.js: last-known device list (per query), devices by id,
  fleet status map, list metrics and Health-overview datasets. In memory
  plus sessionStorage (except the large Health datasets); every storage
  access is guarded.
- DeviceList: seeded from cache; status + metrics fetched in parallel with
  the device list instead of after it; out-of-order search responses are
  ignored; live heartbeats are written back to the cache.
- DeviceDetail: seeded from cache (DeviceList already holds the device),
  reloads after modal saves refresh in place instead of unmounting the
  tab, status comes from the new /mqtt/status/{serial}.
- HealthTab overview: same stale-while-revalidate per device + range.

Health tab firmware lag: the Firmware/OTA tile read the version from the
latest diagnostics report, which the firmware sends only every 5 minutes
(the first 5 minutes after boot), and the tab never re-fetched it while
open — so after an OTA it kept showing the old version. Firmware reports the
same compiled FW_VERSION in heartbeat and diagnostics, so the tile now uses
the heartbeat (30s, pushed live over WebSocket) and only shows the OTA
"update available" badge when the diagnostics report describes the
firmware that is running now. HealthTab also passes deviceId/canEdit down
to LogsTab for the log management actions in the next commit.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 21:34:38 +02:00
bonaminandClaude Opus 5.5 da83f2a1cd perf(mqtt): serve device status from an in-memory latest-row cache
Device list and device detail took several seconds to show online status
because every /mqtt/status call ran SELECT DISTINCT ON (device_serial) over
the whole heartbeats + alert-event history (one heartbeat row per device
every 30s, kept for the full retention window). /mqtt/latest-metrics and
the 60s ping loop paid the same fleet-wide scans for ping samples and
diagnostics.

- database/latest_cache.py: newest heartbeat / alert event / ping sample /
  diagnostics row per device, held in memory. Seeded once at startup
  (warm_latest_cache) or lazily on first read; every insert writes through
  via RETURNING, keeping whichever row is newer so writes that land while
  the seed query runs are never lost. Per-device deletes and the retention
  purge drop the matching entries so the cache never outlives the DB.
  Single uvicorn process owns the MQTT client, so no cross-worker drift.
- GET /api/mqtt/status/{serial}: one device's status (cache, or a single
  indexed lookup) so DeviceDetail no longer downloads the whole fleet.
- devices router: 11 GET/notes/tags handlers were `async def` but call the
  synchronous Firestore client, blocking the event loop (MQTT ingest,
  WebSocket, every other request) for each Firestore round trip. They are
  plain `def` now so FastAPI runs them in its threadpool.
- DELETE /api/mqtt/logs/{serial}?source=&level=&until=: filtered delete of
  console-stored device logs, for the Health tab's new "Delete logs".
  Requires devices:edit and is audit-logged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 21:34:38 +02:00
bonaminandClaude Opus 5.5 9deff308b6 docs(claude): note hw_family / hw_revision naming (schema decision D2)
Device docs now store hardware identity under the firmware's NVS names.
Future sessions need to know that, and that the firmware catalog keeps
hw_type as a variable name on purpose.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 21:03:43 +02:00
bonaminandClaude Opus 5.5 2e3d7ba062 refactor(devices): store hardware identity as hw_family / hw_revision
The firmware moved its NVS identity keys from hw_type / hw_version to
hw_family / hw_revision (NvsMigration.cpp), and the NVS generator, cloudflash
and the device models already used the new names. Firestore device docs and
the manufacturing code still wrote and read hw_type / hw_version, so the
device API's hw_family / hw_revision were always "" (0 of 14 docs had them)
and the console used two names for one value.

Device docs now use the firmware's names (schema v1.1.0, decision D2 in the
bellsystems-schema repo). The apps don't read these fields, so no app change.

- Manufacturing batch-create writes hw_family / hw_revision; the inventory
  API exposes hw_family / hw_revision (filters: ?hw_family= / ?hw_families=).
  Reads fall back to hw_type / hw_version so docs not yet migrated still work.
- devices/firestore_v1.py renames hw_type / hw_version on read and write and
  rejects a hw_family that isn't a code (e.g. "Bell Plus"): when the console
  generates NVS from it, the firmware builds its OTA URL from that value.
- Inventory, provisioning, onboarding and overview pages use the new names.

Unchanged on purpose: the firmware catalog and flash assets
(/api/firmware/{hw_type}/..., hw_type_override) — a separate store and the
URL devices call; same values, only the variable name differs. The public
cloudflash response keeps its hw_type field (public contract).

Data migration (rename + fix 3 display-label values) runs from the
bellsystems-schema repo AFTER this is deployed: the currently deployed
console still reads hw_type.

Verified: 118 backend tests pass; frontend builds; ESLint errors in
ProvisioningWizard.jsx (7) are pre-existing and unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 21:02:20 +02:00
bonaminandClaude Opus 5.5 5ab87fa9f0 docs(readme): point to the shared Firestore schema v1 contract
The tablet and phone apps read the same Firestore device documents as the
console; a wrongly typed field makes them silently hide the device. CLAUDE.md
already documents this for Claude sessions; the README now states the rule
for humans too: device writes go through devices/firestore_v1.py, and shared
fields change in the bellsystems-schema repo first.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 20:49:28 +02:00
bonaminandClaude Opus 5.5 62be80c9d8 fix(devices): write devices in Firestore schema v1 so the apps can read them
The FlutterFlow tablet and phone apps parse each device doc inside safeGet:
one wrongly typed field makes them silently drop the whole device from the
user's list. The console was the source of every such field found in
production on 2026-11-08:

- New devices: DeviceCreate defaulted times to "" and IPs to [], and
  create_device wrote them as-is. Every console-created device was invisible
  in the apps from birth. It also set device_id but not serial_number.
- Round trip: reads formatted Timestamps as "15 January 2026 at 22:01:00
  UTC+0000", the frontend echoed that back on save, and _restore_timestamps
  could not parse it (nor ""), so it stored the string. towerClockTime was
  not in its list at all.
- Key spelling: the console wrote bellGuardSafetyOn / useStaticIP; the apps
  read bellguardSafetyOn / usesStaticIP, so console edits never reached them
  and docs ended up with both spellings disagreeing.
- MelodyMainItem used the melodies-collection shape (information, url, ...)
  instead of the device shape the apps read (mainInformation, binaryUrl, ...);
  Pydantic dropped every real key on read.
- Manufacturing batches created devices with serial_number but no device_id,
  which both apps use to connect over MQTT (7 of 14 devices affected).

The contract now lives in the bellsystems-schema repo (v1 = what the shipped
apps read). backend/devices/firestore_v1.py enforces it on every device
write (to_firestore) and read (to_api):
- Timestamps: ISO 8601 in the API, Firestore Timestamps in the DB, null for
  unset. The old display format is still accepted on write so an open
  browser tab can't corrupt data; anything unparseable is a 422.
- IPs: dotted strings; octet arrays are joined; invalid values are a 422.
- Legacy keys are renamed (v1 key wins over a duplicate); users_list dropped.
- device_id mirrors serial_number (decision D1); conflicting values are a 422.
- user_list / melodyReference entries become DocumentReferences.
- update_device re-normalizes the merged nested maps, so saving a device
  also repairs pre-v1 junk already stored in it.

Models and the frontend now use v1 names and send null (not "") for unset
times. The firmware's network.set_config MQTT payload keeps its own names.

Verified: 114 backend tests pass (new tests/test_firestore_v1.py covers the
production failure shapes; test_timezones.py not run locally, needs tzdata).
A read-only dry run of a console save against all 14 production devices
produced v1-valid docs with no fields lost. Frontend builds. Not deployed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 20:00:33 +02:00
bonaminandClaude Opus 5.5 2a6f9697b8 fix(devices): read device users from user_list, mirror writes to device_users
The Manage tab and Onboarding page list users via GET /devices/{id}/users,
which read the device_users sub-collection first and only fell back to
user_list when it was empty. Every write (add/remove on those pages, the
Users page, PUT with user_list) went to user_list only, so on any device
that had a device_users doc the list showed stale data: users added in the
Console never appeared and removed users never went away. A production
survey found 6 device_users docs (all role "admin") on 6 devices; 2 of them
disagree with user_list.

user_list is now the single source of truth:
- get_device_users reads only user_list; role comes from the mirror if any.
- Every user_list write also adds/removes the device_users mirror doc
  ({role: "admin", user_reference}) in the same atomic batch, in case the
  phone app still reads the sub-collection. It is meant to go away later.
- users.service.assign_device and PUT /devices/{id} now store
  DocumentReferences (the app's format) instead of "users/{id}" strings.

scripts/sync_device_users_mirror.py (dry run by default) reports and fixes
pre-existing drift between the two. Not run yet.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-07 10:37:21 +02:00
bonaminandClaude Opus 5.5 fba5110cc0 docs(api-reference): system.get_config time block uses the firmware 3.x shape
The example still showed gmtOffsetSec/daylightOffsetSec, removed in firmware
3.0.0; it now shows the ntp and tz objects.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 21:10:20 +02:00
bonaminandClaude Opus 5.5 cdf5fc79a0 feat(clock): timezone, NTP, set-time and clocktower sync in the device Clock tab
Console side of the firmware 3.x TimeKeeper overhaul (project-vesper
F-079/F-081/F-083). The Clock tab's "Network & Time" card was read-only and
showed fields the firmware no longer reports, and both analog clocks drew
the browser's own time.

- Time & Timezone card: device local time, zone, mode, UTC offset, DST state
  (incl. expired manual dates), next change, RTC synced. Read live from the
  device (system.get_time, clock.get_timezone) - the device is the source of
  truth for time settings; nothing about them is mirrored to Firestore.
- EditTimezoneModal: Automatic (country -> zone from the backend timezone
  table, or a custom yearly rule built into a POSIX string), Manual DST (std
  offset, amount, this season's start/end), Fixed, Local only.
- SetDeviceTimeModal: this computer's UTC time, or a typed local time.
- NTP Sync card + NtpSettingsModal: automatic on/off, nightly time, servers,
  last result/drift; Sync Now queues clock.sync_ntp and polls clock.get_ntp.
- SyncClockModal (was a placeholder): pause, enter what the face shows,
  clock.set_face + resume.
- EditClockSettingsModal: face sync policy force/smart + max wait; mirrored
  as clockSettings.faceSyncMode / smartMaxWaitMin (added to the backend model,
  which silently dropped unknown keys - the old gmtOffsetSec/ntpServer mirror
  never persisted, so those dead drift checks are removed).
- Device Time / Clocktower clocks now show the device's wall clock and the
  real face position (refreshed every 30 s while the clock runs).

Live reads are chained after the existing clock.get_config drift check and
face polling pauses while a modal or Sync Now is sending, because device
replies are matched FIFO without a request id.

Stage 5 of project-vesper docs/features/timekeeper-overhaul.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 21:10:02 +02:00
bonaminandClaude Opus 5.5 e4ea43a079 feat(timezones): public IANA timezone table with POSIX rules for device clocks
Firmware 3.0.0+ (project-vesper F-079) keeps the RTC in UTC and, in
timezone mode "auto", evaluates a POSIX TZ rule string sent by whoever sets
the timezone. Devices don't carry the IANA database and POSIX signs are
inverted, so the console and apps need one place to get the right rule.

GET /api/public/timezones[?country=GR] returns every country with its zones
(zone.tab), each with the POSIX rule (TZif footer), std/DST offsets in
minutes east of UTC, and the current offset/DST state.
GET /api/public/timezones/zone?name=... resolves one zone, including
aliases zone.tab doesn't list (e.g. a phone reporting Asia/Calcutta).

Public on purpose: IANA data, needed by the phone app (Firebase auth, MQTT)
and for the tablet app's offline bundle (save the full response, ~130 KB).
Source is the tzdata pip package, now pinned (2026.6 = IANA 2026f); bumping
the pin is how new DST rules arrive. Docs in docs/device-timezones.md;
tests in tests/test_timezones.py.

Stage 4 of project-vesper docs/features/timekeeper-overhaul.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 21:01:04 +02:00
bonaminandClaude Opus 5.5 8837eb1e70 docs(api-reference): firmware 3.2.0 smart face sync fields on clock.set_config/get_config
Mirrors project-vesper F-083: face_sync_mode (force | smart) and
smart_max_wait_min (1-359, default 61).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 20:43:07 +02:00
bonaminandClaude Opus 5.5 d1799bd3b1 docs(api-reference): firmware 3.1.0 NTP API (async clock.sync_ntp, clock.set_ntp, clock.get_ntp)
Mirrors project-vesper F-081: clock.sync_ntp queues a session and returns
{ started: true }, the outcome is read from clock.get_ntp last_sync;
clock.set_ntp sets auto / sync_time / servers; clock.get_config reports
"ntp" instead of "ntp_server".

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 20:20:41 +02:00
bonaminandClaude Opus 5.5 ca53d2e871 docs(api-reference): firmware 3.0.0 timezone API (clock.set_time/set_timezone/get_timezone, system.get_time)
Mirrors project-vesper F-079: the RTC holds UTC and the timezone is one
object with modes auto (POSIX rule) / manual (DST dates) / fixed / local.
clock.set_time takes timestamp (UTC) or local plus an optional timezone,
clock.get_config reports "timezone" instead of gmt_offset_sec/dst_offset_sec,
system.get_time gains local/offset_min/dst_active/tz_mode/tz_name/rtc_synced.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 19:15:46 +02:00
bonaminandClaude Opus 5.5 65ff2372ca docs(api-reference): no gap between melody loops (firmware F-078, 2.5.1)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 11:10:06 +02:00
bonaminandClaude Opus 5.5 c2767ca7e0 docs(api-reference): segmented mode "infinite" and exact per-mode timing (firmware F-077)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 10:44:04 +02:00
bonaminandClaude Opus 5.5 bbd356d846 docs(ApiReference): add mqtt.status; playback/reports QoS 1 (confirmed), other outbound topics QoS 0
Mirrors firmware F-071..F-073 (project-vesper, v2.4.0):
- New mqtt.status command (MQTT connection health: connect/disconnect
  counters, last disconnect reason, forced self-recovery resets and reason,
  resent_messages).
- status/playback and control/reports are QoS 1 with PUBACK tracking
  (playback republished on reconnect, reports resent); control/ack, alerts
  and info are QoS 0. Heartbeat unchanged (QoS 1).

Verified the page parses with esbuild.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 22:53:43 +03:00
bonaminandClaude Opus 5.5 18705aaefb fix(docker): keep server Postgres on ./data/postgres, move Windows volume to an override
751cac7 switched the base compose file to an external named volume
(bellsystems-postgres-data) to dodge a WSL2/Docker Desktop bind-mount bug.
That volume only exists on the Windows dev machine: on the VPS, where the
push auto-deploys via deploy-host.sh, `docker compose up` would fail on the
missing external volume (or, if created, start Postgres on an empty
database while the real data sat unused in ./data/postgres).

The base file goes back to the ./data/postgres bind mount the server has
always used (Linux has no such bug). The named volume now lives in
docker-compose.override.yml, which Compose loads automatically, is
gitignored, and is created from docker-compose.override.example.yml on
Windows machines only.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 16:45:58 +03:00
bonaminandClaude Opus 5.5 f1a7c5a7ca feat(devices): crash detail view and fleet Crash Report (F-070)
- CrashDetail (components/shared): headline is abort_msg when present,
  else the Xtensa exception name. For aborts, pc/exception/fault address are
  shown muted with a note that they describe abort() and that the first
  2-4 frames are abort internals. Shows task, uptime at crash, heap stats with
  a "likely heap exhaustion / fragmentation" badge (largest_block < 12000 or
  free_heap < 25000, F-055), PC + backtrace as 0x%08X in ESP serial format,
  a copyable addr2line command (PC, backtrace, then the PC parsed from
  "abort() was called at PC ..."), elf_sha256, and a backtrace-corrupted
  flag. When the server has the build's ELF and addr2line, a Decode button
  shows function + file:line per frame.
- Health tab boot history uses it, previews the headline in the row, and
  gets a "Sync from device" button (telemetry.get_boot_history, merged
  server-side).
- New /devices/crashes page (linked from the Fleet header): crashes grouped
  across devices with per-device counts and the latest occurrence.
- Firmware release modal: optional firmware.elf attachment.
- API reference: boot_report payload documents the F-070 fields.
- lib/crashReport.js holds the parsing/formatting rules; lib/clipboard.js
  a copy helper with a non-secure-context fallback.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 16:28:41 +03:00
bonaminandClaude Opus 5.5 82cf95a9af feat(firmware): ELF symbol store for server-side crash decoding
Crash reports carry elf_sha256 (first 16 hex chars of the crashing build's
ELF SHA-256). ELFs are now stored under that key in
{firmware_storage_path}/elf/, uploaded either with a firmware release
(optional elf_file on POST /upload and PUT /{id}) or standalone via
POST /api/firmware/elf. The ELF is validated before the release is created.

GET /api/firmware/elf/{sha} reports whether that build's ELF exists and
whether the decoder is available; POST /api/firmware/elf/{sha}/decode runs
xtensa-esp32-elf-addr2line -pfiaC over the addresses. The decoder is looked
up via settings.addr2line_path or PATH. It is NOT in the Docker image yet,
so decoding reports "not installed" until the toolchain is added; the
console falls back to a copy-paste addr2line command.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 16:28:41 +03:00
bonaminandClaude Opus 5.5 963516ece0 feat(mqtt): store F-070 crash detail and group crashes fleet-wide
Firmware F-070 adds a fuller `crash` object (backtrace, backtrace_corrupted,
elf_sha256) and a new `pre_crash` snapshot (uptime, heap stats, optional
abort_msg) to boot_report and to telemetry.get_boot_history entries.

- Migration c9d0e1f2a3b4: device_boot_events gains crash / pre_crash JSONB,
  stored verbatim so later additive fields need no migration. The legacy
  crash_* columns are still filled; old rows and old firmware are unchanged.
  JSON is bound as CAST(CAST(:x AS TEXT) AS JSONB): a bare JSONB cast makes
  asyncpg JSON-encode the already-encoded string a second time.
- boot_report ingestion passes both objects through.
- telemetry.get_boot_history replies (control/ack) are merged into boot
  history whoever sent the command: an entry matches an existing row on
  boot_count + reset_reason + time within 30 min (boot_count alone is not
  unique - the counter gets reset), and only fills crash/pre_crash the row
  lacks; unmatched entries are boots we never saw live and are inserted at
  the device's timestamp; entries without ts are skipped.
- GET /api/mqtt/crash-groups: fault boots grouped by abort_msg with hex
  addresses stripped, else task + exception cause, else reset reason. When
  abort_msg is present, pc/exc_cause describe abort() itself and are
  ignored for grouping.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 16:28:40 +03:00
bonaminandClaude Opus 5.5 46c5c0a846 fix(mqtt): treat broker-replayed retained messages as stale state
The firmware publishes status/heartbeat, system/alerts, system/info and
status/playback with retain=true. On every backend (re)connect - every
restart and every uvicorn --reload - the broker replays the last message on
each of those topics for every device that ever connected. We handled those
replays as if they had just happened:

- heartbeats: a row with received_at=now() for every device, so devices
  that have been dead for months showed ONLINE for 90s after each restart
  and got pinged. ~770k such rows exist locally.
- boot_report: the last boot logged again as a new reboot (the phantom
  PANIC entries on the Health tab).
- alerts / other info events: logged again as new occurrences.

MQTT delivers retain=1 only for replays caused by a new subscription; live
publishes always arrive with retain=0. The flag is now passed through to the
handlers and the WS broadcast:

- heartbeat: replays are not stored. A live heartbeat is.
- {"state":"offline"} heartbeat (LWT / graceful disconnect) is no longer
  stored as a sign of life. It marks the device offline immediately in
  a small in-memory set (mqtt/presence.py) used by /mqtt/status and the ping
  loop; a later live heartbeat clears it. Replayed offline markers also mark
  offline, since a retained message is the device's last word.
- boot_report: live -> always a new boot. Replay -> stored only if it
  differs from the device's latest boot row (i.e. we missed it while down).
- alerts: replay still syncs the current-alert row; history gets a row on a
  live alert (even an identical repeat - faults recur) or on a replay that
  changes state. Replaces the 98dd16b rule that dropped identical live alerts.
- other info events: replays are not logged.
- Frontend (DeviceList, DeviceDetail, LogsTab) ignores retained WS messages
  for live updates, and flips a device offline on the offline marker instead
  of marking it online.

Verified locally after a backend restart: only the 7 actually-live devices
got new heartbeat rows (none from the replays), and no boot/alert/info rows
were created.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 16:01:41 +03:00
bonaminandClaude Opus 5.5 18e57c6e5f fix(mqtt): dedupe boot_report against the latest row, not any boot_count
98dd16b skipped a boot_report if ANY earlier row had the same boot_count.
That is wrong: the firmware's lifetime boot counter gets reset (reflash /
telemetry reset), and the data shows counts 1-4 recurring in July and again
in September. With that rule a real later boot reusing a number would be
dropped forever.

A retained redelivery is always a copy of the device's most recent boot, so
compare only against the latest row (boot_count + reset_reason). A genuine
new boot always differs from it - the counter moves forward or was reset.

Note: the one-off cleanup run on 2026-09-30 used the same wrong
(serial, boot_count) key and deleted some genuine boot rows along with the
redelivery duplicates; see the session notes / heartbeat-based reboot list.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 15:55:26 +03:00
bonaminandClaude Opus 5.5 98dd16b597 fix(mqtt): stop logging retained boot_report/alerts as new events
The firmware publishes boot_report on system/info and alerts on
system/alerts with retain=true. Every time the backend (re)connects - which
under uvicorn --reload means every backend file save - the broker redelivers
the last retained message and we inserted it again with occurred_at=now().
Result: the Health tab showed fresh PANIC boots and "Device reset due to
fault" alerts for a device that had been up for 4 days.

- insert_boot_event skips the insert when a row with the same
  (device_serial, boot_count) already exists. boot_count is the firmware's
  lifetime counter, so it uniquely identifies a boot.
- upsert_alert only writes when state/message actually changed and returns
  whether it did; the alert-event history row is only added on a change.
  A redelivered identical alert no longer bumps updated_at either.

Existing duplicate rows are not touched by this commit.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 15:48:48 +03:00
bonaminandClaude Opus 5.5 36f9540a89 feat(users): require password confirmation when creating an app user
Both create paths (Users > Add User page and the CreateUserModal used during
device onboarding) now have a Confirm Password field. A mismatch shows an
inline error and blocks the create call, so a typo can't silently become the
user's Firebase Auth password. The confirm value is client-side only and is
never sent to the backend.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 15:40:51 +03:00
bonaminandClaude Opus 5.5 c1df3b5aa3 fix(users): console-created users use the Firebase uid as doc ID
create_user wrote the profile with .add() (random doc ID). On first login the
FlutterFlow app looks for users/{uid}, doesn't find it, and creates a second,
bare doc - so every console-created user ended up duplicated, and devices
assigned in the console pointed at the doc the app never reads.

Now the profile is written to users/{uid} with created_time set, and the email
is lowercased to match what Firebase Auth stores. If the Firestore write
fails, the just-created Auth account is deleted so no orphan is left.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 15:31:34 +03:00
bonaminandClaude Opus 5.5 3f3d2cc63c fix(ui): offline SignalIndicator is plain grey, no amber slash
The amber diagonal slash on offline devices was too loud on the Fleet list.
Offline now renders all arcs unlit in the neutral dim colour. The amber "?"
for online-but-no-rssi (legacy v1 firmware) is unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 15:31:34 +03:00
bonaminandClaude Opus 5.5 e663b0a609 docs(mqtt-auth): record TLS for app users via NPM + WebSockets
TLS for the phone app went live on the VPS on 2026-09-30:
- Mosquitto got a second, non-published listener on 8083 with
  `protocol websockets`; port 1883 stays plain TCP for the boards
  (ESP32s can't spare RAM for TLS).
- The mosquitto service joined the external Docker network npm_npmnet so
  NPM (NPMplus) can reach mosquitto:8083 by name; it stays on `default`
  to reach the Console backend at 172.20.0.1:8000.
- NPM proxy host mqtt.bellsystems.net -> http://mosquitto:8083 terminates
  TLS and renews the Let's Encrypt cert. proxy_read/send_timeout 3600s
  added so NPM doesn't drop idle MQTT connections after 60s. NPMplus has no
  "Websockets Support" toggle (always on).
- Verified end to end: a paho client over wss://mqtt.bellsystems.net:443
  (path /mqtt) authenticated via the Console backend and received a
  heartbeat.

Chosen over native 8883 because NPM already owns 80/443 and certificate
renewal, so there is no extra cert handling on the host, and 443 also gets
through networks that block 8883.

The doc now gives the app's final transport (wss, 443, /mqtt, never 1883,
keepalive < 3600s), the listener/network/NPM layout, the end-to-end test,
rollback steps, and a new known gap: the backend's port 8000 is published
on 0.0.0.0, so the /mqtt/auth/* endpoints are reachable from the internet.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 01:15:34 +03:00
bonaminandClaude Opus 5.5 61e9bfab7c docs(mqtt-auth): note old-firmware boards subscribe to vesper/{sn}/control
Broker logs after the 2026-09-30 restart show some boards (PV26B02BP01R01,
BSVSPR-26C20B-STD10R-2KCDPH) subscribing to vesper/{serial}/control rather
than control/command. The app ACL only allows publishing to control/command,
so the app can't command those boards until their firmware is updated.
Recorded so nobody widens the ACL by accident.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 01:00:43 +03:00
bonaminandClaude Opus 5.5 43102c617d docs(mqtt-auth): note VPS broker has allow_anonymous false but no TLS listener yet
The full mosquitto.conf (2026-09-30) has a single plain listener on 1883,
used by the boards. The phone app sends a Firebase ID token as its MQTT
password, so a TLS listener must be added before app users go live.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 00:58:59 +03:00
bonaminandClaude Opus 5.5 ecfe00307a docs(mqtt-auth): record verified VPS broker setup and ACL isolation test
Checked the live broker on 2026-09-30:
- mosquitto.conf sets no files-backend ACL path. A live test (device A
  subscribing to device B's topics) was denied while A's own topics were
  delivered, so the files backend does not grant-all and every ACL check
  reaches the Console. The missing ACL file is therefore harmless.
- Recorded the container/image, config and passwd locations, which lines
  already match the new code, and the one change still pending
  (auth/acl cache 300s -> 60s before app users go live).
- Added the copy-paste isolation test so it can be re-run after any broker
  config change.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 00:57:01 +03:00
bonaminandClaude Opus 5.5 6ea7e9d2c5 docs: MQTT app-user auth reference + CLAUDE.md pointer
docs/mqtt-app-user-auth.md records what future sessions (and whoever builds
the phone app) need and can't get from the code alone:
- app connection contract: username app_<uid>, Firebase ID token as
  password, client id prefix app_<uid>_, TLS only, allowed topics per acc,
- serial field (serial_number, legacy device_id) and the device_serials
  mirror + every code path that must keep it in sync,
- the uid-field lookup rule and ACL cache invalidation,
- legacy "vesper" password flag and its log line,
- rollout checklist: backfill, go-auth VPS config (required/recommended),
  files-ACL check, TLS listener,
- decisions/gaps: FlutterFlow must sync device_serials itself; the
  device_users subcollection is intentionally ignored.

CLAUDE.md gets a short section pointing agents at it before they touch
MQTT auth or anything that edits user_list/status.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 00:45:18 +03:00
bonaminandClaude Opus 5.5 f5db83f26c fix(devices): sync users.device_serials when PUT /api/devices/{id} changes user_list
DeviceUpdate accepts user_list, so a device PUT could add or remove users
without touching their device_serials - leaving the MQTT app ACL stale
(a removed user would keep access; an added user would be denied).

update_device now diffs the old vs new user_list and, in the same atomic
batch as the device write, ArrayUnion/ArrayRemoves the device's serial on
each added/removed user, then invalidates their MQTT ACL cache entries.
Dangling user references are skipped (updating a missing doc would fail
the whole batch). PUTs without user_list take the old single-update path.

Covered by tests/test_device_serials_sync.py (fake Firestore).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 00:44:34 +03:00
bonaminandClaude Opus 5.5 3acd89a2c6 test(mqtt-auth): cover /mqtt/auth/user and /mqtt/auth/acl
First pytest suite in the backend (backend/tests/, run from backend/ with
`python -m pytest tests`). firebase_admin.verify_id_token and Firestore
are mocked, so no network access is needed. 82 cases:

- /user devices: HMAC ok / wrong / other serial's HMAC, kiosk HMAC,
  legacy password with flag on/off, legacy rejected for non-device-shaped
  usernames and for app_ users, HMAC rejected for app_ users, legacy-login
  log rate limiting.
- /user app users: valid token (asserts check_revoked=True), token for a
  different uid, revoked, expired, blocked user, unknown uid, empty uid,
  and that a denied token never appears in logs.
- /acl app users: acc 1/2/4 allow/deny per topic, unsupported acc values,
  wildcards, foreign serial, malformed topics, wrong clientid prefixes
  (incl. uid-prefix collision), blocked/unknown users, cache hit +
  invalidate, cache expiry.
- /acl devices/kiosk/superuser: unchanged behaviour.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 00:04:37 +03:00
bonaminandClaude Opus 5.5 81365eed89 feat(mqtt-auth): put legacy "vesper" password behind MQTT_ALLOW_LEGACY_PASSWORD
The shared legacy password is still needed for boards on pre-HMAC
firmware, but it was accepted for any username. Now:
- controlled by MQTT_ALLOW_LEGACY_PASSWORD (config.py, default true;
  documented in .env.example) so it can be switched off without a deploy,
- only accepted for device-shaped usernames (uppercase alphanumeric
  segments joined by "-", optional "-kiosk"), never for app_ users or
  any other shape,
- every successful legacy login is logged at WARNING with the username,
  rate-limited to once per username per hour, so the boards still
  depending on it are visible before the flag is turned off.

HMAC auth is unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 00:03:23 +03:00
bonaminandClaude Opus 5.5 1253ec155e feat(mqtt-auth): per-device topic ACL for phone-app users
POST /mqtt/auth/acl now handles "app_<uid>" users:
- topic must be exactly vesper/{serial}/<a>/<b> with serial in the user's
  device_serials (resolved by the users doc `uid` field),
- publish (acc 2): only control/command,
- subscribe (acc 4) and read/delivery (acc 1): only control/ack,
  status/heartbeat, status/playback,
- wildcard topics (+ / #) are denied,
- clientid must start with "app_<uid>_" so one user cannot reuse another
  user's client id to kick them off,
- blocked users are denied; anything else (incl. other acc values) is 403.

Lookups go through mqtt/app_users.py's 60s TTL cache so per-message
checks don't hit Firestore every time; assign/unassign/block invalidate it.

Also fixes the acc comment: mosquitto passes 1 = read (delivery),
2 = write (publish), 4 = subscribe - not "1 = subscribe, 3 = both".
Device/kiosk ACL is unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 00:02:48 +03:00
bonaminandClaude Opus 5.5 8a668ca60f feat(mqtt-auth): authenticate phone-app users with Firebase ID tokens
The remote FlutterFlow app connects to Mosquitto as "app_<firebase_uid>"
with a Firebase ID token as the password, so no per-user MQTT accounts
need to exist anywhere.

For app_ usernames, POST /mqtt/auth/user now:
- verifies the token with firebase_admin.auth.verify_id_token
  (check_revoked=True),
- requires the decoded uid to equal the uid in the username,
- requires a users doc with that `uid` field (queried, not by doc id)
  whose status is not "blocked" (same meaning as users.service.block_user).
It returns 200/403 and logs the deny reason - never the token.

app_ usernames never fall through to the HMAC / legacy "vesper" check.
Device and kiosk auth are unchanged. App users are still denied every
topic by the existing ACL until the app ACL lands in the next commit.

Both handlers are now plain `def` so the blocking Firestore / Firebase
calls run in FastAPI's threadpool instead of stalling the event loop.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 00:02:21 +03:00
bonaminandClaude Opus 5.5 85bd2f7e51 feat(scripts): idempotent backfill of users.device_serials from devices.user_list
One-off script to populate the new device_serials array for assignments
made before the assign/unassign sync existed. Treats each device's
user_list as the source of truth and sets every user's device_serials to
exactly the matching serials, so re-running it is a no-op.

Dry run by default; --apply writes (batched, <=400 per commit).

It also reports users whose doc ID != uid field (MQTT resolves users by the
uid field), users with no uid, devices with users but no serial, and
user_list entries pointing at non-existent users. user_list entries are
accepted as DocumentReferences, "users/{id}" paths or raw doc IDs, and an
entry that matches a uid field rather than a doc ID is mapped to its doc.

Dry run against current data: 13 devices, 13 users, 11 users to update,
0 doc-ID/uid mismatches, 1 dangling user_list entry
(Cx2Va72sUzDbr1T8Ebbh on BSVSPR-26I047-STD10R-88YFJP).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 00:01:36 +03:00
bonaminandClaude Opus 5.5 79a87e48f1 feat(users): store device_serials on user docs for direct user->device lookup
Adds a `device_serials: [string]` array to Firestore `users` docs so the
MQTT ACL (and get_user_devices) can answer "which boards may this user
reach?" without streaming the entire devices collection.

- The serial is the value used in MQTT topics vesper/{serial}/...: the
  device doc's `serial_number` (flashed into NVS, used by the firmware as
  its MQTT id), falling back to the legacy `device_id` for old docs.
  Centralised in users.service.device_serial_of().
- assign_device / unassign_device now write the device's user_list and the
  user's device_serials (ArrayUnion/ArrayRemove) in one atomic batch.
- The device Manage tab endpoints (POST/DELETE /api/devices/{id}/user-list)
  also edit user_list, so they get the same batched sync - otherwise the
  most common assignment path would silently leave device_serials stale.
- get_user_devices resolves devices via device_serials with chunked
  Firestore "in" queries instead of a full collection scan. Requires the
  backfill script (next commit) to be run for existing assignments.
- New mqtt/app_users.py: resolves users by the `uid` FIELD (not doc id -
  create_user uses .add(), FlutterFlow uses uid as doc id) with a 60s
  in-process TTL cache. Assign/unassign, update, block/unblock and delete
  invalidate that uid's entry.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 00:00:49 +03:00
bonaminandClaude Opus 5.5 017911bece docs(api-reference): rf.* is agnus-only — disabled on Vesper Standard (firmware F-069)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 23:54:12 +03:00
bonaminandClaude Opus 5.5 c36e4c41f8 docs(api-reference): loading playback state and playback_failed report (firmware F-068)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 20:25:38 +03:00
bonaminandClaude Opus 5.5 8b229e7fb3 docs(api-reference): list every playback.play/stop reply and error string (firmware F-067)
Replaces the generic "Playback command failed" with the firmware's specific
messages, documents "Already stopped" as SUCCESS, url no longer sticky,
and the stricter field validation.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 20:18:13 +03:00
bonaminandClaude Opus 5.5 9d9b46056a docs(api-reference): status/playback is republished on every MQTT connect (firmware F-066)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 20:11:20 +03:00
bonaminandClaude Opus 5.5 adec979182 docs(api-reference): document the "stopping" playback state (firmware F-065)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 20:10:03 +03:00
bonaminandClaude Opus 5.5 99baec9fcf docs(api-reference): document new status/playback fields (firmware F-064)
pid, speed, duration, started_at, source, ts on status/playback (and the
same fields on the WebSocket playback INFO event), plus how to handle a
stale retained message and when the epoch fields are 0.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 20:09:16 +03:00
bonaminandClaude Opus 5.5 c56344a6dc docs(api-reference): sync with firmware handler audit — playback, rf namespace, clock/ota/files fixes
Mirrors the firmware repo's api-reference.md audit (project-vesper
docs/reference/api-reference.md):

- playback.play: correct field semantics (url not download_url, speed boot
  default 500 / 0→300, note_assignments value = 1-based bell, sticky fields,
  legacy total_duration ignored without continuous_loop); playback.stop has
  no error path.
- UART whitelist now matches UARTTransport::WHITELIST (5 raw cmd strings).
- Add the missing rf namespace (set_slot/clear_slot/get_slots/enable) with
  every error string.
- Fix clock.set_alerts (camelCase), clock.set_silence (nested), clock.set_time
  offsets, relay.test_bell missing error, ota.update default channel,
  ota.set_channel description, files.download download_url, list_builtin
  "pid" key, logs.list extra error, telemetry boot-history limit=0,
  diagnostics topic, network.set_config AP-mode messages, ping data.type.
- Legacy map now matches LegacyAdapter's tables; message-format card and
  req_id notes reflect MQTT-only req_id and per-transport "v" defaults.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 20:02:58 +03:00
bonaminandClaude Sonnet 5 0c0dd9d0e9 fix(devices): signal glyph polish, fix invisible copy button, even firmware row
Follow-up on 529e866 after review:

- SignalIndicator: offline now renders a diagonal slash (standard
  "no signal" convention) instead of an X. Added a distinct amber "?"
  state for devices that are online but whose firmware never reports rssi
  at all (legacy v1 heartbeats predate the rssi/state/ok fields — see API
  Reference's v2 migration notes) — previously this looked identical to
  "not loaded yet". DeviceListCardView's online block now opts into this
  by passing isOnline explicitly.

- Copy-to-clipboard for the serial number was invisible: the icon button
  had opacity:0 as an inline style, which beats a CSS hover rule at equal
  specificity, so the reveal-on-hover code paths never fired. Replaced
  with a shared CopyableSerial component (components/shared/) where the
  whole serial text is clickable, not just a trailing icon, and the icon
  sits at partial opacity at rest instead of fully hidden. Wired into both
  DeviceDetail's header and OverviewTab's hero Serial Number field.

- GeneralTab firmware hero: all stat columns are now equal-width via a
  grid instead of ad-hoc flex gaps, and backup_version's "Unknown" sentinel
  (the device's own placeholder when no second OTA slot has ever been
  flashed) is no longer rendered as the literal string "vUnknown".

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-22 12:45:01 +03:00
bonaminandClaude Sonnet 5 529e866fff fix(devices): offline signal glyph, plus firmware UI across Device Detail tabs
SignalIndicator now takes an isOnline prop — when a device is offline it
renders a dimmed amber glyph with an X instead of showing the last-known
(possibly full-bars) RSSI reading, which was misleading on the Device List
table view. Card view already special-cased offline devices and is
unaffected.

Also, while working the device details surface:
- DeviceDetail: hover-to-reveal copy button next to the serial number
  subtitle in the page header.
- OverviewTab hero: swapped the redundant "Location" field (already shown
  in detail on the General tab's map) for live Firmware Version.
- GeneralTab: new full-width, compact Firmware hero row (version, channel,
  validation state, boot count, backup slot) sourced from firmware.status.
- ControlTab: max width brought in line with every other tab (2000, was
  1400), and added a 4th "Firmware" section with channel selection,
  Update Now, custom-URL flash, and commit/rollback controls, wired to the
  firmware.status / ota.* / firmware.commit / firmware.rollback commands
  documented in the API Reference.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-22 11:47:10 +03:00
bonaminandClaude Sonnet 5 c8ac0b78c5 docs(api-reference): document req_id, rework Transports/Legacy tabs, fix playback.play fields
req_id (added 2026-09-21 in the v2 topic rebuild, F-062):
- New Extras tab documents it fully: envelope-level (sibling of cmd,
  not inside contents), always optional, exact echo/reply behavior,
  parse-failure edge case, and an MQTT-only gap — WebSocket and HTTP
  transports don't actually read or echo it despite CommandBus
  supporting it generically at the bus level.
- Every command's Contents section now carries a persistent note
  pointing to Extras, instead of duplicating the explanation 40+ times
  or only mentioning it in one Transports card.
- Removed the old "req_id Correlation" card from the Transports tab —
  superseded by the Extras tab.

Transports tab: dropped the V2/Legacy sub-tab switcher. It only ever
showed a "not documented yet" placeholder for Legacy, and the legacy
topic set belongs with the rest of the migration reference, not
alongside the current transport list.

Legacy Migration tab (renamed from "v1 → v2 Migration"): added a
"Legacy Topic Migration" table ahead of the command migration table,
mapping every MQTT topic from the old pre-rewrite firmware
("Controller - Production FW") to its v2 equivalent — including three
v2 topics (system/alerts, system/info, system/metrics) that have no
legacy predecessor at all. Reconstructed from that firmware's source;
it has been fully replaced, so this is historical reference only.

playback.play: filled in the full contents field set per the current
Player.cpp implementation — segment_duration, pause_duration,
total_duration, and continuous_loop are the legacy (no "mode") path,
while duration is the v2 path read only when mode is present. Added a
warning callout since sending mode alongside the legacy duration
fields doesn't merge behavior — only one path is read, based solely on
whether mode is present. This is intentional: mode is how a v2 caller
opts in, and its absence is how a v1 caller's request still works.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-21 20:35:20 +03:00
bonaminandClaude Sonnet 5 80c0e955f0 fix(devices): zero out unassigned bell outputs when saving Bell Mechanisms
relay.set_config is a partial update on the firmware side — any bell
index not present in the durations/outputs maps is left completely
untouched. EditBellOutputsModal and OnboardDevice's bell config step
both only sent entries for the currently-active bell count, so
deselecting a bell (lowering the active count) never actually
deactivated its output on the device — it stayed wired to whatever it
was last set to. The only way to disable a bell was to reselect it and
explicitly set it to "Disabled", which isn't obvious.

Both now send all maxOutputs slots on every save, forcing output to 0
for anything beyond the active count, so lowering the active bell
count reaches the firmware the way it visually appears to in the UI.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-21 20:35:03 +03:00
bonaminandClaude Sonnet 5 ae5da6046f docs(CLAUDE): require every change to be documented and committed
Adds a Documentation & Commit Policy section and a Golden Rules entry
requiring every change, however small, to be committed with a
descriptive message explaining why — so project history stays a
reliable record of what happened over time.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-21 18:36:56 +03:00
bonaminandClaude Sonnet 5 aad5f4b98c chore(strategies): add Health Monitor standalone design mockup
Throwaway HTML prototype for the device Health tab's layout/visual
direction, kept alongside the other planning docs in strategies/.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-21 18:36:50 +03:00
bonaminandClaude Sonnet 5 751cac72ce fix(docker): move postgres data to a named volume, off the WSL2 bind mount
The ./data/postgres bind mount hit a WSL2/Docker Desktop bug where the
9p/virtiofs bridge reports normal postgres:postgres 0600 ownership but
the kernel still refuses the postgres user's own open() calls for
write — silent on read, fatal on any WAL write, which took the whole
database down after an unclean shutdown. Switches to a Docker-managed
named volume (bellsystems-postgres-data) that lives inside the WSL2
VM's own filesystem instead. The old bind-mounted data is left in
place at ./data/postgres/ as an untouched backup — that folder was
too wedged by the same bug to even rename, so it's abandoned rather
than deleted.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-21 18:36:28 +03:00
bonaminandClaude Sonnet 5 cef5e1f0f5 chore(docker): restart backend, frontend, and nginx unless stopped
Matches postgres, which already had restart: unless-stopped — the app
containers were the only ones that didn't come back automatically
after a host reboot or Docker Desktop restart.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-21 18:36:20 +03:00
bonaminandClaude Sonnet 5 f036000769 feat(manufacturing): extract shared useSerialConnection hook for provisioning wizard
WebSerial port ownership was previously held inside StepFlash, which
made it awkward for other steps (StepVerify) to read from the same
port without fighting over exclusive access. useSerialConnection
centralizes port open/close/read/write so the wizard's steps share one
connection lifecycle instead of each managing their own.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-21 18:35:31 +03:00
bonaminandClaude Sonnet 5 d87925516a feat(devices): add ResetStatsRequest/ResetStatsResult models
Missed from the previous Reset Stats commit — these are the
request/response schemas for POST /devices/{id}/reset-stats.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-21 18:35:20 +03:00
bonaminandClaude Sonnet 5 f54500a9d9 feat(devices): add Reset Stats action for clearing pre-ship QA/bench data
New POST /devices/{id}/reset-stats + ResetStatsModal lets staff clear
QA/bench test data accumulated before a device ships to a customer:
Firestore bell/playback counters and Postgres history tables (logs,
heartbeats, commands, boot events, alert events, ping samples,
diagnostics reports, control/reports, and opt-in live alerts). The two
firmware-side resets (telemetry.reset_boot_data, logs.clear) go over
the existing MQTT command/ack flow instead, since they need the device
online and duplicating that round-trip server-side would just be a
second, inferior implementation.

Also includes two incidental cleanups in devices/router.py: audit-log
entries for create/update now use console_name in their label (missed
by the earlier console_name commit), and add/remove-device-user rename
their local Firestore client from `db` to `fs` to stop shadowing the
`db: AsyncSession` dependency param in the same function scope.
AddDeviceUserModal's results list also gets a max-height + scroll so a
long match list doesn't grow the modal off-screen.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-21 18:35:01 +03:00
bonaminandClaude Sonnet 5 4737ab4306 feat(devices): add device onboarding wizard
New guided flow (Bell Cloud > Devices > Onboard) for claiming a
manufactured/flashed device into a customer's fleet in one pass:
looks up the device by serial, finds or creates the customer
(CreateCustomerModal for a quick inline create), finds or creates the
app user account (reuses CreateUserModal from the user-creation work),
and assigns the device — replacing what used to require jumping
between the inventory, CRM, and user-management pages separately.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-21 18:34:32 +03:00
bonaminandClaude Sonnet 5 6686faad6b feat(manufacturing): enrich inventory list with customer/user details and filters
The inventory list and detail page previously only showed raw
customer_id / user_list references. list_devices now batch-resolves
customer names and user display names/emails (via Firestore get_all(),
avoiding an N+1 round trip per device) and exposes them as
customer_name / users on DeviceInventoryItem. Search now matches
against device name, console name, customer name, and assigned users
in addition to serial/owner/batch.

Also adds hw_types (multi-select board type) and has_users filters to
GET /manufacturing/devices, and carries console_name through for
display. DeviceInventoryDetail is updated to show and use all of this
(customer name, assigned users, new UI components for signal/charts).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-21 18:34:08 +03:00
bonaminandClaude Sonnet 5 b07bdafd85 fix(header): resolve breadcrumb labels for devices and melodies correctly
- devices: breadcrumb now falls back through console_name -> device_name
  -> device_id, matching every other device display label in the console
- melodies/archetypes: breadcrumb was reading a bare d.name field that
  doesn't exist on the melody schema (name lives at
  d.information.name.<locale>), so these breadcrumbs always showed blank.
  Now uses getLocalizedValue like the rest of the melodies UI.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-21 18:33:55 +03:00
bonaminandClaude Sonnet 5 dff1a35560 feat(settings): add log retention settings page
Sysadmin/admin-only settings page for configuring how long device log
history is kept before pruning. GET/PUT /api/settings/log-retention,
new LogRetentionSettings page, nav entry, and route.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-21 18:33:40 +03:00
bonaminandClaude Sonnet 5 acd1896788 feat(devices): add Health tab, log explorer, and fleet health indicators
Surfaces the new device-health telemetry (boot events, ping RTT,
diagnostics reports, alert events) across the console:

- HealthTab: boot/diagnostics timeline, CPU temp and RSSI charts
  (LineChart), current alert status, and a Settings sub-tab for
  DeviceHealthSettings thresholds
- LogsTab: dedicated log explorer embedded in the Health tab, with
  level/source filtering and fmtLogTimestamp for dense timestamp rows
- OverviewTab: a "Latest Device Issue" card showing the most recent
  alert event, colour-coded by severity and fading with age, plus a
  modal to inspect the surrounding log lines
- DeviceList/DeviceListCardView/DeviceListMapView: fleet list gains a
  SignalIndicator-based RSSI display in place of the plain online dot

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-21 18:32:06 +03:00
bonaminandClaude Sonnet 5 0d79a9f72c feat(users): support creating app users with a Firebase Auth account
New users can now be created with a password, which creates a real
Firebase Auth account (so they can log into the mobile app immediately)
alongside the Firestore profile document. UserCreate is now
UserProfile + password (request-only, never persisted or echoed back);
deleting a user also removes their Auth account.

- backend/users: split UserCreate into UserProfile (persisted shape)
  and UserCreate (adds password), wire firebase_auth create/delete
- CreateUserModal: new lightweight modal for creating a user from
  other flows (e.g. device onboarding) without leaving the page
- UserForm: adds the password field for new users; also fixes
  useToast() being used undestructured (toast.success(...) was being
  called on the hook's return value instead of its .toast method)

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-21 18:31:37 +03:00
bonaminandClaude Sonnet 5 6e0a291228 feat(devices): add console-only display name (console_name)
Lets staff set a friendly name for a device independent of whatever
name the end user gave it in the app. console_name is never shown to
app users and never synced from/to device_name; every display label
across search, equipment/helpdesk name resolution, device search, and
the Manage tab's issue linker now falls back through console_name ->
device_name -> serial rather than device_name alone.

Also includes an incidental one-line fix in devices/service.py: the
nested-struct deep-merge in update_device() was missing the newly
added device_health_settings key.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-21 18:31:10 +03:00
bonaminandClaude Sonnet 5 8ec13947cb fix(devices): restore warranty/maintenance dates missing from timestamp field list
subscrStart, warrantyStart, and maintainedOn are written to Firestore as
Timestamps like the other date fields here, but were missing from
_TIMESTAMP_FIELD_NAMES, so they weren't being converted back to ISO
strings on read.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-21 18:30:15 +03:00
bonaminandClaude Sonnet 5 0bec4c4648 feat(devices): add DeviceHealthSettings model for per-device alert thresholds
Two-tier (warning/critical) threshold config per device — restarts/week,
RSSI floor, free-heap floor, CPU temp ceiling, plus an offline timeout
used for both a client-computed health status icon and the Health tab
chart's gap detection. Purely advisory for now: no server-side
email/push alerting infra exists yet, so email_on_threshold and
push_on_crash_boot are placeholders for that future work.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-21 18:27:35 +03:00
bonaminandClaude Sonnet 5 cc138e3d82 feat(devices): push General/Clock/Bells/Alerts config live over MQTT
Adopts useDeviceCommand across DeviceDetail and its tabs so config
changes (log levels, clock settings, bell outputs, alert thresholds,
backlight, attributes) are sent to the device immediately via
control commands and only persisted to Firestore once the device
acks success, instead of writing Firestore first and hoping the
device eventually picks it up.

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

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-21 18:25:30 +03:00
bonaminandClaude Sonnet 5 7c533b9245 feat(mqtt): add device health telemetry and migrate to v2 topic spec
Two efforts that landed together because the v2 topic work extends
tables the health-telemetry effort added days earlier in the same
files/functions, making them impractical to separate cleanly:

Health/diagnostics telemetry (schema, Jul 13-17):
- New Postgres tables: device_alert_events, device_boot_events,
  device_ping_samples, device_diagnostics_reports, plus a `source`
  column on device_logs to distinguish log origins
- Query/service layer in pg_mqtt.py and database/__init__.py for
  inserting and listing this history, plus a "latest metrics" endpoint
  combining most-recent diagnostics + ping RTT per device
- mqtt/router.py gains list endpoints for alert/boot/ping/diagnostics
  history, consumed by the upcoming Health tab

MQTT v2 topic migration (Sep 21):
- Heartbeat payload flattened per vesper_mqtt_topic_spec_v2.md, adding
  rssi/free_heap/state/ok fields
- Command replies move to control/ack, device-initiated events to
  control/reports; mqtt/client.py subscribes to the new topic set and
  runs a ping_loop (wired up in main.py) for RTT sampling
- mqtt/logger.py and pg_mqtt.py updated to parse and persist the new
  payload shape alongside the legacy fields for backwards compatibility

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-21 18:24:36 +03:00
bonaminandClaude Sonnet 5 e5d556fee1 feat(devices): extract useDeviceCommand hook for shared MQTT command/ack flow
Pulls the send-command-and-await-ack machinery out of DeviceDetail.jsx
into a reusable hook, so other pages (the onboarding wizard, etc.) can
send a device a command and await its control/ack reply the same way,
with a live-updating toast for non-silent commands.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-21 18:22:48 +03:00
bonaminandClaude Sonnet 5 38750ba951 fix(scrollbar): theme scrollbars inside portal-rendered elements
Scrollbar theming was scoped to .app, so anything rendered outside it via
createPortal(..., document.body) — Modal, Select/MultiSelect's floating
menu, DataTable's column-visibility picker — fell back to the browser's
default light-on-dark scrollbar. Extends the same scrollbar-color rules
to .modal, .select-menu, and .dt-col-picker.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-21 18:22:30 +03:00
bonaminandClaude Sonnet 5 7f6145ca35 fix(header): match header glass tint to sidebar, add drop shadow
.header used a lighter 0.30 background tint than .sidebar's 0.40, so
scrolled content underneath showed through almost undimmed even though
backdrop-filter was applied — the two fixed chrome surfaces no longer
read as one consistent glass layer. Aligns the tint and adds a shadow
to give the header separation from content.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-21 18:22:23 +03:00
bonaminandClaude Sonnet 5 2f7c5e859d feat(ui): add MultiSelect, LineChart, SignalIndicator, PressHoldButton, EditableText, TimeRangeSelect
Six new design-system components, all documented with live examples in
the StyleGuide as required by CLAUDE.md before any page can use them:

- MultiSelect: checkbox dropdown for filters/tags, built on Select's
  trigger/menu styling
- LineChart: telemetry/time-series charting for the upcoming Health tab
- SignalIndicator: signal-strength glyph for device RSSI display
- PressHoldButton: press-and-hold confirmation for destructive actions
- EditableText: inline click-to-edit text with a hover/focus-revealed
  pencil affordance
- TimeRangeSelect: preset + custom time-range picker, backed by the new
  lib/timeRange.js helper

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-21 18:22:02 +03:00
bonaminandClaude Sonnet 5 883c0556dd feat(ui): add pending/update toast state and shared floating-menu positioning
Toast gains a pending/update lifecycle so async actions can show a single
toast that transitions from in-progress to success/error, instead of
firing a new one. Select's floating-menu placement logic is extracted
into a shared helper so other dropdown-style components (MultiSelect)
can reuse it.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-21 18:20:26 +03:00
bonaminandClaude Sonnet 5 1ce0137ba9 feat(mqtt): implement useMqttWebSocket hook
Was previously a dead stub (TODO: implement). This real implementation
is the foundation for live heartbeats, ping RTT, and the device command
ack flow that later commits build on.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-21 18:20:15 +03:00
bonaminandClaude Sonnet 5 eaf92f1581 docs(api-reference): add MQTT v2 topic spec, split Transports into V2/Legacy
Firmware rebuilt its MQTT topics to v2 (control/command+ack+reports,
status/playback, system/alerts+info+logs+metrics, LWT, req_id, per-topic
switches — see project-vesper's docs/reference/vesper_mqtt_topic_spec_v2.md
and feature-catalog.md F-062). Mirrors that in the console's API Reference:

- Transports tab now splits into V2 (fully documented: topic table with
  per-topic switches, req_id correlation, heartbeat/playback/reports/
  alerts/boot-report/metrics payload cards) and Legacy (placeholder,
  to be filled in later)
- mqtt namespace gains mqtt.get_topics / mqtt.set_topics command docs
- mqtt.disable description updated for its new graceful-offline behavior
- Message envelope docs (top of page) note the new optional req_id field

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-21 10:49:02 +03:00
bonaminandClaude Sonnet 5 cc28ed880b docs(ApiReferencePage): document system.set_identity console command
Firmware side added an MQTT-only sysadmin command to override a
device's factory-set identity (serial/hw_family/hw_revision) — see
project-vesper commit 64a8bc2. Per docs/README.md's console-sync
rule, mirrors the same command into the console's live API Reference
page.

Note: this repo had substantial other pending uncommitted work
(diagnostics reports, boot history, log retention, etc.) in this
same file and elsewhere at the time of this commit — left untouched
and still uncommitted, only the system.set_identity hunk is included
here.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-20 20:11:26 +03:00
bonamin 44609352b2 docs(ApiReference): document logs.list/logs.download and extended firmware.status
Mirrors firmware changes: new SD log retrieval commands on LoggingHandler
(logs.list, logs.download — chunked/paginated for offline-device
troubleshooting), and firmware.status now returns OTA rollback safety-net
diagnostics (retry/failure counts, backup partition info).
2026-07-15 00:06:26 +03:00
bonaminandClaude Sonnet 4.6 70e0f9f734 docs(api-reference): add heartbeat payload card with rssi field
Adds a dedicated Heartbeat Payload card to the Transports tab showing
the full JSON schema with per-field descriptions, including the new rssi field.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-13 02:14:53 +03:00
bonaminandClaude Sonnet 4.6 a9b3b4e9b0 feat(ApiReference): redesign network.info and network.status documentation
network.info: updated description and response example to reflect new fields
(subnet, mac, hostname, ssid, connection_type). Notes it as the command to use
for console panel population.

network.status: updated to show slimmed response (connected, ap_mode, rssi,
uptime_ms, state). Notes it as the command for monitoring/polling, not display.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-13 00:53:42 +03:00
bonaminandClaude Sonnet 4.6 65ce446e44 fix(ApiReference): clock.get_config — add timezone fields, fix backlight/bell docs
- clock.get_config response example now includes gmt_offset_sec, dst_offset_sec, ntp_server
- Description updated to note it supersedes clock.get_timezone
- clock.set_backlight field names corrected to match wire format
  (backlight, backlight_output, backlight_on, backlight_off)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-12 19:38:21 +03:00
bonaminandClaude Sonnet 4.6 bff90965bf feat(ApiReference): add clock.set_config, clock.set_alerts_config, relay.set_config entries
Document three new batch commands with full response/errors/example fields:
- relay.set_config: combined bell durations + outputs
- clock.set_config: clock hardware settings (enabled, c1, c2, timings)
- clock.set_alerts_config: alert type, bell assignments, silence windows

Also updated output field notes throughout clock and relay commands to reflect
the enforced 1-based output numbering convention (0 = disabled, 255 = unconfigured).

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-12 18:45:12 +03:00
bonaminandClaude Sonnet 4.6 3394716f8f docs(ApiReferencePage): full v2 API reference update
Fixes and additions across all namespaces to accurately reflect firmware v2.1.0:

Fixes:
- system.get_settings → system.get_config (backward compat alias noted)
- network.status returns now includes ssid, mac, hostname
- clock.set_alerts: correct alert_type values (OFF|SINGLE|HOURS, not none|hour|quarter)
- ota: removed non-existent ota.status and ota.check commands
- telemetry.get_loads returns now includes max_loads and guard_enabled

Additions:
- relay.test_bell and relay.test_batch (F-038)
- clock.test_c1 and clock.test_c2 (F-039)
- system.get_config, system.get_all, system.get_telemetry (F-035)
- telemetry.set_max_loads, telemetry.set_guard_enabled, telemetry.get_metrics, telemetry.reset_metrics (F-030, F-031, F-034)
- log.get_config and mqtt.get_config (F-036)
- ota.set_channel
- bells namespace: bells.enable, bells.disable, bells.get_config (F-029, F-036)
- UART whitelist updated for new commands
- Legacy map updated: get_full_settings → system.get_config

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-10 19:55:08 +03:00
bonaminandClaude Sonnet 4.6 abf3c3825b docs(ApiReference): align V2 command reference with actual firmware
playback namespace: replaced stale root-level 'playback' command with
proper playback.play / playback.stop split. playback.play now documents
all firmware attributes: pid, uid, name, url, speed, note_assignments,
mode (single/timed/interval/infinite), duration, pause_duration,
total_duration.

clock namespace: filled in previously empty contents for set_timings
(pulse_duration, pause_duration), set_alerts (alert_type, alert_interval,
hour/half/quarter_bell outputs), set_backlight (backlight, backlight_output,
backlight_on/off), set_silence (daytime and nighttime windows with HH:MM
strings). Fixed clock.get_timezone returns (ntp_server field, removed
non-existent timezone_name). Added exact returns shape for clock.get_face
and full field list for clock.get_config matching handler output.

system namespace: added exact returns shapes for system.status
(player_status, time_elapsed_ms, projected_run_time, strike_counters)
and system.health (critical_count, warning_count, firmware_stable,
subsystems array).

Legacy map: updated playback row to show play→playback.play and
stop→playback.stop. UART whitelist updated to playback.play/stop.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-09 10:03:52 +03:00
126 changed files with 19291 additions and 1480 deletions
+4
View File
@@ -17,6 +17,10 @@ MOSQUITTO_PASSWORD_FILE=/etc/mosquitto/passwd
MQTT_CLIENT_ID=bellsystems-admin-panel
# HMAC secret used to derive per-device MQTT passwords (must match firmware)
MQTT_SECRET=change-me-in-production
# Accept the legacy shared "vesper" MQTT password for device usernames
# (old firmware). Each use is logged once/hour per board; set to false
# once no boards show up in those logs.
MQTT_ALLOW_LEGACY_PASSWORD=true
# App
BACKEND_CORS_ORIGINS=["http://localhost:5173"]
+2
View File
@@ -41,3 +41,5 @@ Thumbs.db
# claude
.claude/
# Per-machine compose overrides (e.g. Windows Postgres volume)
docker-compose.override.yml
+46
View File
@@ -85,6 +85,7 @@ Never use relative `../` paths except inside `providers/` and `hooks/` when refe
- **Source every UI element from `@/components/ui/`** — no raw HTML elements for styled things
- **Use only CSS tokens** — never raw hex, rgb, or pixel values in component or page files
- **Use `.masonry-grid` for all content pages with multiple variable-height sections** — never `display: grid` with fixed columns for card layouts. See DESIGN.md §11.
- **Every change, major or minor, must be documented and committed** — see "Documentation & Commit Policy" below.
---
@@ -99,6 +100,7 @@ Check the live Style Guide at `/dev/styleguide` to see all variants and states.
| `StatusBadge` | `@/components/ui/StatusBadge` | Coloured status pills |
| `FormField` | `@/components/ui/FormField` | Every text/email/password/textarea input |
| `Select` | `@/components/ui/Select` | Custom dropdown (used inside FormField type="select") |
| `MultiSelect` | `@/components/ui/MultiSelect` | Checkbox dropdown for selecting multiple values (filters, tags) |
| `Modal` | `@/components/ui/Modal` | All overlay dialogs |
| `ConfirmDialog` | `@/components/ui/ConfirmDialog` | Destructive / confirmation prompts |
| `DataTable` | `@/components/ui/DataTable` | All tabular data with sorting/selection |
@@ -363,6 +365,37 @@ used in a page must have a visible example there first.
---
## MQTT Auth (devices + phone-app users)
Read `docs/mqtt-app-user-auth.md` before touching `backend/mqtt/auth.py`,
`backend/mqtt/app_users.py`, or any code that changes a device's `user_list` or a
user's `status`. Any code that edits `user_list` must also update the user's
`device_serials` in the same batch and invalidate the MQTT ACL cache, or app users
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
```js
@@ -381,3 +414,16 @@ All pages import from `@/lib/api`, never directly from `_archive`.
These are the ONLY two files permitted to import from `_archive/auth/`.
All other files use `@/hooks/useAuth`.
---
## Documentation & Commit Policy
**Every change to this project — major or minor — must be documented and committed.** This is how we keep a record of what happened over time. Uncommitted or undocumented work is effectively invisible to future sessions.
- **Commit every change**, no matter how small (a copy tweak, a token rename, a bug fix, a new page). Do not batch unrelated work silently into "cleanup later" — if it changed, commit it.
- **Write descriptive commit messages** that explain *why*, not just *what* — future sessions rely on `git log` to reconstruct project history since this isn't otherwise tracked elsewhere.
- **Never leave work uncommitted** at the end of a session/task unless the user explicitly says to hold off.
- Follow the repo's existing commit message conventions (see recent `git log` for style/format).
- If a change is large enough to warrant explanation beyond the commit message (a new module, a non-obvious fix, a schema/API change), note the reasoning in the commit body — don't rely on memory or chat history to preserve it.
- This applies to backend, frontend, and config changes alike — even though `backend/` and `_archive/` are off-limits to modify directly in most cases, any change made anywhere in the repo still follows this same commit discipline.
+14
View File
@@ -39,6 +39,20 @@ bellsystems-admin/
└── .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
See `BellSystems_AdminPanel_Strategy.md` for the full architecture and build plan.
@@ -0,0 +1,73 @@
"""device diagnostics reports
Adds device_diagnostics_reports — structured storage for the firmware's
diagnostics_report MQTT event (vesper/{uid}/status/info, type="diagnostics_report"),
published every 5 minutes. Cleanly separate from device_boot_events (one row per
boot, event-driven) and heartbeats (one row every 30s, transport/liveness facts):
this table is periodic health telemetry — CPU temperature (min/max/avg over the
5-minute window), WiFi reconnect count + last disconnect reason, OTA/firmware
check state, and per-task stack high-water marks (bytes free).
stack_high_water is stored as a JSON-encoded TEXT column rather than flattened
columns — unlike the other three groups (fixed field sets), the set of
monitored tasks is open-ended on the firmware side (see project-vesper's
Telemetry::registerTaskForStackMonitoring), so a fixed column per task would
need a migration every time a task is added. TEXT (not JSONB) matches this
codebase's existing convention for JSON blobs stored via raw SQL — see
commands.command_payload / response_payload.
Revision ID: a7b8c9d0e1f2
Revises: f6a7b8c9d0e1
Create Date: 2026-07-17 00:00:00.000000
"""
from typing import Sequence, Union
import sqlalchemy as sa
from alembic import op
revision: str = "a7b8c9d0e1f2"
down_revision: Union[str, None] = "f6a7b8c9d0e1"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None:
op.create_table(
"device_diagnostics_reports",
sa.Column("id", sa.BigInteger(), primary_key=True, autoincrement=True),
sa.Column("device_serial", sa.String(128), nullable=False),
# cpu_temp — omitted by firmware (all null here) if no samples were
# taken yet this window (e.g. very first report shortly after boot).
sa.Column("cpu_temp_avg", sa.Float(), nullable=True),
sa.Column("cpu_temp_min", sa.Float(), nullable=True),
sa.Column("cpu_temp_max", sa.Float(), nullable=True),
sa.Column("cpu_temp_samples", sa.Integer(), nullable=True),
# wifi_reconnects — this-boot-only lifetime count, not device lifetime.
sa.Column("wifi_reconnect_count", sa.Integer(), nullable=True),
sa.Column("wifi_last_disconnect_reason", sa.String(64), nullable=True),
sa.Column("wifi_last_disconnect_uptime_ms", sa.BigInteger(), nullable=True),
# ota
sa.Column("ota_current_version", sa.String(32), nullable=True),
sa.Column("ota_update_available", sa.Boolean(), nullable=True),
sa.Column("ota_available_version", sa.String(32), nullable=True),
sa.Column("ota_last_check_uptime_ms", sa.BigInteger(), nullable=True),
sa.Column("ota_last_error", sa.String(32), nullable=True),
# stack_high_water — open-ended task set, see module docstring.
sa.Column("stack_high_water", sa.Text(), nullable=True),
sa.Column("received_at", sa.DateTime(timezone=True), nullable=False,
server_default=sa.func.now()),
)
op.create_index(
"idx_device_diagnostics_reports_serial_received",
"device_diagnostics_reports",
["device_serial", sa.text("received_at DESC")],
)
def downgrade() -> None:
op.drop_index("idx_device_diagnostics_reports_serial_received", table_name="device_diagnostics_reports")
op.drop_table("device_diagnostics_reports")
@@ -0,0 +1,78 @@
"""mqtt v2 topic migration
Firmware moved to a new MQTT topic spec (project-vesper's
docs/reference/vesper_mqtt_topic_spec_v2.md, feature-catalog F-062). Three
schema changes needed to keep ingestion correct against the new payload shapes:
1. heartbeats.state / heartbeats.ok — the v2 heartbeat payload is flat (no more
{"status":"INFO","type":"heartbeat","payload":{...}} wrapper) and adds two
new fields: state ("idle"/"playing"/"paused"/"error"/"booting") and ok
(overall health), both independently derived on the firmware side — not
mirrored from status/playback or system/alerts. Nullable: older rows
(pre-migration) and any device still reporting have no value for these.
2. device_diagnostics_reports gains bell_strikes / bell_loads / cooling_active.
The 5-min diagnostics report moved from status/info to system/metrics and
picked up per-bell strike/heat data along the way (the topic spec calls out
"bell heat ratings" explicitly for this topic). Stored as JSON-encoded TEXT,
matching this table's existing stack_high_water column — same reasoning:
16 fixed bell slots, but keeping the encoding consistent with the sibling
column is simpler than mixing raw JSONB and TEXT in one row shape.
3. device_reports — new table for the new control/reports topic. Board-
initiated, unsolicited, critical events (currently only bell_overload).
Distinct from device_alert_events (subsystem health transitions) and
device_logs (routine log lines) — this is a narrow, insert-only table for
a different kind of signal: urgent, bell-mechanism-specific events the
physical tablets act on in real time. The console side is deliberately
light for now — store + list for historical/audit purposes; the tablets
are the real-time consumer of control/reports, not this console.
Revision ID: b8c9d0e1f2a3
Revises: a7b8c9d0e1f2
Create Date: 2026-09-21 00:00:00.000000
"""
from typing import Sequence, Union
import sqlalchemy as sa
from alembic import op
revision: str = "b8c9d0e1f2a3"
down_revision: Union[str, None] = "a7b8c9d0e1f2"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None:
op.add_column("heartbeats", sa.Column("state", sa.String(16), nullable=True))
op.add_column("heartbeats", sa.Column("ok", sa.Boolean(), nullable=True))
op.add_column("device_diagnostics_reports", sa.Column("bell_strikes", sa.Text(), nullable=True))
op.add_column("device_diagnostics_reports", sa.Column("bell_loads", sa.Text(), nullable=True))
op.add_column("device_diagnostics_reports", sa.Column("cooling_active", sa.Boolean(), nullable=True))
op.create_table(
"device_reports",
sa.Column("id", sa.BigInteger(), primary_key=True, autoincrement=True),
sa.Column("device_serial", sa.String(128), nullable=False),
sa.Column("report_type", sa.String(64), nullable=False),
sa.Column("payload", sa.Text(), nullable=True),
sa.Column("occurred_at", sa.DateTime(timezone=True), nullable=False,
server_default=sa.func.now()),
)
op.create_index(
"idx_device_reports_serial_occurred",
"device_reports",
["device_serial", sa.text("occurred_at DESC")],
)
def downgrade() -> None:
op.drop_index("idx_device_reports_serial_occurred", table_name="device_reports")
op.drop_table("device_reports")
op.drop_column("device_diagnostics_reports", "cooling_active")
op.drop_column("device_diagnostics_reports", "bell_loads")
op.drop_column("device_diagnostics_reports", "bell_strikes")
op.drop_column("heartbeats", "ok")
op.drop_column("heartbeats", "state")
@@ -0,0 +1,32 @@
"""boot event crash detail (firmware F-070)
Firmware F-070 enriches boot_report (and telemetry.get_boot_history entries)
with a fuller `crash` object (backtrace, backtrace_corrupted, elf_sha256) and a
new, independent `pre_crash` object (uptime/heap snapshot + optional
abort_msg). Both are stored verbatim as JSONB so future additive fields don't
need another migration. The existing flat crash_* columns stay and are still
filled, so older rows and older firmware keep working unchanged.
Revision ID: c9d0e1f2a3b4
Revises: b8c9d0e1f2a3
Create Date: 2026-09-30 00:00:00.000000
"""
from typing import Sequence, Union
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql
from alembic import op
revision: str = "c9d0e1f2a3b4"
down_revision: Union[str, None] = "b8c9d0e1f2a3"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None:
op.add_column("device_boot_events", sa.Column("crash", postgresql.JSONB(), nullable=True))
op.add_column("device_boot_events", sa.Column("pre_crash", postgresql.JSONB(), nullable=True))
def downgrade() -> None:
op.drop_column("device_boot_events", "pre_crash")
op.drop_column("device_boot_events", "crash")
@@ -0,0 +1,48 @@
"""device_alert_events
Adds an insert-only history log of device alert transitions (WARNING/CRITICAL/
FAILED only — CLEARED is not logged here). device_alerts remains the current-
state table and is untouched; this is purely additive, used to answer "when
was the most recent issue on this device" even after it has been resolved.
Also adds an optional rssi column to heartbeats, for a signal-strength
indicator once firmware starts reporting it on the heartbeat payload.
Revision ID: d4e5f6a7b8c9
Revises: c3d4e5f6a7b8
Create Date: 2026-07-13 00:00:00.000000
"""
from typing import Sequence, Union
import sqlalchemy as sa
from alembic import op
revision: str = "d4e5f6a7b8c9"
down_revision: Union[str, None] = "c3d4e5f6a7b8"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None:
op.create_table(
"device_alert_events",
sa.Column("id", sa.BigInteger(), primary_key=True, autoincrement=True),
sa.Column("device_serial", sa.String(128), nullable=False),
sa.Column("subsystem", sa.String(128), nullable=False),
sa.Column("state", sa.String(64), nullable=False),
sa.Column("message", sa.Text(), nullable=True),
sa.Column("occurred_at", sa.DateTime(timezone=True), nullable=False,
server_default=sa.func.now()),
)
op.create_index(
"idx_device_alert_events_serial_occurred",
"device_alert_events",
["device_serial", sa.text("occurred_at DESC")],
)
op.add_column("heartbeats", sa.Column("rssi", sa.Integer(), nullable=True))
def downgrade() -> None:
op.drop_column("heartbeats", "rssi")
op.drop_index("idx_device_alert_events_serial_occurred", table_name="device_alert_events")
op.drop_table("device_alert_events")
@@ -0,0 +1,39 @@
"""device_logs source column
Adds a 'source' column to device_logs distinguishing the debug log stream
(vesper/{id}/logs, source='log') from the general info stream
(vesper/{id}/status/info, source='info'), which was previously discarded
after only being written to the server debug log. Existing rows default to
'log' since that's the only source ever persisted before this migration.
Adding a column to a partitioned parent table applies it to all existing
and future partitions automatically.
Revision ID: e5f6a7b8c9d0
Revises: d4e5f6a7b8c9
Create Date: 2026-07-14 00:00:00.000000
"""
from typing import Sequence, Union
import sqlalchemy as sa
from alembic import op
revision: str = "e5f6a7b8c9d0"
down_revision: Union[str, None] = "d4e5f6a7b8c9"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None:
op.execute("""
ALTER TABLE device_logs
ADD COLUMN source TEXT NOT NULL DEFAULT 'log'
""")
op.execute("""
CREATE INDEX idx_device_logs_source
ON device_logs(device_serial, source, received_at DESC)
""")
def downgrade() -> None:
op.execute("DROP INDEX IF EXISTS idx_device_logs_source")
op.execute("ALTER TABLE device_logs DROP COLUMN source")
@@ -0,0 +1,82 @@
"""device health tab — boot events, heartbeat free_heap, ping samples
Adds three pieces of schema needed for the device Health tab:
1. device_boot_events — structured, insert-only history of the firmware's
boot_report MQTT event (vesper/{uid}/status/info, type="boot_report").
Previously this payload was flattened into a single device_logs text line
with all structured fields (boot_count, crash detail) discarded on arrival.
This table gives the console a real timeline to query and chart against,
instead of parsing log strings.
2. heartbeats.free_heap — firmware now includes free_heap on every 30s
heartbeat (previously only available once per boot via boot_report), so
the console can chart heap trend instead of seeing one point per boot.
3. device_ping_samples — backend-computed RTT samples. The firmware's ping
command now echoes back a caller-supplied timestamp; the backend pings
each online device on an interval and records (now - echoed_ts) here.
A dedicated table rather than reusing `commands` because `commands` isn't
shaped for time-series charting (mixed command types, no fast per-device
time-range query path) and pruning ping history independently of other
command history is desirable.
Revision ID: f6a7b8c9d0e1
Revises: e5f6a7b8c9d0
Create Date: 2026-07-16 00:00:00.000000
"""
from typing import Sequence, Union
import sqlalchemy as sa
from alembic import op
revision: str = "f6a7b8c9d0e1"
down_revision: Union[str, None] = "e5f6a7b8c9d0"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None:
op.create_table(
"device_boot_events",
sa.Column("id", sa.BigInteger(), primary_key=True, autoincrement=True),
sa.Column("device_serial", sa.String(128), nullable=False),
sa.Column("boot_count", sa.Integer(), nullable=True),
sa.Column("reset_reason", sa.String(64), nullable=True),
sa.Column("is_fault", sa.Boolean(), nullable=False, server_default=sa.false()),
sa.Column("free_heap", sa.Integer(), nullable=True),
sa.Column("crash_task", sa.String(64), nullable=True),
sa.Column("crash_pc", sa.BigInteger(), nullable=True),
sa.Column("crash_exc_cause", sa.Integer(), nullable=True),
sa.Column("crash_exc_vaddr", sa.BigInteger(), nullable=True),
sa.Column("occurred_at", sa.DateTime(timezone=True), nullable=False,
server_default=sa.func.now()),
)
op.create_index(
"idx_device_boot_events_serial_occurred",
"device_boot_events",
["device_serial", sa.text("occurred_at DESC")],
)
op.add_column("heartbeats", sa.Column("free_heap", sa.Integer(), nullable=True))
op.create_table(
"device_ping_samples",
sa.Column("id", sa.BigInteger(), primary_key=True, autoincrement=True),
sa.Column("device_serial", sa.String(128), nullable=False),
sa.Column("rtt_ms", sa.Integer(), nullable=False),
sa.Column("sampled_at", sa.DateTime(timezone=True), nullable=False,
server_default=sa.func.now()),
)
op.create_index(
"idx_device_ping_samples_serial_sampled",
"device_ping_samples",
["device_serial", sa.text("sampled_at DESC")],
)
def downgrade() -> None:
op.drop_index("idx_device_ping_samples_serial_sampled", table_name="device_ping_samples")
op.drop_table("device_ping_samples")
op.drop_column("heartbeats", "free_heap")
op.drop_index("idx_device_boot_events_serial_occurred", table_name="device_boot_events")
op.drop_table("device_boot_events")
+6
View File
@@ -19,6 +19,9 @@ class Settings(BaseSettings):
mqtt_admin_username: str = "admin"
mqtt_admin_password: str = ""
mqtt_secret: str = "change-me-in-production"
# Accept the old shared "vesper" password for device-shaped usernames
# (boards on pre-HMAC firmware). Turn off once the logs show no users.
mqtt_allow_legacy_password: bool = True
mosquitto_password_file: str = "/etc/mosquitto/passwd"
mqtt_client_id: str = "bellsystems-admin-panel"
@@ -32,6 +35,9 @@ class Settings(BaseSettings):
# Local file storage
built_melodies_storage_path: str = "./storage/built_melodies"
firmware_storage_path: str = "./storage/firmware"
# xtensa-esp32-elf-addr2line for server-side crash decoding (firmware/elf_store.py).
# Empty = look it up on PATH; if absent, the console shows a copy-paste command instead.
addr2line_path: str = ""
flash_assets_storage_path: str = "./storage/flash_assets"
melody_binaries_storage_path: str = "./storage/melody_binaries"
melody_download_base_url: str = "http://melodies.bellsystems.net/download"
+60
View File
@@ -12,10 +12,40 @@ from database.pg_mqtt import (
get_heartbeats,
get_commands,
get_latest_heartbeats,
get_latest_heartbeat,
warm_latest_cache,
get_pending_command,
upsert_alert,
delete_alert,
get_alerts,
insert_alert_event,
get_latest_alert_events,
get_latest_alert_event,
get_alert_events,
insert_boot_event,
get_boot_events,
get_latest_boot_event,
merge_device_boot_history,
get_crash_events,
insert_ping_sample,
get_ping_samples,
get_latest_ping_samples,
insert_diagnostics_report,
get_diagnostics_reports,
get_latest_diagnostics_report,
get_latest_diagnostics_reports,
insert_report,
get_reports,
delete_device_logs,
delete_device_logs_filtered,
delete_device_heartbeats,
delete_device_commands,
delete_device_alert_events,
delete_device_current_alerts,
delete_device_boot_events,
delete_device_ping_samples,
delete_device_diagnostics_reports,
delete_device_reports,
partition_manager_loop,
ensure_current_partitions,
)
@@ -38,10 +68,40 @@ __all__ = [
"get_heartbeats",
"get_commands",
"get_latest_heartbeats",
"get_latest_heartbeat",
"warm_latest_cache",
"get_pending_command",
"upsert_alert",
"delete_alert",
"get_alerts",
"insert_alert_event",
"get_latest_alert_events",
"get_latest_alert_event",
"get_alert_events",
"insert_boot_event",
"get_boot_events",
"get_latest_boot_event",
"merge_device_boot_history",
"get_crash_events",
"insert_ping_sample",
"get_ping_samples",
"get_latest_ping_samples",
"insert_diagnostics_report",
"get_diagnostics_reports",
"get_latest_diagnostics_report",
"get_latest_diagnostics_reports",
"insert_report",
"get_reports",
"delete_device_logs",
"delete_device_logs_filtered",
"delete_device_heartbeats",
"delete_device_commands",
"delete_device_alert_events",
"delete_device_current_alerts",
"delete_device_boot_events",
"delete_device_ping_samples",
"delete_device_diagnostics_reports",
"delete_device_reports",
"partition_manager_loop",
"ensure_current_partitions",
]
+91
View File
@@ -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]
File diff suppressed because it is too large Load Diff
+241
View File
@@ -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
+116 -25
View File
@@ -1,7 +1,12 @@
from pydantic import BaseModel, Field
from pydantic import BaseModel, ConfigDict, Field
from typing import Any, Dict, List, Optional
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 ---
@@ -30,12 +35,14 @@ class DeviceTiers(str, Enum):
class DeviceNetworkSettings(BaseModel):
hostname: str = ""
useStaticIP: bool = False
ipAddress: Any = []
gateway: Any = []
subnet: Any = []
dns1: Any = []
dns2: Any = []
usesStaticIP: bool = False
# Dotted strings ("10.0.0.5"); "" = not set. The firmware's network.set_config
# MQTT command uses its own names (useStaticIP / ip) — convert at that boundary.
ipAddress: str = ""
gateway: str = ""
subnet: str = ""
dns1: str = ""
dns2: str = ""
class DeviceClockSettings(BaseModel):
@@ -49,14 +56,18 @@ class DeviceClockSettings(BaseModel):
quarterAlertsBell: int = 0
isDaySilenceOn: bool = False
isNightSilenceOn: bool = False
daySilenceFrom: str = ""
daySilenceTo: str = ""
nightSilenceFrom: str = ""
nightSilenceTo: str = ""
backlightTurnOnTime: str = ""
backlightTurnOffTime: str = ""
# Time of day carried in a Timestamp (v1 quirk); only the UTC time part matters.
daySilenceFrom: Optional[str] = None
daySilenceTo: Optional[str] = None
nightSilenceFrom: Optional[str] = None
nightSilenceTo: Optional[str] = None
backlightTurnOnTime: Optional[str] = None
backlightTurnOffTime: Optional[str] = None
isBacklightAutomationOn: bool = False
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):
@@ -67,9 +78,9 @@ class DeviceAttributes(BaseModel):
bellOutputs: List[int] = []
hammerTimings: List[int] = []
bellGuardOn: bool = False
bellGuardSafetyOn: bool = False
bellguardSafetyOn: bool = False # lower-case g: the exact key the apps read
warningsOn: bool = False
towerClockTime: str = ""
towerClockTime: Optional[str] = None
clockSettings: DeviceClockSettings = DeviceClockSettings()
deviceLocale: HelperMelodyTypes = HelperMelodyTypes.all
networkSettings: DeviceNetworkSettings = DeviceNetworkSettings()
@@ -80,7 +91,7 @@ class DeviceAttributes(BaseModel):
class DeviceSubInformation(BaseModel):
subscrTier: DeviceTiers = DeviceTiers.basic
subscrStart: str = ""
subscrStart: Optional[str] = None
subscrDuration: int = 0
maxUsers: int = 0
maxOutputs: int = 0
@@ -92,32 +103,74 @@ class DeviceStatistics(BaseModel):
perBellStrikes: List[int] = []
totalWarningsGiven: int = 0
warrantyActive: bool = False
warrantyStart: str = ""
warrantyStart: Optional[str] = None
warrantyPeriod: int = 0
maintainedOn: str = ""
maintainancePeriod: int = 0
maintainedOn: Optional[str] = None
maintainancePeriod: int = 0 # misspelled in v1 on purpose: the apps read this key
class HealthThresholdTier(BaseModel):
"""One severity tier's worth of metric thresholds. Two tiers (warning,
critical) make up DeviceHealthSettings — see there for why."""
restarts_per_week_threshold: int
rssi_floor_dbm: int
free_heap_floor_kb: int
cpu_temp_ceiling_c: int
class DeviceHealthSettings(BaseModel):
"""Per-device alert thresholds shown/edited on the Health tab's Settings
sub-tab. Purely advisory today — thresholds drive a client-computed
ok/warning/critical status icon, not any server-side alerting yet (no
email/push infra exists). Two severity tiers per metric (warning fires
first, critical is the harder breach) so the header status icon can show
orange vs. red rather than a single degraded/healthy binary.
offline_timeout_sec also feeds the Health tab's chart gap detection
(LineChart's gapThresholdMs) so both share one source of truth."""
warning: HealthThresholdTier = HealthThresholdTier(
restarts_per_week_threshold=6, rssi_floor_dbm=-80, free_heap_floor_kb=30, cpu_temp_ceiling_c=65,
)
critical: HealthThresholdTier = HealthThresholdTier(
restarts_per_week_threshold=12, rssi_floor_dbm=-90, free_heap_floor_kb=15, cpu_temp_ceiling_c=80,
)
offline_timeout_sec: int = 90
email_on_threshold: bool = False
push_on_crash_boot: bool = False
class MelodyMainItem(BaseModel):
"""Mirrors the Melody schema used in the melodies collection."""
information: dict = {}
default_settings: dict = {}
type: str = ""
url: str = ""
"""One melody as stored inside devices.device_melodies_all (v1 MelodyMainItem).
NOT the melodies/{id} document shape: the apps read camelCase keys here
(mainInformation / defaultSettings / settings / binaryUrl / melodyReference).
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 = ""
pid: str = ""
mainInformation: Dict[str, Any] = {}
defaultSettings: Dict[str, Any] = {}
settings: Dict[str, Any] = {}
binaryUrl: str = ""
# --- Request / Response schemas ---
class DeviceCreate(BaseModel):
device_name: str = ""
# Console-only friendly name — set by staff, independent of the name the
# end user gave the device in the app. Never shown to app users, never
# synced from/to device_name. Falls back to device_name when empty.
console_name: str = ""
device_photo: str = ""
device_location: str = ""
is_Online: bool = False
device_attributes: DeviceAttributes = DeviceAttributes()
device_subscription: DeviceSubInformation = DeviceSubInformation()
device_stats: DeviceStatistics = DeviceStatistics()
device_health_settings: DeviceHealthSettings = DeviceHealthSettings()
events_on: bool = False
device_location_coordinates: Any = None # GeoPoint dict {lat, lng} or legacy str
device_melodies_all: List[MelodyMainItem] = []
@@ -136,6 +189,7 @@ class DeviceCreate(BaseModel):
class DeviceUpdate(BaseModel):
device_name: Optional[str] = None
console_name: Optional[str] = None
device_photo: Optional[str] = None
device_location: Optional[str] = None
is_Online: Optional[bool] = None
@@ -143,6 +197,7 @@ class DeviceUpdate(BaseModel):
device_attributes: Optional[Dict[str, Any]] = None
device_subscription: Optional[Dict[str, Any]] = None
device_stats: Optional[Dict[str, Any]] = None
device_health_settings: Optional[Dict[str, Any]] = None
events_on: Optional[bool] = None
device_location_coordinates: Optional[Any] = None # dict {lat, lng} or legacy str
device_melodies_all: Optional[List[MelodyMainItem]] = None
@@ -179,7 +234,7 @@ class DeviceNoteUpdate(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 = ""
display_name: str = ""
email: str = ""
@@ -190,3 +245,39 @@ class DeviceUserInfo(BaseModel):
class DeviceUsersResponse(BaseModel):
users: List[DeviceUserInfo]
total: int
class ResetStatsRequest(BaseModel):
"""Which categories of QA/bench test data to clear before shipping a
device to a customer. Each flag is independent — callers check only the
boxes they want. device_stats (Firestore) and current_alerts both default
to False since they need extra care (current_alerts especially — see
ResetStatsResult.current_alerts note)."""
bell_stats: bool = False # Firestore device_stats: totalHammerStrikes, perBellStrikes
playback_stats: bool = False # Firestore device_stats: totalPlaybacks, totalWarningsGiven
device_logs: bool = False # Postgres device_logs
heartbeats: bool = False # Postgres heartbeats
commands: bool = False # Postgres commands
boot_events: bool = False # Postgres device_boot_events (console-side history)
alert_history: bool = False # Postgres device_alert_events
ping_samples: bool = False # Postgres device_ping_samples
diagnostics_reports: bool = False # Postgres device_diagnostics_reports
reports: bool = False # Postgres device_reports (control/reports history, e.g. bell_overload)
current_alerts: bool = False # Postgres device_alerts (LIVE state — opt-in only)
class ResetStatsResult(BaseModel):
"""Per-category outcome. Postgres/Firestore categories always run
(device connectivity doesn't matter); counts are rows deleted, or null
for categories that weren't requested."""
bell_stats: Optional[bool] = None
playback_stats: Optional[bool] = None
device_logs: Optional[int] = None
heartbeats: Optional[int] = None
commands: Optional[int] = None
boot_events: Optional[int] = None
alert_history: Optional[int] = None
ping_samples: Optional[int] = None
diagnostics_reports: Optional[int] = None
reports: Optional[int] = None
current_alerts: Optional[int] = None
+111 -22
View File
@@ -10,8 +10,10 @@ from devices.models import (
DeviceCreate, DeviceUpdate, DeviceInDB, DeviceListResponse,
DeviceUsersResponse, DeviceUserInfo,
DeviceNoteCreate, DeviceNoteUpdate,
ResetStatsRequest, ResetStatsResult,
)
from devices import service
from users import service as users_service
import database as mqtt_db
from mqtt.models import DeviceAlertEntry, DeviceAlertsResponse
from shared.firebase import get_db as get_firestore
@@ -25,7 +27,7 @@ CRM_COLLECTION = "crm_customers"
@router.get("", response_model=DeviceListResponse)
async def list_devices(
def list_devices(
search: Optional[str] = Query(None),
online: Optional[bool] = Query(None),
tier: Optional[str] = Query(None),
@@ -40,7 +42,7 @@ async def list_devices(
@router.get("/{device_id}", response_model=DeviceInDB)
async def get_device(
def get_device(
device_id: str,
_user: TokenPayload = Depends(require_permission("devices", "view")),
):
@@ -48,7 +50,7 @@ async def get_device(
@router.get("/{device_id}/users", response_model=DeviceUsersResponse)
async def get_device_users(
def get_device_users(
device_id: str,
_user: TokenPayload = Depends(require_permission("devices", "view")),
):
@@ -65,7 +67,7 @@ async def create_device(
):
device = service.create_device(body)
await log_action(db, _user.sub, _user.name or _user.email, "CREATE", "device",
device.device_id, device.device_name or device.device_id)
device.device_id, device.console_name or device.device_name or device.device_id)
return device
@@ -87,7 +89,7 @@ async def update_device(
if "tags" in body.model_fields_set and (old.tags or []) != (device.tags or []):
changes["tags"] = {"old": sorted(old.tags or []), "new": sorted(device.tags or [])}
await log_action(db, _user.sub, _user.name or _user.email, "UPDATE", "device",
device_id, device.device_name or device_id, changes=changes or None)
device_id, device.console_name or device.device_name or device_id, changes=changes or None)
return device
@@ -117,7 +119,7 @@ async def get_device_alerts(
# ─────────────────────────────────────────────────────────────────────────────
@router.get("/{device_id}/notes")
async def list_device_notes(
def list_device_notes(
device_id: str,
_user: TokenPayload = Depends(require_permission("devices", "view")),
):
@@ -137,7 +139,7 @@ async def list_device_notes(
@router.post("/{device_id}/notes", status_code=201)
async def create_device_note(
def create_device_note(
device_id: str,
body: DeviceNoteCreate,
_user: TokenPayload = Depends(require_permission("devices", "edit")),
@@ -161,7 +163,7 @@ async def create_device_note(
@router.put("/{device_id}/notes/{note_id}")
async def update_device_note(
def update_device_note(
device_id: str,
note_id: str,
body: DeviceNoteUpdate,
@@ -185,7 +187,7 @@ async def update_device_note(
@router.delete("/{device_id}/notes/{note_id}", status_code=204)
async def delete_device_note(
def delete_device_note(
device_id: str,
note_id: str,
_user: TokenPayload = Depends(require_permission("devices", "edit")),
@@ -208,7 +210,7 @@ class TagsUpdate(BaseModel):
@router.put("/{device_id}/tags", response_model=DeviceInDB)
async def update_device_tags(
def update_device_tags(
device_id: str,
body: TagsUpdate,
_user: TokenPayload = Depends(require_permission("devices", "edit")),
@@ -234,7 +236,7 @@ class AssignCustomerBody(BaseModel):
@router.get("/{device_id}/customer-search")
async def search_customers_for_device(
def search_customers_for_device(
device_id: str,
q: str = Query(""),
_user: TokenPayload = Depends(require_permission("devices", "view")),
@@ -355,7 +357,7 @@ async def unassign_device_from_customer(
# ─────────────────────────────────────────────────────────────────────────────
@router.get("/{device_id}/customer")
async def get_device_customer(
def get_device_customer(
device_id: str,
_user: TokenPayload = Depends(require_permission("devices", "view")),
):
@@ -397,7 +399,7 @@ class UserSearchResult(BaseModel):
@router.get("/{device_id}/user-search")
async def search_users_for_device(
def search_users_for_device(
device_id: str,
q: str = Query(""),
_user: TokenPayload = Depends(require_permission("devices", "view")),
@@ -437,14 +439,14 @@ async def add_user_to_device(
db: AsyncSession = Depends(get_pg_session),
):
"""Add a user reference to the device's user_list field."""
db = get_firestore()
device_ref = db.collection("devices").document(device_id)
fs = get_firestore()
device_ref = fs.collection("devices").document(device_id)
device_doc = device_ref.get()
if not device_doc.exists:
raise HTTPException(status_code=404, detail="Device not found")
# Verify user exists
user_doc = db.collection("users").document(body.user_id).get()
user_doc = fs.collection("users").document(body.user_id).get()
if not user_doc.exists:
raise HTTPException(status_code=404, detail="User not found")
@@ -460,10 +462,17 @@ async def add_user_to_device(
elif isinstance(entry, str):
existing_ids.add(entry.split("/")[-1])
# 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)
batch = fs.batch()
if body.user_id not in existing_ids:
user_ref = db.collection("users").document(body.user_id)
user_list.append(user_ref)
device_ref.update({"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)
service.stage_device_users_mirror(batch, device_ref, user_ref, linked=True)
batch.commit()
users_service.invalidate_mqtt_acl_cache(user_doc.to_dict())
await log_action(db, _user.sub, _user.name or _user.email, "UPDATE", "device",
device_id, device_id, meta={"action_detail": "user_added",
@@ -479,8 +488,8 @@ async def remove_user_from_device(
db: AsyncSession = Depends(get_pg_session),
):
"""Remove a user reference from the device's user_list field."""
db = get_firestore()
device_ref = db.collection("devices").document(device_id)
fs = get_firestore()
device_ref = fs.collection("devices").document(device_id)
device_doc = device_ref.get()
if not device_doc.exists:
raise HTTPException(status_code=404, detail="Device not found")
@@ -499,9 +508,89 @@ async def remove_user_from_device(
# Remove any entry that resolves to this user_id (handles both DocRef and string paths)
new_list = [entry for entry in user_list if not resolves_to(entry, user_id)]
device_ref.update({"user_list": new_list})
batch = fs.batch()
batch.update(device_ref, {"user_list": new_list})
user_ref = fs.collection("users").document(user_id)
user_doc = user_ref.get()
if user_doc.exists:
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()
if user_doc.exists:
users_service.invalidate_mqtt_acl_cache(user_doc.to_dict())
await log_action(db, _user.sub, _user.name or _user.email, "UPDATE", "device",
device_id, device_id, meta={"action_detail": "user_removed",
"user_id": user_id})
return {"status": "removed", "user_id": user_id}
@router.post("/{device_id}/reset-stats", response_model=ResetStatsResult)
async def reset_device_stats(
device_id: str,
body: ResetStatsRequest,
_user: TokenPayload = Depends(require_permission("devices", "edit")),
db: AsyncSession = Depends(get_pg_session),
):
"""Clears QA/bench test data accumulated before a device ships to a
customer. Only handles categories that don't require the device itself
to be online — Postgres history tables and Firestore device_stats
counters. The two firmware-side resets (telemetry.reset_boot_data,
logs.clear) are sent directly by the frontend over MQTT via the existing
command-ack flow, since they need the device online and this console
already has that round-trip built (see DeviceDetail.jsx's
sendMqttCommand) — duplicating it backend-side would just be a second,
inferior implementation of the same wait-for-device-reply logic.
Nothing here touches device identity, customer assignment, notes, tags,
warranty/maintenance fields, or audit logs — see ResetStatsRequest's
field list for exactly what's in scope.
"""
device = service.get_device(device_id)
serial = device.serial_number or device.device_id
result = ResetStatsResult()
# Firestore device_stats — field-level only. DeviceStatistics mixes true
# counters with warranty/maintenance fields in one object; a blanket
# clear would destroy warranty data, so only the 4 named counter fields
# are ever sent here (service.update_device writes field paths only, so
# every other key is untouched, including warrantyActive/warrantyStart/etc.).
stats_update = {}
if body.bell_stats:
stats_update["totalHammerStrikes"] = 0
stats_update["perBellStrikes"] = []
if body.playback_stats:
stats_update["totalPlaybacks"] = 0
stats_update["totalWarningsGiven"] = 0
if stats_update:
service.update_device(device_id, DeviceUpdate(device_stats=stats_update))
if body.bell_stats:
result.bell_stats = True
if body.playback_stats:
result.playback_stats = True
# Postgres — pure history/telemetry tables, per-device row deletes.
if body.device_logs:
result.device_logs = await mqtt_db.delete_device_logs(serial)
if body.heartbeats:
result.heartbeats = await mqtt_db.delete_device_heartbeats(serial)
if body.commands:
result.commands = await mqtt_db.delete_device_commands(serial)
if body.boot_events:
result.boot_events = await mqtt_db.delete_device_boot_events(serial)
if body.alert_history:
result.alert_history = await mqtt_db.delete_device_alert_events(serial)
if body.ping_samples:
result.ping_samples = await mqtt_db.delete_device_ping_samples(serial)
if body.diagnostics_reports:
result.diagnostics_reports = await mqtt_db.delete_device_diagnostics_reports(serial)
if body.reports:
result.reports = await mqtt_db.delete_device_reports(serial)
if body.current_alerts:
result.current_alerts = await mqtt_db.delete_device_current_alerts(serial)
await log_action(db, _user.sub, _user.name or _user.email, "UPDATE", "device",
device_id, device.console_name or device.device_name or serial,
meta={"action_detail": "reset_stats", "categories": body.model_dump()})
return result
+155 -164
View File
@@ -1,11 +1,12 @@
import secrets
import string
from datetime import datetime
from google.cloud.firestore_v1 import GeoPoint, DocumentReference
from google.cloud.firestore_v1 import DocumentReference
from google.cloud.firestore_v1.field_path import FieldPath
from shared.firebase import get_db
from shared.exceptions import NotFoundError
from devices import firestore_v1
from devices.models import DeviceCreate, DeviceUpdate, DeviceInDB
COLLECTION = "devices"
@@ -14,34 +15,6 @@ COLLECTION = "devices"
SN_CHARS = string.ascii_uppercase + string.digits
SN_SEGMENT_LEN = 4
# Clock/silence/backlight fields stored as Firestore Timestamps (written as datetime)
_TIMESTAMP_FIELD_NAMES = {
"daySilenceFrom", "daySilenceTo",
"nightSilenceFrom", "nightSilenceTo",
"backlightTurnOnTime", "backlightTurnOffTime",
}
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:
"""Generate a unique serial number in the format BS-XXXX-XXXX."""
seg1 = "".join(secrets.choice(SN_CHARS) for _ in range(SN_SEGMENT_LEN))
@@ -66,36 +39,6 @@ def _ensure_unique_serial(db) -> str:
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:
"""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."""
@@ -117,7 +60,7 @@ def _doc_to_device(doc) -> DeviceInDB:
"""
raw = doc.to_dict()
raw = _auto_upgrade_claimed(doc.reference, raw)
data = _sanitize_dict(raw)
data = firestore_v1.to_api(raw)
return DeviceInDB(id=doc.id, **data)
@@ -158,9 +101,10 @@ def list_devices(
if search:
search_lower = search.lower()
name_match = search_lower in (device.device_name or "").lower()
console_name_match = search_lower in (device.console_name or "").lower()
location_match = search_lower in (device.device_location or "").lower()
sn_match = search_lower in (device.serial_number or "").lower()
if not (name_match or location_match or sn_match):
if not (name_match or console_name_match or location_match or sn_match):
continue
results.append(device)
@@ -185,22 +129,31 @@ def create_device(data: DeviceCreate) -> DeviceInDB:
serial_number = _ensure_unique_serial(db)
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)
return DeviceInDB(id=doc_ref.id, **doc_data)
return _doc_to_device(doc_ref.get())
def _deep_merge(base: dict, overrides: dict) -> dict:
"""Recursively merge overrides into base, preserving unmentioned nested keys."""
result = dict(base)
for k, v in overrides.items():
if isinstance(v, dict) and isinstance(result.get(k), dict):
result[k] = _deep_merge(result[k], v)
def _leaf_field_paths(value: dict, prefix: tuple = ()) -> dict:
"""Flatten a nested map into {firestore field path: leaf value}.
Lists and scalars are leaves; a non-empty map is descended into, so writing
{"device_attributes": {"hasBells": True}} touches ONLY
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:
result[k] = v
return result
out[FieldPath(*path).to_api_repr()] = v
return out
def update_device(device_doc_id: str, data: DeviceUpdate) -> DeviceInDB:
@@ -211,34 +164,122 @@ def update_device(device_doc_id: str, data: DeviceUpdate) -> DeviceInDB:
if not doc.exists:
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
coords = update_data.get("device_location_coordinates")
if isinstance(coords, dict) and "lat" in coords and "lng" in coords:
update_data["device_location_coordinates"] = GeoPoint(coords["lat"], coords["lng"])
# Deep-merge nested structs so unmentioned sub-fields are preserved
# Nested structs are written field-by-field (dotted paths), so only the
# exact leaves the caller sent are touched. Rewriting the whole parent map
# (the old read-merge-write) clobbered sibling fields whenever two writes
# raced, or the FlutterFlow apps wrote in between our read and our write.
existing = doc.to_dict()
nested_keys = (
"device_attributes", "device_subscription", "device_stats",
"device_attributes", "device_subscription", "device_stats", "device_health_settings",
)
for key in nested_keys:
if key in update_data and isinstance(existing.get(key), dict):
update_data[key] = _deep_merge(existing[key], update_data[key])
if isinstance(update_data.get(key), dict) and update_data[key]:
update_data.update(_leaf_field_paths(update_data.pop(key), (key,)))
update_data = _restore_timestamps(update_data)
doc_ref.update(update_data)
if "user_list" not in update_data:
doc_ref.update(update_data)
else:
# A user_list change must also update each affected user's
# device_serials (MQTT ACL) and the device_users mirror, in the
# same atomic batch.
from users import service as users_service
new_ids = []
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)
mirror = device_users_by_user(doc_ref)
batch = db.batch()
batch.update(doc_ref, update_data)
touched = []
for user_id in (old_ids ^ set(new_ids)):
linked = user_id in new_ids
user_ref = db.collection("users").document(user_id)
user_doc = user_ref.get()
if not user_doc.exists:
if not linked:
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())
batch.commit()
for user_data in touched:
users_service.invalidate_mqtt_acl_cache(user_data)
updated_doc = doc_ref.get()
return _doc_to_device(updated_doc)
def get_device_users(device_doc_id: str) -> list[dict]:
"""Get users assigned to a device from the device_users sub-collection.
def user_list_entry_id(entry) -> str:
"""user_list entries are DocumentReferences, "users/{id}" paths or raw doc IDs."""
if isinstance(entry, DocumentReference):
return entry.id
if isinstance(entry, str):
return entry.strip().split("/")[-1]
return ""
Falls back to the user_list field on the device document if the
sub-collection is empty.
# ─── device_users sub-collection mirror ──────────────────────────────────────
# 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.
DEVICE_USERS_SUBCOLLECTION = "device_users"
# 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()
doc_ref = db.collection(COLLECTION).document(device_doc_id)
@@ -246,83 +287,33 @@ def get_device_users(device_doc_id: str) -> list[dict]:
if not doc.exists:
raise NotFoundError("Device")
# Try sub-collection first
sub_docs = list(doc_ref.collection("device_users").stream())
roles = {
uid: (snaps[0].to_dict() or {}).get("role", "")
for uid, snaps in device_users_by_user(doc_ref).items()
}
users = []
if sub_docs:
for sub_doc in sub_docs:
sub_data = sub_doc.to_dict()
role = sub_data.get("role", "")
user_ref = sub_data.get("user_reference")
# Resolve user reference
user_id = ""
display_name = ""
email = ""
photo_url = ""
if isinstance(user_ref, DocumentReference):
try:
user_doc = user_ref.get()
if user_doc.exists:
user_data = user_doc.to_dict()
user_id = user_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 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}")
seen = set()
for entry in (doc.to_dict() or {}).get("user_list") or []:
uid = user_list_entry_id(entry)
if not uid or uid in seen:
continue
seen.add(uid)
try:
user_doc = db.collection("users").document(uid).get()
except Exception as e:
print(f"[devices] Error resolving user_list entry {uid}: {e}")
continue
if not user_doc.exists:
continue
user_data = user_doc.to_dict() or {}
users.append({
"user_id": user_doc.id,
"display_name": user_data.get("display_name", ""),
"email": user_data.get("email", ""),
"role": roles.get(uid, ""),
"photo_url": user_data.get("photo_url", ""),
})
return users
+2 -1
View File
@@ -48,7 +48,8 @@ def _resolve_names(db, device_id: str | None, user_id: str | None) -> tuple[str,
if device_id and isinstance(device_id, str) and device_id.strip():
device_doc = db.collection("devices").document(device_id.strip()).get()
if device_doc.exists:
device_name = device_doc.to_dict().get("device_name", "")
device_data = device_doc.to_dict()
device_name = device_data.get("console_name") or device_data.get("device_name", "")
if user_id and isinstance(user_id, str) and user_id.strip():
user_doc = db.collection("users").document(user_id.strip()).get()
+129
View File
@@ -0,0 +1,129 @@
"""Firmware ELF symbol store + server-side crash decoding (firmware F-070).
Crash reports carry `elf_sha256`: the first 16 hex chars of the SHA-256 of the
crashing build's firmware.elf. ELFs uploaded here are stored under that same
key, so a crash can be matched to its exact build and its PC/backtrace
addresses decoded to function + file:line with xtensa addr2line.
Decoding is optional: it needs a matching ELF AND the xtensa-esp32-elf-addr2line
binary in the backend container (settings.addr2line_path, or on PATH). When
either is missing the console falls back to a copy-paste addr2line command.
"""
import hashlib
import json
import re
import shutil
import subprocess
from datetime import datetime, timezone
from pathlib import Path
from config import settings
from shared.exceptions import NotFoundError, ValidationError
ADDR2LINE_NAME = "xtensa-esp32-elf-addr2line"
_SHA_PREFIX = re.compile(r"^[0-9a-f]{16}$")
_MAX_ADDRESSES = 40
def _elf_dir() -> Path:
return Path(settings.firmware_storage_path) / "elf"
def elf_sha_prefix(data: bytes) -> str:
return hashlib.sha256(data).hexdigest()[:16]
def _check_sha(sha: str) -> str:
sha = (sha or "").lower()
if not _SHA_PREFIX.match(sha):
raise ValidationError("elf_sha256 must be 16 hex characters.")
return sha
def addr2line_path() -> str | None:
configured = getattr(settings, "addr2line_path", "") or ""
if configured and Path(configured).is_file():
return configured
return shutil.which(ADDR2LINE_NAME)
def validate_elf(data: bytes) -> None:
if not data.startswith(b"\x7fELF"):
raise ValidationError("Not an ELF file — upload the firmware.elf from the build, not the .bin.")
def save_elf(data: bytes, filename: str | None, uploaded_by: str | None,
firmware: dict | None = None) -> dict:
"""Store an ELF keyed by its sha256 prefix. Re-uploading the same file is a
no-op overwrite. `firmware` optionally records which release it belongs to."""
validate_elf(data)
sha = elf_sha_prefix(data)
d = _elf_dir()
d.mkdir(parents=True, exist_ok=True)
(d / f"{sha}.elf").write_bytes(data)
meta = {
"elf_sha256": sha,
"filename": filename or "firmware.elf",
"size": len(data),
"uploaded_at": datetime.now(timezone.utc).isoformat(),
"uploaded_by": uploaded_by,
"firmware": firmware,
}
(d / f"{sha}.json").write_text(json.dumps(meta), encoding="utf-8")
return meta
def get_elf_info(sha: str) -> dict:
"""Whether a matching ELF exists and whether the decoder is installed —
the crash view uses this to pick decode-in-console vs. copy-command."""
sha = _check_sha(sha)
meta_path = _elf_dir() / f"{sha}.json"
meta = None
if (_elf_dir() / f"{sha}.elf").is_file():
try:
meta = json.loads(meta_path.read_text(encoding="utf-8"))
except (OSError, ValueError):
meta = {"elf_sha256": sha}
return {
"elf_sha256": sha,
"exists": meta is not None,
"meta": meta,
"decoder_available": addr2line_path() is not None,
}
def decode(sha: str, addresses: list[int]) -> list[dict]:
"""Run addr2line -pfiaC over the addresses. Returns one entry per address:
{"address": "0x400D8A3F", "frames": ["func at file:line", "(inlined by) ..."]}."""
sha = _check_sha(sha)
elf = _elf_dir() / f"{sha}.elf"
if not elf.is_file():
raise NotFoundError("ELF")
tool = addr2line_path()
if tool is None:
raise ValidationError(f"{ADDR2LINE_NAME} is not installed on the server.")
addrs = [a for a in addresses if isinstance(a, int) and 0 <= a <= 0xFFFFFFFF][:_MAX_ADDRESSES]
if not addrs:
return []
hex_addrs = [f"0x{a:08X}" for a in addrs]
proc = subprocess.run(
[tool, "-pfiaC", "-e", str(elf), *hex_addrs],
capture_output=True, text=True, timeout=20,
)
if proc.returncode != 0:
raise ValidationError(f"addr2line failed: {proc.stderr.strip()[:300]}")
# With -a each address starts a new block "0x400d8a3f: func at file:line";
# -i adds " (inlined by) ..." continuation lines under it.
results: list[dict] = []
for line in proc.stdout.splitlines():
if not line.strip():
continue
m = re.match(r"^(0x[0-9a-fA-F]+):\s*(.*)$", line)
if m:
results.append({"address": f"0x{int(m.group(1), 16):08X}", "frames": [m.group(2).strip()]})
elif results:
results[-1]["frames"].append(line.strip())
return results
+51 -1
View File
@@ -8,7 +8,7 @@ from sqlalchemy.ext.asyncio import AsyncSession
from auth.models import TokenPayload
from auth.dependencies import require_permission
from firmware.models import FirmwareVersion, FirmwareListResponse, FirmwareMetadataResponse, UpdateType
from firmware import service
from firmware import service, elf_store
from database.postgres import get_pg_session
from shared.audit import log_action
@@ -29,10 +29,15 @@ async def upload_firmware(
release_note: Optional[str] = Form(None),
bespoke_uid: Optional[str] = Form(None),
file: UploadFile = File(...),
elf_file: Optional[UploadFile] = File(None),
_user: TokenPayload = Depends(require_permission("manufacturing", "add")),
db: AsyncSession = Depends(get_pg_session),
):
file_bytes = await file.read()
elf_bytes = await elf_file.read() if elf_file and elf_file.filename else None
if elf_bytes is not None:
# Validate before the release is created, so a wrong file doesn't leave a half-done upload.
elf_store.validate_elf(elf_bytes)
fw = service.upload_firmware(
hw_type=hw_type,
channel=channel,
@@ -44,11 +49,48 @@ async def upload_firmware(
release_note=release_note,
bespoke_uid=bespoke_uid,
)
if elf_bytes is not None:
elf_store.save_elf(elf_bytes, elf_file.filename, _user.name or _user.email,
firmware={"id": fw.id, "hw_type": hw_type, "channel": channel, "version": version})
await log_action(db, _user.sub, _user.name or _user.email, "CREATE", "firmware",
fw.id, f"{hw_type} v{version} ({channel})")
return fw
# ── Firmware ELF symbols (crash decoding, F-070) ─────────────────────────────
# Registered before the /{hw_type}/... routes. Viewing/decoding is gated on
# mqtt:view like the crash data itself; uploading is a firmware-release action.
class ElfDecodeRequest(BaseModel):
addresses: list[int]
@router.post("/elf", status_code=201)
async def upload_elf(
file: UploadFile = File(...),
_user: TokenPayload = Depends(require_permission("manufacturing", "add")),
):
data = await file.read()
return elf_store.save_elf(data, file.filename, _user.name or _user.email)
@router.get("/elf/{elf_sha256}")
def get_elf_info(
elf_sha256: str,
_user: TokenPayload = Depends(require_permission("mqtt", "view")),
):
return elf_store.get_elf_info(elf_sha256)
@router.post("/elf/{elf_sha256}/decode")
def decode_addresses(
elf_sha256: str,
body: ElfDecodeRequest,
_user: TokenPayload = Depends(require_permission("mqtt", "view")),
):
return {"elf_sha256": elf_sha256.lower(), "results": elf_store.decode(elf_sha256, body.addresses)}
@router.get("", response_model=FirmwareListResponse)
def list_firmware(
hw_type: Optional[str] = Query(None),
@@ -114,10 +156,14 @@ async def edit_firmware(
release_note: Optional[str] = Form(None),
bespoke_uid: Optional[str] = Form(None),
file: Optional[UploadFile] = File(None),
elf_file: Optional[UploadFile] = File(None),
_user: TokenPayload = Depends(require_permission("manufacturing", "add")),
db: AsyncSession = Depends(get_pg_session),
):
file_bytes = await file.read() if file and file.filename else None
elf_bytes = await elf_file.read() if elf_file and elf_file.filename else None
if elf_bytes is not None:
elf_store.validate_elf(elf_bytes)
fw = service.edit_firmware(
doc_id=firmware_id,
channel=channel,
@@ -129,6 +175,10 @@ async def edit_firmware(
bespoke_uid=bespoke_uid,
file_bytes=file_bytes,
)
if elf_bytes is not None:
elf_store.save_elf(elf_bytes, elf_file.filename, _user.name or _user.email,
firmware={"id": firmware_id, "hw_type": fw.hw_type if fw else None,
"channel": fw.channel if fw else None, "version": fw.version if fw else None})
await log_action(db, _user.sub, _user.name or _user.email, "UPDATE", "firmware",
firmware_id, f"{fw.hw_type} v{fw.version} ({fw.channel})" if fw else firmware_id)
return fw
+2 -1
View File
@@ -50,7 +50,8 @@ def _resolve_device_name(db, device_id: str) -> str:
try:
doc = db.collection("devices").document(device_id.strip()).get()
if doc.exists:
return doc.to_dict().get("device_name", "")
data = doc.to_dict()
return data.get("console_name") or data.get("device_name", "")
except Exception as e:
print(f"[helpdesk] Error resolving device name: {e}")
return ""
+7
View File
@@ -29,6 +29,7 @@ from notes.router import router as notes_router
from tickets.router import router as tickets_router
from audit.router import router as audit_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.mail_accounts import get_mail_accounts
from mqtt.client import mqtt_manager
@@ -78,6 +79,7 @@ app.include_router(notes_router)
app.include_router(tickets_router)
app.include_router(audit_router)
app.include_router(search_router)
app.include_router(timezones_router)
async def nextcloud_keepalive_loop():
@@ -114,8 +116,13 @@ async def startup():
await sqlite_init_db()
await melody_service.migrate_from_firestore()
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.purge_loop())
asyncio.create_task(mqtt_manager.ping_loop())
asyncio.create_task(nextcloud_keepalive_loop())
asyncio.create_task(crm_poll_loop())
sync_accounts = [a for a in get_mail_accounts() if a.get("sync_inbound") and a.get("imap_host")]
+16 -3
View File
@@ -80,20 +80,33 @@ class BatchResponse(BaseModel):
created_at: str
class DeviceUserSummary(BaseModel):
user_id: str
display_name: str = ""
email: str = ""
class DeviceInventoryItem(BaseModel):
id: str
serial_number: str
hw_type: str
hw_version: str
hw_family: str # board family code (BoardType value or bespoke UID) = firmware NVS "hw_family"
hw_revision: str # hardware revision, e.g. "1.0" = firmware NVS "hw_revision"
mfg_status: str
mfg_batch_id: Optional[str] = None
created_at: Optional[str] = None
owner: Optional[str] = None
assigned_to: Optional[str] = None
device_name: Optional[str] = None
# Console-only friendly name (mirrors devices.models.DeviceCreate.console_name).
# Only populated once a device has been claimed/onboarded in the app — null
# for freshly manufactured inventory, which is expected and should render
# as a graceful fallback (e.g. serial number) on the frontend.
console_name: Optional[str] = None
lifecycle_history: Optional[List["LifecycleEntry"]] = None
customer_id: Optional[str] = None
customer_name: Optional[str] = None
user_list: Optional[List[str]] = None
users: Optional[List[DeviceUserSummary]] = None
class DeviceInventoryListResponse(BaseModel):
@@ -121,7 +134,7 @@ class CustomerSearchResult(BaseModel):
class RecentActivityItem(BaseModel):
serial_number: str
hw_type: str
hw_family: str
mfg_status: str
owner: Optional[str] = None
updated_at: Optional[str] = None
+8 -4
View File
@@ -71,7 +71,9 @@ async def create_batch(
@router.get("/devices", response_model=DeviceInventoryListResponse)
def list_devices(
status: Optional[str] = Query(None),
hw_type: Optional[str] = Query(None),
hw_family: Optional[str] = Query(None),
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"),
search: Optional[str] = Query(None),
limit: int = Query(100, ge=1, le=500),
offset: int = Query(0, ge=0),
@@ -79,7 +81,9 @@ def list_devices(
):
items = service.list_devices(
status=status,
hw_type=hw_type,
hw_family=hw_family,
hw_families=hw_families,
has_users=has_users,
search=search,
limit=limit,
offset=offset,
@@ -601,7 +605,7 @@ def download_bootloader(
):
"""Return the bootloader.bin for this device's hw_type (flashed at 0x1000)."""
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:
data = service.get_flash_asset(hw_type, "bootloader.bin")
except NotFoundError as e:
@@ -621,7 +625,7 @@ def download_partitions(
):
"""Return the partitions.bin for this device's hw_type (flashed at 0x8000)."""
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:
data = service.get_flash_asset(hw_type, "partitions.bin")
except NotFoundError as e:
+93 -19
View File
@@ -11,9 +11,11 @@ from shared.firebase import get_db
from shared.exceptions import NotFoundError
from utils.serial_number import generate_serial
from utils.nvs_generator import generate as generate_nvs_binary
from manufacturing.models import BatchCreate, BatchResponse, DeviceInventoryItem, DeviceStatusUpdate, DeviceAssign, ManufacturingStats, RecentActivityItem, BOARD_TYPE_LABELS
from manufacturing.models import BatchCreate, BatchResponse, DeviceInventoryItem, DeviceStatusUpdate, DeviceAssign, ManufacturingStats, RecentActivityItem, BOARD_TYPE_LABELS, DeviceUserSummary
COLLECTION = "devices"
CRM_COLLECTION = "crm_customers"
USERS_COLLECTION = "users"
_BATCH_ID_CHARS = string.ascii_uppercase + string.digits
@@ -45,7 +47,7 @@ def _resolve_user_list(raw_list: list) -> list[str]:
return result
def _doc_to_inventory_item(doc) -> DeviceInventoryItem:
def _doc_to_inventory_item(doc, customer_names: dict | None = None, user_infos: dict | None = None) -> DeviceInventoryItem:
data = doc.to_dict() or {}
created_raw = data.get("created_at")
if isinstance(created_raw, datetime):
@@ -53,23 +55,68 @@ def _doc_to_inventory_item(doc) -> DeviceInventoryItem:
else:
created_str = str(created_raw) if created_raw else None
customer_names = customer_names or {}
user_infos = user_infos or {}
user_ids = _resolve_user_list(data.get("user_list") or [])
users = [user_infos[uid] for uid in user_ids if uid in user_infos]
customer_id = data.get("customer_id")
return DeviceInventoryItem(
id=doc.id,
serial_number=data.get("serial_number", ""),
hw_type=data.get("hw_type", ""),
hw_version=data.get("hw_version", ""),
# hw_type / hw_version: names used before 2026-11-08 (kept as read fallback)
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_batch_id=data.get("mfg_batch_id"),
created_at=created_str,
owner=data.get("owner"),
assigned_to=data.get("assigned_to"),
device_name=data.get("device_name") or None,
console_name=data.get("console_name") or None,
lifecycle_history=data.get("lifecycle_history") or [],
customer_id=data.get("customer_id"),
user_list=_resolve_user_list(data.get("user_list") or []),
customer_id=customer_id,
customer_name=customer_names.get(customer_id) if customer_id else None,
user_list=user_ids,
users=users,
)
def _bulk_resolve_names(db, docs_data: list[dict]) -> tuple[dict, dict]:
"""Batch-resolve customer names and user summaries referenced across a
list of device docs, so listing N devices costs a handful of get_all()
calls instead of an N+1 Firestore round trip per device."""
customer_ids = {d.get("customer_id") for d in docs_data if d.get("customer_id")}
user_ids = {uid for d in docs_data for uid in _resolve_user_list(d.get("user_list") or [])}
customer_names: dict[str, str] = {}
if customer_ids:
refs = [db.collection(CRM_COLLECTION).document(cid) for cid in customer_ids]
for snap in db.get_all(refs):
if not snap.exists:
continue
cdata = snap.to_dict() or {}
name = " ".join(filter(None, [cdata.get("name"), cdata.get("surname")])) or cdata.get("email") or snap.id
customer_names[snap.id] = name
user_infos: dict[str, DeviceUserSummary] = {}
if user_ids:
refs = [db.collection(USERS_COLLECTION).document(uid) for uid in user_ids]
for snap in db.get_all(refs):
if not snap.exists:
continue
udata = snap.to_dict() or {}
user_infos[snap.id] = DeviceUserSummary(
user_id=snap.id,
display_name=udata.get("display_name") or "",
email=udata.get("email") or "",
)
return customer_names, user_infos
def create_batch(data: BatchCreate) -> BatchResponse:
db = get_db()
existing_sns = _get_existing_sns(db)
@@ -88,8 +135,11 @@ def create_batch(data: BatchCreate) -> BatchResponse:
db.collection(COLLECTION).add({
"serial_number": sn,
"hw_type": data.board_type.value,
"hw_version": data.board_version,
"device_id": sn, # schema v1 / D1: both apps connect over MQTT with device_id
# Same names as the firmware NVS keys.
"hw_family": data.board_type.value,
"hw_revision": data.board_version,
"mfg_status": "manufactured",
"mfg_batch_id": batch_id,
"created_at": now,
@@ -122,7 +172,9 @@ def create_batch(data: BatchCreate) -> BatchResponse:
def list_devices(
status: str | None = None,
hw_type: str | None = None,
hw_family: str | None = None,
hw_families: list[str] | None = None,
has_users: bool | None = None,
search: str | None = None,
limit: int = 100,
offset: int = 0,
@@ -132,11 +184,28 @@ def list_devices(
if status:
query = query.where("mfg_status", "==", status)
if hw_type:
query = query.where("hw_type", "==", hw_type)
if hw_family:
query = query.where("hw_family", "==", hw_family)
docs = list(query.stream())
items = [_doc_to_inventory_item(doc) for doc in docs]
docs_data = [doc.to_dict() or {} for doc in docs]
if hw_families:
family_set = set(hw_families)
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_data = [docs_data[i] for i in keep]
if has_users is not None:
keep = [
i for i, d in enumerate(docs_data)
if bool(d.get("user_list")) == has_users
]
docs = [docs[i] for i in keep]
docs_data = [docs_data[i] for i in keep]
customer_names, user_infos = _bulk_resolve_names(db, docs_data)
items = [_doc_to_inventory_item(doc, customer_names, user_infos) for doc in docs]
if search:
search_lower = search.lower()
@@ -145,6 +214,10 @@ def list_devices(
if search_lower in (item.serial_number or "").lower()
or search_lower in (item.owner or "").lower()
or search_lower in (item.mfg_batch_id or "").lower()
or search_lower in (item.device_name or "").lower()
or search_lower in (item.console_name or "").lower()
or search_lower in (item.customer_name or "").lower()
or any(search_lower in (u.display_name or "").lower() or search_lower in (u.email or "").lower() for u in (item.users or []))
]
return items[offset: offset + limit]
@@ -155,7 +228,9 @@ def get_device_by_sn(sn: str) -> DeviceInventoryItem:
docs = list(db.collection(COLLECTION).where("serial_number", "==", sn).limit(1).stream())
if not docs:
raise NotFoundError("Device")
return _doc_to_inventory_item(docs[0])
doc = docs[0]
customer_names, user_infos = _bulk_resolve_names(db, [doc.to_dict() or {}])
return _doc_to_inventory_item(doc, customer_names, user_infos)
def update_device_status(sn: str, data: DeviceStatusUpdate, set_by: str | None = None) -> DeviceInventoryItem:
@@ -201,8 +276,8 @@ def get_nvs_binary(sn: str, hw_type_override: str | None = None, hw_revision_ove
item = get_device_by_sn(sn)
return generate_nvs_binary(
serial_number=item.serial_number,
hw_family=hw_type_override if hw_type_override else item.hw_type,
hw_revision=hw_revision_override if hw_revision_override else item.hw_version,
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_revision,
legacy=legacy,
)
@@ -260,7 +335,7 @@ def assign_device(sn: str, data: DeviceAssign) -> DeviceInventoryItem:
for item in owned_items
)
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({
"type": "console_device",
"console_device": {
@@ -330,7 +405,7 @@ def get_stats() -> ManufacturingStats:
activity_candidates.append(RecentActivityItem(
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,
owner=data.get("owner"),
updated_at=ts_str,
@@ -490,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."""
from firmware.service import get_latest
item = get_device_by_sn(sn)
hw_type = item.hw_type.lower()
latest = get_latest(hw_type, "stable")
latest = get_latest(item.hw_family.lower(), "stable")
# download_url is a relative path like /api/firmware/vs/stable/1.4.2/firmware.bin
return latest.download_url
+89
View File
@@ -0,0 +1,89 @@
"""
Firebase app-user lookup for the MQTT auth/ACL endpoints.
App users connect to Mosquitto as "app_<firebase_uid>". Their allowed
devices come from the `device_serials` array on their `users` doc.
User docs are resolved by the `uid` FIELD, never by document ID: docs created
by the Console (users.service.create_user) get random IDs via .add(), while
FlutterFlow uses the Firebase uid as the doc ID.
Per-message ACL checks would otherwise hit Firestore on every publish and
delivery, so lookups are cached in-process for CACHE_TTL_SECONDS. Anything
that changes a user's device_serials or status calls invalidate(uid).
"""
import logging
import threading
import time
from dataclasses import dataclass
from shared.firebase import get_db
logger = logging.getLogger("mqtt.app_users")
USERS_COLLECTION = "users"
CACHE_TTL_SECONDS = 60.0
@dataclass(frozen=True)
class AppUser:
uid: str
blocked: bool
device_serials: frozenset[str]
_cache: dict[str, tuple[float, AppUser | None]] = {}
_lock = threading.Lock()
def _load(uid: str) -> AppUser | None:
db = get_db()
if db is None:
raise RuntimeError("Firestore not initialized")
docs = list(db.collection(USERS_COLLECTION).where("uid", "==", uid).limit(5).stream())
if not docs:
return None
if len(docs) > 1:
# Duplicate profiles for one Firebase account: be conservative on
# blocked, permissive on devices (union), and make it visible.
logger.warning("Multiple user docs share uid=%s: %s", uid, [d.id for d in docs])
blocked = False
serials: set[str] = set()
for doc in docs:
data = doc.to_dict() or {}
if data.get("status") == "blocked":
blocked = True
serials.update(s for s in (data.get("device_serials") or []) if isinstance(s, str) and s)
return AppUser(uid=uid, blocked=blocked, device_serials=frozenset(serials))
def get_app_user(uid: str, *, use_cache: bool = True) -> AppUser | None:
"""Return the app user for a Firebase uid, or None if no user doc has that uid.
use_cache=False forces a Firestore read (and refreshes the cache).
"""
now = time.monotonic()
if use_cache:
with _lock:
hit = _cache.get(uid)
if hit and hit[0] > now:
return hit[1]
user = _load(uid)
with _lock:
_cache[uid] = (now + CACHE_TTL_SECONDS, user)
return user
def invalidate(uid: str) -> None:
with _lock:
_cache.pop(uid, None)
def clear_cache() -> None:
with _lock:
_cache.clear()
+178 -12
View File
@@ -9,8 +9,10 @@ Password strategy: HMAC-SHA256(MQTT_SECRET, username)[:32]
- Deterministic: no storage needed, re-derive on every auth check
- Rotating MQTT_SECRET invalidates all passwords at once if needed
Transition support: during rollout, the legacy password "vesper" is also
accepted so that devices still on old firmware stay connected.
Transition support: while MQTT_ALLOW_LEGACY_PASSWORD is on (default), the
legacy password "vesper" is also accepted for device-shaped usernames so
boards still on old firmware stay connected. Each such login is logged
(once per username per hour) to show which boards still depend on it.
User types handled:
- Device users (e.g. "PV25L22BP01R01", "PV-26A18-BC02R-X7KQA"):
@@ -18,21 +20,49 @@ User types handled:
- Kiosk users (e.g. "PV25L22BP01R01-kiosk"):
Same HMAC auth derived from the full kiosk username.
ACL: allowed to access topics of their base device (suffix stripped).
- App users (e.g. "app_<firebase_uid>"):
Remote phone app. Password = a Firebase ID token, verified with
firebase_admin (revocation checked). No per-user MQTT accounts exist.
Never accepted via HMAC or the legacy password.
- admin, bonamin, NodeRED, and other non-device users:
These connect via the passwd file backend (go-auth file backend).
They never reach this HTTP backend — go-auth resolves them first.
The ACL endpoint below handles them defensively anyway (superuser list).
The handlers are plain `def` on purpose: they make blocking Firestore /
Firebase Auth calls, which FastAPI then runs in its threadpool instead of
stalling the event loop.
"""
import hmac
import hashlib
import logging
import re
import threading
import time
from fastapi import APIRouter, Form, Response
from firebase_admin import auth as firebase_auth
from config import settings
from mqtt import app_users
logger = logging.getLogger("mqtt.auth")
router = APIRouter(prefix="/mqtt/auth", tags=["mqtt-auth"])
LEGACY_PASSWORD = "vesper"
APP_USER_PREFIX = "app_"
# Uppercase alphanumeric segments joined by "-", optional "-kiosk" suffix.
# Covers PV25L22BP01R01, PV-26A18-BC02R-X7KQA, BSVSPR-26C13X-STD01R-X7KQA.
DEVICE_USERNAME_RE = re.compile(r"[A-Z0-9]{2,}(?:-[A-Z0-9]+)*(?:-kiosk)?")
LEGACY_LOG_INTERVAL_SECONDS = 3600
_legacy_log_last: dict[str, float] = {}
_legacy_log_lock = threading.Lock()
# Users authenticated via passwd file (go-auth file backend).
# If they somehow reach the HTTP ACL endpoint, grant full access.
SUPERUSERS = {"admin", "bonamin", "NodeRED"}
@@ -47,18 +77,44 @@ def _derive_password(username: str) -> str:
).hexdigest()[:32]
def _is_device_username(username: str) -> bool:
"""Board serial (optionally with -kiosk), e.g. "PV25L22BP01R01",
"BSVSPR-26C13X-STD01R-X7KQA", "PV25L22BP01R01-kiosk"."""
return bool(DEVICE_USERNAME_RE.fullmatch(username))
def _log_legacy_auth(username: str) -> None:
"""Log a legacy-password login, at most once per username per interval."""
now = time.monotonic()
with _legacy_log_lock:
last = _legacy_log_last.get(username)
if last is not None and now - last < LEGACY_LOG_INTERVAL_SECONDS:
return
_legacy_log_last[username] = now
logger.warning("MQTT legacy password accepted for %s — board still on pre-HMAC firmware", username)
def _is_valid_password(username: str, password: str) -> bool:
"""
Accept the password if it matches either:
- The HMAC-derived password (new firmware)
- The legacy hardcoded "vesper" password (old firmware, transition period)
Remove the legacy check in Stage 7 once all devices are on new firmware.
- The legacy hardcoded "vesper" password (old firmware, transition period),
only when MQTT_ALLOW_LEGACY_PASSWORD is on and the username is
device-shaped (never app_ users or unknown shapes).
"""
expected = _derive_password(username)
hmac_ok = hmac.compare_digest(expected, password)
legacy_ok = hmac.compare_digest(LEGACY_PASSWORD, password)
return hmac_ok or legacy_ok
if hmac.compare_digest(expected, password):
return True
if (
settings.mqtt_allow_legacy_password
and _is_device_username(username)
and hmac.compare_digest(LEGACY_PASSWORD, password)
):
_log_legacy_auth(username)
return True
return False
def _base_sn(username: str) -> str:
@@ -72,8 +128,52 @@ def _base_sn(username: str) -> str:
return username
def _deny_app(username: str, reason: str) -> Response:
# Never log the password — for app users it is a bearer token.
logger.warning("MQTT app auth denied for %s: %s", username, reason)
return Response(status_code=403)
def _auth_app_user(username: str, token: str) -> Response:
"""Authenticate "app_<firebase_uid>" with a Firebase ID token as password."""
uid = username[len(APP_USER_PREFIX):]
if not uid:
return _deny_app(username, "empty uid")
if not token:
return _deny_app(username, "empty token")
try:
decoded = firebase_auth.verify_id_token(token, check_revoked=True)
except firebase_auth.RevokedIdTokenError:
return _deny_app(username, "token revoked")
except firebase_auth.ExpiredIdTokenError:
return _deny_app(username, "token expired")
except firebase_auth.UserDisabledError:
return _deny_app(username, "firebase account disabled")
except firebase_auth.InvalidIdTokenError as e:
return _deny_app(username, f"invalid token ({type(e).__name__})")
except Exception as e:
return _deny_app(username, f"token verification failed ({type(e).__name__})")
if decoded.get("uid") != uid:
return _deny_app(username, "token uid does not match username")
try:
# Fresh read on CONNECT (also refreshes the ACL cache).
user = app_users.get_app_user(uid, use_cache=False)
except Exception as e:
return _deny_app(username, f"user lookup failed ({type(e).__name__})")
if user is None:
return _deny_app(username, "no user doc with this uid")
if user.blocked:
return _deny_app(username, "user is blocked")
return Response(status_code=200)
@router.post("/user")
async def mqtt_auth_user(
def mqtt_auth_user(
username: str = Form(...),
password: str = Form(...),
clientid: str = Form(default=""),
@@ -84,37 +184,103 @@ async def mqtt_auth_user(
Username = device SN (new format: "PV-26A18-BC02R-X7KQA", old format: "PV25L22BP01R01")
or kiosk variant: "PV25L22BP01R01-kiosk"
or app user: "app_<firebase_uid>"
Password = HMAC-derived (new firmware) or "vesper" (legacy firmware)
or, for app users, a Firebase ID token
Note: admin, bonamin and NodeRED authenticate via the go-auth passwd file backend
and never reach this endpoint.
"""
if username.startswith(APP_USER_PREFIX):
return _auth_app_user(username, password)
if _is_valid_password(username, password):
return Response(status_code=200)
return Response(status_code=403)
# Mosquitto access values as passed through by go-auth (`acc`).
ACC_READ = 1 # message delivery to the client
ACC_WRITE = 2 # publish
ACC_SUBSCRIBE = 4 # subscribe
# App-user topic allowlist, relative to vesper/{serial}/
APP_WRITE_TOPICS = frozenset({"control/command"})
APP_READ_TOPICS = frozenset({"control/ack", "status/heartbeat", "status/playback"})
def _app_acl_allowed(username: str, clientid: str, topic: str, acc: int) -> tuple[bool, str]:
"""ACL decision for "app_<uid>". Returns (allowed, reason)."""
uid = username[len(APP_USER_PREFIX):]
if not uid:
return False, "empty uid"
# Client id must be owned by this user, so one user can't take over
# (and disconnect) another user's session by reusing its client id.
if not clientid.startswith(f"{APP_USER_PREFIX}{uid}_"):
return False, f"clientid {clientid!r} not prefixed with app_<uid>_"
if "+" in topic or "#" in topic:
return False, "wildcards not allowed"
parts = topic.split("/")
if len(parts) != 4 or parts[0] != "vesper" or not parts[1]:
return False, "topic not vesper/{serial}/<a>/<b>"
serial, leaf = parts[1], f"{parts[2]}/{parts[3]}"
if acc == ACC_WRITE:
if leaf not in APP_WRITE_TOPICS:
return False, "publish not allowed on this topic"
elif acc in (ACC_READ, ACC_SUBSCRIBE):
if leaf not in APP_READ_TOPICS:
return False, "read/subscribe not allowed on this topic"
else:
return False, f"unsupported acc={acc}"
try:
user = app_users.get_app_user(uid)
except Exception as e:
return False, f"user lookup failed ({type(e).__name__})"
if user is None:
return False, "no user doc with this uid"
if user.blocked:
return False, "user is blocked"
if serial not in user.device_serials:
return False, "serial not assigned to user"
return True, ""
@router.post("/acl")
async def mqtt_auth_acl(
def mqtt_auth_acl(
username: str = Form(...),
topic: str = Form(...),
clientid: str = Form(default=""),
acc: int = Form(...), # 1 = subscribe, 2 = publish, 3 = subscribe+publish
acc: int = Form(...), # 1 = read (delivery), 2 = write (publish), 4 = subscribe
):
"""
Called by Mosquitto on every SUBSCRIBE and PUBLISH.
Called by Mosquitto on every SUBSCRIBE, PUBLISH and message delivery.
Returns 200 to allow, 403 to deny.
Topic pattern: vesper/{sn}/...
- Device users: may only access their own SN segment
- Kiosk users: stripped of -kiosk suffix, then same rule applies
- App users (app_<uid>): only their assigned serials, only the
command/ack/heartbeat/playback topics — see _app_acl_allowed
- Superusers (bonamin, NodeRED): full access
"""
# Superusers get full access (shouldn't reach here but handled defensively)
if username in SUPERUSERS:
return Response(status_code=200)
if username.startswith(APP_USER_PREFIX):
allowed, reason = _app_acl_allowed(username, clientid, topic, acc)
if allowed:
return Response(status_code=200)
logger.info("MQTT app ACL denied for %s (acc=%s, topic=%s): %s", username, acc, topic, reason)
return Response(status_code=403)
# Derive the base SN (handles -kiosk suffix)
base = _base_sn(username)
+68 -9
View File
@@ -1,12 +1,19 @@
import json
import logging
import asyncio
import time
from typing import Set
import paho.mqtt.client as paho_mqtt
from config import settings
logger = logging.getLogger("mqtt.client")
PING_INTERVAL_SECONDS = 60
# Only devices heard from within this window get pinged — no point spending
# broker traffic/RTT samples on a device that's already known offline; its
# heartbeat-derived "online" state will already reflect that on the console.
PING_ONLINE_WINDOW_SECONDS = 90
class MqttManager:
"""Singleton MQTT client manager."""
@@ -61,12 +68,17 @@ class MqttManager:
if reason_code == 0:
self._connected = True
logger.info("MQTT connected, subscribing to topics")
# v2 topic set — see vesper_mqtt_topic_spec_v2.md in the firmware repo.
# control/command is inbound-to-device only; the console never subscribes to it.
client.subscribe([
("vesper/+/data", 1),
("vesper/+/control/ack", 1),
("vesper/+/control/reports", 1),
("vesper/+/status/heartbeat", 1),
("vesper/+/status/alerts", 1),
("vesper/+/status/info", 0),
("vesper/+/logs", 1),
("vesper/+/status/playback", 1),
("vesper/+/system/alerts", 1),
("vesper/+/system/info", 1),
("vesper/+/system/logs", 0),
("vesper/+/system/metrics", 0),
])
else:
logger.error(f"MQTT connection failed: {reason_code}")
@@ -87,10 +99,17 @@ class MqttManager:
serial = parts[1]
topic_type = "/".join(parts[2:])
# The broker sets retain=1 only on a message it replays from its
# retained store because we just (re)subscribed: a stale snapshot
# of the device's last state, not something that just happened.
# Live publishes always arrive with retain=0, even on topics the
# firmware publishes retained. Every backend restart (and every
# uvicorn --reload) replays these for every device.
retained = bool(msg.retain)
if self._loop and self._loop.is_running():
asyncio.run_coroutine_threadsafe(
self._process_message(serial, topic_type, payload, topic),
self._process_message(serial, topic_type, payload, topic, retained),
self._loop,
)
except json.JSONDecodeError:
@@ -99,15 +118,16 @@ class MqttManager:
logger.error(f"Error processing MQTT message: {e}")
async def _process_message(self, serial: str, topic_type: str,
payload: dict, raw_topic: str):
payload: dict, raw_topic: str, retained: bool = False):
from mqtt.logger import handle_message
await handle_message(serial, topic_type, payload)
await handle_message(serial, topic_type, payload, retained=retained)
ws_data = {
"type": topic_type,
"device_serial": serial,
"payload": payload,
"topic": raw_topic,
"retained": retained,
}
await self._broadcast_ws(ws_data)
@@ -132,10 +152,49 @@ class MqttManager:
if not self._client or not self._connected:
return False
topic = f"vesper/{device_serial}/control"
payload = json.dumps({"cmd": cmd, "contents": contents})
topic = f"vesper/{device_serial}/control/command"
payload = json.dumps({"v": 2, "cmd": cmd, "contents": contents})
result = self._client.publish(topic, payload, qos=1)
return result.rc == paho_mqtt.MQTT_ERR_SUCCESS
async def ping_loop(self):
"""Periodically pings every recently-online device with a client
timestamp so mqtt/logger.py::_handle_data_response can compute RTT
from the echoed pong. Deliberately bypasses db.insert_command — this
is a background health check, not a user-initiated command, and
shouldn't clutter the Control tab's command history.
Only available on RTC-equipped firmware builds (see API Reference —
ping is compiled out on agnus/agnus-mini). A pong simply never
arrives for those devices, so no ping-latency samples accumulate for
them; the Health tab handles an empty series as "unsupported".
"""
while True:
await asyncio.sleep(PING_INTERVAL_SECONDS)
try:
await self._ping_online_devices()
except Exception as e:
logger.error(f"Ping loop error: {e}")
async def _ping_online_devices(self):
import database as db
from mqtt import presence
heartbeats = await db.get_latest_heartbeats()
now = time.time()
for hb in heartbeats:
try:
from datetime import datetime
received = datetime.fromisoformat(hb["received_at"])
age = now - received.timestamp()
except (ValueError, TypeError, KeyError):
continue
if age > PING_ONLINE_WINDOW_SECONDS or presence.is_marked_offline(hb["device_serial"]):
continue
self.publish_command(
device_serial=hb["device_serial"],
cmd="ping",
contents={"ts": int(now * 1000)},
)
mqtt_manager = MqttManager()
+90
View File
@@ -0,0 +1,90 @@
"""Fleet-wide crash grouping (firmware F-070).
Groups fault boots so recurring crash types are visible across devices:
- with an abort_msg: by the message with hex addresses stripped, since the
same assert/abort reports different addresses per build;
- otherwise: by faulting task + Xtensa exception cause;
- fault resets with no coredump and no abort_msg: by reset reason alone.
When abort_msg is present, pc/exc_cause/exc_vaddr describe the abort()
mechanism (always StoreProhibited at 0x0), so they must NOT drive the grouping.
"""
import re
# Xtensa EXCCAUSE values the ESP32 actually produces.
EXC_CAUSE_NAMES = {
0: "IllegalInstruction",
2: "InstructionFetchError",
3: "LoadStoreError",
6: "IntegerDivideByZero",
9: "LoadStoreAlignment",
28: "LoadProhibited",
29: "StoreProhibited",
}
_HEX = re.compile(r"0x[0-9a-fA-F]+")
_SPACES = re.compile(r"\s+")
def normalize_abort_msg(msg: str) -> str:
return _SPACES.sub(" ", _HEX.sub("0x…", msg)).strip()
def exc_cause_name(cause) -> str:
if cause is None:
return "Unknown exception"
return EXC_CAUSE_NAMES.get(cause, f"Exception cause {cause}")
def group_key(event: dict) -> tuple[str, str, str]:
"""(key, kind, title) for one boot event."""
crash = event.get("crash") or {}
pre = event.get("pre_crash") or {}
abort_msg = pre.get("abort_msg")
if abort_msg:
norm = normalize_abort_msg(abort_msg)
return f"abort:{norm}", "abort", norm
task = crash.get("task", event.get("crash_task"))
cause = crash.get("exc_cause", event.get("crash_exc_cause"))
if task is not None or cause is not None:
title = f"{exc_cause_name(cause)} in {task or 'unknown task'}"
return f"exc:{task}:{cause}", "exception", title
reason = event.get("reset_reason") or "UNKNOWN"
return f"reason:{reason}", "reason", f"{reason.replace('_', ' ')} (no coredump)"
def group_crashes(events: list[dict]) -> list[dict]:
"""events must be newest-first (as get_crash_events returns them)."""
groups: dict[str, dict] = {}
for ev in events:
key, kind, title = group_key(ev)
g = groups.get(key)
if g is None:
g = groups[key] = {
"key": key,
"kind": kind,
"title": title,
"count": 0,
"first_at": ev["occurred_at"],
"last_at": ev["occurred_at"],
"latest": ev,
"devices": {},
}
g["count"] += 1
g["first_at"] = ev["occurred_at"] # newest-first input, so the last seen is the oldest
d = g["devices"].setdefault(ev["device_serial"], {
"device_serial": ev["device_serial"], "count": 0, "last_at": ev["occurred_at"],
})
d["count"] += 1
result = []
for g in groups.values():
devices = sorted(g["devices"].values(), key=lambda d: (-d["count"], d["device_serial"]))
result.append({**g, "devices": devices, "device_count": len(devices)})
# Most frequent first; ties broken by most recent (two stable sorts).
result.sort(key=lambda g: g["last_at"], reverse=True)
result.sort(key=lambda g: g["count"], reverse=True)
return result
+199 -25
View File
@@ -1,5 +1,7 @@
import logging
import time
import database as db
from mqtt import presence
logger = logging.getLogger("mqtt.logger")
@@ -14,36 +16,70 @@ LEVEL_MAP = {
}
async def handle_message(serial: str, topic_type: str, payload: dict):
async def handle_message(serial: str, topic_type: str, payload: dict,
retained: bool = False):
"""`retained` is True when the broker replayed this from its retained store
on (re)subscribe: a stale copy of the device's last message, NOT a new
event. The firmware publishes status/heartbeat, system/alerts, system/info
and status/playback retained, so every backend restart replays them for
every device that ever connected. Handlers for those topics must never
record a retained replay as something that just happened."""
try:
# v2 topic set — see project-vesper's vesper_mqtt_topic_spec_v2.md.
if topic_type == "status/heartbeat":
await _handle_heartbeat(serial, payload)
elif topic_type == "status/alerts":
await _handle_alerts(serial, payload)
elif topic_type == "status/info":
await _handle_info(serial, payload)
elif topic_type == "logs":
await _handle_heartbeat(serial, payload, retained)
elif topic_type == "system/alerts":
await _handle_alerts(serial, payload, retained)
elif topic_type == "system/info":
await _handle_info(serial, payload, retained)
elif topic_type == "system/logs":
await _handle_log(serial, payload)
elif topic_type == "data":
await _handle_data_response(serial, payload)
elif topic_type == "system/metrics":
await _handle_metrics(serial, payload)
elif topic_type == "control/ack":
await _handle_ack(serial, payload)
elif topic_type == "control/reports":
await _handle_report(serial, payload)
elif topic_type == "status/playback":
pass # no console-side storage needed — WS broadcast already carries it live
else:
logger.debug(f"Unhandled topic type: {topic_type} for {serial}")
except Exception as e:
logger.error(f"Error handling {topic_type} for {serial}: {e}")
async def _handle_heartbeat(serial: str, payload: dict):
async def _handle_heartbeat(serial: str, payload: dict, retained: bool = False):
# Online status is "a heartbeat row newer than 90s", so only a live sign of
# life may be stored:
# - retained replay: the device's last heartbeat from whenever. Storing it
# with received_at=now() marked every device ever seen (even long-dead
# ones) online for 90s after each backend restart.
# - state "offline": the LWT / graceful-disconnect marker published when
# the device goes AWAY. Not a heartbeat, but it IS current state even
# when replayed (a retained message is the device's last word).
if payload.get("state") == "offline":
presence.mark_offline(serial)
return
if retained:
return
presence.mark_alive(serial)
# Store silently — do not log as a visible event.
# The console surfaces an alert only when the device goes silent (no heartbeat for 90s).
inner = payload.get("payload", {})
# v2 heartbeat payload is FLAT — no {"status","type","payload"} wrapper,
# and field names changed: firmware_version -> fw_version, timestamp -> uptime_human.
# See vesper_mqtt_topic_spec_v2.md and mqtt-events.md for the full shape.
await db.insert_heartbeat(
device_serial=serial,
device_id=inner.get("device_id", ""),
firmware_version=inner.get("firmware_version", ""),
ip_address=inner.get("ip_address", ""),
gateway=inner.get("gateway", ""),
uptime_ms=inner.get("uptime_ms", 0),
uptime_display=inner.get("timestamp", ""),
device_id=payload.get("device_id", ""),
firmware_version=payload.get("fw_version", ""),
ip_address=payload.get("ip_address", ""),
gateway=payload.get("gateway", ""),
uptime_ms=payload.get("uptime_ms", 0),
uptime_display=payload.get("uptime_human", ""),
rssi=payload.get("rssi"),
free_heap=payload.get("free_heap"),
state=payload.get("state"),
ok=payload.get("ok"),
)
@@ -58,10 +94,11 @@ async def _handle_log(serial: str, payload: dict):
level=level,
message=message,
device_timestamp=device_timestamp,
source="log",
)
async def _handle_alerts(serial: str, payload: dict):
async def _handle_alerts(serial: str, payload: dict, retained: bool = False):
subsystem = payload.get("subsystem", "")
state = payload.get("state", "")
if not subsystem or not state:
@@ -71,24 +108,161 @@ async def _handle_alerts(serial: str, payload: dict):
if state == "CLEARED":
await db.delete_alert(serial, subsystem)
else:
await db.upsert_alert(serial, subsystem, state, payload.get("msg"))
# Retained replays still sync the current-alert row, so a fresh DB
# learns about alerts raised while the backend was down.
changed = await db.upsert_alert(serial, subsystem, state, payload.get("msg"))
# Append-only history — survives past the alert being resolved, used to
# answer "when was the most recent issue" even once it's cleared.
# A live alert is always a new occurrence (the same fault can recur);
# a retained replay only counts if it isn't already the current state.
if changed or not retained:
await db.insert_alert_event(serial, subsystem, state, payload.get("msg"))
async def _handle_info(serial: str, payload: dict):
async def _handle_info(serial: str, payload: dict, retained: bool = False):
event_type = payload.get("type", "")
# boot_report carries structured fields (boot_count, crash detail, etc.) —
# parsed into device_boot_events instead of flattened into a text log line,
# so the Health tab can query/chart it. Not routed through insert_log at
# all: a text summary here would just duplicate the structured row.
#
# Note: diagnostics_report used to also arrive here (F-056) but moved to
# its own system/metrics topic in the v2 spec — see _handle_metrics below.
if event_type == "boot_report":
await _handle_boot_report(serial, payload, retained)
return
# Any other info event replayed from the retained store (e.g. an old
# playback_started) already happened in the past — don't log it again.
if retained:
return
data = payload.get("payload", {})
if event_type == "playback_started":
logger.debug(f"{serial}: playback started — melody_uid={data.get('melody_uid')}")
message = f"Playback started — melody_uid={data.get('melody_uid')}"
elif event_type == "playback_stopped":
logger.debug(f"{serial}: playback stopped")
message = "Playback stopped"
else:
logger.debug(f"{serial}: info event '{event_type}'")
message = f"Info event '{event_type}'" + (f" — {data}" if data else "")
await db.insert_log(
device_serial=serial,
level="INFO",
message=message,
source="info",
)
async def _handle_data_response(serial: str, payload: dict):
async def _handle_boot_report(serial: str, payload: dict, retained: bool = False):
"""Parses the firmware's consolidated boot_report event (see
CommunicationRouter::reportBootOnce() / publishInfo()) into
device_boot_events. Like all status/info events, the report fields are
nested under "payload" — CommunicationRouter::publishInfo() wraps every
info event as { "type": ..., "payload": {...} }.
"""
data = payload.get("payload", {})
# F-070: `crash` (coredump summary, now incl. backtrace/elf_sha256) and
# `pre_crash` (heap/uptime snapshot + optional abort_msg) are stored
# verbatim. Older firmware omits them / sends the 4-field crash only.
crash = data.get("crash") if isinstance(data.get("crash"), dict) else None
pre_crash = data.get("pre_crash") if isinstance(data.get("pre_crash"), dict) else None
await db.insert_boot_event(
device_serial=serial,
boot_count=data.get("boot_count"),
reset_reason=data.get("reset_reason"),
is_fault=bool(data.get("is_fault", False)),
free_heap=data.get("free_heap"),
crash=crash,
pre_crash=pre_crash,
# A live boot_report is always a new boot. A retained replay is the
# device's last boot, recorded only if we missed it while down.
skip_if_latest=retained,
)
async def _handle_metrics(serial: str, payload: dict):
"""Parses the firmware's periodic metrics payload (see
CommunicationRouter::reportDiagnosticsIfDue() in project-vesper) into
device_diagnostics_reports. Unlike status/info events, system/metrics has
NO {"type","payload"} wrapper — the payload IS the metrics object,
flat at the top level. See vesper_mqtt_topic_spec_v2.md / mqtt-events.md.
cpu_temp is entirely absent from the firmware payload (not present as a
key at all, not present-with-nulls) when no samples were taken yet this
window — .get() on a missing "cpu_temp" key correctly falls back to {}
below, leaving every cpu_temp_* column null for that row.
"""
cpu_temp = payload.get("cpu_temp") or {}
wifi = payload.get("wifi_reconnects") or {}
ota = payload.get("ota") or {}
stack = payload.get("stack_high_water") or {}
bell_strikes = payload.get("bell_strikes") or {}
bell_loads = payload.get("bell_loads") or {}
await db.insert_diagnostics_report(
device_serial=serial,
cpu_temp_avg=cpu_temp.get("avg"),
cpu_temp_min=cpu_temp.get("min"),
cpu_temp_max=cpu_temp.get("max"),
cpu_temp_samples=cpu_temp.get("samples"),
wifi_reconnect_count=wifi.get("lifetime_count"),
wifi_last_disconnect_reason=wifi.get("last_reason"),
wifi_last_disconnect_uptime_ms=wifi.get("last_at_uptime_ms"),
ota_current_version=ota.get("current_version"),
ota_update_available=ota.get("update_available"),
ota_available_version=ota.get("available_version"),
ota_last_check_uptime_ms=ota.get("last_check_uptime_ms"),
ota_last_error=ota.get("last_error"),
stack_high_water=stack if stack else None,
bell_strikes=bell_strikes if bell_strikes else None,
bell_loads=bell_loads if bell_loads else None,
cooling_active=payload.get("cooling_active"),
)
async def _handle_report(serial: str, payload: dict):
"""Parses control/reports — critical, unsolicited board-initiated events
(currently only bell_overload). Console-side storage is intentionally
light: history/audit only. The tablets are the real-time consumer."""
report_type = payload.get("type", "")
if not report_type:
logger.warning(f"Malformed report payload from {serial}: {payload}")
return
await db.insert_report(
device_serial=serial,
report_type=report_type,
payload=payload.get("payload"),
)
logger.warning(f"Report '{report_type}' received from {serial}: {payload.get('payload')}")
async def _handle_ack(serial: str, payload: dict):
status = payload.get("status", "")
# Health-check pings (see MqttManager.ping_loop) are published directly,
# bypassing db.insert_command, so scheduled liveness checks don't clutter
# the user-facing command history. The device echoes the caller's own
# send-time ("ts", epoch-ms) back unchanged, so RTT is computed here
# without needing to correlate against any pending-command bookkeeping.
if payload.get("type") == "pong":
ts = (payload.get("data") or {}).get("ts")
if isinstance(ts, (int, float)):
rtt_ms = max(0, int(time.time() * 1000) - int(ts))
await db.insert_ping_sample(device_serial=serial, rtt_ms=rtt_ms)
return
# The device's own SD boot log — merged into device_boot_events whoever
# asked for it (Health tab "Sync from device", API reference, Control tab),
# so crash detail for boots we never saw live isn't lost.
if payload.get("type") == "telemetry.get_boot_history" and status == "SUCCESS":
boots = (payload.get("data") or {}).get("boots")
if isinstance(boots, list):
result = await db.merge_device_boot_history(serial, boots)
logger.info(f"Merged device boot history for {serial}: {result}")
pending = await db.get_pending_command(serial)
if pending:
cmd_status = "success" if status == "SUCCESS" else "error"
@@ -98,4 +272,4 @@ async def _handle_data_response(serial: str, payload: dict):
response_payload=payload,
)
else:
logger.debug(f"Received data response for {serial} with no pending command")
logger.debug(f"Received control/ack for {serial} with no pending command")
+137
View File
@@ -27,6 +27,7 @@ class DeviceLogEntry(BaseModel):
level: str
message: str
device_timestamp: Optional[int] = None
source: str = "log"
received_at: str
@@ -39,6 +40,10 @@ class HeartbeatEntry(BaseModel):
gateway: Optional[str] = None
uptime_ms: Optional[int] = None
uptime_display: Optional[str] = None
rssi: Optional[int] = None
free_heap: Optional[int] = None
state: Optional[str] = None # "idle" | "playing" | "paused" | "error" | "booting" (v2 firmware only)
ok: Optional[bool] = None # overall device health, independent of playback state (v2 firmware only)
received_at: str
@@ -53,11 +58,21 @@ class CommandEntry(BaseModel):
responded_at: Optional[str] = None
class AlertEventEntry(BaseModel):
id: int
device_serial: str
subsystem: str
state: str
message: Optional[str] = None
occurred_at: str
class DeviceMqttStatus(BaseModel):
device_serial: str
online: bool
last_heartbeat: Optional[HeartbeatEntry] = None
seconds_since_heartbeat: Optional[int] = None
last_alert_event: Optional[AlertEventEntry] = None
class MqttStatusResponse(BaseModel):
@@ -96,3 +111,125 @@ class DeviceAlertEntry(BaseModel):
class DeviceAlertsResponse(BaseModel):
alerts: List[DeviceAlertEntry]
class AlertEventListResponse(BaseModel):
events: List[AlertEventEntry]
total: int
class BootEventEntry(BaseModel):
id: int
device_serial: str
boot_count: Optional[int] = None
reset_reason: Optional[str] = None
is_fault: bool = False
free_heap: Optional[int] = None
crash_task: Optional[str] = None
crash_pc: Optional[int] = None
crash_exc_cause: Optional[int] = None
crash_exc_vaddr: Optional[int] = None
# Firmware F-070 objects, verbatim — None for older firmware/rows.
crash: Optional[Dict[str, Any]] = None
pre_crash: Optional[Dict[str, Any]] = None
occurred_at: str
class BootEventListResponse(BaseModel):
events: List[BootEventEntry]
total: int
class CrashGroupDevice(BaseModel):
device_serial: str
count: int
last_at: str
class CrashGroup(BaseModel):
key: str
kind: str # "abort" | "exception" | "reason"
title: str
count: int
device_count: int
first_at: str
last_at: str
latest: BootEventEntry
devices: List[CrashGroupDevice]
class CrashGroupListResponse(BaseModel):
groups: List[CrashGroup]
total_crashes: int
class PingSampleEntry(BaseModel):
id: int
device_serial: str
rtt_ms: int
sampled_at: str
class PingSampleListResponse(BaseModel):
samples: List[PingSampleEntry]
total: int
class DiagnosticsReportEntry(BaseModel):
id: int
device_serial: str
cpu_temp_avg: Optional[float] = None
cpu_temp_min: Optional[float] = None
cpu_temp_max: Optional[float] = None
cpu_temp_samples: Optional[int] = None
wifi_reconnect_count: Optional[int] = None
wifi_last_disconnect_reason: Optional[str] = None
wifi_last_disconnect_uptime_ms: Optional[int] = None
ota_current_version: Optional[str] = None
ota_update_available: Optional[bool] = None
ota_available_version: Optional[str] = None
ota_last_check_uptime_ms: Optional[int] = None
ota_last_error: Optional[str] = None
stack_high_water: Optional[str] = None # JSON-encoded string — see insert_diagnostics_report
bell_strikes: Optional[str] = None # JSON-encoded string, {"0": count, ...} — v2 firmware only
bell_loads: Optional[str] = None # JSON-encoded string, {"0": load, ...} — v2 firmware only
cooling_active: Optional[bool] = None # v2 firmware only
received_at: str
class DiagnosticsReportListResponse(BaseModel):
reports: List[DiagnosticsReportEntry]
total: int
class DeviceReportEntry(BaseModel):
"""A control/reports event (currently only bell_overload) — see
project-vesper's vesper_mqtt_topic_spec_v2.md. Console-side storage is
intentionally light: history/audit only, not a real-time UI surface."""
id: int
device_serial: str
report_type: str
payload: Optional[str] = None # JSON-encoded string
occurred_at: str
class DeviceReportListResponse(BaseModel):
reports: List[DeviceReportEntry]
total: int
class LatestDiagnosticsEntry(BaseModel):
device_serial: str
cpu_temp_avg: Optional[float] = None
received_at: str
class LatestPingEntry(BaseModel):
device_serial: str
rtt_ms: int
sampled_at: str
class LatestMetricsResponse(BaseModel):
diagnostics: List[LatestDiagnosticsEntry]
pings: List[LatestPingEntry]
+26
View File
@@ -0,0 +1,26 @@
"""Devices that announced they went offline.
The firmware's LWT (unclean disconnect) and its graceful-disconnect message both
publish {"state": "offline", "ok": false} to status/heartbeat, retained. Online
status is otherwise "a heartbeat newer than 90s", which would keep showing a
device that just dropped as online for up to 90s. This remembers the marker so
/mqtt/status and the ping loop treat the device as offline right away.
In-memory only, which is enough: on backend start the broker replays each
device's retained heartbeat, so a device whose last word was "offline" gets
re-marked, and any live heartbeat clears the mark.
"""
_offline: set[str] = set()
def mark_offline(serial: str) -> None:
_offline.add(serial)
def mark_alive(serial: str) -> None:
_offline.discard(serial)
def is_marked_offline(serial: str) -> bool:
return serial in _offline
+185 -25
View File
@@ -1,48 +1,90 @@
from fastapi import APIRouter, Depends, Query, WebSocket, WebSocketDisconnect
from typing import Optional
from fastapi import APIRouter, Depends, HTTPException, Query, WebSocket, WebSocketDisconnect
from sqlalchemy.ext.asyncio import AsyncSession
from typing import Optional, List
from auth.models import TokenPayload
from auth.dependencies import require_permission
from mqtt.models import (
MqttCommandRequest, CommandSendResponse, MqttStatusResponse,
DeviceMqttStatus, LogListResponse, HeartbeatListResponse,
CommandListResponse, HeartbeatEntry,
CommandListResponse, HeartbeatEntry, AlertEventEntry,
AlertEventListResponse, BootEventListResponse, PingSampleListResponse,
DiagnosticsReportListResponse, LatestMetricsResponse,
LatestDiagnosticsEntry, LatestPingEntry, DeviceReportListResponse,
CrashGroupListResponse,
)
from mqtt.crash_groups import group_crashes
from mqtt.client import mqtt_manager
from mqtt import presence
import database as db
from database.postgres import get_pg_session
from shared.audit import log_action
from datetime import datetime, timezone
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)
async def get_all_device_status(
_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()
alert_events = await db.get_latest_alert_events()
alert_by_serial = {a["device_serial"]: a for a in alert_events}
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
devices.append(DeviceMqttStatus(
device_serial=hb["device_serial"],
online=seconds_ago < 90,
last_heartbeat=HeartbeatEntry(**hb),
seconds_since_heartbeat=seconds_ago,
))
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,
)
@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)
async def get_latest_metrics(
_user: TokenPayload = Depends(require_permission("mqtt", "view")),
):
# Fleet-wide "last known" CPU temp + ping RTT, one query each — used by
# DeviceList to render optional columns without polling any device.
# Uptime/firmware/RSSI don't need this: they're already in /mqtt/status.
diag_reports = await db.get_latest_diagnostics_reports()
ping_samples = await db.get_latest_ping_samples()
return LatestMetricsResponse(
diagnostics=[LatestDiagnosticsEntry(**d) for d in diag_reports],
pings=[LatestPingEntry(**p) for p in ping_samples],
)
@router.post("/command/{device_serial}", response_model=CommandSendResponse)
async def send_command(
device_serial: str,
@@ -81,27 +123,58 @@ async def send_command(
async def get_device_logs(
device_serial: str,
level: Optional[str] = Query(None, description="Filter: INFO, WARN, ERROR"),
min_level: bool = Query(False, description="If true, level is a floor — also includes higher-severity levels"),
search: Optional[str] = Query(None),
source: Optional[List[str]] = Query(None, description="Filter by source: log, info. Repeat param to include several."),
limit: int = Query(100, ge=1, le=1000),
offset: int = Query(0, ge=0),
since: Optional[datetime] = Query(None, description="ISO timestamp — only rows at/after this time"),
until: Optional[datetime] = Query(None, description="ISO timestamp — only rows at/before this time"),
_user: TokenPayload = Depends(require_permission("mqtt", "view")),
):
logs, total = await db.get_logs(
device_serial, level=level, search=search,
limit=limit, offset=offset,
device_serial, level=level, search=search, source=source,
min_level=min_level, limit=limit, offset=offset, since=since, until=until,
)
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)
async def get_device_heartbeats(
device_serial: str,
limit: int = Query(100, ge=1, le=1000),
limit: int = Query(100, ge=1, le=5000),
offset: int = Query(0, ge=0),
since: Optional[datetime] = Query(None, description="ISO timestamp — only rows at/after this time"),
until: Optional[datetime] = Query(None, description="ISO timestamp — only rows at/before this time"),
_user: TokenPayload = Depends(require_permission("mqtt", "view")),
):
heartbeats, total = await db.get_heartbeats(
device_serial, limit=limit, offset=offset,
device_serial, limit=limit, offset=offset, since=since, until=until,
)
return HeartbeatListResponse(heartbeats=heartbeats, total=total)
@@ -119,6 +192,93 @@ async def get_device_commands(
return CommandListResponse(commands=commands, total=total)
@router.get("/alert-events/{device_serial}", response_model=AlertEventListResponse)
async def get_device_alert_events(
device_serial: str,
limit: int = Query(100, ge=1, le=1000),
offset: int = Query(0, ge=0),
_user: TokenPayload = Depends(require_permission("mqtt", "view")),
):
events, total = await db.get_alert_events(
device_serial, limit=limit, offset=offset,
)
return AlertEventListResponse(events=events, total=total)
@router.get("/boot-events/{device_serial}", response_model=BootEventListResponse)
async def get_device_boot_events(
device_serial: str,
limit: int = Query(100, ge=1, le=2000),
offset: int = Query(0, ge=0),
since: Optional[datetime] = Query(None, description="ISO timestamp — only rows at/after this time"),
until: Optional[datetime] = Query(None, description="ISO timestamp — only rows at/before this time"),
_user: TokenPayload = Depends(require_permission("mqtt", "view")),
):
events, total = await db.get_boot_events(
device_serial, limit=limit, offset=offset, since=since, until=until,
)
return BootEventListResponse(events=events, total=total)
@router.get("/crash-groups", response_model=CrashGroupListResponse)
async def get_crash_groups(
since: Optional[datetime] = Query(None, description="ISO timestamp — only crashes at/after this time"),
until: Optional[datetime] = Query(None, description="ISO timestamp — only crashes at/before this time"),
_user: TokenPayload = Depends(require_permission("mqtt", "view")),
):
"""Fault boots across the whole fleet, grouped by crash signature."""
events = await db.get_crash_events(since=since, until=until)
return CrashGroupListResponse(groups=group_crashes(events), total_crashes=len(events))
@router.get("/ping-samples/{device_serial}", response_model=PingSampleListResponse)
async def get_device_ping_samples(
device_serial: str,
limit: int = Query(200, ge=1, le=5000),
offset: int = Query(0, ge=0),
since: Optional[datetime] = Query(None, description="ISO timestamp — only rows at/after this time"),
until: Optional[datetime] = Query(None, description="ISO timestamp — only rows at/before this time"),
_user: TokenPayload = Depends(require_permission("mqtt", "view")),
):
samples, total = await db.get_ping_samples(
device_serial, limit=limit, offset=offset, since=since, until=until,
)
return PingSampleListResponse(samples=samples, total=total)
@router.get("/diagnostics-reports/{device_serial}", response_model=DiagnosticsReportListResponse)
async def get_device_diagnostics_reports(
device_serial: str,
limit: int = Query(200, ge=1, le=5000),
offset: int = Query(0, ge=0),
since: Optional[datetime] = Query(None, description="ISO timestamp — only rows at/after this time"),
until: Optional[datetime] = Query(None, description="ISO timestamp — only rows at/before this time"),
_user: TokenPayload = Depends(require_permission("mqtt", "view")),
):
reports, total = await db.get_diagnostics_reports(
device_serial, limit=limit, offset=offset, since=since, until=until,
)
return DiagnosticsReportListResponse(reports=reports, total=total)
@router.get("/reports/{device_serial}", response_model=DeviceReportListResponse)
async def get_device_reports(
device_serial: str,
limit: int = Query(200, ge=1, le=2000),
offset: int = Query(0, ge=0),
since: Optional[datetime] = Query(None, description="ISO timestamp — only rows at/after this time"),
until: Optional[datetime] = Query(None, description="ISO timestamp — only rows at/before this time"),
_user: TokenPayload = Depends(require_permission("mqtt", "view")),
):
"""Critical, unsolicited board-initiated events from control/reports
(currently only bell_overload). History/audit only — the tablets are the
real-time consumer of this data, not the console."""
reports, total = await db.get_reports(
device_serial, limit=limit, offset=offset, since=since, until=until,
)
return DeviceReportListResponse(reports=reports, total=total)
@router.websocket("/ws")
async def mqtt_websocket(websocket: WebSocket):
"""Live MQTT data stream. Auth via query param: ?token=JWT"""
+3 -3
View File
@@ -109,9 +109,9 @@ async def validate_serial(serial_number: str):
device = get_device_by_sn(sn)
return SerialValidationResult(
valid=True,
hw_type=device.hw_type,
hw_type_label=HW_TYPE_LABELS.get(device.hw_type, device.hw_type.replace("_", " ").title()),
hw_version=device.hw_version,
hw_type=device.hw_family,
hw_type_label=HW_TYPE_LABELS.get(device.hw_family, device.hw_family.replace("_", " ").title()),
hw_version=device.hw_revision,
)
except Exception:
return SerialValidationResult(valid=False)
+2
View File
@@ -18,3 +18,5 @@ pdf2image>=1.17.0
asyncpg==0.30.0
sqlalchemy[asyncio]==2.0.36
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,149 @@
"""
Backfill `device_serials` on Firestore `users` docs from the devices' `user_list`.
`device_serials` is what the MQTT ACL uses to decide which vesper/{serial}/...
topics an app user may reach (see mqtt/app_users.py). New assignments keep it
in sync automatically; this script builds it for assignments that predate that.
The devices' user_list is treated as the source of truth: each user's
device_serials is set to exactly the serials of the devices that list them.
Running it twice is a no-op the second time.
Also reports:
- users whose document ID != their `uid` field (or who have no uid) — the
MQTT layer resolves users by the uid field, so this is informational,
but a user without a uid can never connect via the app
- devices that have users but no serial (can't be reached over MQTT)
- user_list entries that point to users that don't exist
Run from backend/ (locally or inside the backend container):
python scripts/backfill_user_device_serials.py # dry run
python scripts/backfill_user_device_serials.py --apply # write changes
"""
import argparse
import sys
from collections import defaultdict
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
from google.cloud.firestore_v1 import DocumentReference # noqa: E402
from shared.firebase import init_firebase, get_db # noqa: E402
from users.service import device_serial_of # noqa: E402
BATCH_SIZE = 400 # Firestore batch limit is 500 writes
def _entry_user_id(entry) -> str:
"""user_list entries are DocumentReferences, "users/{id}" paths or raw doc IDs."""
if isinstance(entry, DocumentReference):
return entry.id
if isinstance(entry, str) and entry.strip():
return entry.strip().split("/")[-1]
return ""
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
mode = "APPLY" if args.apply else "DRY RUN"
print(f"=== backfill device_serials ({mode}) ===\n")
# 1. devices -> {user_doc_id: {serials}}
wanted: dict[str, set[str]] = defaultdict(set)
devices_without_serial = []
device_count = 0
for doc in db.collection("devices").stream():
device_count += 1
data = doc.to_dict() or {}
user_ids = [u for u in (_entry_user_id(e) for e in (data.get("user_list") or [])) if u]
if not user_ids:
continue
serial = device_serial_of(data)
if not serial:
devices_without_serial.append(doc.id)
continue
for uid in user_ids:
wanted[uid].add(serial)
# 2. users
users = {doc.id: (doc.reference, doc.to_dict() or {}) for doc in db.collection("users").stream()}
by_uid_field = {data.get("uid"): doc_id for doc_id, (_, data) in users.items() if data.get("uid")}
# user_list entries that don't match a doc ID but do match a uid field
dangling = []
for ref_id in list(wanted):
if ref_id in users:
continue
if ref_id in by_uid_field:
wanted[by_uid_field[ref_id]].update(wanted.pop(ref_id))
else:
dangling.append((ref_id, sorted(wanted.pop(ref_id))))
id_mismatch = []
no_uid = []
changes = []
for doc_id, (ref, data) in sorted(users.items()):
uid = data.get("uid") or ""
if not uid:
no_uid.append(doc_id)
elif uid != doc_id:
id_mismatch.append((doc_id, uid))
current = data.get("device_serials")
desired = sorted(wanted.get(doc_id, set()))
if current is None and not desired:
continue # nothing assigned and field absent — leave the doc alone
if list(current or []) != desired:
changes.append((doc_id, ref, list(current or []), desired))
# 3. report
print(f"Scanned {device_count} devices, {len(users)} users.\n")
print(f"Users to update: {len(changes)}")
for doc_id, _, current, desired in changes:
print(f" users/{doc_id}: {current} -> {desired}")
print(f"\nUsers whose doc ID != uid: {len(id_mismatch)}")
for doc_id, uid in id_mismatch:
print(f" users/{doc_id} uid={uid}")
print(f"\nUsers with no uid field (cannot use app MQTT login): {len(no_uid)}")
for doc_id in no_uid:
print(f" users/{doc_id}")
print(f"\nDevices with users but no serial_number/device_id: {len(devices_without_serial)}")
for doc_id in devices_without_serial:
print(f" devices/{doc_id}")
print(f"\nuser_list entries pointing to missing users: {len(dangling)}")
for ref_id, serials in dangling:
print(f" {ref_id} (on devices {serials})")
# 4. write
if not args.apply:
print("\nDry run — nothing written. Re-run with --apply to write.")
return 0
for i in range(0, len(changes), BATCH_SIZE):
batch = db.batch()
for _, ref, _, desired in changes[i:i + BATCH_SIZE]:
batch.update(ref, {"device_serials": desired})
batch.commit()
print(f"\nWrote device_serials on {len(changes)} user docs.")
return 0
if __name__ == "__main__":
sys.exit(main())
@@ -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())
+3 -2
View File
@@ -26,8 +26,9 @@ def _search_devices(q: str) -> list[dict]:
return []
out = []
for d in results[:LIMIT]:
label = d.device_name or d.serial_number or d.device_id or d.id
sublabel = d.serial_number if d.device_name else None
display_name = d.console_name or d.device_name
label = display_name or d.serial_number or d.device_id or d.id
sublabel = d.serial_number if display_name else None
out.append({
"type": "device",
"id": d.id,
+10
View File
@@ -0,0 +1,10 @@
from pydantic import BaseModel
from typing import Optional
class LogRetentionSettings(BaseModel):
days: int = 180
class LogRetentionSettingsUpdate(BaseModel):
days: Optional[int] = None
+31
View File
@@ -0,0 +1,31 @@
from shared.firebase import get_db
from settings.log_retention_models import LogRetentionSettings, LogRetentionSettingsUpdate
COLLECTION = "admin_settings"
DOC_ID = "log_retention"
def get_log_retention() -> LogRetentionSettings:
"""Get log retention settings from Firestore. Creates defaults if not found."""
db = get_db()
doc = db.collection(COLLECTION).document(DOC_ID).get()
if doc.exists:
return LogRetentionSettings(**doc.to_dict())
defaults = LogRetentionSettings()
db.collection(COLLECTION).document(DOC_ID).set(defaults.model_dump())
return defaults
def update_log_retention(data: LogRetentionSettingsUpdate) -> LogRetentionSettings:
"""Update log retention settings. Only provided fields are updated."""
db = get_db()
doc_ref = db.collection(COLLECTION).document(DOC_ID)
doc = doc_ref.get()
existing = doc.to_dict() if doc.exists else LogRetentionSettings().model_dump()
update_data = data.model_dump(exclude_none=True)
existing.update(update_data)
normalized = LogRetentionSettings(**existing)
doc_ref.set(normalized.model_dump())
return normalized
+19
View File
@@ -4,8 +4,10 @@ from auth.dependencies import require_permission, require_roles
from auth.models import Role
from settings.models import MelodySettings, MelodySettingsUpdate
from settings.public_features_models import PublicFeaturesSettings, PublicFeaturesSettingsUpdate
from settings.log_retention_models import LogRetentionSettings, LogRetentionSettingsUpdate
from settings import service
from settings import public_features_service
from settings import log_retention_service
router = APIRouter(prefix="/api/settings", tags=["settings"])
@@ -40,3 +42,20 @@ async def update_public_features(
_user: TokenPayload = Depends(require_roles(Role.sysadmin, Role.admin)),
):
return public_features_service.update_public_features(body)
# ── Log Retention Settings (sysadmin / admin only) ───────────────────────────
@router.get("/log-retention", response_model=LogRetentionSettings)
async def get_log_retention(
_user: TokenPayload = Depends(require_roles(Role.sysadmin, Role.admin)),
):
return log_retention_service.get_log_retention()
@router.put("/log-retention", response_model=LogRetentionSettings)
async def update_log_retention(
body: LogRetentionSettingsUpdate,
_user: TokenPayload = Depends(require_roles(Role.sysadmin, Role.admin)),
):
return log_retention_service.update_log_retention(body)
+5
View File
@@ -0,0 +1,5 @@
import sys
from pathlib import Path
# Tests import backend modules the same way the app does (cwd = backend/).
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
+207
View File
@@ -0,0 +1,207 @@
"""
Device user assignment: `user_list` is the source of truth. Every write must
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
from google.cloud.firestore_v1 import ArrayRemove, ArrayUnion, DocumentReference
from devices import service as devices_service
from devices.models import DeviceUpdate
from mqtt import app_users
from users import service as users_service
SERIAL = "BSVSPR-26C13X-STD01R-X7KQA"
MIRROR = "devices/dev1/device_users"
class _Snap:
def __init__(self, ref, data):
self.reference = ref
self.id = ref.id
self._data = data
self.exists = data is not None
def to_dict(self):
return dict(self._data) if self._data is not None else None
class _Ref(DocumentReference):
"""A real DocumentReference subclass, so isinstance checks and .id/.path work."""
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):
return _Snap(self, self._db.docs[self._col].get(self.id))
def update(self, 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:
def __init__(self, db):
self._db, self.ops = db, []
def update(self, 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):
for op, ref, data in self.ops:
getattr(ref, op)(*([data] if data is not None else []))
self._db.commits += 1
class _Collection:
def __init__(self, db, path):
self._db, self._path = db, path
def document(self, doc_id=None):
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:
def __init__(self):
self.docs = {"devices": {}, "users": {}, MIRROR: {}}
self.commits = 0
self.ids = itertools.count(1)
def collection(self, name):
return _Collection(self, name)
def 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):
doc = self.docs[col][doc_id]
for key, val in data.items():
if isinstance(val, ArrayUnion):
doc[key] = list(doc.get(key) or []) + [v for v in val.values if v not in (doc.get(key) or [])]
elif isinstance(val, ArrayRemove):
doc[key] = [v for v in (doc.get(key) or []) if v not in val.values]
else:
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
def db(monkeypatch):
fake = FakeDB()
fake.docs["devices"]["dev1"] = {
"serial_number": SERIAL, "mfg_status": "claimed",
"user_list": [fake.ref("users/alice"), "users/bob"], # both formats seen in the wild
}
fake.docs[MIRROR]["m1"] = {"role": "admin", "user_reference": fake.ref("users/alice")}
fake.docs["users"]["alice"] = {"uid": "alice", "device_serials": [SERIAL], "display_name": "Alice"}
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(users_service, "get_db", lambda: fake)
monkeypatch.setattr(app_users, "invalidate", lambda uid: None)
return fake
# ── PUT /api/devices/{id} with user_list ─────────────────────────────────────
def test_put_user_list_syncs_added_and_removed_users(db, monkeypatch):
invalidated = []
monkeypatch.setattr(app_users, "invalidate", invalidated.append)
devices_service.update_device("dev1", DeviceUpdate(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"]["bob"]["device_serials"] == ["OTHER"] # removed
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 db.commits == 1 # one atomic batch
def test_put_user_list_ignores_dangling_user_refs(db):
devices_service.update_device("dev1", DeviceUpdate(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.mirror_user_ids()
def test_put_without_user_list_does_not_touch_users(db):
devices_service.update_device("dev1", DeviceUpdate(device_name="Church"))
assert db.docs["devices"]["dev1"]["device_name"] == "Church"
assert db.commits == 0
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() == []
+190
View File
@@ -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"
+357
View File
@@ -0,0 +1,357 @@
"""
Tests for the mosquitto-go-auth HTTP backend endpoints (mqtt/auth.py):
POST /mqtt/auth/user and POST /mqtt/auth/acl.
firebase_admin token verification and Firestore are mocked; nothing here
touches the network.
"""
import pytest
from fastapi import FastAPI
from fastapi.testclient import TestClient
from firebase_admin import auth as firebase_auth
from config import settings
from mqtt import app_users
from mqtt import auth as mqtt_auth
UID = "uidAlice123"
OTHER_UID = "uidBob456"
SERIAL = "BSVSPR-26C13X-STD01R-X7KQA"
FOREIGN_SERIAL = "PV25L22BP01R01"
APP_USER = f"app_{UID}"
APP_CLIENT = f"app_{UID}_phone1"
GOOD_TOKEN = "good-token"
# ---------------------------------------------------------------------------
# Fakes
# ---------------------------------------------------------------------------
class _FakeDoc:
def __init__(self, doc_id, data):
self.id = doc_id
self._data = data
def to_dict(self):
return dict(self._data)
class _FakeQuery:
def __init__(self, docs, field=None, value=None):
self._docs = docs
self._field = field
self._value = value
def where(self, field, op, value):
assert op == "=="
return _FakeQuery(self._docs, field, value)
def limit(self, _n):
return self
def stream(self):
return [d for d in self._docs if d.to_dict().get(self._field) == self._value]
class FakeFirestore:
"""Just enough of the Firestore client for app_users._load()."""
def __init__(self):
self.users: list[_FakeDoc] = []
self.reads = 0
def add_user(self, doc_id, **data):
self.users.append(_FakeDoc(doc_id, data))
def collection(self, name):
assert name == "users"
self.reads += 1
return _FakeQuery(self.users)
@pytest.fixture
def fs(monkeypatch):
db = FakeFirestore()
# Doc ID deliberately != uid, like Console-created users.
db.add_user("randomDocId1", uid=UID, status="active", device_serials=[SERIAL])
db.add_user(OTHER_UID, uid=OTHER_UID, status="blocked", device_serials=[FOREIGN_SERIAL])
monkeypatch.setattr(app_users, "get_db", lambda: db)
app_users.clear_cache()
yield db
app_users.clear_cache()
@pytest.fixture
def verify(monkeypatch):
"""Mock verify_id_token. Set `verify.result` to a dict or an exception."""
class _Verify:
result = {"uid": UID}
calls = []
def __call__(self, token, check_revoked=False):
self.calls.append((token, check_revoked))
if isinstance(self.result, Exception):
raise self.result
return self.result
v = _Verify()
v.calls = []
monkeypatch.setattr(mqtt_auth.firebase_auth, "verify_id_token", v)
return v
@pytest.fixture
def client():
app = FastAPI()
app.include_router(mqtt_auth.router)
return TestClient(app)
@pytest.fixture(autouse=True)
def _defaults(monkeypatch):
monkeypatch.setattr(settings, "mqtt_secret", "test-secret")
monkeypatch.setattr(settings, "mqtt_allow_legacy_password", True)
mqtt_auth._legacy_log_last.clear()
def auth_user(client, username, password, clientid="c1"):
return client.post(
"/mqtt/auth/user",
data={"username": username, "password": password, "clientid": clientid},
).status_code
def acl(client, username, topic, acc, clientid=APP_CLIENT):
return client.post(
"/mqtt/auth/acl",
data={"username": username, "topic": topic, "clientid": clientid, "acc": acc},
).status_code
# ---------------------------------------------------------------------------
# /mqtt/auth/user — devices
# ---------------------------------------------------------------------------
@pytest.mark.parametrize("username", [SERIAL, FOREIGN_SERIAL, f"{FOREIGN_SERIAL}-kiosk"])
def test_device_hmac_ok(client, username):
assert auth_user(client, username, mqtt_auth._derive_password(username)) == 200
def test_device_hmac_wrong_password(client):
assert auth_user(client, SERIAL, "0" * 32) == 403
def test_device_hmac_of_other_serial_rejected(client):
assert auth_user(client, SERIAL, mqtt_auth._derive_password(FOREIGN_SERIAL)) == 403
def test_legacy_password_accepted_when_flag_on(client):
assert auth_user(client, FOREIGN_SERIAL, "vesper") == 200
assert auth_user(client, f"{FOREIGN_SERIAL}-kiosk", "vesper") == 200
def test_legacy_password_rejected_when_flag_off(client, monkeypatch):
monkeypatch.setattr(settings, "mqtt_allow_legacy_password", False)
assert auth_user(client, FOREIGN_SERIAL, "vesper") == 403
# HMAC still works with the flag off
assert auth_user(client, FOREIGN_SERIAL, mqtt_auth._derive_password(FOREIGN_SERIAL)) == 200
@pytest.mark.parametrize("username", ["somebody", "NodeRED", "pv25l22bp01r01", "PV-", "PV 25"])
def test_legacy_password_rejected_for_non_device_usernames(client, username):
assert auth_user(client, username, "vesper") == 403
def test_legacy_password_never_accepted_for_app_users(client, fs, verify):
verify.result = firebase_auth.InvalidIdTokenError("not a jwt")
assert auth_user(client, APP_USER, "vesper") == 403
def test_hmac_never_accepted_for_app_users(client, fs, verify):
verify.result = firebase_auth.InvalidIdTokenError("not a jwt")
assert auth_user(client, APP_USER, mqtt_auth._derive_password(APP_USER)) == 403
def test_legacy_login_logged_once_per_hour(client, caplog):
with caplog.at_level("WARNING", logger="mqtt.auth"):
for _ in range(3):
assert auth_user(client, FOREIGN_SERIAL, "vesper") == 200
assert auth_user(client, SERIAL, "vesper") == 200
legacy = [r for r in caplog.records if "legacy password" in r.getMessage()]
assert [r.getMessage().split(" for ")[1].split(" ")[0] for r in legacy] == [FOREIGN_SERIAL, SERIAL]
# ---------------------------------------------------------------------------
# /mqtt/auth/user — app users
# ---------------------------------------------------------------------------
def test_app_valid_token(client, fs, verify):
assert auth_user(client, APP_USER, GOOD_TOKEN) == 200
assert verify.calls == [(GOOD_TOKEN, True)] # check_revoked=True
def test_app_token_for_other_uid(client, fs, verify):
verify.result = {"uid": OTHER_UID}
assert auth_user(client, APP_USER, GOOD_TOKEN) == 403
def test_app_revoked_token(client, fs, verify):
verify.result = firebase_auth.RevokedIdTokenError("revoked")
assert auth_user(client, APP_USER, GOOD_TOKEN) == 403
def test_app_expired_token(client, fs, verify):
verify.result = firebase_auth.ExpiredIdTokenError("expired", cause=None)
assert auth_user(client, APP_USER, GOOD_TOKEN) == 403
def test_app_blocked_user(client, fs, verify):
verify.result = {"uid": OTHER_UID}
assert auth_user(client, f"app_{OTHER_UID}", GOOD_TOKEN) == 403
def test_app_unknown_user(client, fs, verify):
verify.result = {"uid": "ghost"}
assert auth_user(client, "app_ghost", GOOD_TOKEN) == 403
def test_app_empty_uid(client, fs, verify):
verify.result = {"uid": ""}
assert auth_user(client, "app_", GOOD_TOKEN) == 403
def test_app_deny_never_logs_token(client, fs, verify, caplog):
secret_token = "eyJhbGciOi.SECRET-TOKEN-VALUE.sig"
verify.result = {"uid": OTHER_UID}
with caplog.at_level("DEBUG"):
assert auth_user(client, APP_USER, secret_token) == 403
assert "token uid does not match" in caplog.text
assert secret_token not in caplog.text
# ---------------------------------------------------------------------------
# /mqtt/auth/acl — app users
# ---------------------------------------------------------------------------
@pytest.mark.parametrize("leaf", ["control/ack", "status/heartbeat", "status/playback"])
@pytest.mark.parametrize("acc", [mqtt_auth.ACC_READ, mqtt_auth.ACC_SUBSCRIBE])
def test_app_acl_read_subscribe_allowed(client, fs, leaf, acc):
assert acl(client, APP_USER, f"vesper/{SERIAL}/{leaf}", acc) == 200
def test_app_acl_publish_command_allowed(client, fs):
assert acl(client, APP_USER, f"vesper/{SERIAL}/control/command", mqtt_auth.ACC_WRITE) == 200
@pytest.mark.parametrize("leaf", ["control/ack", "status/heartbeat", "status/playback", "system/info"])
def test_app_acl_publish_other_topics_denied(client, fs, leaf):
assert acl(client, APP_USER, f"vesper/{SERIAL}/{leaf}", mqtt_auth.ACC_WRITE) == 403
@pytest.mark.parametrize("acc", [mqtt_auth.ACC_READ, mqtt_auth.ACC_SUBSCRIBE])
@pytest.mark.parametrize("leaf", ["control/command", "system/info", "system/alerts", "control/reports"])
def test_app_acl_read_subscribe_other_topics_denied(client, fs, acc, leaf):
assert acl(client, APP_USER, f"vesper/{SERIAL}/{leaf}", acc) == 403
@pytest.mark.parametrize("acc", [0, 3, 5, 8])
def test_app_acl_unknown_acc_denied(client, fs, acc):
assert acl(client, APP_USER, f"vesper/{SERIAL}/control/ack", acc) == 403
@pytest.mark.parametrize("topic", [
f"vesper/{SERIAL}/#",
f"vesper/{SERIAL}/status/+",
"vesper/+/control/ack",
"#",
])
@pytest.mark.parametrize("acc", [mqtt_auth.ACC_READ, mqtt_auth.ACC_WRITE, mqtt_auth.ACC_SUBSCRIBE])
def test_app_acl_wildcards_denied(client, fs, topic, acc):
assert acl(client, APP_USER, topic, acc) == 403
@pytest.mark.parametrize("acc", [mqtt_auth.ACC_READ, mqtt_auth.ACC_WRITE, mqtt_auth.ACC_SUBSCRIBE])
def test_app_acl_foreign_serial_denied(client, fs, acc):
leaf = "control/command" if acc == mqtt_auth.ACC_WRITE else "control/ack"
assert acl(client, APP_USER, f"vesper/{FOREIGN_SERIAL}/{leaf}", acc) == 403
@pytest.mark.parametrize("clientid", [
"",
"phone1",
f"app_{UID}", # missing trailing "_"
f"app_{OTHER_UID}_x", # another user's prefix
f"app_{UID}x_phone", # uid prefix collision
])
def test_app_acl_wrong_clientid_denied(client, fs, clientid):
assert acl(client, APP_USER, f"vesper/{SERIAL}/control/ack", mqtt_auth.ACC_SUBSCRIBE, clientid=clientid) == 403
@pytest.mark.parametrize("topic", [
f"vesper/{SERIAL}/control/command/extra",
f"vesper/{SERIAL}/control",
f"other/{SERIAL}/control/command",
"vesper//control/command",
])
def test_app_acl_malformed_topics_denied(client, fs, topic):
assert acl(client, APP_USER, topic, mqtt_auth.ACC_WRITE) == 403
def test_app_acl_blocked_user_denied(client, fs):
user = f"app_{OTHER_UID}"
assert acl(client, user, f"vesper/{FOREIGN_SERIAL}/control/ack", mqtt_auth.ACC_SUBSCRIBE,
clientid=f"{user}_phone") == 403
def test_app_acl_unknown_user_denied(client, fs):
assert acl(client, "app_ghost", f"vesper/{SERIAL}/control/ack", mqtt_auth.ACC_SUBSCRIBE,
clientid="app_ghost_phone") == 403
def test_app_acl_uses_cache_and_invalidate_refreshes(client, fs):
topic = f"vesper/{SERIAL}/control/ack"
assert acl(client, APP_USER, topic, mqtt_auth.ACC_SUBSCRIBE) == 200
reads = fs.reads
for _ in range(5):
assert acl(client, APP_USER, topic, mqtt_auth.ACC_READ) == 200
assert fs.reads == reads # served from cache
# Unassign the device; the cached entry still allows until invalidated.
fs.users[0]._data["device_serials"] = []
assert acl(client, APP_USER, topic, mqtt_auth.ACC_READ) == 200
app_users.invalidate(UID)
assert acl(client, APP_USER, topic, mqtt_auth.ACC_READ) == 403
def test_app_acl_cache_expires(client, fs, monkeypatch):
topic = f"vesper/{SERIAL}/control/ack"
assert acl(client, APP_USER, topic, mqtt_auth.ACC_READ) == 200
fs.users[0]._data["device_serials"] = []
clock = app_users.time.monotonic() + app_users.CACHE_TTL_SECONDS + 1
monkeypatch.setattr(app_users.time, "monotonic", lambda: clock)
assert acl(client, APP_USER, topic, mqtt_auth.ACC_READ) == 403
# ---------------------------------------------------------------------------
# /mqtt/auth/acl — devices (unchanged behaviour)
# ---------------------------------------------------------------------------
@pytest.mark.parametrize("acc", [1, 2, 4])
def test_device_acl_own_topics(client, acc):
assert acl(client, SERIAL, f"vesper/{SERIAL}/status/heartbeat", acc, clientid="") == 200
@pytest.mark.parametrize("acc", [1, 2, 4])
def test_device_acl_foreign_topics_denied(client, acc):
assert acl(client, SERIAL, f"vesper/{FOREIGN_SERIAL}/status/heartbeat", acc, clientid="") == 403
def test_kiosk_acl_base_device_topics(client):
assert acl(client, f"{FOREIGN_SERIAL}-kiosk", f"vesper/{FOREIGN_SERIAL}/control/command", 2, clientid="") == 200
assert acl(client, f"{FOREIGN_SERIAL}-kiosk", f"vesper/{SERIAL}/control/command", 2, clientid="") == 403
def test_superuser_acl(client):
assert acl(client, "NodeRED", "vesper/#", 4, clientid="") == 200
+117
View File
@@ -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
View File
+33
View File
@@ -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
+170
View File
@@ -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
+6 -2
View File
@@ -4,7 +4,7 @@ from typing import List, Optional
# --- Request / Response schemas ---
class UserCreate(BaseModel):
class UserProfile(BaseModel):
email: str = ""
display_name: str = ""
photo_url: str = ""
@@ -17,6 +17,10 @@ class UserCreate(BaseModel):
quickSettingsPIN: str = ""
class UserCreate(UserProfile):
password: str = "" # request-only — used to create the Firebase Auth account, never persisted to Firestore or echoed back
class UserUpdate(BaseModel):
email: Optional[str] = None
display_name: Optional[str] = None
@@ -29,7 +33,7 @@ class UserUpdate(BaseModel):
quickSettingsPIN: Optional[str] = None
class UserInDB(UserCreate):
class UserInDB(UserProfile):
id: str
created_time: str = ""
lastActive: str = ""
+133 -54
View File
@@ -1,6 +1,6 @@
from datetime import datetime
from datetime import datetime, timezone
from google.cloud.firestore_v1 import DocumentReference
from google.cloud.firestore_v1 import DocumentReference, ArrayUnion, ArrayRemove
from firebase_admin import auth as firebase_auth
from shared.firebase import get_db, get_bucket
@@ -9,6 +9,37 @@ from users.models import UserCreate, UserUpdate, UserInDB
COLLECTION = "users"
# Firestore "in" queries accept at most 30 values.
_IN_QUERY_LIMIT = 30
def device_serial_of(device_data: dict) -> str:
"""The board serial as used in MQTT topics (vesper/{serial}/...).
`serial_number` is what gets flashed into NVS and what the firmware uses
as its MQTT username/topic id. Legacy docs predating the lifecycle system
only carry it in `device_id`.
"""
return (device_data.get("serial_number") or device_data.get("device_id") or "").strip()
def stage_device_serial_link(batch, user_ref: DocumentReference, serial: str, linked: bool) -> None:
"""Add (linked=True) or remove the serial from the user's `device_serials`
inside the caller's write batch, so it commits together with the device's
`user_list` change."""
if not serial:
return
op = ArrayUnion([serial]) if linked else ArrayRemove([serial])
batch.update(user_ref, {"device_serials": op})
def invalidate_mqtt_acl_cache(user_data: dict | None) -> None:
"""Drop the MQTT ACL cache entry for this user's Firebase uid."""
uid = (user_data or {}).get("uid") or ""
if uid:
from mqtt.app_users import invalidate
invalidate(uid)
def _convert_firestore_value(val):
"""Convert Firestore-specific types (Timestamp, DocumentReference) to strings."""
@@ -84,15 +115,46 @@ def get_user(user_doc_id: str) -> UserInDB:
def create_user(data: UserCreate) -> UserInDB:
"""Create a new user document in Firestore."""
"""Create a new user: a Firebase Auth account (so they can log into the app
immediately) plus the matching Firestore profile document.
The profile doc ID MUST be the Firebase Auth uid. The FlutterFlow app looks
up `users/{uid}` on login and creates a bare doc there if it's missing, and
MQTT auth (mqtt/app_users.py) + device `user_list` paths assume the same.
"""
if not data.password or len(data.password) < 6:
raise ValidationError("Password must be at least 6 characters.")
# Firebase Auth lowercases emails; store the same form so the profile
# matches what the app sees for the signed-in user.
email = (data.email or "").strip().lower()
if not email:
raise ValidationError("Email is required.")
db = get_db()
doc_data = data.model_dump()
doc_data = data.model_dump(exclude={"password"})
doc_data["email"] = email
doc_data["friendsList"] = []
doc_data["friendsInvited"] = []
doc_data["created_time"] = datetime.now(timezone.utc)
_, doc_ref = db.collection(COLLECTION).add(doc_data)
try:
firebase_user = firebase_auth.create_user(
email=email,
password=data.password,
display_name=data.display_name or None,
)
except firebase_auth.EmailAlreadyExistsError:
raise ValidationError(f"A user with email {email} already exists.")
doc_data["uid"] = firebase_user.uid
return UserInDB(id=doc_ref.id, **doc_data)
try:
db.collection(COLLECTION).document(firebase_user.uid).set(doc_data)
except Exception:
# Don't leave an Auth account behind with no profile doc.
firebase_auth.delete_user(firebase_user.uid)
raise
return UserInDB(id=firebase_user.uid, **_sanitize_dict(doc_data))
def update_user(user_doc_id: str, data: UserUpdate) -> UserInDB:
@@ -105,20 +167,29 @@ def update_user(user_doc_id: str, data: UserUpdate) -> UserInDB:
update_data = data.model_dump(exclude_none=True)
doc_ref.update(update_data)
invalidate_mqtt_acl_cache(doc.to_dict()) # status may have changed
updated_doc = doc_ref.get()
return _doc_to_user(updated_doc)
def delete_user(user_doc_id: str) -> None:
"""Delete a user document from Firestore."""
"""Delete a user document from Firestore, plus their Firebase Auth account if one exists."""
db = get_db()
doc_ref = db.collection(COLLECTION).document(user_doc_id)
doc = doc_ref.get()
if not doc.exists:
raise NotFoundError("User")
uid = doc.to_dict().get("uid", "")
if uid:
try:
firebase_auth.delete_user(uid)
except firebase_auth.UserNotFoundError:
pass
doc_ref.delete()
invalidate_mqtt_acl_cache(doc.to_dict())
def block_user(user_doc_id: str) -> UserInDB:
@@ -130,6 +201,7 @@ def block_user(user_doc_id: str) -> UserInDB:
raise NotFoundError("User")
doc_ref.update({"status": "blocked"})
invalidate_mqtt_acl_cache(doc.to_dict())
updated_doc = doc_ref.get()
return _doc_to_user(updated_doc)
@@ -143,6 +215,7 @@ def unblock_user(user_doc_id: str) -> UserInDB:
raise NotFoundError("User")
doc_ref.update({"status": "active"})
invalidate_mqtt_acl_cache(doc.to_dict())
updated_doc = doc_ref.get()
return _doc_to_user(updated_doc)
@@ -163,25 +236,25 @@ def assign_device(user_doc_id: str, device_doc_id: str) -> UserInDB:
if not device_doc.exists:
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()
user_list = device_data.get("user_list", [])
user_path = f"users/{user_doc_id}"
# Check if already assigned (handle both string paths and DocumentReferences)
already_assigned = False
for entry in user_list:
if isinstance(entry, DocumentReference):
if entry.path == user_path:
already_assigned = True
break
elif entry == user_path:
already_assigned = True
break
user_list = device_data.get("user_list", []) or []
already_assigned = any(devices_service.user_list_entry_id(e) == user_doc_id for e in user_list)
# Device user_list, the user's device_serials and the device_users mirror
# are written in one atomic batch. device_serials and the mirror are
# re-synced even when already assigned, to heal drift.
batch = db.batch()
if not already_assigned:
user_list.append(user_path)
device_ref.update({"user_list": user_list})
user_list.append(user_ref)
batch.update(device_ref, {"user_list": user_list})
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()
invalidate_mqtt_acl_cache(user_doc.to_dict())
return _doc_to_user(user_ref.get())
@@ -202,26 +275,25 @@ def unassign_device(user_doc_id: str, device_doc_id: str) -> UserInDB:
if not device_doc.exists:
raise NotFoundError("Device")
# Remove user from device's user_list
from devices import service as devices_service
# Remove user from device's user_list (any entry format)
device_data = device_doc.to_dict()
user_list = device_data.get("user_list", [])
user_path = f"users/{user_doc_id}"
user_list = device_data.get("user_list", []) or []
new_list = [e for e in user_list if devices_service.user_list_entry_id(e) != user_doc_id]
new_list = []
for entry in user_list:
if isinstance(entry, DocumentReference):
if entry.path != user_path:
new_list.append(entry)
elif entry != user_path:
new_list.append(entry)
device_ref.update({"user_list": new_list})
batch = db.batch()
batch.update(device_ref, {"user_list": new_list})
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()
invalidate_mqtt_acl_cache(user_doc.to_dict())
return _doc_to_user(user_ref.get())
def get_user_devices(user_doc_id: str) -> list[dict]:
"""Get all devices assigned to a user."""
"""Get all devices assigned to a user, via the user's `device_serials`."""
db = get_db()
# Verify user exists
@@ -230,25 +302,32 @@ def get_user_devices(user_doc_id: str) -> list[dict]:
if not user_doc.exists:
raise NotFoundError("User")
user_path = f"users/{user_doc_id}"
serials = [s for s in dict.fromkeys(user_doc.to_dict().get("device_serials") or []) if s]
# Match on serial_number first; fall back to the legacy device_id field for the rest.
found: dict[str, object] = {}
for field in ("serial_number", "device_id"):
remaining = [s for s in serials if s not in found]
for i in range(0, len(remaining), _IN_QUERY_LIMIT):
chunk = remaining[i:i + _IN_QUERY_LIMIT]
for doc in db.collection("devices").where(field, "in", chunk).stream():
sn = doc.to_dict().get(field)
if sn not in found:
found[sn] = doc
# Search all devices for this user in their user_list
devices = []
for doc in db.collection("devices").stream():
for sn in serials:
doc = found.get(sn)
if doc is None:
continue
data = doc.to_dict()
user_list = data.get("user_list", [])
for entry in user_list:
entry_path = entry.path if isinstance(entry, DocumentReference) else entry
if entry_path == user_path:
devices.append({
"id": doc.id,
"device_name": data.get("device_name", ""),
"device_id": data.get("device_id", ""),
"device_location": data.get("device_location", ""),
"is_Online": data.get("is_Online", False),
})
break
devices.append({
"id": doc.id,
"device_name": data.get("device_name", ""),
"device_id": data.get("device_id", ""),
"device_location": data.get("device_location", ""),
"is_Online": data.get("is_Online", False),
})
return devices
@@ -256,7 +335,7 @@ def get_user_devices(user_doc_id: str) -> list[dict]:
def set_password(user_doc_id: str, new_password: str) -> None:
"""Set a Firebase Auth password for a user via their Firestore document ID.
Requires the user document to have a non-empty `uid` field — populated
Requires the user document to have a non-empty `uid` field — populated
automatically for users who registered via the Flutter app.
"""
if not new_password or len(new_password) < 6:
@@ -270,7 +349,7 @@ def set_password(user_doc_id: str, new_password: str) -> None:
uid = doc.to_dict().get("uid", "")
if not uid:
raise ValidationError("This user has no Firebase Auth UID — they may not have signed up via the app yet.")
raise ValidationError("This user has no Firebase Auth UID — they may not have signed up via the app yet.")
try:
firebase_auth.update_user(uid, password=new_password)
+18
View File
@@ -0,0 +1,18 @@
# Windows / Docker Desktop dev machines only — copy to docker-compose.override.yml
# (gitignored; Docker Compose loads it automatically). The server does NOT use this.
#
# Why: a ./data/postgres bind mount onto the Windows filesystem hits a
# WSL2/Docker Desktop bug where the 9p/virtiofs bridge reports normal
# postgres:postgres 0600 ownership but the kernel still refuses the postgres
# user's own open() calls for write — silent on read, fatal on any WAL write.
# A Docker-managed named volume lives inside the WSL2 VM's own filesystem and
# avoids it. Create it once with: docker volume create bellsystems-postgres-data
services:
postgres:
volumes:
- postgres-data:/var/lib/postgresql/data
volumes:
postgres-data:
name: bellsystems-postgres-data
external: true
+6
View File
@@ -2,6 +2,7 @@ services:
backend:
build: ./backend
container_name: bellsystems-backend
restart: unless-stopped
env_file: .env
volumes:
- ./backend:/app
@@ -22,12 +23,14 @@ services:
frontend:
build: ./frontend
container_name: bellsystems-frontend
restart: unless-stopped
networks:
- internal
nginx:
image: nginx:alpine
container_name: bellsystems-nginx
restart: unless-stopped
ports:
- "90:80" # access v2 on localhost:8001
volumes:
@@ -47,6 +50,9 @@ services:
POSTGRES_USER: ${POSTGRES_USER}
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}
volumes:
# Server default: plain folder on the host (Linux, no WSL2 issues).
# Windows dev machines override this with a Docker volume in
# docker-compose.override.yml — see docker-compose.override.example.yml.
- ./data/postgres:/var/lib/postgresql/data
networks:
- internal
+84
View File
@@ -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
```
+226
View File
@@ -0,0 +1,226 @@
# MQTT Authentication for Phone-App Users
## Why this exists
The remote phone app (FlutterFlow + Firebase Auth) talks to Vesper boards over MQTT.
We did not want to create an MQTT account per app user, so app users log into
Mosquitto with their **Firebase identity**, and the Console backend decides what
each one may do, based on which devices are assigned to them.
Mosquitto uses **mosquitto-go-auth** with two backends:
- **files** (passwd file on the VPS): `admin`, `bonamin`, `NodeRED`.
- **http** (this Console): `POST /mqtt/auth/user` (on CONNECT) and
`POST /mqtt/auth/acl` (on SUBSCRIBE, PUBLISH and every message delivery).
Code: `backend/mqtt/auth.py`, `backend/mqtt/app_users.py`.
The Mosquitto / go-auth config lives on the VPS, **not in this repo**.
## Connection contract for the app (read this if you build the app)
| Setting | Value |
|------------|------------------------------------------------------------------------|
| Username | `app_<firebase_uid>` |
| Password | The user's current **Firebase ID token** (`getIdToken()`) |
| Client ID | Must start with `app_<firebase_uid>_`, e.g. `app_<uid>_<installId>` |
| Transport | **MQTT over secure WebSockets**: `wss://mqtt.bellsystems.net:443`, path `/mqtt` |
| Wildcards | Not allowed (`+` / `#` are denied) |
**Never connect the app to port 1883.** It is plain TCP for the boards only. The broker
would still check the login there, but by then the token has already been sent
unencrypted. Keep the MQTT keepalive below 3600 s (e.g. 30–60 s).
Any other client ID is refused on every topic. The prefix rule stops one user from
reusing another user's client ID to kick them off.
Allowed topics, only for serials assigned to that user:
| Action | `acc` | Topics |
|---------------------------------|-------|------------------------------------------------------------------------|
| Publish | 2 | `vesper/{serial}/control/command` |
| Subscribe / receive messages | 4 / 1 | `vesper/{serial}/control/ack`, `vesper/{serial}/status/heartbeat`, `vesper/{serial}/status/playback` |
Everything else is denied (403).
Token lifetime: Mosquitto checks the password **only at CONNECT**. When the app
reconnects, it must fetch a fresh ID token (`getIdToken()` refreshes an expired one).
A connection stays open past token expiry. Blocking or unassigning still takes effect
on that connection, because every publish or delivery goes through the ACL (within
about 60 s of the go-auth ACL cache).
## Which field is the device serial
The serial in `vesper/{serial}/...` is the device doc's **`serial_number`**: it is
flashed into NVS and the firmware uses it as its MQTT id. Legacy docs only have it in
**`device_id`**. `users.service.device_serial_of()` holds that rule; always use it.
## How access is decided
- `users/{doc}.device_serials: [string]` lists the serials a user may reach.
It mirrors the devices' `user_list` and is written in the **same atomic Firestore
batch** by every Console path that edits `user_list`:
- `users.service.assign_device` / `unassign_device`
- `POST` / `DELETE /api/devices/{id}/user-list` (device Manage tab)
- `PUT /api/devices/{id}` when the body contains `user_list`
(`devices.service.update_device`)
- Users are resolved by the **`uid` field** (a query), **never by doc ID**. Console-
created users used to get random doc IDs (`.add()`) — fixed 2026-09-30, the Console
now writes `users/{uid}` like FlutterFlow does — but older docs may still have a
random ID, so keep resolving by the `uid` field.
- A user is refused when `status == "blocked"`.
- Lookups are cached in-process for 60 s (`mqtt/app_users.py`). Assign/unassign,
update, block/unblock and delete call `invalidate(uid)`. If you add a new code path
that changes `user_list`, `device_serials` or `status`, it must do the same.
The cache is per process: if uvicorn ever runs multiple workers, invalidation only
reaches one of them (entries still expire after 60 s).
- `app_` usernames never go through the device HMAC or the legacy password.
## Legacy "vesper" password
Boards on pre-HMAC firmware still use the shared password `vesper`.
`MQTT_ALLOW_LEGACY_PASSWORD` (default `true`) controls it. It is only accepted for
device-shaped usernames. Each use is logged at WARNING, once per board per hour:
MQTT legacy password accepted for <serial> — board still on pre-HMAC firmware
When those lines stop appearing, set `MQTT_ALLOW_LEGACY_PASSWORD=false`.
## Rollout checklist
1. Deploy the backend.
2. **Backfill** `device_serials` for existing assignments (run it right after the deploy):
cd backend
python scripts/backfill_user_device_serials.py # dry run, writes nothing
python scripts/backfill_user_device_serials.py --apply # writes
It only writes the `device_serials` field on `users` docs. It is idempotent: a second
run finds nothing to change. Until it runs, the Console shows existing users with no
devices, and app users are denied everything.
3. **go-auth config on the VPS** (R = required, r = recommended):
auth_opt_backends files, http # R files first, then http
auth_opt_http_host <host reaching the backend> # R
auth_opt_http_port 8000 # R
auth_opt_http_getuser_uri /mqtt/auth/user # R
auth_opt_http_aclcheck_uri /mqtt/auth/acl # R
auth_opt_http_params_mode form # R endpoints read form fields; go-auth's default is json
auth_opt_http_response_mode status # r
auth_opt_http_method POST # r
auth_opt_http_timeout 5 # r
auth_opt_disable_superuser true # r no superuser endpoint exists or is needed
auth_opt_cache true # r
auth_opt_cache_type go-cache # r
auth_opt_auth_cache_seconds 60 # r
auth_opt_acl_cache_seconds 60 # r
auth_opt_auth_jitter_seconds 10 # r
auth_opt_acl_jitter_seconds 10 # r
allow_anonymous false # R
4. **Files-backend ACL: verified OK (2026-09-30).** The VPS config sets no
`auth_opt_files_acl_path` (nor `acl_file`). A live test confirmed the files backend
does **not** grant ACLs to everyone, so every ACL check reaches the Console. If an
ACL file is ever added, only lines under `user admin` / `user bonamin` /
`user NodeRED` are safe. A `pattern` line, or a `topic` line placed before the first
`user` line, applies to every user (app users included) and must not cover `vesper/...`.
Re-run the isolation test after any broker config change (on the VPS host):
A=PV25L22BP01R01; B=PV26B02BP01R01
PW=$(docker exec bellsystems-backend python -c "from mqtt.auth import _derive_password; print(_derive_password('$A'))")
# own topics -> should print messages
docker exec mosquitto mosquitto_sub -h localhost -i acl-test-own -u "$A" -P "$PW" -t "vesper/$A/#" -v -W 5
# foreign topics -> must say "All subscription requests were denied."
docker exec mosquitto mosquitto_sub -h localhost -i acl-test-foreign -u "$A" -P "$PW" -t "vesper/$B/#" -v -W 5
5. **TLS for the app: done (2026-09-30).** See "Current VPS broker setup" below.
Test it from the VPS host (should print `connect: Success` and a `got:` line):
docker exec -i bellsystems-backend python - <<'EOF'
import time, paho.mqtt.client as m
from mqtt.auth import _derive_password
A = "PV25L22BP01R01"
c = m.Client(m.CallbackAPIVersion.VERSION2, client_id="wss-test", transport="websockets")
c.ws_set_options(path="/mqtt")
c.tls_set()
c.username_pw_set(A, _derive_password(A))
c.on_connect = lambda c, u, f, rc, p: (print("connect:", rc), c.subscribe(f"vesper/{A}/#"))
c.on_message = lambda c, u, msg: print("got:", msg.topic)
c.connect("mqtt.bellsystems.net", 443, 30)
c.loop_start(); time.sleep(8); c.loop_stop()
EOF
### Current VPS broker setup (as of 2026-09-30)
- Container `mosquitto`, image `iegomez/mosquitto-go-auth:latest`.
- Config: host `/home/bellsystems/stacks/mosquitto/config/mosquitto.conf`, mounted at
`/etc/mosquitto/mosquitto.conf` (Docker images usually use `/mosquitto/config`; this
one does not). Passwd file: `/home/bellsystems/stacks/mosquitto/passwd`.
- Already set correctly: `backends files,http`, `http_host 172.20.0.1` (Docker bridge),
`http_port 8000`, both URIs, `http_method post`, `params_mode form`,
`response_mode status`, `cache true`, `cache_reset true`.
- `allow_anonymous false` ✓. `auth_cache_seconds 60`, `acl_cache_seconds 60` ✓.
`auth_opt_hasher` is not set (a harmless "defaulting to PBKDF2" warning at start).
- Listeners:
- `listener 1883 0.0.0.0`: plain TCP, **boards only** (ESP32 can't spare RAM for TLS).
Published on the host as `1883:1883`.
- `listener 8083` + `protocol websockets`: plain WebSockets, **not published** on the
host. Only reachable from the Docker network `npm_npmnet`.
- TLS is terminated by **NPM** (NPMplus, container `npm-npm-1`), which also renews the
Let's Encrypt certificate. Proxy host: `mqtt.bellsystems.net` → `http://mosquitto:8083`,
Force SSL + HTTP/2 on. Advanced config:
proxy_read_timeout 3600s;
proxy_send_timeout 3600s;
(Without these, NPM drops idle MQTT connections after 60 s.) NPMplus has no
"Websockets Support" toggle; WebSockets are always on.
- Compose file: `/home/bellsystems/stacks/mosquitto/docker-compose.yml`. The service is
on `default` (reaches the backend at `172.20.0.1:8000`) **and** the external network
`npm_npmnet` (so NPM can reach `mosquitto:8083`). Removing `default` breaks all
board logins.
- Rollback for the TLS change: `.bak` copies of `mosquitto.conf` and `docker-compose.yml`
sit next to the originals. Restore them, run `docker compose up -d` in that folder,
then delete the NPM proxy host.
## Known gaps / decisions
- **Console backend port 8000 is public.** It is published as `0.0.0.0:8000` and the VPS
has no firewall (Docker-published ports bypass host firewall rules anyway), so anyone
can call `/mqtt/auth/user` and `/mqtt/auth/acl`. The passwords can't realistically be
guessed, so it's not urgent, but these endpoints are meant only for Mosquitto.
To be fixed separately, carefully, so nginx/NPM keep reaching the Console.
- **Old-firmware boards use a different command topic.** Broker logs (2026-09-30) show
some boards (e.g. `PV26B02BP01R01`, `BSVSPR-26C20B-STD10R-2KCDPH`) subscribing to
`vesper/{serial}/control`, not `vesper/{serial}/control/command`. The app ACL only
allows publishing to `control/command`, so the app cannot command those boards until
they run current firmware. (The Console's own `publish_command` has the same limitation.)
Do not widen the ACL to `control` without deciding it deliberately.
- **FlutterFlow writes to `user_list`.** If the app changes `user_list` directly in
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
cannot reach the device over MQTT. The app owner will handle this in the app.
- **The `device_users` subcollection** on devices (`{role, user_reference}`, the older
way of recording device users) is a **write-only mirror** since 2026-11. `user_list`
is the only source of truth: the Console reads assignments only from it
(`devices.service.get_device_users`, which takes just the `role` from the mirror).
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
legacy-password logins are WARNING.
## Tests
cd backend
pip install pytest # not in requirements.txt
python -m pytest tests
`tests/test_mqtt_auth.py` covers the auth and ACL endpoints.
`tests/test_device_serials_sync.py` covers the device PUT sync.
Firebase and Firestore are mocked.
+14 -3
View File
@@ -9,6 +9,7 @@ import { Link, useLocation, useNavigate } from 'react-router-dom'
import { useAuth } from '@/hooks/useAuth'
import api from '@/lib/api'
import HeaderSearch from '@/components/ui/HeaderSearch'
import { getLocalizedValue } from '@/lib/melodyUtils'
// ─── Breadcrumb config ────────────────────────────────────────────────────────
@@ -52,10 +53,10 @@ const ENTITY_RESOLVERS = {
customers: { path: (id) => `/crm/customers/${id}`, label: (d) => [d.name, d.surname].filter(Boolean).join(' ') || d.organization || null },
products: { path: (id) => `/crm/products/${id}`, label: (d) => d.name || null },
quotations: { path: (id) => `/crm/quotations/${id}`, label: (d) => d.quotation_number || null },
devices: { path: (id) => `/devices/${id}`, label: (d) => d.name || d.device_id || null },
devices: { path: (id) => `/devices/${id}`, label: (d) => d.console_name || d.device_name || d.device_id || null },
orders: { path: (id) => `/crm/orders/${id}`, label: (d) => d.order_number || null },
melodies: { path: (id) => `/melodies/${id}`, label: (d) => d.name || null },
archetypes: { path: (id) => `/builder/melodies/${id}`, label: (d) => d.name || null },
melodies: { path: (id) => `/melodies/${id}`, label: (d) => getLocalizedValue(d.information?.name, 'en', '') || null },
archetypes: { path: (id) => `/builder/melodies/${id}`, label: (d) => getLocalizedValue(d.information?.name, 'en', '') || null },
users: { path: (id) => `/users/${id}`, label: (d) => d.name || d.display_name || null },
notes: { path: (id) => `/equipment/notes/${id}`, label: (d) => d.title || d.subject || null },
staff: { path: (id) => `/staff/${id}`, label: (d) => d.name || null },
@@ -292,6 +293,16 @@ const SETTINGS_ITEMS = [
</svg>
),
},
{
to: '/settings/log-retention',
label: 'Log Retention',
icon: (
<svg width="14" height="14" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
<circle cx="8" cy="8" r="6"/>
<path d="M8 5v3l2 1.5"/>
</svg>
),
},
{
to: '/settings/pages',
label: 'Page Settings',
@@ -68,6 +68,7 @@ const Icons = {
commandCenter: () => <S><rect x="2" y="2" width="12" height="12" rx="1.5"/><path d="M5 6l2 2-2 2M9 10h2"/></S>,
blackBox: () => <SvgIcon Component={IcoBlackbox} />,
deviceSettings: () => <SvgIcon Component={IcoMelodySettings} />,
onboard: () => <S><path d="M5 8l2 2 4-4"/><rect x="2" y="2" width="12" height="12" rx="2"/></S>,
appUsers: () => <S><circle cx="6" cy="5" r="2.5"/><path d="M2 13c0-2.2 1.8-4 4-4"/><circle cx="12" cy="7" r="2"/><path d="M9.5 13c0-1.65 1.12-3 2.5-3s2.5 1.35 2.5 3"/></S>,
melodies: () => <SvgIcon Component={IcoMelodies} />,
library: () => <SvgIcon Component={IcoMelodiesEditor} />,
@@ -132,6 +133,7 @@ const navSections = [
{ to: '/mqtt/commands', label: 'Command Center', icon: 'commandCenter' },
{ to: '/equipment/notes', label: 'BlackBox', icon: 'blackBox' },
{ to: '/devices/settings', label: 'Device Settings', icon: 'deviceSettings', placeholder: true },
{ to: '/devices/onboard', label: 'Onboard', icon: 'onboard' },
],
},
{ to: '/users', label: 'App Users', icon: 'appUsers', permission: 'app_users' },
@@ -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 &amp; resolve</Button>
)}
{status !== 'checking' && (
<Button variant="ghost" size="sm" icon={<Icon name="refresh" size={13} />} onClick={onRecheck}>
{status === 'unreachable' ? 'Retry' : 'Re-check'}
</Button>
)}
</div>
)
}
@@ -0,0 +1,71 @@
// frontend/src/components/shared/CopyableSerial.jsx
// Serial number display with click-to-copy — the whole text is clickable,
// not just the trailing icon, and the icon stays dimly visible at rest so
// its affordance isn't hover-only-discoverable (it was previously opacity:0
// at rest via an inline style, which beat the hover CSS rule and made the
// button invisible at all times).
import { useState } from 'react'
import Icon from '@/components/ui/Icon'
function copyText(text, onDone) {
if (navigator.clipboard) {
navigator.clipboard.writeText(text).then(onDone).catch(() => {
const ta = document.createElement('textarea')
ta.value = text; ta.style.cssText = 'position:fixed;opacity:0'
document.body.appendChild(ta); ta.select()
try { document.execCommand('copy'); onDone() } catch { /* clipboard unavailable */ }
document.body.removeChild(ta)
})
}
}
export default function CopyableSerial({ serial, className = '', style = {}, textStyle = {}, iconSize = 12 }) {
const [copied, setCopied] = useState(false)
if (!serial) return <span className={className} style={{ ...textStyle, ...style }}>—</span>
const handleCopy = () => {
copyText(serial, () => { setCopied(true); setTimeout(() => setCopied(false), 1500) })
}
return (
<button
type="button"
onClick={handleCopy}
title={copied ? 'Copied!' : 'Click to copy serial number'}
aria-label={copied ? 'Serial number copied' : 'Copy serial number'}
className={['copyable-serial', className].filter(Boolean).join(' ')}
style={{
display: 'inline-flex',
alignItems: 'center',
gap: 'var(--space-1)',
padding: 0,
border: 'none',
background: 'none',
cursor: 'pointer',
font: 'inherit',
color: 'inherit',
...style,
}}
>
<span style={textStyle}>{serial}</span>
<Icon
name={copied ? 'check' : 'copy'}
size={iconSize}
color={copied ? 'var(--color-success)' : 'currentColor'}
className="copyable-serial__icon"
/>
<style>{`
.copyable-serial .copyable-serial__icon {
opacity: 0.45;
transition: opacity 0.15s, color 0.15s;
}
.copyable-serial:hover .copyable-serial__icon,
.copyable-serial:focus-visible .copyable-serial__icon {
opacity: 1;
}
`}</style>
</button>
)
}
@@ -0,0 +1,200 @@
// frontend/src/components/shared/CrashDetail.jsx
// Crash detail for one fault boot event (firmware F-070): headline, task,
// uptime + heap snapshot at crash, PC/backtrace in ESP serial format, a
// ready-to-run addr2line command, the crashing build's ELF id, and — when the
// server has that build's firmware.elf and the xtensa addr2line binary —
// in-console decoding to function + file:line.
//
// Used by the device Health tab's boot history and the fleet Crash Report.
//
// Props:
// event — a boot event from /mqtt/boot-events (crash / pre_crash objects,
// or only the legacy crash_* columns for older firmware)
import { useState, useEffect } from 'react'
import api from '@/lib/api'
import Button from '@/components/ui/Button'
import StatusBadge from '@/components/ui/StatusBadge'
import Icon from '@/components/ui/Icon'
import { copyText } from '@/lib/clipboard'
import {
crashOf, preCrashOf, crashHeadline, excCauseName, hex32, isHeapExhaustion,
addressLine, addr2lineCommand, decodeAddresses, fmtBytes, fmtUptime,
} from '@/lib/crashReport'
const labelStyle = {
fontSize: 'var(--font-size-xs)', color: 'var(--color-text-muted)',
textTransform: 'uppercase', letterSpacing: 'var(--tracking-wide)',
}
const monoBlockStyle = {
flex: 1, minWidth: 0, margin: 0,
padding: 'var(--space-2) var(--space-3)',
background: 'var(--color-bg-abyss)', border: '1px solid var(--color-border)',
borderRadius: 'var(--radius-md)',
fontFamily: 'var(--font-family-mono)', fontSize: 'var(--font-size-xs)',
color: 'var(--color-text-primary)',
whiteSpace: 'pre-wrap', wordBreak: 'break-all',
}
function Field({ label, value, muted, mono = true }) {
return (
<div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-1)', minWidth: 0 }}>
<span style={labelStyle}>{label}</span>
<span style={{
fontSize: 'var(--font-size-sm)',
fontFamily: mono ? 'var(--font-family-mono)' : undefined,
color: muted ? 'var(--color-text-muted)' : 'var(--color-text-primary)',
wordBreak: 'break-all',
}}>
{value ?? '—'}
</span>
</div>
)
}
function CopyRow({ label, text }) {
const [copied, setCopied] = useState(false)
const handleCopy = () => {
copyText(text).then(() => {
setCopied(true)
setTimeout(() => setCopied(false), 1500)
}).catch(() => {})
}
return (
<div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-1)' }}>
<span style={labelStyle}>{label}</span>
<div style={{ display: 'flex', alignItems: 'flex-start', gap: 'var(--space-2)' }}>
<pre style={monoBlockStyle}>{text}</pre>
<Button
variant="ghost"
size="sm"
icon={<Icon name={copied ? 'check' : 'copy'} size={14} />}
onClick={handleCopy}
aria-label={`Copy ${label}`}
>
{copied ? 'Copied' : 'Copy'}
</Button>
</div>
</div>
)
}
function DecodePanel({ event, elfSha256 }) {
const [info, setInfo] = useState(null) // /firmware/elf/{sha}
const [results, setResults] = useState(null) // decoded frames
const [decoding, setDecoding] = useState(false)
const [error, setError] = useState('')
useEffect(() => {
let cancelled = false
setInfo(null); setResults(null); setError('')
api.get(`/firmware/elf/${elfSha256}`)
.then(res => { if (!cancelled) setInfo(res) })
.catch(() => { if (!cancelled) setInfo({ exists: false, decoder_available: false, unavailable: true }) })
return () => { cancelled = true }
}, [elfSha256])
const handleDecode = async () => {
setDecoding(true); setError('')
try {
const res = await api.post(`/firmware/elf/${elfSha256}/decode`, { addresses: decodeAddresses(event) })
setResults(res.results || [])
} catch (err) {
setError(err.message || 'Decoding failed.')
} finally {
setDecoding(false)
}
}
if (!info) return null
let note = null
if (info.unavailable) note = 'Could not check the symbol store for this build.'
else if (!info.exists) note = `No firmware.elf uploaded for build ${elfSha256}. Attach it to the firmware release to decode here — or use the command above.`
else if (!info.decoder_available) note = 'The ELF for this build is on the server, but the xtensa addr2line decoder is not installed there — use the command above.'
return (
<div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-2)' }}>
<span style={labelStyle}>Decoded backtrace</span>
{note ? (
<span style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-text-muted)' }}>{note}</span>
) : results ? (
results.length === 0 ? (
<span style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-text-muted)' }}>No addresses to decode.</span>
) : (
<pre style={monoBlockStyle}>
{results.map(r => `${r.address}: ${r.frames.join('\n ')}`).join('\n')}
</pre>
)
) : (
<div>
<Button variant="secondary" size="sm" onClick={handleDecode} loading={decoding}>
Decode with firmware.elf
</Button>
</div>
)}
{error && <span style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-danger)' }}>{error}</span>}
</div>
)
}
export default function CrashDetail({ event }) {
const crash = crashOf(event)
const pre = preCrashOf(event)
if (!crash && !pre) return null
const abortMsg = pre?.abort_msg || null
const headline = crashHeadline(event)
const heapLow = isHeapExhaustion(pre)
const addrs = addressLine(crash)
const command = addr2lineCommand(event)
return (
<div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-4)', minWidth: 0 }}>
{/* Headline — abort_msg when present, else the exception cause name */}
<div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-2)' }}>
<span style={{
fontFamily: 'var(--font-family-mono)', fontSize: 'var(--font-size-md)',
fontWeight: 'var(--font-weight-semibold)', color: 'var(--color-danger)', wordBreak: 'break-word',
}}>
{headline || 'Fault reset (no coredump)'}
</span>
<div style={{ display: 'flex', flexWrap: 'wrap', gap: 'var(--space-2)' }}>
{heapLow && <StatusBadge variant="warning" size="sm">Likely heap exhaustion / fragmentation</StatusBadge>}
{crash?.backtraceCorrupted && <StatusBadge variant="warning" size="sm">Backtrace corrupted</StatusBadge>}
{!crash && <StatusBadge variant="neutral" size="sm">No coredump</StatusBadge>}
</div>
{abortMsg && crash && (
<span style={{ fontSize: 'var(--font-size-xs)', color: 'var(--color-text-muted)' }}>
This was an abort. The PC and exception below describe the abort() mechanism, not the cause,
and the first 2–4 backtrace frames are abort internals — the real call site is further down.
</span>
)}
</div>
<div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(150px, 1fr))', gap: 'var(--space-3)' }}>
<Field label="Faulting task" value={crash?.task} />
<Field label="Uptime at crash" value={pre ? fmtUptime(pre.uptime_ms) : null} />
<Field label="Free heap" value={pre ? fmtBytes(pre.free_heap) : null} />
<Field label="Largest free block" value={pre ? fmtBytes(pre.largest_block) : null} />
<Field label="Min free heap" value={pre ? fmtBytes(pre.min_free_heap) : null} />
{crash && (
<>
<Field
label="Exception"
value={crash.excCause != null ? `${excCauseName(crash.excCause)} (${crash.excCause})` : null}
muted={!!abortMsg}
/>
<Field label="Program counter" value={hex32(crash.pc)} muted={!!abortMsg} />
<Field label="Faulting address" value={hex32(crash.excVaddr)} muted={!!abortMsg} />
<Field label="Build (ELF SHA-256)" value={crash.elfSha256} />
</>
)}
</div>
{addrs && <CopyRow label="PC + backtrace" text={addrs} />}
{command && <CopyRow label="addr2line command" text={command} />}
{crash?.elfSha256 && command && <DecodePanel event={event} elfSha256={crash.elfSha256} />}
</div>
)
}
+123
View File
@@ -0,0 +1,123 @@
// src/components/ui/EditableText.jsx
// Inline hover-to-edit text — shows a pencil icon on hover, click swaps to a
// text input in place. Enter/blur saves, Escape cancels. Use for a single
// display value that's editable in-place without a modal (e.g. a page hero
// title) — for anything with more than one field, use a Modal instead.
//
// Props:
// value — string — current display value
// placeholder — string — shown (italic, muted) when value is empty
// onSave — (newValue) => void | Promise — called on confirm; not called if unchanged
// editable — bool — hide the pencil / disable editing entirely (default: true)
// textStyle — style object applied to the display span AND the input, so
// swapping between them doesn't shift surrounding layout
// className — extra class on the root element
// inputAriaLabel — string — accessible label for the input while editing
import { useState, useRef, useEffect } from 'react'
import Icon from '@/components/ui/Icon'
export default function EditableText({
value,
placeholder = 'Untitled',
onSave,
editable = true,
textStyle = {},
className = '',
inputAriaLabel = 'Edit value',
}) {
const [editing, setEditing] = useState(false)
const [draft, setDraft] = useState(value || '')
const [saving, setSaving] = useState(false)
const inputRef = useRef(null)
useEffect(() => {
if (editing) {
setDraft(value || '')
// Wait a tick so the input exists before focusing.
requestAnimationFrame(() => inputRef.current?.select())
}
}, [editing, value])
const commit = async () => {
const trimmed = draft.trim()
setEditing(false)
if (trimmed === (value || '')) return
setSaving(true)
try {
await onSave?.(trimmed)
} finally {
setSaving(false)
}
}
const cancel = () => {
setDraft(value || '')
setEditing(false)
}
if (editing) {
return (
<input
ref={inputRef}
type="text"
value={draft}
onChange={(e) => setDraft(e.target.value)}
onBlur={commit}
onKeyDown={(e) => {
if (e.key === 'Enter') { e.preventDefault(); commit() }
if (e.key === 'Escape') { e.preventDefault(); cancel() }
}}
aria-label={inputAriaLabel}
disabled={saving}
className={className}
style={{
...textStyle,
background: 'var(--color-bg-elevated)',
border: '1px solid var(--color-border-strong)',
borderRadius: 'var(--radius-sm)',
padding: '1px 6px',
outline: 'none',
minWidth: '120px',
}}
/>
)
}
return (
<span
className={['editable-text', className].filter(Boolean).join(' ')}
style={{ display: 'inline-flex', alignItems: 'center', gap: 'var(--space-2)' }}
>
<span style={{ ...textStyle, ...(value ? {} : { color: 'var(--color-text-muted)', fontStyle: 'italic' }) }}>
{value || placeholder}
</span>
{editable && (
<button
type="button"
onClick={() => setEditing(true)}
aria-label={inputAriaLabel}
title={inputAriaLabel}
className="editable-text__pencil"
style={{
display: 'inline-flex',
alignItems: 'center',
justifyContent: 'center',
width: 24,
height: 24,
padding: 0,
border: 'none',
borderRadius: 'var(--radius-sm)',
background: 'transparent',
color: 'var(--color-text-muted)',
cursor: 'pointer',
opacity: 0,
transition: 'opacity 0.15s, color 0.15s, background 0.15s',
}}
>
<Icon name="edit" size={14} />
</button>
)}
</span>
)
}
+514
View File
@@ -0,0 +1,514 @@
// src/components/ui/LineChart.jsx
// Time-series line chart — hand-rolled SVG, no charting library. Single primitive
// reused for every metric-over-time graph in the console (RSSI, ping latency,
// free heap, etc). Never build a one-off inline chart in a page — use this.
//
// Props:
// data — array<{ x: number|string (ms epoch or index), y: number|null }>
// null y-values render as gaps (device offline / no sample), not zeros.
// color — CSS color token, e.g. 'var(--color-primary)' (default: 'var(--color-primary)')
// Ignored if colorStops is set.
// colorStops — array<{ value: number, color: string }>, sorted ascending by
// value — colors the line/fill as a smooth vertical gradient
// keyed to the Y VALUE (not x-position), so "danger red" always
// means the same y-value everywhere on the chart regardless of
// when it occurred. Requires >= 2 stops.
// height — number, px (default: 160)
// formatValue — (y) => string — used in tooltip + trailing value badge
// formatX — (x) => string — used in tooltip
// unit — string appended after formatValue in the trailing badge, e.g. 'dBm', 'ms', 'KB'
// xMin, xMax — number (ms epoch) — explicit axis bounds. When provided, the
// chart renders this FULL span even if data covers less of it
// (e.g. a 30-day range with 1 day of real data shows the data
// bunched at one end, not silently zoomed to fit). Omit to
// auto-fit to the data's own x-range (previous behaviour).
// gapThresholdMs — if the x-gap between two consecutive points exceeds this,
// the segment break is drawn as a dotted "possibly offline"
// connector instead of a silent gap. Omit to just break silently.
// offlineWindows — array<{ start: number, end: number }> (ms epoch) — explicit
// "known offline" windows to render as dotted baseline
// regardless of this chart's own data gaps. Use this instead
// of (or alongside) gapThresholdMs when offline periods are
// computed once from a shared/authoritative signal (e.g. the
// device's heartbeat cadence) and applied identically across
// several charts whose own series may be too sparse for
// per-series gap detection to find the same windows —
// otherwise a chart fed from a low-frequency series (ping,
// diagnostics) can under- or over-detect gaps relative to one
// fed from a high-frequency series (heartbeats) even though
// both describe the same device over the same real outage.
// Always rendered in the 'baseline' style (see gapStyle)
// since these are known facts, not inferred from this
// chart's own two neighboring points.
// gapStyle — 'connector' | 'baseline' (default: 'connector')
// 'connector' draws the dotted line directly between the last point
// before the gap and the first point after it (diagonal if their
// y-values differ). 'baseline' instead draws it as a flat dotted
// line along the chart's bottom edge, spanning the same x-range —
// reads as "no data" rather than implying a value in between.
// emptyLabel — string shown when data has no non-null points
// className — extra classes on the root element
import { useMemo, useState, useRef, useId } from 'react'
const PAD = { top: 12, right: 12, bottom: 22, left: 8 }
// Above this many raw points, downsample to ~2 points (min+max) per pixel
// column so spikes survive being zoomed out over a wide time range instead
// of getting smoothed away by naive decimation.
const DOWNSAMPLE_THRESHOLD = 400
// Centripetal Catmull-Rom → cubic Bezier. Using each segment's actual
// Euclidean distance (not a fixed 1/6 fraction) keeps tangents proportional
// to real point spacing — with the naive uniform version, a run of tightly-
// packed points followed by a big gap produces an overshooting tangent that
// visibly loops the curve backward before continuing forward.
function clampToRange(v, a, b) {
return Math.min(Math.max(v, Math.min(a, b)), Math.max(a, b))
}
function smoothPath(seg) {
if (seg.length < 2) return `M${seg[0].px},${seg[0].py}`
if (seg.length === 2) return `M${seg[0].px},${seg[0].py}L${seg[1].px},${seg[1].py}`
const dist = (a, b) => Math.max(1e-3, Math.hypot(b.px - a.px, b.py - a.py))
const n = seg.length
let d = `M${seg[0].px},${seg[0].py}`
for (let i = 0; i < n - 1; i++) {
const p0 = seg[i - 1] || seg[i]
const p1 = seg[i]
const p2 = seg[i + 1]
const p3 = seg[i + 2] || p2
const d1 = dist(p0, p1)
const d2 = dist(p1, p2)
const d3 = dist(p2, p3)
// Tangent at p1, scaled by the ratio of the adjacent segment length to
// the sum of both neighboring segments — this is what makes it
// "centripetal": short segments pull the tangent in, long ones don't
// over-extend it.
const t1 = d1 / (d1 + d2)
let c1x = p1.px + (p2.px - p0.px) * (t1 / 3)
const c1y = p1.py + (p2.py - p0.py) * (t1 / 3)
const t2 = d2 / (d2 + d3)
let c2x = p2.px - (p3.px - p1.px) * ((1 - t2) / 3)
const c2y = p2.py - (p3.py - p1.py) * ((1 - t2) / 3)
// X is always time in these charts, so it must be monotonic — a cubic
// segment whose control point x strays outside its own [p1.x, p2.x] span
// renders as the line visibly reversing direction (looping backward)
// before continuing forward. This happens whenever a neighboring point
// pulls the tangent estimate too far: most commonly right at a segment's
// open boundary (next to a data gap, where there's no further point to
// temper the tangent), and also wherever the min/max-per-bucket
// downsampler emits two points with nearly identical x — a near-vertical
// spike that the same tangent math overshoots on either side of. Clamping
// x keeps every curve horizontally monotonic without altering its y
// shape, which is what removes the loop while leaving normal smoothing
// (evenly spaced points, no reordering) completely unaffected.
c1x = clampToRange(c1x, p1.px, p2.px)
c2x = clampToRange(c2x, p1.px, p2.px)
d += `C${c1x},${c1y} ${c2x},${c2y} ${p2.px},${p2.py}`
}
return d
}
function buildSegments(points) {
// Splits into contiguous segments at null gaps — each becomes its own path.
const segments = []
let current = []
for (const p of points) {
if (p.y == null) {
if (current.length) segments.push(current)
current = []
} else {
current.push(p)
}
}
if (current.length) segments.push(current)
return segments
}
// Min/max-per-pixel-bucket downsampling. Guarantees any spike/dip within a
// bucket survives (both the min AND max point are kept), unlike averaging
// which can smooth a brief extreme out of existence when zoomed out over a
// wide range. Null (gap) points pass through untouched — they carry their
// own meaning and must never be merged into a bucket.
function downsample(points, targetBuckets) {
if (points.length <= targetBuckets * 2) return points
const validXs = points.filter(p => p.y != null).map(p => p.x)
if (validXs.length === 0) return points
const xMin = Math.min(...validXs)
const xMax = Math.max(...validXs)
const span = Math.max(1, xMax - xMin)
const buckets = new Map()
for (const p of points) {
if (p.y == null) continue
const bucketIdx = Math.min(targetBuckets - 1, Math.floor(((p.x - xMin) / span) * targetBuckets))
const existing = buckets.get(bucketIdx)
if (!existing) {
buckets.set(bucketIdx, { min: p, max: p })
} else {
if (p.y < existing.min.y) existing.min = p
if (p.y > existing.max.y) existing.max = p
}
}
// Each bucket contributes its min and max point (the same point twice if
// only one sample fell in that bucket) — order doesn't matter here since
// gap markers are merged back in and everything is sorted by x afterward.
const flattened = []
for (const { min, max } of buckets.values()) {
flattened.push(min)
if (max !== min) flattened.push(max)
}
const gaps = points.filter(p => p.y == null)
return [...flattened, ...gaps].sort((a, b) => a.x - b.x)
}
export default function LineChart({
data = [],
color = 'var(--color-primary)',
colorStops = null,
height = 160,
formatValue = v => String(v),
formatX = x => String(x),
unit = '',
xMin: xMinProp = null,
xMax: xMaxProp = null,
gapThresholdMs = null,
offlineWindows = null,
gapStyle = 'connector',
emptyLabel = 'No data yet.',
className = '',
}) {
const containerRef = useRef(null)
const [width, setWidth] = useState(600)
const [hoverIdx, setHoverIdx] = useState(null)
const gradientId = useId().replace(/[^a-zA-Z0-9_-]/g, '')
// Measure container width responsively — ResizeObserver is the only
// chart-sizing mechanism in the app.
const measureRef = el => {
containerRef.current = el
if (!el) return
const ro = new ResizeObserver(entries => {
const w = entries[0]?.contentRect?.width
if (w) setWidth(w)
})
ro.observe(el)
el._ro = ro
}
const validPoints = data.filter(d => d.y != null)
const hasData = validPoints.length > 0
const { points, yMin, yMax, xMin, xMax } = useMemo(() => {
if (!hasData) return { points: [], yMin: 0, yMax: 1, xMin: 0, xMax: 1 }
const xs = data.map(d => Number(d.x))
const ys = validPoints.map(d => Number(d.y))
// Explicit range props win — the chart must render the FULL requested
// span (e.g. "last 30 days") even when real data only covers a sliver of
// it, rather than silently auto-zooming to whatever data happens to exist.
let xMin = xMinProp != null ? Number(xMinProp) : Math.min(...xs)
let xMax = xMaxProp != null ? Number(xMaxProp) : Math.max(...xs)
let yMin = Math.min(...ys)
let yMax = Math.max(...ys)
// colorStops are value-anchored on an absolute scale (e.g. alert
// thresholds), not the data's own range — if the y-axis only auto-fit to
// the data, stops outside that range would clamp to the same 0%/100%
// gradient offset and collapse into a hard edge instead of a smooth
// blend. Widening yMin/yMax to cover every stop keeps the full gradient
// visible even when the data currently sits well inside a safe band.
if (colorStops && colorStops.length) {
const stopValues = colorStops.map(s => s.value)
yMin = Math.min(yMin, ...stopValues)
yMax = Math.max(yMax, ...stopValues)
}
if (xMin === xMax) { xMin -= 1; xMax += 1 }
if (yMin === yMax) { yMin -= 1; yMax += 1 }
// Headroom so the line/dots never touch the plot edge.
const yPad = (yMax - yMin) * 0.12
yMin -= yPad
yMax += yPad
const innerW = Math.max(1, width - PAD.left - PAD.right)
const innerH = Math.max(1, height - PAD.top - PAD.bottom)
let mapped = data.map(d => {
const x = Number(d.x)
const px = PAD.left + ((x - xMin) / (xMax - xMin)) * innerW
const py = d.y == null ? null : PAD.top + innerH - ((Number(d.y) - yMin) / (yMax - yMin)) * innerH
return { x, y: d.y, px, py: py ?? 0 }
})
// Drop points that fall outside the explicit range entirely (can happen
// if a caller passes data slightly wider than xMin/xMax).
mapped = mapped.filter(p => p.x >= xMin - 1 && p.x <= xMax + 1)
// Cut every real segment at explicit offline-window boundaries —
// offlineWindows is computed externally (e.g. from a denser series like
// heartbeats) and can disagree with THIS series' own point spacing. Two
// distinct cases both need handling, not just one:
// 1. A real sample happens to fall inside the window (mask it to null).
// 2. No sample at all falls inside a narrow window in a sparse series
// (ping every 60s, diagnostics every 5min) — the point just before
// and just after the window are still adjacent in the array with
// nothing between them, so without inserting explicit boundary gap
// markers, smoothPath() draws one continuous curve straight across
// the "offline" stretch, right on top of the dotted connector.
// Inserting a null-y marker at both edges of the window forces
// buildSegments() to break there even when case 2 applies.
if (offlineWindows && offlineWindows.length) {
mapped = mapped.map(p => {
if (p.y == null) return p
const inWindow = offlineWindows.some(w => p.x >= w.start && p.x <= w.end)
return inWindow ? { ...p, y: null } : p
})
const boundaryMarkers = []
for (const w of offlineWindows) {
const spansWindow = mapped.some(p => p.x < w.start) && mapped.some(p => p.x > w.end)
if (!spansWindow) continue
for (const x of [w.start, w.end]) {
if (x < xMin || x > xMax) continue
const px = PAD.left + ((x - xMin) / (xMax - xMin)) * innerW
boundaryMarkers.push({ x, y: null, px, py: 0 })
}
}
if (boundaryMarkers.length) {
mapped = [...mapped, ...boundaryMarkers].sort((a, b) => a.x - b.x)
}
}
const targetBuckets = Math.max(50, Math.ceil(width / 3))
if (mapped.length > DOWNSAMPLE_THRESHOLD) {
mapped = downsample(mapped, targetBuckets)
}
return { points: mapped, yMin, yMax, xMin, xMax }
}, [data, width, height, hasData, validPoints, xMinProp, xMaxProp, colorStops, offlineWindows])
if (!hasData) {
return (
<div
className={['linechart linechart--empty', className].filter(Boolean).join(' ')}
style={{
height,
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
color: 'var(--color-text-muted)',
fontSize: 'var(--font-size-sm)',
fontStyle: 'italic',
}}
>
{emptyLabel}
</div>
)
}
const segments = buildSegments(points)
const innerW = Math.max(1, width - PAD.left - PAD.right)
const innerH = Math.max(1, height - PAD.top - PAD.bottom)
const baseline = PAD.top + innerH
const hovered = hoverIdx != null ? points[hoverIdx] : null
const latest = [...points].reverse().find(p => p.y != null)
// colorStops → an SVG linearGradient keyed to Y VALUE. gradientUnits
// userSpaceOnUse + y1/y2 in pixel-space (not objectBoundingBox) is what
// makes "red" always mean the same underlying value across every chart,
// rather than always meaning "top of whatever this chart's own range is."
const strokeColor = colorStops ? `url(#${gradientId})` : color
const sortedStops = colorStops ? [...colorStops].sort((a, b) => a.value - b.value) : null
// Dotted "possibly offline" connectors — drawn between the last point of one
// segment and the first point of the next, only when the real x-gap between
// them exceeds gapThresholdMs. A shorter gap (e.g. one missed 30s heartbeat)
// is just a silent break; a longer one is worth flagging visually.
// gapStyle 'baseline' flattens the connector to the chart's bottom edge
// instead of a diagonal between the two real y-values — a straight line
// at the actual readings would visually imply an interpolated value that
// was never measured, which is misleading for a gap that means "offline."
const offlineConnectors = []
if (gapThresholdMs) {
for (let i = 0; i < segments.length - 1; i++) {
const end = segments[i][segments[i].length - 1]
const start = segments[i + 1][0]
if (start.x - end.x > gapThresholdMs) {
if (gapStyle === 'baseline') {
offlineConnectors.push({ x1: end.px, y1: baseline, x2: start.px, y2: baseline })
} else {
offlineConnectors.push({ x1: end.px, y1: end.py, x2: start.px, y2: start.py })
}
}
}
}
// Explicit offline windows (computed once, shared across charts — see the
// prop doc above) mapped straight into this chart's own pixel space using
// the same xMin/xMax/innerW as the data points, and always drawn along the
// baseline — these are known facts about the device/console, not something
// inferred from this particular series' own two neighboring points, so they
// render even in a stretch where this series happens to have no points at
// all on either side of the window.
if (offlineWindows && offlineWindows.length) {
const toPx = x => PAD.left + ((x - xMin) / (xMax - xMin)) * innerW
for (const w of offlineWindows) {
const clampedStart = Math.max(w.start, xMin)
const clampedEnd = Math.min(w.end, xMax)
if (clampedEnd <= clampedStart) continue
offlineConnectors.push({ x1: toPx(clampedStart), y1: baseline, x2: toPx(clampedEnd), y2: baseline })
}
}
const handleMove = e => {
if (!containerRef.current) return
const rect = containerRef.current.getBoundingClientRect()
const relX = e.clientX - rect.left
// Nearest point by px distance.
let nearest = 0
let nearestDist = Infinity
points.forEach((p, i) => {
const d = Math.abs(p.px - relX)
if (d < nearestDist) { nearestDist = d; nearest = i }
})
setHoverIdx(nearest)
}
// Gridlines: 3 horizontal bands (min/mid/max) — recessive, label-free except axis text.
const gridY = [yMin + (yMax - yMin) * 0.0, yMin + (yMax - yMin) * 0.5, yMin + (yMax - yMin) * 1.0]
const legendColor = sortedStops
? (latest ? sortedStops.reduce((closest, s) => Math.abs(s.value - latest.y) < Math.abs(closest.value - latest.y) ? s : closest, sortedStops[0]).color : sortedStops[0].color)
: color
return (
<div
ref={measureRef}
className={['linechart', className].filter(Boolean).join(' ')}
style={{ position: 'relative', width: '100%', height }}
onMouseMove={handleMove}
onMouseLeave={() => setHoverIdx(null)}
>
{/* Trailing value badge — top-right, current/most-recent reading */}
{latest && (
<div style={{
position: 'absolute', top: 0, right: 0,
fontSize: 'var(--font-size-sm)', fontWeight: 'var(--font-weight-semibold)',
color: legendColor, fontFamily: 'var(--font-family-mono)', zIndex: 1,
}}>
{formatValue(latest.y)}{unit}
</div>
)}
<svg width="100%" height={height} viewBox={`0 0 ${width} ${height}`} style={{ display: 'block', overflow: 'visible' }}>
{sortedStops && (
<defs>
<linearGradient id={gradientId} gradientUnits="userSpaceOnUse" x1={0} y1={PAD.top + innerH} x2={0} y2={PAD.top}>
{sortedStops.map((s, i) => {
const py = PAD.top + innerH - ((s.value - yMin) / (yMax - yMin)) * innerH
const offset = Math.max(0, Math.min(1, (py - PAD.top) / innerH))
// Gradient offsets run top(1)→bottom(0) in our y1/y2 direction
// (y1 at bottom = offset 0), so invert: a stop's pixel-y needs
// to map to (1 - offset-from-top).
return <stop key={i} offset={`${(1 - offset) * 100}%`} stopColor={s.color} />
})}
</linearGradient>
</defs>
)}
{/* Gridlines */}
{gridY.map((gy, i) => {
const py = PAD.top + innerH - ((gy - yMin) / (yMax - yMin)) * innerH
return (
<line key={i} x1={PAD.left} x2={PAD.left + innerW} y1={py} y2={py}
stroke="var(--color-border)" strokeWidth={1} />
)
})}
{/* Area fill under each segment — same color/gradient as the line,
low opacity, closed down to the plot baseline. Each fill path is
its own closed shape per segment, so a gap never produces a
spurious rectangle spanning the whole chart. */}
{segments.map((seg, i) => {
if (seg.length < 2) return null
const curve = smoothPath(seg)
const fillPath = `${curve}L${seg[seg.length - 1].px},${baseline}L${seg[0].px},${baseline}Z`
return <path key={`fill-${i}`} d={fillPath} fill={strokeColor} opacity={0.1} stroke="none" />
})}
{/* Dotted connectors across long gaps — "device likely offline" cue,
drawn under the solid segments so segment ends stay crisp on top. */}
{offlineConnectors.map((c, i) => (
<line key={`gap-${i}`} x1={c.x1} y1={c.y1} x2={c.x2} y2={c.y2}
stroke="var(--color-text-muted)" strokeWidth={1.5} strokeDasharray="3,4" opacity={0.6} />
))}
{/* Line segments (smoothed, gaps at null y) */}
{segments.map((seg, i) => (
<path key={i} d={smoothPath(seg)} fill="none" stroke={strokeColor} strokeWidth={2}
strokeLinecap="round" strokeLinejoin="round" />
))}
{/* Rounded data-end on the most recent point */}
{latest && (
<circle cx={latest.px} cy={latest.py} r={4} fill={legendColor} stroke="var(--color-bg-surface)" strokeWidth={2} />
)}
{/* Hover crosshair + marker */}
{hovered && (
<g>
<line x1={hovered.px} x2={hovered.px} y1={PAD.top} y2={PAD.top + innerH}
stroke="var(--color-border-strong)" strokeWidth={1} strokeDasharray="3,3" />
{hovered.y != null && (
<circle cx={hovered.px} cy={hovered.py} r={5} fill={strokeColor} stroke="var(--color-bg-surface)" strokeWidth={2} />
)}
</g>
)}
{/* X-axis endpoints — always the resolved range bounds, not just
whatever the first/last real sample happens to be, so the axis
reflects the selected time range even when data is sparse. */}
<text x={PAD.left} y={height - 6} fontSize="10" fill="var(--color-text-muted)" fontFamily="var(--font-family-base)">
{formatX(xMin)}
</text>
<text x={PAD.left + innerW} y={height - 6} fontSize="10" fill="var(--color-text-muted)"
fontFamily="var(--font-family-base)" textAnchor="end">
{formatX(xMax)}
</text>
</svg>
{/* Tooltip */}
{hovered && (
<div style={{
position: 'absolute',
left: Math.min(Math.max(hovered.px, 60), width - 60),
top: 0,
transform: 'translateX(-50%)',
background: 'var(--color-bg-elevated)',
border: '1px solid var(--color-border-strong)',
borderRadius: 'var(--radius-md)',
padding: 'var(--space-1) var(--space-2)',
fontSize: 'var(--font-size-xs)',
color: 'var(--color-text-primary)',
pointerEvents: 'none',
whiteSpace: 'nowrap',
boxShadow: 'var(--shadow-md)',
zIndex: 2,
}}>
<div style={{ color: 'var(--color-text-muted)' }}>{formatX(hovered.x)}</div>
<div style={{ fontWeight: 'var(--font-weight-semibold)', color: hovered.y != null ? legendColor : 'var(--color-text-muted)' }}>
{hovered.y != null ? `${formatValue(hovered.y)}${unit}` : 'No data'}
</div>
</div>
)}
</div>
)
}
+150
View File
@@ -0,0 +1,150 @@
// src/components/ui/MultiSelect.jsx
// Multi-select dropdown — same visual language as Select.jsx (floating portal
// menu, .select-* trigger styling) but with checkbox rows so multiple options
// can be chosen at once. Trigger shows "All", a single label, or "N selected".
//
// Props:
// options — Array<{ value: string, label: ReactNode }>
// value — Array<string> — currently selected values (empty = "all")
// onChange — (nextValues: string[]) => void
// placeholder — shown when value is empty (default: 'All')
// disabled — boolean
// className — extra classes on the trigger button
// id — forwarded for label association
import { useState, useRef, useEffect } from 'react'
import { createPortal } from 'react-dom'
import { computeFloatingMenuPosition } from '@/lib/floatingMenuPosition'
export default function MultiSelect({
options = [],
value = [],
onChange,
placeholder = 'All',
disabled = false,
className = '',
id,
...props
}) {
const [open, setOpen] = useState(false)
const [menuPos, setMenuPos] = useState({ top: 0, left: 0, width: 0, maxHeight: 280 })
const triggerRef = useRef(null)
const menuRef = useRef(null)
useEffect(() => {
if (!open) return
function close(e) {
if (triggerRef.current?.contains(e.target)) return
if (menuRef.current?.contains(e.target)) return
setOpen(false)
}
function closeOnScroll(e) {
if (menuRef.current?.contains(e.target)) return
if (triggerRef.current?.contains(e.target)) return
setOpen(false)
}
document.addEventListener('mousedown', close)
document.addEventListener('scroll', closeOnScroll, true)
return () => {
document.removeEventListener('mousedown', close)
document.removeEventListener('scroll', closeOnScroll, true)
}
}, [open])
function openMenu() {
if (disabled) return
if (triggerRef.current) {
setMenuPos(computeFloatingMenuPosition(triggerRef.current.getBoundingClientRect()))
}
setOpen(true)
}
function handleToggle() {
if (open) setOpen(false)
else openMenu()
}
function toggleValue(v) {
const next = value.includes(v) ? value.filter((x) => x !== v) : [...value, v]
onChange?.(next)
}
const label = value.length === 0
? placeholder
: value.length === 1
? (options.find((o) => o.value === value[0])?.label ?? value[0])
: `${value.length} selected`
const menu = open && createPortal(
<div
ref={menuRef}
className="select-menu multi-select-menu"
style={{ top: menuPos.top, bottom: menuPos.bottom, left: menuPos.left, width: menuPos.width, maxHeight: menuPos.maxHeight }}
role="listbox"
aria-multiselectable="true"
aria-label="Options"
>
{value.length > 0 && (
<div
className="select-option multi-select-clear"
onMouseDown={(e) => { e.preventDefault(); onChange?.([]) }}
>
<span>Clear selection</span>
</div>
)}
{options.map((opt) => {
const checked = value.includes(opt.value)
return (
<div
key={opt.value}
role="option"
aria-selected={checked}
className={['select-option', checked ? 'select-option-selected' : ''].filter(Boolean).join(' ')}
onMouseDown={(e) => { e.preventDefault(); toggleValue(opt.value) }}
>
<input
type="checkbox"
checked={checked}
readOnly
tabIndex={-1}
style={{ accentColor: 'var(--color-primary)', flexShrink: 0, pointerEvents: 'none' }}
/>
<span>{opt.label}</span>
</div>
)
})}
</div>,
document.body
)
return (
<>
<button
ref={triggerRef}
type="button"
id={id}
disabled={disabled}
onClick={handleToggle}
className={[
'input',
'select-trigger',
open ? 'select-trigger-open' : '',
className,
].filter(Boolean).join(' ')}
aria-haspopup="listbox"
aria-expanded={open}
{...props}
>
<span className={value.length ? 'select-value' : 'select-placeholder'}>
{label}
</span>
<span className="select-chevron" aria-hidden="true">
<svg width="16" height="16" viewBox="0 0 16 16" fill="none">
<path d="M4 6l4 4 4-4" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
</svg>
</span>
</button>
{menu}
</>
)
}
@@ -0,0 +1,124 @@
// src/components/ui/PressHoldButton.jsx
// A button that requires holding it down for a fixed duration to confirm,
// rather than a single click — for destructive actions where a misclick
// should not be able to trigger the action (a slip releases instantly and
// does nothing). Renders a fill sweeping left-to-right as visual progress.
//
// Props:
// holdMs — number — how long the button must be held, in ms (default: 3000)
// onConfirm — () => void — called once the hold completes
// variant — 'danger' | 'primary' (default: 'danger')
// size — 'sm' | 'md' | 'lg' (default: 'md')
// disabled — boolean
// children — ReactNode — label shown when not held
// holdingLabel — ReactNode — label shown while holding (falls back to children)
// className — extra classes
import { useRef, useState, useCallback } from 'react'
export default function PressHoldButton({
holdMs = 3000,
onConfirm,
variant = 'danger',
size = 'md',
disabled = false,
children,
holdingLabel,
className = '',
}) {
const [progress, setProgress] = useState(0) // 0–100
const [holding, setHolding] = useState(false)
const rafRef = useRef(null)
const startRef = useRef(0)
const stop = useCallback(() => {
if (rafRef.current) cancelAnimationFrame(rafRef.current)
rafRef.current = null
setHolding(false)
setProgress(0)
}, [])
// Named function expression — `tickFrame` inside the body refers to the
// function itself via its own name, not the outer `tick` const binding,
// so there's no self-reference-before-declaration issue on the recursive
// requestAnimationFrame call.
const tick = useCallback(function tickFrame() {
const elapsed = Date.now() - startRef.current
const pct = Math.min(100, (elapsed / holdMs) * 100)
setProgress(pct)
if (pct >= 100) {
setHolding(false)
setProgress(0)
onConfirm?.()
return
}
rafRef.current = requestAnimationFrame(tickFrame)
}, [holdMs, onConfirm])
const start = useCallback(() => {
if (disabled) return
startRef.current = Date.now()
setHolding(true)
rafRef.current = requestAnimationFrame(tick)
}, [disabled, tick])
const color = variant === 'danger' ? 'var(--color-danger)' : 'var(--color-primary)'
const bg = variant === 'danger' ? 'var(--color-danger-bg)' : 'var(--color-primary-subtle)'
const sizeStyles = {
sm: { height: 32, paddingInline: 'var(--space-3)', fontSize: 'var(--font-size-xs)' },
md: { height: 38, paddingInline: 'var(--space-4)', fontSize: 'var(--font-size-sm)' },
lg: { height: 44, paddingInline: 'var(--space-5)', fontSize: 'var(--font-size-base)' },
}[size] || {}
return (
<button
type="button"
disabled={disabled}
onMouseDown={start}
onMouseUp={stop}
onMouseLeave={stop}
onTouchStart={start}
onTouchEnd={stop}
onTouchCancel={stop}
className={className}
aria-pressed={holding}
style={{
position: 'relative',
overflow: 'hidden',
border: `1px solid ${color}`,
borderRadius: 'var(--radius-md)',
background: bg,
color,
fontWeight: 'var(--font-weight-semibold)',
cursor: disabled ? 'not-allowed' : 'pointer',
opacity: disabled ? 0.5 : 1,
userSelect: 'none',
WebkitUserSelect: 'none',
touchAction: 'none',
display: 'inline-flex',
alignItems: 'center',
justifyContent: 'center',
gap: 'var(--space-2)',
transition: 'opacity 0.15s',
...sizeStyles,
}}
>
<span
aria-hidden="true"
style={{
position: 'absolute',
inset: 0,
width: `${progress}%`,
background: color,
opacity: 0.28,
transition: progress === 0 ? 'width 0.15s ease-out' : 'none',
pointerEvents: 'none',
}}
/>
<span style={{ position: 'relative' }}>
{holding ? (holdingLabel ?? children) : children}
</span>
</button>
)
}
+4 -4
View File
@@ -16,6 +16,7 @@
import { useState, useRef, useEffect, Children, isValidElement } from 'react'
import { createPortal } from 'react-dom'
import { computeFloatingMenuPosition } from '@/lib/floatingMenuPosition'
// Parse React <option> children into a flat [{value, label, disabled}] array
function parseOptions(children) {
@@ -46,7 +47,7 @@ export default function Select({
...props
}) {
const [open, setOpen] = useState(false)
const [menuPos, setMenuPos] = useState({ top: 0, left: 0, width: 0 })
const [menuPos, setMenuPos] = useState({ top: 0, left: 0, width: 0, maxHeight: 280 })
const triggerRef = useRef(null)
const menuRef = useRef(null)
@@ -105,8 +106,7 @@ export default function Select({
function openMenu() {
if (disabled) return
if (triggerRef.current) {
const r = triggerRef.current.getBoundingClientRect()
setMenuPos({ top: r.bottom + 4, left: r.left, width: r.width })
setMenuPos(computeFloatingMenuPosition(triggerRef.current.getBoundingClientRect()))
}
setOpen(true)
}
@@ -130,7 +130,7 @@ export default function Select({
<div
ref={menuRef}
className="select-menu"
style={{ top: menuPos.top, left: menuPos.left, width: menuPos.width }}
style={{ top: menuPos.top, bottom: menuPos.bottom, left: menuPos.left, width: menuPos.width, maxHeight: menuPos.maxHeight }}
role="listbox"
aria-label="Options"
>
@@ -0,0 +1,120 @@
// src/components/ui/SignalIndicator.jsx
// Wi-Fi signal-strength glyph — concentric arcs + dot, filled by RSSI (dBm).
// Never use a raw icon/emoji for signal strength — always use SignalIndicator.
//
// Props:
// rssi — number | null | undefined — signal strength in dBm (e.g. -62). null/undefined = unknown.
// isOnline — boolean | undefined — when explicitly false, renders a fully grey
// (unlit) glyph regardless of rssi, so a stale last-known reading from
// an offline device never reads as a live "full signal". When true (or undefined) but rssi is null/undefined,
// renders an amber "?" instead — legacy v1-firmware devices report a
// heartbeat with no rssi field at all (see API Reference: legacy
// heartbeats predate rssi/state/ok), so "online with unknown signal"
// is a distinct, expected state from "we haven't loaded it yet".
// size — 'sm' | 'md' (default: 'md')
// className — extra classes
//
// RSSI → level (4 levels: dot + 3 arcs, lit from the center outward):
// > -50 dBm → Excellent (4/4 lit), var(--color-success)
// >= -60 dBm → Good (3/4 lit), var(--color-info)
// >= -70 dBm → Fair (2/4 lit), var(--color-warning)
// < -70 dBm → Weak (1/4 lit), var(--color-danger)
// null/undefined → 0/4 lit, var(--color-text-muted) — "unknown", not "bad"
function rssiToLevel(rssi) {
if (rssi > -50) return 4
if (rssi >= -60) return 3
if (rssi >= -70) return 2
return 1
}
function rssiToColor(rssi) {
if (rssi == null) return 'var(--color-text-muted)'
if (rssi > -50) return 'var(--color-success)'
if (rssi >= -60) return 'var(--color-info)'
if (rssi >= -70) return 'var(--color-warning)'
return 'var(--color-danger)'
}
const SIZES = {
sm: { box: 16, strokeWidth: 1.6 },
md: { box: 20, strokeWidth: 1.8 },
}
const DIM_COLOR = 'var(--color-bg-island)'
export default function SignalIndicator({ rssi, isOnline, size = 'md', className = '' }) {
const offline = isOnline === false
const known = !offline && rssi != null && Number.isFinite(rssi)
// Online, but the device firmware never reports rssi at all (legacy v1 API).
const unsupported = !offline && !known && isOnline === true
const muted = offline || unsupported
const level = known ? rssiToLevel(rssi) : 0
const color = unsupported ? 'var(--color-warning)' : rssiToColor(known ? rssi : null)
const { box, strokeWidth } = SIZES[size] || SIZES.md
const label = offline
? 'Signal strength unavailable — device offline'
: unsupported
? 'Signal strength not reported by this device\'s firmware'
: known
? `Signal strength: ${['weak', 'fair', 'good', 'excellent'][level - 1]} (${rssi} dBm)`
: 'Signal strength unknown'
return (
<svg
width={box}
height={box}
viewBox="0 0 24 24"
className={['signal-indicator', className].filter(Boolean).join(' ')}
role="img"
aria-label={label}
style={{ flexShrink: 0 }}
>
<title>{label}</title>
{/* Center dot — level 1 */}
<circle cx="12" cy="18.5" r="1.6" fill={muted ? DIM_COLOR : (level >= 1 ? color : DIM_COLOR)} style={{ transition: 'fill 0.2s' }} />
{/* Inner arc — level 2 */}
<path
d="M8.2 14.8a5.4 5.4 0 0 1 7.6 0"
fill="none"
stroke={muted ? DIM_COLOR : (level >= 2 ? color : DIM_COLOR)}
strokeWidth={strokeWidth}
strokeLinecap="round"
style={{ transition: 'stroke 0.2s' }}
/>
{/* Middle arc — level 3 */}
<path
d="M5 11.6a9.8 9.8 0 0 1 14 0"
fill="none"
stroke={muted ? DIM_COLOR : (level >= 3 ? color : DIM_COLOR)}
strokeWidth={strokeWidth}
strokeLinecap="round"
style={{ transition: 'stroke 0.2s' }}
/>
{/* Outer arc — level 4 */}
<path
d="M1.8 8.4a14.2 14.2 0 0 1 20.4 0"
fill="none"
stroke={muted ? DIM_COLOR : (level >= 4 ? color : DIM_COLOR)}
strokeWidth={strokeWidth}
strokeLinecap="round"
style={{ transition: 'stroke 0.2s' }}
/>
{/* Unsupported overlay — amber "?", device is online but its firmware never reports rssi (v1 API) */}
{unsupported && (
<text
x="12"
y="16.5"
textAnchor="middle"
fontSize="11"
fontWeight="700"
fontFamily="var(--font-family-base, sans-serif)"
fill={color}
stroke="none"
>
?
</text>
)}
</svg>
)
}
@@ -0,0 +1,83 @@
// src/components/ui/TimeRangeSelect.jsx
// Time-range picker for history/telemetry pages — a preset dropdown (10m
// through all-time) plus a "Custom…" option opening a small range modal.
// Drives every time-scoped section on a page from one control: pass the
// resolved { since, until } down to whatever fetches/filters data.
//
// Props:
// value — { key: string, since: Date|null, until: Date|null } — since=null means "all-time"
// onChange — (value) => void
// className — extra classes on the trigger
import { useState } from 'react'
import Select from '@/components/ui/Select'
import Modal from '@/components/ui/Modal'
import Button from '@/components/ui/Button'
import DateTimePicker from '@/components/ui/DateTimePicker'
import { PRESETS, resolveRange } from '@/lib/timeRange'
function CustomRangeModal({ open, onClose, initialSince, initialUntil, onApply }) {
const [since, setSince] = useState(initialSince ? initialSince.toISOString() : '')
const [until, setUntil] = useState(initialUntil ? initialUntil.toISOString() : '')
const apply = () => {
onApply({
since: since ? new Date(since) : null,
until: until ? new Date(until) : null,
})
onClose()
}
return (
<Modal open={open} onClose={onClose} title="Custom Time Range" size="sm">
<div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-4)' }}>
<DateTimePicker label="From" name="range-since" value={since} onChange={setSince} />
<DateTimePicker label="To" name="range-until" value={until} onChange={setUntil} placeholder="Leave empty for now" />
<div style={{ display: 'flex', justifyContent: 'flex-end', gap: 'var(--space-2)' }}>
<Button variant="ghost" onClick={onClose}>Cancel</Button>
<Button variant="primary" disabled={!since} onClick={apply}>Apply</Button>
</div>
</div>
</Modal>
)
}
export default function TimeRangeSelect({ value, onChange, className = '' }) {
const [showCustom, setShowCustom] = useState(false)
const handleSelectChange = e => {
const key = e.target.value
if (key === 'custom') {
setShowCustom(true)
return
}
onChange(resolveRange(key))
}
const selectValue = value?.key === 'custom' ? 'custom' : (value?.key || '7d')
return (
<>
<Select
id="time-range-select"
name="time-range"
value={selectValue}
onChange={handleSelectChange}
className={className}
>
{PRESETS.map(p => (
<option key={p.key} value={p.key}>{p.label}</option>
))}
<option value="custom">Custom range…</option>
</Select>
<CustomRangeModal
open={showCustom}
onClose={() => setShowCustom(false)}
initialSince={value?.since}
initialUntil={value?.until}
onApply={({ since, until }) => onChange({ key: 'custom', since, until })}
/>
</>
)
}
+31 -13
View File
@@ -12,8 +12,9 @@
// Each toast auto-dismisses after `duration` ms (default 4000).
// ToastProvider renders the stack itself via a portal — no extra component needed.
import { createContext, useContext, useState, useCallback, useRef } from 'react'
import { createContext, useContext, useState, useCallback, useRef, useEffect } from 'react'
import { createPortal } from 'react-dom'
import Spinner from '@/components/ui/Spinner'
// ---------------------------------------------------------------------------
// Context
@@ -49,7 +50,7 @@ function ToastIcon({ variant }) {
// ---------------------------------------------------------------------------
// Single Toast item
// ---------------------------------------------------------------------------
function ToastItem({ id, variant = 'info', title, message, duration = 4000, onDismiss }) {
function ToastItem({ id, variant = 'info', title, message, duration = 4000, pending = false, onDismiss }) {
const [exiting, setExiting] = useState(false)
const dismiss = useCallback(() => {
@@ -57,15 +58,21 @@ function ToastItem({ id, variant = 'info', title, message, duration = 4000, onDi
setTimeout(() => onDismiss(id), 300)
}, [id, onDismiss])
// Auto-dismiss timer
// Auto-dismiss timer — does not run while `pending` (e.g. waiting on a command reply)
const timerRef = useRef(null)
const startTimer = () => {
if (pending) return
timerRef.current = setTimeout(dismiss, duration)
}
const clearTimer = () => clearTimeout(timerRef.current)
// Start timer on mount
useState(() => { startTimer() })
// (Re)start the timer whenever `pending` resolves to false, or on mount if already resolved
useEffect(() => {
clearTimer()
startTimer()
return clearTimer
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [pending, duration])
return (
<div
@@ -76,7 +83,7 @@ function ToastItem({ id, variant = 'info', title, message, duration = 4000, onDi
onMouseLeave={startTimer}
>
<div className="toast-icon">
<ToastIcon variant={variant} />
{pending ? <Spinner size="sm" /> : <ToastIcon variant={variant} />}
</div>
<div className="toast-content">
@@ -94,11 +101,13 @@ function ToastItem({ id, variant = 'info', title, message, duration = 4000, onDi
</svg>
</button>
{/* Progress bar — shrinks over duration */}
<div
className="toast-progress"
style={{ animationDuration: `${duration}ms` }}
/>
{/* Progress bar — shrinks over duration. Hidden while pending (no timeout running). */}
{!pending && (
<div
className="toast-progress"
style={{ animationDuration: `${duration}ms` }}
/>
)}
</div>
)
}
@@ -111,9 +120,9 @@ let _nextId = 1
export function ToastProvider({ children }) {
const [toasts, setToasts] = useState([])
const addToast = useCallback((variant, title, message, duration) => {
const addToast = useCallback((variant, title, message, duration, pending = false) => {
const id = _nextId++
setToasts((prev) => [...prev, { id, variant, title, message, duration }])
setToasts((prev) => [...prev, { id, variant, title, message, duration, pending }])
return id
}, [])
@@ -121,11 +130,20 @@ export function ToastProvider({ children }) {
setToasts((prev) => prev.filter((t) => t.id !== id))
}, [])
// Update an existing toast in place — e.g. flip a `pending` (blue) toast to
// success/danger/warning once a command reply (or timeout) arrives.
const update = useCallback((id, patch) => {
setToasts((prev) => prev.map((t) => (t.id === id ? { ...t, ...patch } : t)))
}, [])
const toast = {
success: (title, message, duration) => addToast('success', title, message, duration),
danger: (title, message, duration) => addToast('danger', title, message, duration),
warning: (title, message, duration) => addToast('warning', title, message, duration),
info: (title, message, duration) => addToast('info', title, message, duration),
// pending: creates a toast with no auto-dismiss timer until update() clears `pending`
pending: (title, message) => addToast('info', title, message, 4000, true),
update,
dismiss,
}
+161
View File
@@ -0,0 +1,161 @@
// frontend/src/hooks/useDeviceCommand.js
// Shared MQTT command-send + ack-tracking machinery, extracted from
// DeviceDetail.jsx so any page (DeviceDetail, the onboarding wizard, …) can
// send a command to a device and await its reply the same way.
//
// 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
// doesn't send one yet, so replies are matched to in-flight commands by the
// 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 } }.
//
// Usage:
// const { sendMqttCommand, sendMqttCommandSilent, sendingCmd, connected } =
// useDeviceCommand({ deviceSerial, onNonAckMessage, onCommandSent })
//
// sendMqttCommand(cmd, contents) — shows a live-updating toast (blue → success/danger/warning)
// sendMqttCommandSilent(cmd, contents, timeoutMs) — no toast, used for background GET-config refreshes
// onNonAckMessage(msg) — optional: receives every WS message that ISN'T a
// 'control/ack' reply for this device (e.g. status/heartbeat),
// so callers don't need a second WebSocket connection.
// onCommandSent(cmd) — optional: fires the instant a (non-silent) command is
// accepted for sending (POST resolved), before the device
// has replied — e.g. to refresh a command-history list.
import { useRef, useCallback, useState } from 'react'
import api from '@/lib/api'
import { useMqttWebSocket } from '@/hooks/useMqttWebSocket'
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 } = {}) {
const { toast } = useToast()
const [sendingCmd, setSendingCmd] = useState('')
// [{ cmd, toastId?, resolve, reject, timeoutId }]
const pendingAcksRef = useRef([])
const { connected } = useMqttWebSocket({
enabled: !!deviceSerial,
onMessage: (msg) => {
if (msg?.device_serial !== deviceSerial) return
if (msg.type !== 'control/ack') {
onNonAckMessage?.(msg)
return
}
const idx = findPendingFor(pendingAcksRef.current, msg.payload?.type)
if (idx === -1) return
const [ack] = pendingAcksRef.current.splice(idx, 1)
const payload = msg.payload || {}
clearTimeout(ack.timeoutId)
const isSuccess = payload.status === 'SUCCESS'
if (ack.toastId != null) {
toast.update(ack.toastId, {
variant: isSuccess ? 'success' : 'danger',
title: isSuccess ? 'Success' : 'Failed',
message: payload.message || `Command "${payload.type || ack.cmd}" ${isSuccess ? 'succeeded' : 'failed'}.`,
pending: false,
duration: isSuccess ? 1000 : 6000,
})
}
if (isSuccess) ack.resolve?.(payload)
else ack.reject?.(new Error(payload.message || `Command "${ack.cmd}" failed.`))
},
})
// Sends a command and shows a live-updating toast. Returns a promise
// resolving with the reply payload on SUCCESS and rejecting on
// ERROR/timeout/send-failure.
const sendMqttCommand = useCallback((cmd, contents = {}) => {
if (!deviceSerial) return Promise.reject(new Error('No device id.'))
setSendingCmd(cmd)
const toastId = toast.pending(cmd, 'Sent — waiting for reply…')
return new Promise((resolve, reject) => {
// Registered before the POST so a reply that beats the HTTP response
// still finds its command.
const ackEntry = { cmd, toastId, resolve, reject, timeoutId: null }
const forget = () => {
clearTimeout(ackEntry.timeoutId)
pendingAcksRef.current = pendingAcksRef.current.filter((a) => a !== ackEntry)
}
ackEntry.timeoutId = setTimeout(() => {
forget()
toast.update(toastId, {
variant: 'warning',
title: 'No reply received',
message: `"${cmd}" was sent but the device did not reply in time.`,
pending: false,
duration: 4000,
})
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) => {
forget()
toast.update(toastId, {
variant: 'danger',
title: 'Failed to send',
message: err.message || 'Failed to send command.',
pending: false,
duration: 6000,
})
reject(err)
})
.finally(() => setSendingCmd(''))
})
}, [deviceSerial, toast, onCommandSent])
// Silent variant — no toast, no sendingCmd flicker. Used for background
// GET-config refreshes and other non-user-initiated commands.
const sendMqttCommandSilent = useCallback((cmd, contents = {}, timeoutMs = 5000) => {
return new Promise((resolve, reject) => {
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 })
.catch((err) => { forget(); reject(err) })
})
}, [deviceSerial])
return { sendMqttCommand, sendMqttCommandSilent, sendingCmd, connected }
}
export default useDeviceCommand
@@ -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
+61 -2
View File
@@ -1,2 +1,61 @@
// TODO: implement
export function useMqttWebSocket() {}
// frontend/src/hooks/useMqttWebSocket.js
// Subscribes to /api/mqtt/ws — broadcasts every inbound MQTT message
// (status/heartbeat, status/alerts, status/info, logs, data) as it arrives.
//
// Usage:
// useMqttWebSocket({ onMessage: (msg) => { ... } })
// msg shape: { type: 'data'|'status/heartbeat'|..., device_serial, payload, topic }
import { useEffect, useRef, useState } from 'react'
export function useMqttWebSocket({ enabled = true, onMessage } = {}) {
const [connected, setConnected] = useState(false)
const onMessageRef = useRef(onMessage)
useEffect(() => {
onMessageRef.current = onMessage
}, [onMessage])
useEffect(() => {
if (!enabled) return
let ws = null
let reconnectTimer = null
let stopped = false
const connect = () => {
const token = localStorage.getItem('access_token')
if (!token) return
const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:'
ws = new WebSocket(`${protocol}//${window.location.host}/api/mqtt/ws?token=${token}`)
ws.onopen = () => setConnected(true)
ws.onclose = () => {
setConnected(false)
if (!stopped) reconnectTimer = setTimeout(connect, 5000)
}
ws.onerror = () => {}
ws.onmessage = (event) => {
try {
const data = JSON.parse(event.data)
onMessageRef.current?.(data)
} catch {
// ignore invalid JSON
}
}
}
connect()
return () => {
stopped = true
clearTimeout(reconnectTimer)
ws?.close()
}
}, [enabled])
return { connected }
}
export default useMqttWebSocket
+113
View File
@@ -0,0 +1,113 @@
// frontend/src/hooks/useSerialConnection.js
// Owns one WebSerial port connection across the Provisioning Wizard's Flash
// and Verify steps. Lifted out of StepFlash so the same live serial session
// (and its accumulated log) survives the step transition — a fresh device
// reboot after flashing is exactly the window the Verify step needs to watch.
import { useState, useRef, useCallback } from 'react'
export function useSerialConnection() {
const [portConnected, setPortConnected] = useState(false)
const [portName, setPortName] = useState('')
const [monitoring, setMonitoring] = useState(false)
const [lines, setLines] = useState([])
const portRef = useRef(null)
const readerRef = useRef(null)
const monitorActiveRef = useRef(false)
const appendLine = useCallback((msg) => {
setLines((prev) => [...prev, String(msg)])
}, [])
const clearLines = useCallback(() => setLines([]), [])
const requestPort = useCallback(async () => {
const port = await navigator.serial.requestPort()
portRef.current = port
const info = port.getInfo?.() || {}
const label = info.usbVendorId
? `USB ${info.usbVendorId.toString(16).toUpperCase()}:${(info.usbProductId || 0).toString(16).toUpperCase()}`
: 'Serial Port'
setPortName(label)
setPortConnected(true)
return port
}, [])
// Starts (or restarts) the 115200-baud monitor on the currently held port.
// Safe to call after esptool has just disconnected its own transport —
// the small delay lets the OS release the port before we reopen it.
const startMonitor = useCallback(async (port, { delayMs = 1000 } = {}) => {
const target = port || portRef.current
if (!target) return
monitorActiveRef.current = true
setMonitoring(true)
if (delayMs) await new Promise((r) => setTimeout(r, delayMs))
try {
await target.open({ baudRate: 115200 })
} catch (openErr) {
appendLine(`[Error opening port: ${openErr.message}]`)
setMonitoring(false)
return
}
let reader
try {
reader = target.readable.getReader()
} catch (readerErr) {
appendLine(`[Error getting reader: ${readerErr.message}]`)
try { await target.close() } catch (_) {}
setMonitoring(false)
return
}
readerRef.current = reader
const dec = new TextDecoder()
let buf = ''
try {
while (monitorActiveRef.current) {
const { value, done } = await reader.read()
if (done) break
buf += dec.decode(value, { stream: true })
const parts = buf.split(/\r?\n/)
buf = parts.pop()
for (const line of parts) { if (line.trim()) appendLine(line) }
}
} catch (_) {
// reader cancelled/port lost — fall through to cleanup
} finally {
try { reader.releaseLock() } catch (_) {}
setMonitoring(false)
}
}, [appendLine])
const stopMonitor = useCallback(async () => {
monitorActiveRef.current = false
try { await readerRef.current?.cancel() } catch (_) {}
try { readerRef.current?.releaseLock() } catch (_) {}
setMonitoring(false)
}, [])
const disconnect = useCallback(async () => {
await stopMonitor()
try { await portRef.current?.close() } catch (_) {}
portRef.current = null
setPortConnected(false)
setPortName('')
appendLine('[Port disconnected]')
}, [stopMonitor, appendLine])
return {
portRef,
portConnected,
portName,
monitoring,
lines,
appendLine,
clearLines,
requestPort,
startMonitor,
stopMonitor,
disconnect,
}
}
export default useSerialConnection
+28
View File
@@ -0,0 +1,28 @@
// frontend/src/lib/clipboard.js
// Copy text to the clipboard, with a textarea fallback for non-secure
// contexts (plain-HTTP LAN access) where navigator.clipboard is undefined.
export function copyText(text) {
if (navigator.clipboard?.writeText) {
return navigator.clipboard.writeText(text).catch(() => fallbackCopy(text))
}
return fallbackCopy(text)
}
function fallbackCopy(text) {
return new Promise((resolve, reject) => {
const ta = document.createElement('textarea')
ta.value = text
ta.setAttribute('readonly', '')
ta.style.cssText = 'position:fixed;opacity:0'
document.body.appendChild(ta)
ta.select()
try {
document.execCommand('copy') ? resolve() : reject(new Error('Copy failed'))
} catch (err) {
reject(err)
} finally {
document.body.removeChild(ta)
}
})
}
+124
View File
@@ -0,0 +1,124 @@
// frontend/src/lib/crashReport.js
// Helpers for firmware crash detail (F-070) on boot events: the `crash`
// (coredump summary) and `pre_crash` (heap/uptime snapshot + optional
// abort_msg) objects from boot_report, with fallback to the legacy flat
// crash_* columns for older rows/firmware.
//
// Key rule: when pre_crash.abort_msg is present, pc / exc_cause 29 /
// exc_vaddr 0 describe the abort() mechanism, NOT the real cause — the
// abort_msg is the headline and those fields are de-emphasised.
// Xtensa EXCCAUSE values the ESP32 actually produces.
export const EXC_CAUSE_NAMES = {
0: 'IllegalInstruction',
2: 'InstructionFetchError',
3: 'LoadStoreError',
6: 'IntegerDivideByZero',
9: 'LoadStoreAlignment',
28: 'LoadProhibited',
29: 'StoreProhibited',
}
// Firmware F-055 thresholds: below these the crash was most likely caused by
// heap exhaustion or fragmentation rather than a logic bug.
export const HEAP_LARGEST_BLOCK_WARN = 12000
export const HEAP_FREE_WARN = 25000
export function excCauseName(cause) {
if (cause == null) return 'Unknown exception'
return EXC_CAUSE_NAMES[cause] ?? `Exception cause ${cause}`
}
// 0x%08X — the ESP serial monitor's address format.
export function hex32(n) {
if (n == null || !Number.isFinite(Number(n))) return '—'
return `0x${(Number(n) >>> 0).toString(16).toUpperCase().padStart(8, '0')}`
}
// Merge the JSON `crash` object with the legacy flat columns so callers deal
// with one shape. Returns null when the boot has no coredump summary at all.
export function crashOf(event) {
const c = event?.crash || {}
const task = c.task ?? event?.crash_task
const pc = c.pc ?? event?.crash_pc
if (task == null && pc == null && !event?.crash) return null
return {
task,
pc,
excCause: c.exc_cause ?? event?.crash_exc_cause,
excVaddr: c.exc_vaddr ?? event?.crash_exc_vaddr,
backtrace: Array.isArray(c.backtrace) ? c.backtrace : [],
backtraceCorrupted: !!c.backtrace_corrupted,
elfSha256: c.elf_sha256 || null,
}
}
export function preCrashOf(event) {
return event?.pre_crash || null
}
export function hasCrashDetail(event) {
return !!(crashOf(event) || preCrashOf(event))
}
// "abort() was called at PC 0x400d8a3f on core 0" → 0x400D8A3F (the caller of
// abort(), worth decoding too). Only that phrasing carries a PC.
export function abortCallerPc(abortMsg) {
const m = /abort\(\) was called at PC (0x[0-9a-fA-F]+)/.exec(abortMsg || '')
return m ? parseInt(m[1], 16) : null
}
export function crashHeadline(event) {
const abortMsg = preCrashOf(event)?.abort_msg
if (abortMsg) return abortMsg
const crash = crashOf(event)
if (crash) return excCauseName(crash.excCause)
return null
}
export function isHeapExhaustion(preCrash) {
if (!preCrash) return false
return (preCrash.largest_block != null && preCrash.largest_block < HEAP_LARGEST_BLOCK_WARN)
|| (preCrash.free_heap != null && preCrash.free_heap < HEAP_FREE_WARN)
}
// One line, space separated, like the ESP panic handler prints it.
export function addressLine(crash) {
if (!crash) return ''
return [crash.pc, ...crash.backtrace].filter(a => a != null).map(hex32).join(' ')
}
// Every address worth decoding: PC, backtrace, then the abort() caller PC.
export function decodeAddresses(event) {
const crash = crashOf(event)
const out = []
if (crash?.pc != null) out.push(Number(crash.pc))
for (const a of crash?.backtrace || []) out.push(Number(a))
const caller = abortCallerPc(preCrashOf(event)?.abort_msg)
if (caller != null) out.push(caller)
return out
}
export function addr2lineCommand(event) {
const addrs = decodeAddresses(event)
if (!addrs.length) return ''
return `xtensa-esp32-elf-addr2line -pfiaC -e firmware.elf ${addrs.map(hex32).join(' ')}`
}
export function fmtBytes(n) {
if (n == null) return '—'
if (n >= 1024) return `${(n / 1024).toFixed(1)} KB`
return `${n} B`
}
export function fmtUptime(ms) {
if (ms == null) return '—'
const s = Math.floor(ms / 1000)
const d = Math.floor(s / 86400)
const h = Math.floor((s % 86400) / 3600)
const m = Math.floor((s % 3600) / 60)
const sec = s % 60
const parts = [d && `${d}d`, h && `${h}h`, m && `${m}m`]
if (!d && !h) parts.push(`${sec}s`)
return parts.filter(Boolean).join(' ') || '0s'
}
+113
View File
@@ -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
}
+324
View File
@@ -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]) }))
}
+120
View File
@@ -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)
}
+32
View File
@@ -0,0 +1,32 @@
// frontend/src/lib/floatingMenuPosition.js
// Positions a fixed-position dropdown menu relative to its trigger, flipping
// above the trigger and clamping its height when there isn't enough room
// below in the viewport (e.g. a Select near the bottom of the screen).
//
// Used by Select.jsx and MultiSelect.jsx — both render their menu via
// createPortal(..., document.body) with position: fixed, so they need to
// account for viewport edges themselves (page scroll doesn't move a
// position:fixed element into view).
const MENU_GAP = 4
const MENU_MARGIN = 8 // minimum breathing room from the viewport edge
const PREFERRED_MAX_HEIGHT = 280 // matches .select-menu's CSS max-height
export function computeFloatingMenuPosition(triggerRect) {
const spaceBelow = window.innerHeight - triggerRect.bottom - MENU_GAP - MENU_MARGIN
const spaceAbove = triggerRect.top - MENU_GAP - MENU_MARGIN
// Prefer opening below; flip above only when below doesn't fit but above has more room.
const openAbove = spaceBelow < PREFERRED_MAX_HEIGHT && spaceAbove > spaceBelow
const maxHeight = Math.max(120, Math.min(PREFERRED_MAX_HEIGHT, openAbove ? spaceAbove : spaceBelow))
return {
left: triggerRect.left,
width: triggerRect.width,
maxHeight,
...(openAbove
? { bottom: window.innerHeight - triggerRect.top + MENU_GAP }
: { top: triggerRect.bottom + MENU_GAP }),
}
}
+40
View File
@@ -110,6 +110,14 @@ export function fmtTime24(iso) {
return d.toLocaleTimeString(LOCALE_LONG, { hour: '2-digit', minute: '2-digit', second: '2-digit', hour12: false })
}
/** "2026-07-14 19:03:21" — dense log-row timestamp (date + time incl. seconds, 24h) */
export function fmtLogTimestamp(iso) {
const d = safeDate(iso)
if (!d) return '—'
const pad = n => String(n).padStart(2, '0')
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`
}
/** Relative time: "just now", "5 minutes ago", "3 days ago", etc. */
export function fmtRelative(iso) {
const d = safeDate(iso)
@@ -167,3 +175,35 @@ export function fmtEuro(n) {
const f = parseFloat(n) || 0
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')}`
}
+26
View File
@@ -0,0 +1,26 @@
// frontend/src/lib/timeRange.js
// Shared time-range presets + resolution logic for TimeRangeSelect and any
// page/component that needs to compute a { since, until } window from a key.
export const PRESETS = [
{ key: '10m', label: 'Last 10 minutes', ms: 10 * 60 * 1000 },
{ key: '1h', label: 'Last hour', ms: 60 * 60 * 1000 },
{ key: '3h', label: 'Last 3 hours', ms: 3 * 60 * 60 * 1000 },
{ key: '24h', label: 'Last 24 hours', ms: 24 * 60 * 60 * 1000 },
{ key: '3d', label: 'Last 3 days', ms: 3 * 24 * 60 * 60 * 1000 },
{ key: '7d', label: 'Last 7 days', ms: 7 * 24 * 60 * 60 * 1000 },
{ key: '30d', label: 'Last 30 days', ms: 30 * 24 * 60 * 60 * 1000 },
{ key: '3mo', label: 'Last 3 months', ms: 90 * 24 * 60 * 60 * 1000 },
{ key: '6mo', label: 'Last 6 months', ms: 182 * 24 * 60 * 60 * 1000 },
{ key: 'all', label: 'All time', ms: null },
]
/** Resolve a preset key (or 'custom') into { key, since: Date|null, until: Date|null }. */
export function resolveRange(key, customSince, customUntil) {
if (key === 'custom') {
return { key, since: customSince ?? null, until: customUntil ?? null }
}
const preset = PRESETS.find(p => p.key === key) || PRESETS[5] // default: 7d
if (preset.ms == null) return { key: preset.key, since: null, until: null }
return { key: preset.key, since: new Date(Date.now() - preset.ms), until: null }
}
@@ -172,7 +172,7 @@ export default function AddDeviceUserModal({ open, deviceId, existingUserIds = [
)}
{/* Results */}
<div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-2)', minHeight: 80 }}>
<div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-2)', minHeight: 80, maxHeight: 260, overflowY: 'auto' }}>
{loading ? (
<div style={{ display: 'flex', justifyContent: 'center', padding: 'var(--space-6)' }}>
<Spinner size="sm" />
@@ -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&apos;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 &amp; 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>
)
}
@@ -3,7 +3,7 @@ import Modal from '@/components/ui/Modal'
import Button from '@/components/ui/Button'
export default function DeleteDeviceModal({ device, onConfirm, onCancel, error }) {
const name = device?.device_name || 'this device'
const name = device?.console_name || device?.device_name || 'this device'
const serial = device?.serial_number || device?.device_id
return (
@@ -20,7 +20,7 @@ function extractTime(tsStr) {
}
function timeToIso(hhmm) {
if (!hhmm) return ''
if (!hhmm) return null
return `2000-01-01T${hhmm}:00Z`
}
@@ -112,8 +112,23 @@ function SilenceBlock({ title, isOn, onToggle, from, onFromChange, to, onToChang
)
}
export default function EditAlertsModal({ open, onClose, onSaved, clock, attr, id }) {
const totalBells = attr?.totalBells || 8
// Console UI uses alertType 'disabled'|'single'|'multi'; firmware uses
// alert_type 'OFF'|'SINGLE'|'HOURS'. Bell fields: console uses 0 = disabled,
// firmware uses 255 = disabled.
const ALERT_TYPE_TO_FIRMWARE = { disabled: 'OFF', single: 'SINGLE', multi: 'HOURS' }
const toFirmwareBell = (n) => (n === 0 ? 255 : n)
export default function EditAlertsModal({ open, onClose, onSaved, clock, attr, id, sendMqttCommand }) {
// Only bells that actually have a relay output assigned — same source of
// truth as BellsTab's bell cards. Ignores attr.totalBells, which can drift
// from the real configured count. 0 and 65535 both mean "no output assigned"
// on the wire (uint16 "unset" sentinel) — treat both as disconnected here too,
// in case older Firestore data still has 65535 values from before that was
// normalized on write.
const connectedBellIndexes = (attr?.bellOutputs || [])
.map((output, i) => ({ output, bellNumber: i + 1 }))
.filter(({ output }) => output > 0 && output !== 65535)
.map(({ bellNumber }) => bellNumber)
const [alertType, setAlertType] = useState(clock?.ringAlerts || 'disabled')
const [ringIntervals, setRingIntervals] = useState(clock?.ringIntervals ?? 1000)
@@ -141,28 +156,44 @@ export default function EditAlertsModal({ open, onClose, onSaved, clock, attr, i
setSaving(true)
setError('')
try {
// Push to the device first — clock.set_alerts_config batches alert type/bells
// and both silence windows into one round trip. Firestore is only written
// once the device confirms.
await sendMqttCommand('clock.set_alerts_config', {
alert_type: ALERT_TYPE_TO_FIRMWARE[alertType],
alert_interval: alertType === 'multi' ? ringIntervals : undefined,
hour_bell: toFirmwareBell(Number(hourBell)),
half_bell: toFirmwareBell(Number(halfBell)),
quarter_bell: toFirmwareBell(Number(quarterBell)),
daytime_silence: isDayOn,
daytime_on: isDayOn ? daySilenceFrom : undefined,
daytime_off: isDayOn ? daySilenceTo : undefined,
night_silence: isNightOn,
night_on: isNightOn ? nightFrom : undefined,
night_off: isNightOn ? nightTo : undefined,
})
await api.put(`/devices/${id}`, {
device_attributes: {
clockSettings: {
...clock,
ringAlerts: alertType,
ringAlertsMasterOn: alertType !== 'disabled',
ringIntervals: alertType === 'multi' ? ringIntervals : clock?.ringIntervals,
hourAlertsBell: Number(hourBell),
halfhourAlertsBell: Number(halfBell),
quarterAlertsBell: Number(quarterBell),
isDaySilenceOn: isDayOn,
daySilenceFrom: isDayOn && daySilenceFrom ? timeToIso(daySilenceFrom) : (clock?.daySilenceFrom || ''),
daySilenceTo: isDayOn && daySilenceTo ? timeToIso(daySilenceTo) : (clock?.daySilenceTo || ''),
daySilenceFrom: isDayOn && daySilenceFrom ? timeToIso(daySilenceFrom) : (clock?.daySilenceFrom ?? null),
daySilenceTo: isDayOn && daySilenceTo ? timeToIso(daySilenceTo) : (clock?.daySilenceTo ?? null),
isNightSilenceOn: isNightOn,
nightSilenceFrom: isNightOn && nightFrom ? timeToIso(nightFrom) : (clock?.nightSilenceFrom || ''),
nightSilenceTo: isNightOn && nightTo ? timeToIso(nightTo) : (clock?.nightSilenceTo || ''),
nightSilenceFrom: isNightOn && nightFrom ? timeToIso(nightFrom) : (clock?.nightSilenceFrom ?? null),
nightSilenceTo: isNightOn && nightTo ? timeToIso(nightTo) : (clock?.nightSilenceTo ?? null),
},
},
})
await onSaved()
onClose()
} catch (err) {
// sendMqttCommand already surfaced a failure toast if the device rejected it.
setError(err.message || 'Failed to save.')
} finally {
setSaving(false)
@@ -171,7 +202,7 @@ export default function EditAlertsModal({ open, onClose, onSaved, clock, attr, i
const bellOptions = [
{ value: '0', label: 'Disabled' },
...Array.from({ length: totalBells }, (_, i) => ({ value: String(i + 1), label: `Bell ${i + 1}` })),
...connectedBellIndexes.map((n) => ({ value: String(n), label: `Bell ${n}` })),
]
return (
@@ -9,10 +9,8 @@ const toBool = (v) => v === 'true' || v === true
export default function EditAttributesModal({ open, onClose, onSaved, attr, id }) {
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 [hasBells, setHasBells] = useState(String(attr?.hasBells ?? false))
const [hasClock, setHasClock] = useState(String(attr?.hasClock ?? false))
const [saving, setSaving] = useState(false)
const [error, setError] = useState('')
@@ -20,13 +18,12 @@ export default function EditAttributesModal({ open, onClose, onSaved, attr, id }
setSaving(true)
setError('')
try {
// App-only settings — no device-side equivalent, Firestore is the source of truth.
await api.put(`/devices/${id}`, {
device_attributes: {
bellGuardOn: toBool(bellGuardOn),
warningsOn: toBool(warningsOn),
bellGuardSafetyOn: toBool(bellGuardSafetyOn),
hasBells: toBool(hasBells),
hasClock: toBool(hasClock),
bellguardSafetyOn: toBool(bellGuardSafetyOn),
},
})
await onSaved()
@@ -42,7 +39,7 @@ export default function EditAttributesModal({ open, onClose, onSaved, attr, id }
<Modal
open={open}
onClose={onClose}
title="Edit Basic Attributes"
title="Edit Safety Settings"
size="sm"
footer={
<div style={{ display: 'flex', justifyContent: 'flex-end', gap: 'var(--space-3)' }}>
@@ -84,31 +81,6 @@ export default function EditAttributesModal({ open, onClose, onSaved, attr, id }
<option value="true">Active</option>
<option value="false">Disabled</option>
</FormField>
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 'var(--space-3)' }}>
<FormField
label="Bells Mechanism"
name="hasBells"
type="select"
value={hasBells}
onChange={(e) => setHasBells(e.target.value)}
>
<option value="true">Enabled</option>
<option value="false">Disabled</option>
</FormField>
<FormField
label="Clock Output"
name="hasClock"
type="select"
value={hasClock}
onChange={(e) => setHasClock(e.target.value)}
>
<option value="true">Enabled</option>
<option value="false">Disabled</option>
</FormField>
</div>
<p style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-text-muted)' }}>
Connected bells: {Number.isFinite(attr?.totalBells) ? attr.totalBells : '—'} — managed via Bell Mechanisms tab.
</p>
{error && (
<p style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-danger)' }}>{error}</p>
)}
@@ -17,13 +17,13 @@ function extractTime(tsStr) {
}
function timeToIso(hhmm) {
if (!hhmm) return ''
if (!hhmm) return null
return `2000-01-01T${hhmm}:00Z`
}
const toBool = (v) => v === 'true' || v === true
export default function EditBacklightModal({ open, onClose, onSaved, attr, clock, sub, id }) {
export default function EditBacklightModal({ open, onClose, onSaved, attr, clock, sub, id, sendMqttCommand }) {
const maxOutputs = sub?.maxOutputs || 8
const bellOutputsUsed = (attr?.bellOutputs || []).filter((o) => o > 0)
const clockOutputsUsed = (clock?.clockOutputs || []).filter((o) => o > 0)
@@ -47,20 +47,29 @@ export default function EditBacklightModal({ open, onClose, onSaved, attr, clock
setSaving(true)
setError('')
try {
const enabled = toBool(isOn)
// Push to the device first — only write Firestore once it confirms.
await sendMqttCommand('clock.set_backlight', {
backlight: enabled,
backlight_output: Number(output),
backlight_on: enabled ? onTime : undefined,
backlight_off: enabled ? offTime : undefined,
})
await api.put(`/devices/${id}`, {
device_attributes: {
clockSettings: {
...clock,
isBacklightAutomationOn: toBool(isOn),
isBacklightAutomationOn: enabled,
backlightOutput: Number(output),
backlightTurnOnTime: toBool(isOn) && onTime ? timeToIso(onTime) : '',
backlightTurnOffTime: toBool(isOn) && offTime ? timeToIso(offTime) : '',
backlightTurnOnTime: enabled && onTime ? timeToIso(onTime) : null,
backlightTurnOffTime: enabled && offTime ? timeToIso(offTime) : null,
},
},
})
await onSaved()
onClose()
} catch (err) {
// sendMqttCommand already surfaced a failure toast if the device rejected it.
setError(err.message || 'Failed to save.')
} finally {
setSaving(false)
@@ -17,7 +17,7 @@ const TIMING_LABELS = {
140: 'Max — 140ms',
}
export default function EditBellOutputsModal({ open, onClose, onSaved, attr, sub, id }) {
export default function EditBellOutputsModal({ open, onClose, onSaved, attr, sub, id, sendMqttCommand }) {
const maxOutputs = sub?.maxOutputs || 8
const existingCount = attr?.totalBells || 0
const existingOutputs = attr?.bellOutputs || []
@@ -25,10 +25,15 @@ export default function EditBellOutputsModal({ open, onClose, onSaved, attr, sub
const [activeBells, setActiveBells] = useState(existingCount)
const [rows, setRows] = useState(() =>
Array.from({ length: maxOutputs }, (_, i) => ({
output: existingOutputs[i] ?? 0,
timing: existingTimings[i] ?? 90,
}))
Array.from({ length: maxOutputs }, (_, i) => {
// 65535 is the firmware's uint16 "unset" sentinel — treat it like 0 (Disabled)
// in case stale Firestore data still has it from before this was normalized.
const rawOutput = existingOutputs[i] ?? 0
return {
output: rawOutput === 65535 ? 0 : rawOutput,
timing: existingTimings[i] ?? 90,
}
})
)
const [saving, setSaving] = useState(false)
const [error, setError] = useState('')
@@ -43,6 +48,25 @@ export default function EditBellOutputsModal({ open, onClose, onSaved, attr, sub
setSaving(true)
setError('')
try {
// Push to the device first — relay.set_config takes both maps in one call.
// Only write to Firestore once the device confirms it actually applied
// and persisted the change (sendMqttCommand's toast reports the outcome).
//
// relay.set_config is a partial update — any bell index NOT present in
// these maps is left untouched by the firmware. So every slot beyond
// activeBells must be sent explicitly as output 0 (disabled), or a bell
// that was previously active stays wired to its old output forever,
// even though it's no longer shown as active here. The only way to
// deactivate a bell today is to select it and set it to Disabled — this
// makes "deselect it" do the same thing implicitly.
const durations = {}
const outputs = {}
rows.forEach((r, i) => {
durations[i] = r.timing
outputs[i] = i < activeBells ? r.output : 0
})
await sendMqttCommand('relay.set_config', { durations, outputs })
await api.put(`/devices/${id}`, {
device_attributes: {
totalBells: activeBells,
@@ -53,6 +77,7 @@ export default function EditBellOutputsModal({ open, onClose, onSaved, attr, sub
await onSaved()
onClose()
} catch (err) {
// sendMqttCommand already surfaced a failure toast if the device rejected it.
setError(err.message || 'Failed to save.')
} finally {
setSaving(false)
@@ -1,10 +1,13 @@
// 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 Modal from '@/components/ui/Modal'
import Button from '@/components/ui/Button'
import FormField from '@/components/ui/FormField'
import SegmentedControl from '@/components/ui/SegmentedControl'
import api from '@/lib/api'
// Pulse options in milliseconds — shown as sliders with labelled steps
@@ -55,7 +58,7 @@ function StepSlider({ steps, value, onChange, label }) {
)
}
export default function EditClockSettingsModal({ open, onClose, onSaved, attr, sub, id }) {
export default function EditClockSettingsModal({ open, onClose, onSaved, attr, sub, id, sendMqttCommand }) {
const clock = attr?.clockSettings || {}
const maxOutputs = sub?.maxOutputs || 8
const bellOutputsUsed = (attr?.bellOutputs || []).filter(o => o > 0)
@@ -68,6 +71,8 @@ export default function EditClockSettingsModal({ open, onClose, onSaved, attr, s
const [clockOut2, setClockOut2] = useState(String(existingClockOutputs[1] ?? 0))
const [runPulse, setRunPulse] = useState(existingTimings[0] || PULSE_STEPS[3]) // default 500ms
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 [error, setError] = useState('')
@@ -78,26 +83,44 @@ export default function EditClockSettingsModal({ open, onClose, onSaved, attr, s
const validationMsg = hasClock && (out1 === 0 || out2 === 0)
? 'Both outputs must be assigned when the clock is enabled.'
: 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 () => {
if (!canSave) return
setSaving(true)
setError('')
try {
// Push to the device first — clock.set_config batches enable/outputs/timings
// into one round trip. Firestore is only written once the device confirms.
await sendMqttCommand('clock.set_config', {
enabled: hasClock,
c1: out1,
c2: out2,
pulse_duration: runPulse,
pause_duration: pauseMs,
face_sync_mode: faceSync,
...(faceSync === 'smart' ? { smart_max_wait_min: maxWaitNum } : {}),
})
await api.put(`/devices/${id}`, {
device_attributes: {
hasClock,
clockSettings: {
...clock,
clockOutputs: [out1, out2].filter(o => o > 0),
clockTimings: [runPulse, pauseMs],
faceSyncMode: faceSync,
...(faceSync === 'smart' ? { smartMaxWaitMin: maxWaitNum } : {}),
},
},
})
await onSaved()
onClose()
} catch (err) {
// sendMqttCommand already surfaced a failure toast if the device rejected it.
setError(err.message || 'Failed to save.')
} finally {
setSaving(false)
@@ -217,10 +240,42 @@ export default function EditClockSettingsModal({ open, onClose, onSaved, attr, s
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 */}
{(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)' }}>
{conflictMsg || validationMsg}
{conflictMsg || validationMsg || maxWaitMsg}
</p>
)}
{error && (
@@ -1,97 +0,0 @@
// frontend/src/modals/devices/EditLoggingModal.jsx
import { useState } from 'react'
import Modal from '@/components/ui/Modal'
import Button from '@/components/ui/Button'
import FormField from '@/components/ui/FormField'
import api from '@/lib/api'
const LOG_LEVELS = [
{ value: '0', label: '(0) Disabled' },
{ value: '1', label: '(1) Error' },
{ value: '2', label: '(2) Warning' },
{ value: '3', label: '(3) Info' },
{ value: '4', label: '(4) Debug' },
{ value: '5', label: '(5) Verbose' },
]
export default function EditLoggingModal({ open, onClose, onSaved, attr, id }) {
const [serialLevel, setSerialLevel] = useState(String(attr?.serialLogLevel ?? 0))
const [sdLevel, setSdLevel] = useState(String(attr?.sdLogLevel ?? 0))
const [mqttLevel, setMqttLevel] = useState(String(attr?.mqttLogLevel ?? 0))
const [saving, setSaving] = useState(false)
const [error, setError] = useState('')
const handleSave = async () => {
setSaving(true)
setError('')
try {
await api.put(`/devices/${id}`, {
device_attributes: {
serialLogLevel: Number(serialLevel),
sdLogLevel: Number(sdLevel),
mqttLogLevel: Number(mqttLevel),
},
})
await onSaved()
onClose()
} catch (err) {
setError(err.message || 'Failed to save.')
} finally {
setSaving(false)
}
}
return (
<Modal
open={open}
onClose={onClose}
title="Edit Log Levels"
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} onClick={handleSave}>Save</Button>
</div>
}
>
<div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-4)' }}>
<FormField
label="Serial Log Level"
name="serialLevel"
type="select"
value={serialLevel}
onChange={(e) => setSerialLevel(e.target.value)}
>
{LOG_LEVELS.map((l) => (
<option key={l.value} value={l.value}>{l.label}</option>
))}
</FormField>
<FormField
label="SD Card Log Level"
name="sdLevel"
type="select"
value={sdLevel}
onChange={(e) => setSdLevel(e.target.value)}
>
{LOG_LEVELS.map((l) => (
<option key={l.value} value={l.value}>{l.label}</option>
))}
</FormField>
<FormField
label="MQTT Log Level"
name="mqttLevel"
type="select"
value={mqttLevel}
onChange={(e) => setMqttLevel(e.target.value)}
>
{LOG_LEVELS.map((l) => (
<option key={l.value} value={l.value}>{l.label}</option>
))}
</FormField>
{error && (
<p style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-danger)' }}>{error}</p>
)}
</div>
</Modal>
)
}
@@ -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,281 @@
// frontend/src/modals/bellcloud/devices/ResetStatsModal.jsx
// QA-to-shipping reset — clears test data accumulated on the bench (bell
// fires, playback, reboots, debug logs) across both the console's own
// database and the physical device itself, category by category.
//
// Two categories (device_boot_data, device_logs_clear) fire real MQTT
// commands and need the device online; the rest are console-database-only
// and always run regardless of connectivity. See backend's
// POST /devices/{id}/reset-stats for the DB/Firestore side — the two
// device-side commands are sent directly here via sendMqttCommand, reusing
// the existing ack/toast infrastructure rather than duplicating a
// wait-for-device-reply mechanism in the backend.
import { useState } from 'react'
import Modal from '@/components/ui/Modal'
import Button from '@/components/ui/Button'
import PressHoldButton from '@/components/ui/PressHoldButton'
import StatusBadge from '@/components/ui/StatusBadge'
import Icon from '@/components/ui/Icon'
import api from '@/lib/api'
import { useToast } from '@/components/ui/Toast'
// ─── Category definitions ──────────────────────────────────────────────────
// `key` matches ResetStatsRequest's field names on the backend for the
// Postgres/Firestore categories. `firmware` categories are sent as MQTT
// commands directly from this modal instead.
const CATEGORIES = [
{
group: 'Device (firmware)', items: [
{ key: 'device_boot_data', firmware: 'telemetry.reset_boot_data', label: 'Boot count & history', description: 'Lifetime boot counter and on-device SD boot log.', defaultChecked: true },
{ key: 'device_logs_clear', firmware: 'logs.clear', label: 'SD debug logs', description: 'Day-rotated debug log files stored on the device SD card.', defaultChecked: true },
],
},
{
group: 'Bell & Playback (console)', items: [
{ key: 'bell_stats', label: 'Bell strike stats', description: 'Lifetime hammer strikes and per-bell strike counts.', defaultChecked: true },
{ key: 'playback_stats', label: 'Playback stats', description: 'Lifetime melody playback count and warning count.', defaultChecked: true },
],
},
{
group: 'Console History', items: [
{ key: 'device_logs', label: 'Device logs', description: 'Console-stored debug/info log history for this device.', defaultChecked: true },
{ key: 'heartbeats', label: 'Heartbeats', description: 'RSSI/uptime/free-heap history — also clears RSSI & heap graphs.', defaultChecked: true },
{ key: 'commands', label: 'Command history', description: 'Sent-command log shown in the Control tab.', defaultChecked: true },
{ key: 'boot_events', label: 'Boot event history', description: 'Console-side boot/crash timeline (separate from the on-device log above).', defaultChecked: true },
{ key: 'alert_history', label: 'Alert history', description: 'Past alert transitions (warnings/critical/failed).', defaultChecked: true },
{ key: 'ping_samples', label: 'Ping samples', description: 'Latency history shown in the ping-latency graph.', defaultChecked: true },
{ key: 'diagnostics_reports', label: 'Diagnostics reports', description: 'CPU temp/WiFi/OTA/stack/bell-heat history from the 5-min metrics report.', defaultChecked: true },
{ key: 'reports', label: 'Device reports', description: 'History of critical board-initiated events (e.g. bell overload) from control/reports.', defaultChecked: true },
],
},
{
group: 'Advanced', items: [
{ key: 'current_alerts', label: 'Current active alerts', description: 'Clears LIVE alert state — if the device genuinely has an active fault right now, this hides it from the console until its next state change. Only enable if you are sure the device is idle/healthy.', defaultChecked: false, danger: true },
],
},
]
const ALL_KEYS = CATEGORIES.flatMap(g => g.items.map(i => i.key))
function defaultSelection() {
const sel = {}
for (const g of CATEGORIES) for (const i of g.items) sel[i.key] = i.defaultChecked
return sel
}
// ─── Checkbox row ───────────────────────────────────────────────────────────
function CategoryRow({ item, 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(item.key)}
disabled={disabled}
style={{ accentColor: item.danger ? 'var(--color-danger)' : 'var(--color-primary)', flexShrink: 0, marginTop: 3 }}
/>
<div style={{ flex: 1, minWidth: 0 }}>
<p style={{ fontSize: 'var(--font-size-sm)', fontWeight: 'var(--font-weight-medium)', color: item.danger ? 'var(--color-danger)' : 'var(--color-text-primary)' }}>
{item.label}
</p>
<p style={{ fontSize: 'var(--font-size-xs)', color: 'var(--color-text-muted)', marginTop: 2 }}>
{item.description}
</p>
</div>
</label>
)
}
// ─── ResetStatsModal ────────────────────────────────────────────────────────
export default function ResetStatsModal({ open, onClose, deviceId, isOnline, sendMqttCommand }) {
const { toast } = useToast()
const [selection, setSelection] = useState(defaultSelection)
const [running, setRunning] = useState(false)
const [results, setResults] = useState(null) // { [key]: { ok, detail } } once run completes
const toggle = (key) => setSelection(prev => ({ ...prev, [key]: !prev[key] }))
const toggleAll = (value) => {
const sel = {}
for (const key of ALL_KEYS) sel[key] = value
setSelection(sel)
}
const anySelected = ALL_KEYS.some(k => selection[k])
const firmwareItems = CATEGORIES[0].items
const backendKeys = ALL_KEYS.filter(k => !firmwareItems.some(f => f.key === k))
const handleClose = () => {
if (running) return
setResults(null)
onClose()
}
const runReset = async () => {
setRunning(true)
const outcome = {}
// Firmware commands — only attempt if online; skip cleanly if not.
for (const item of firmwareItems) {
if (!selection[item.key]) continue
if (!isOnline) {
outcome[item.key] = { ok: false, detail: 'Device offline — skipped' }
continue
}
try {
await sendMqttCommand(item.firmware, {})
outcome[item.key] = { ok: true, detail: 'Reset on device' }
} catch (err) {
outcome[item.key] = { ok: false, detail: err.message || 'Command failed' }
}
}
// Backend (Postgres + Firestore) — always attempted regardless of connectivity.
const backendBody = {}
for (const key of backendKeys) backendBody[key] = !!selection[key]
const anyBackend = backendKeys.some(k => selection[k])
if (anyBackend) {
try {
const res = await api.post(`/devices/${deviceId}/reset-stats`, backendBody)
for (const key of backendKeys) {
if (!selection[key]) continue
const val = res[key]
outcome[key] = { ok: val !== null && val !== undefined, detail: typeof val === 'number' ? `${val} row(s) cleared` : (val ? 'Cleared' : 'No change') }
}
} catch (err) {
for (const key of backendKeys) {
if (selection[key]) outcome[key] = { ok: false, detail: err.message || 'Failed' }
}
}
}
setResults(outcome)
setRunning(false)
const failed = Object.values(outcome).filter(o => !o.ok).length
if (failed === 0) {
toast.success('Stats Reset', 'Selected categories were cleared successfully.')
} else {
toast.warning('Partially Completed', `${failed} categor${failed === 1 ? 'y' : 'ies'} could not be reset — see details below.`)
}
}
return (
<Modal
open={open}
onClose={handleClose}
title="Reset Device Stats"
size="lg"
persistent={running}
>
<div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-5)' }}>
{!results && (
<>
<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-warning-bg)', border: '1px solid var(--color-warning)',
fontSize: 'var(--font-size-sm)', color: 'var(--color-warning)',
}}>
<Icon name="warning" size={16} color="var(--color-warning)" style={{ flexShrink: 0, marginTop: 1 }} />
<span>
This clears QA/bench test data before shipping to a customer. It does not affect network settings, bell/clock configuration, melodies, warranty records, or customer assignment. <strong>This action cannot be undone.</strong>
</span>
</div>
{!isOnline && (
<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-bg-elevated)', border: '1px solid var(--color-border)',
fontSize: 'var(--font-size-sm)', color: 'var(--color-text-muted)',
}}>
<Icon name="info" size={16} color="var(--color-text-muted)" style={{ flexShrink: 0, marginTop: 1 }} />
<span>Device is offline — console history will still be cleared, but on-device resets (boot count, SD logs) will be skipped.</span>
</div>
)}
<div style={{ display: 'flex', justifyContent: 'flex-end', gap: 'var(--space-2)' }}>
<Button variant="ghost" size="sm" onClick={() => toggleAll(true)}>Select All</Button>
<Button variant="ghost" size="sm" onClick={() => toggleAll(false)}>Select None</Button>
</div>
<div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-4)', maxHeight: '50vh', overflowY: 'auto' }}>
{CATEGORIES.map(group => (
<div key={group.group}>
<span style={{
fontSize: 'var(--font-size-xs)', fontWeight: 'var(--font-weight-semibold)',
color: 'var(--color-text-muted)', letterSpacing: 'var(--tracking-wide)',
textTransform: 'uppercase',
}}>
{group.group}
</span>
<div style={{ borderTop: '1px solid var(--color-border)', marginTop: 'var(--space-2)' }}>
{group.items.map(item => (
<CategoryRow
key={item.key}
item={item}
checked={!!selection[item.key]}
onChange={toggle}
disabled={running}
/>
))}
</div>
</div>
))}
</div>
<div style={{ display: 'flex', justifyContent: 'flex-end', gap: 'var(--space-3)', paddingTop: 'var(--space-2)', borderTop: '1px solid var(--color-border)' }}>
<Button variant="ghost" onClick={handleClose} disabled={running}>Cancel</Button>
<PressHoldButton
variant="danger"
holdMs={3000}
disabled={running || !anySelected}
holdingLabel="Keep holding to reset…"
onConfirm={runReset}
>
{running ? 'Resetting…' : 'Hold to Reset Selected'}
</PressHoldButton>
</div>
</>
)}
{results && (
<>
<div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-2)', maxHeight: '55vh', overflowY: 'auto' }}>
{CATEGORIES.flatMap(g => g.items).filter(item => selection[item.key]).map(item => {
const r = results[item.key]
return (
<div key={item.key} style={{
display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 'var(--space-3)',
padding: 'var(--space-2) var(--space-3)', borderRadius: 'var(--radius-md)',
backgroundColor: 'var(--color-bg-elevated)', border: '1px solid var(--color-border)',
}}>
<span style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-text-primary)' }}>{item.label}</span>
<div style={{ display: 'flex', alignItems: 'center', gap: 'var(--space-2)' }}>
<span style={{ fontSize: 'var(--font-size-xs)', color: 'var(--color-text-muted)' }}>{r?.detail}</span>
<StatusBadge variant={r?.ok ? 'success' : 'warning'} size="sm">{r?.ok ? 'Done' : 'Skipped'}</StatusBadge>
</div>
</div>
)
})}
</div>
<div style={{ display: 'flex', justifyContent: 'flex-end' }}>
<Button variant="primary" onClick={handleClose}>Close</Button>
</div>
</>
)}
</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&apos;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
// 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 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 sn = device?.serial_number || device?.device_id
const HOURS = Array.from({ length: 12 }, (_, i) => i + 1)
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 (
<Modal
open={open}
onClose={onClose}
onClose={handleClose}
title="Sync Clocktower"
size="sm"
persistent={paused}
footer={
<div style={{ display: 'flex', justifyContent: 'flex-end', gap: 'var(--space-3)' }}>
<Button variant="ghost" onClick={onClose}>Close</Button>
<Button variant="primary" disabled>
Sync (Coming Soon)
</Button>
<Button variant="ghost" onClick={handleClose}>{paused ? 'Cancel & Resume' : 'Cancel'}</Button>
<Button variant="primary" loading={saving} onClick={handleSave}>Save & Resume</Button>
</div>
}
>
<div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 'var(--space-5)', padding: 'var(--space-4) 0', textAlign: 'center' }}>
<div style={{
width: 64,
height: 64,
borderRadius: 'var(--radius-full)',
backgroundColor: 'var(--color-primary-subtle)',
display: 'flex',
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.
<div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-5)' }}>
<p style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-text-muted)' }}>
The device thinks the clocktower shows{' '}
<span style={{ fontFamily: 'var(--font-family-mono)', color: 'var(--color-text-primary)' }}>
{face ? `${pad(face.clock_hour)}:${pad(face.clock_minute)}` : '—'}
</span>
. If the hands show something else, enter what they really show.
</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>
</Modal>
)
@@ -0,0 +1,112 @@
// frontend/src/modals/bellcloud/users/CreateUserModal.jsx
// Create a new app user (Firebase Auth account + Firestore profile) from anywhere in the console.
import { useState, useEffect } from 'react'
import api from '@/lib/api'
import Modal from '@/components/ui/Modal'
import Button from '@/components/ui/Button'
import FormField from '@/components/ui/FormField'
export default function CreateUserModal({ open, onClose, onCreated }) {
const [email, setEmail] = useState('')
const [displayName, setDisplayName] = useState('')
const [password, setPassword] = useState('')
const [confirm, setConfirm] = useState('')
const [saving, setSaving] = useState(false)
const [error, setError] = useState('')
useEffect(() => {
if (!open) return
setEmail(''); setDisplayName(''); setPassword(''); setConfirm(''); setError('')
}, [open])
const handleCreate = async () => {
setError('')
if (!email || !displayName || !password) {
setError('Email, display name, and password are required.')
return
}
if (password.length < 6) {
setError('Password must be at least 6 characters.')
return
}
if (password !== confirm) {
setError('Passwords do not match.')
return
}
setSaving(true)
try {
const created = await api.post('/users', {
email,
display_name: displayName,
password,
status: 'active',
})
onCreated(created)
} catch (err) {
setError(err.message || 'Failed to create user.')
} finally {
setSaving(false)
}
}
return (
<Modal
open={open}
onClose={onClose}
title="Create App User"
size="sm"
footer={
<div style={{ display: 'flex', justifyContent: 'flex-end', gap: 'var(--space-3)' }}>
<Button variant="ghost" onClick={onClose}>Cancel</Button>
<Button variant="primary" onClick={handleCreate} loading={saving}>Create User</Button>
</div>
}
>
<div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-4)' }}>
<FormField
label="Email"
name="email"
type="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
required
placeholder="user@example.com"
autoFocus
/>
<FormField
label="Display Name"
name="display_name"
type="text"
value={displayName}
onChange={(e) => setDisplayName(e.target.value)}
required
placeholder="e.g. Jane Smith"
/>
<FormField
label="Password"
name="password"
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
required
placeholder="Min. 6 characters"
hint="Used to sign into the mobile app immediately."
/>
<FormField
label="Confirm Password"
name="confirm_password"
type="password"
value={confirm}
onChange={(e) => setConfirm(e.target.value)}
required
placeholder="Re-enter password"
error={confirm && password !== confirm ? 'Passwords do not match.' : undefined}
/>
{error && (
<p style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-danger)' }}>{error}</p>
)}
</div>
</Modal>
)
}
@@ -0,0 +1,140 @@
// frontend/src/modals/crm/customers/CreateCustomerModal.jsx
// On-the-fly customer creation with minimal fields — mirrors CreateUserModal.
// Everything beyond name/folder_id/organization/email can be filled in later
// on the full customer detail page.
import { useState, useEffect } from 'react'
import api from '@/lib/api'
import Modal from '@/components/ui/Modal'
import Button from '@/components/ui/Button'
import FormField from '@/components/ui/FormField'
function slugify(str) {
return str
.toLowerCase()
.normalize('NFD').replace(/[̀-ͯ]/g, '') // strip accents
.replace(/[^a-z0-9]+/g, '-')
.replace(/^-+|-+$/g, '')
}
export default function CreateCustomerModal({ open, onClose, onCreated }) {
const [name, setName] = useState('')
const [surname, setSurname] = useState('')
const [organization, setOrganization] = useState('')
const [email, setEmail] = useState('')
const [folderId, setFolderId] = useState('')
const [folderIdTouched, setFolderIdTouched] = useState(false)
const [saving, setSaving] = useState(false)
const [error, setError] = useState('')
useEffect(() => {
if (!open) return
setName(''); setSurname(''); setOrganization(''); setEmail('')
setFolderId(''); setFolderIdTouched(false); setError('')
}, [open])
// Auto-suggest a folder slug from name+surname until the user edits it directly.
useEffect(() => {
if (folderIdTouched) return
setFolderId(slugify([name, surname].filter(Boolean).join('-')))
}, [name, surname, folderIdTouched])
const handleFolderIdChange = (e) => {
setFolderIdTouched(true)
setFolderId(e.target.value.toLowerCase().replace(/[^a-z0-9-]/g, ''))
}
const handleCreate = async () => {
setError('')
if (!name.trim()) { setError('First name is required.'); return }
const folder = folderId.trim()
if (!folder) { setError('Internal Folder ID is required.'); return }
if (!/^[a-z0-9][a-z0-9-]*[a-z0-9]$/.test(folder)) {
setError('Folder ID must contain only lowercase letters, numbers, and hyphens, and cannot start or end with a hyphen.')
return
}
setSaving(true)
try {
const created = await api.post('/crm/customers', {
name: name.trim(),
surname: surname.trim() || null,
organization: organization.trim() || null,
folder_id: folder,
relationship_status: 'lead',
contacts: email.trim() ? [{ type: 'email', label: '', value: email.trim(), primary: true }] : [],
})
onCreated(created)
} catch (err) {
setError(err.message || 'Failed to create customer.')
} finally {
setSaving(false)
}
}
return (
<Modal
open={open}
onClose={onClose}
title="Create Customer"
size="sm"
footer={
<div style={{ display: 'flex', justifyContent: 'flex-end', gap: 'var(--space-3)' }}>
<Button variant="ghost" onClick={onClose}>Cancel</Button>
<Button variant="primary" onClick={handleCreate} loading={saving}>Create Customer</Button>
</div>
}
>
<div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-4)' }}>
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 'var(--space-3)' }}>
<FormField
label="First Name"
name="name"
type="text"
value={name}
onChange={(e) => setName(e.target.value)}
required
placeholder="First name"
autoFocus
/>
<FormField
label="Surname"
name="surname"
type="text"
value={surname}
onChange={(e) => setSurname(e.target.value)}
placeholder="Last name"
/>
</div>
<FormField
label="Organization"
name="organization"
type="text"
value={organization}
onChange={(e) => setOrganization(e.target.value)}
placeholder="e.g. Saint John's Church"
/>
<FormField
label="Contact Email"
name="email"
type="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
placeholder="name@example.com"
/>
<FormField
label="Internal Folder ID"
name="folder_id"
type="text"
value={folderId}
onChange={handleFolderIdChange}
required
placeholder="e.g. saint-john-corfu"
hint="Lowercase letters, numbers and hyphens only. Becomes the Nextcloud folder name and cannot be changed. Auto-filled from the name — edit if needed."
/>
{error && (
<p style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-danger)' }}>{error}</p>
)}
</div>
</Modal>
)
}
@@ -0,0 +1,191 @@
// frontend/src/pages/bellcloud/devices/CrashReport.jsx
// Fleet-wide crash report (firmware F-070): every fault boot with crash
// detail, grouped so recurring crash types stand out across devices.
// Grouping (backend mqtt/crash_groups.py): abort_msg with hex addresses
// stripped when present, else faulting task + exception cause, else reset
// reason for fault resets with no coredump.
import { useState, useEffect, useCallback, useMemo } from 'react'
import { Link } from 'react-router-dom'
import api from '@/lib/api'
import PageHeader from '@/components/ui/PageHeader'
import Card from '@/components/ui/Card'
import Button from '@/components/ui/Button'
import StatusBadge from '@/components/ui/StatusBadge'
import Spinner from '@/components/ui/Spinner'
import Icon from '@/components/ui/Icon'
import TimeRangeSelect from '@/components/ui/TimeRangeSelect'
import { resolveRange } from '@/lib/timeRange'
import CrashDetail from '@/components/shared/CrashDetail'
import { fmtDateTimeMedium, fmtRelative } from '@/lib/formatters'
import { isHeapExhaustion } from '@/lib/crashReport'
const KIND_LABEL = { abort: 'Abort', exception: 'Exception', reason: 'No coredump' }
const KIND_VARIANT = { abort: 'danger', exception: 'danger', reason: 'warning' }
function deviceLabel(device) {
return device?.console_name || device?.device_name || null
}
function CrashGroupCard({ group, devicesBySerial }) {
const [showDetail, setShowDetail] = useState(false)
const heapLow = isHeapExhaustion(group.latest?.pre_crash)
return (
<Card
title={group.title}
subtitle={`${group.count} ${group.count === 1 ? 'crash' : 'crashes'} on ${group.device_count} ${group.device_count === 1 ? 'device' : 'devices'} · last ${fmtRelative(group.last_at)}`}
action={<StatusBadge variant={KIND_VARIANT[group.kind] || 'neutral'} size="sm">{KIND_LABEL[group.kind] || group.kind}</StatusBadge>}
>
<div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-4)' }}>
<div style={{ display: 'flex', flexWrap: 'wrap', gap: 'var(--space-2) var(--space-4)', fontSize: 'var(--font-size-xs)', color: 'var(--color-text-muted)' }}>
<span>First seen {fmtDateTimeMedium(group.first_at)}</span>
<span>Last seen {fmtDateTimeMedium(group.last_at)}</span>
{heapLow && <StatusBadge variant="warning" size="sm">Latest: likely heap exhaustion</StatusBadge>}
</div>
<div style={{ display: 'flex', flexDirection: 'column' }}>
{group.devices.map(d => {
const device = devicesBySerial[d.device_serial]
const name = deviceLabel(device)
return (
<div
key={d.device_serial}
style={{
display: 'flex', alignItems: 'center', gap: 'var(--space-3)', flexWrap: 'wrap',
padding: 'var(--space-2) 0', borderBottom: '1px solid var(--color-border)',
}}
>
<span style={{ flex: 1, minWidth: 0, display: 'flex', flexDirection: 'column' }}>
{device ? (
<Link to={`/devices/${device.id}?tab=health`} style={{ color: 'var(--color-text-accent)', fontSize: 'var(--font-size-sm)' }}>
{name || d.device_serial}
</Link>
) : (
<span style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-text-primary)' }}>{d.device_serial}</span>
)}
{name && (
<span style={{ fontSize: 'var(--font-size-xs)', color: 'var(--color-text-muted)', fontFamily: 'var(--font-family-mono)' }}>
{d.device_serial}
</span>
)}
</span>
<span style={{ fontSize: 'var(--font-size-xs)', color: 'var(--color-text-muted)', fontFamily: 'var(--font-family-mono)' }}>
{d.count}×
</span>
</div>
)
})}
</div>
<div>
<Button
variant="ghost"
size="sm"
iconRight={<Icon name="chevron_down" size={14} style={{ transform: showDetail ? 'rotate(180deg)' : 'none', transition: 'transform 0.15s' }} />}
onClick={() => setShowDetail(v => !v)}
>
{showDetail ? 'Hide latest occurrence' : 'Show latest occurrence'}
</Button>
</div>
{showDetail && (
<div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-3)' }}>
<span style={{ fontSize: 'var(--font-size-xs)', color: 'var(--color-text-muted)' }}>
{group.latest.device_serial} · boot #{group.latest.boot_count ?? '—'} · {fmtDateTimeMedium(group.latest.occurred_at)}
</span>
<CrashDetail event={group.latest} />
</div>
)}
</div>
</Card>
)
}
export default function CrashReport() {
const [range, setRange] = useState(() => resolveRange('30d'))
const [groups, setGroups] = useState([])
const [totalCrashes, setTotalCrashes] = useState(0)
const [devices, setDevices] = useState([])
const [loading, setLoading] = useState(true)
const [error, setError] = useState('')
const load = useCallback(async () => {
setLoading(true)
setError('')
try {
const p = new URLSearchParams()
if (range.since) p.set('since', range.since.toISOString())
if (range.until) p.set('until', range.until.toISOString())
const qs = p.toString()
const [crashRes, deviceRes] = await Promise.all([
api.get(`/mqtt/crash-groups${qs ? `?${qs}` : ''}`),
// Only for names/links — the report itself doesn't depend on it.
api.get('/devices').catch(() => ({ devices: [] })),
])
setGroups(crashRes.groups || [])
setTotalCrashes(crashRes.total_crashes || 0)
setDevices(deviceRes.devices || [])
} catch (err) {
setError(err.message || 'Failed to load crash report.')
} finally {
setLoading(false)
}
}, [range])
useEffect(() => { load() }, [load])
const devicesBySerial = useMemo(() => {
const map = {}
for (const d of devices) {
const sn = d.serial_number || d.device_id
if (sn) map[sn] = d
}
return map
}, [devices])
const affectedDevices = useMemo(
() => new Set(groups.flatMap(g => g.devices.map(d => d.device_serial))).size,
[groups],
)
return (
<div className="page-wrapper">
<PageHeader
title="Crash Report"
subtitle="Fault resets across the fleet, grouped by crash signature"
breadcrumbs={[{ label: 'Device Fleet', href: '/devices' }, { label: 'Crash Report' }]}
>
<div style={{ width: 'min(220px, 100%)' }}>
<TimeRangeSelect value={range} onChange={setRange} />
</div>
</PageHeader>
{loading ? (
<div style={{ display: 'flex', justifyContent: 'center', padding: 'var(--space-16)' }}>
<Spinner size="lg" />
</div>
) : error ? (
<div role="alert" style={{ backgroundColor: 'var(--color-danger-bg)', border: '1px solid var(--color-danger)', borderRadius: 'var(--radius-md)', padding: 'var(--space-4)', color: 'var(--color-danger)' }}>
{error}
</div>
) : groups.length === 0 ? (
<Card>
<div style={{ padding: 'var(--space-8)', textAlign: 'center', color: 'var(--color-text-muted)', fontSize: 'var(--font-size-sm)' }}>
No crashes recorded in this range.
</div>
</Card>
) : (
<>
<span style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-text-muted)' }}>
{totalCrashes} {totalCrashes === 1 ? 'crash' : 'crashes'} in {groups.length} {groups.length === 1 ? 'group' : 'groups'} across {affectedDevices} {affectedDevices === 1 ? 'device' : 'devices'}
</span>
<div className="masonry-grid masonry-grid--2">
{groups.map(g => (
<CrashGroupCard key={g.key} group={g} devicesBySerial={devicesBySerial} />
))}
</div>
</>
)}
</div>
)
}
@@ -1,20 +1,25 @@
// frontend/src/pages/bellcloud/devices/DeviceDetail.jsx
// 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 api from '@/lib/api'
import { getCachedDevice, setCachedDevice, getCachedStatus, setCachedStatus } from '@/lib/deviceCache'
import { useAuth } from '@/hooks/useAuth'
import { useToast } from '@/components/ui/Toast'
import { useDeviceCommand } from '@/hooks/useDeviceCommand'
import PageHeader from '@/components/ui/PageHeader'
import Button from '@/components/ui/Button'
import SignalIndicator from '@/components/ui/SignalIndicator'
import EditableText from '@/components/ui/EditableText'
import Icon from '@/components/ui/Icon'
import CopyableSerial from '@/components/shared/CopyableSerial'
import Tabs from '@/components/ui/Tabs'
import Spinner from '@/components/ui/Spinner'
import ConfirmDialog from '@/components/ui/ConfirmDialog'
import EditLocationModal from '@/modals/bellcloud/devices/EditLocationModal'
import EditAttributesModal from '@/modals/bellcloud/devices/EditAttributesModal'
import EditLoggingModal from '@/modals/bellcloud/devices/EditLoggingModal'
import EditMiscModal from '@/modals/bellcloud/devices/EditMiscModal'
import EditBellOutputsModal from '@/modals/bellcloud/devices/EditBellOutputsModal'
import EditClockSettingsModal from '@/modals/bellcloud/devices/EditClockSettingsModal'
@@ -31,11 +36,13 @@ import ClockTab from '@/pages/bellcloud/devices/tabs/ClockTab'
import WarrantyTab from '@/pages/bellcloud/devices/tabs/WarrantyTab'
import ManageTab from '@/pages/bellcloud/devices/tabs/ManageTab'
import ControlTab from '@/pages/bellcloud/devices/tabs/ControlTab'
import HealthTab from '@/pages/bellcloud/devices/tabs/HealthTab'
// ─── Tab config ───────────────────────────────────────────────────────────────
const TABS = [
{ key: 'overview', label: 'Overview' },
{ key: 'health', label: 'Health' },
{ key: 'general', label: 'General' },
{ key: 'bells', label: 'Bell Mechanisms' },
{ key: 'clock', label: 'Clock & Alerts' },
@@ -44,10 +51,15 @@ const TABS = [
{ key: 'control', label: 'Control' },
]
// 'logs' used to be its own top-level tab — now a sub-tab of Health.
// Old bookmarks/links with ?tab=logs still land somewhere sensible.
const LEGACY_TAB_REDIRECTS = { logs: 'health' }
function resolveInitialTab(searchParams) {
const raw = searchParams.get('tab')
const raw = searchParams.get('tab')?.toLowerCase()
if (!raw) return 'overview'
const match = TABS.find(t => t.key === raw.toLowerCase())
if (LEGACY_TAB_REDIRECTS[raw]) return LEGACY_TAB_REDIRECTS[raw]
const match = TABS.find(t => t.key === raw)
return match ? match.key : 'overview'
}
@@ -62,10 +74,19 @@ export default function DeviceDetail() {
const canEdit = hasPermission('devices', 'edit')
// ── State ──────────────────────────────────────────────────────────────────
const [device, setDevice] = useState(null)
const [loading, setLoading] = useState(true)
// Seeded from the last-known cache (lib/deviceCache — filled by DeviceList
// 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 [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 [deviceUsers, setDeviceUsers] = useState([])
@@ -73,20 +94,21 @@ export default function DeviceDetail() {
const [ownerCustomer, setOwnerCustomer] = useState(null)
const [assigningCustomer, setAssigningCustomer] = useState(false)
const [tags, setTags] = useState([])
const [staffNotes, setStaffNotes] = useState('')
const [tags, setTags] = useState(() => {
const t = getCachedDevice(id)?.tags
return Array.isArray(t) ? t : []
})
const [staffNotes, setStaffNotes] = useState(() => getCachedDevice(id)?.staffNotes || '')
const [showDelete, setShowDelete] = useState(false)
const [deleting, setDeleting] = useState(false)
const [cmdHistory, setCmdHistory] = useState([])
const [cmdHistoryLoading, setCmdHistoryLoading] = useState(false)
const [sendingCmd, setSendingCmd] = useState('')
// Modal open flags
const [editingLocation, setEditingLocation] = useState(false)
const [editingAttributes, setEditingAttributes] = useState(false)
const [editingLogging, setEditingLogging] = useState(false)
const [editingMisc, setEditingMisc] = useState(false)
const [editingBellOutputs, setEditingBellOutputs] = useState(false)
const [editingClockSettings, setEditingClockSettings] = useState(false)
@@ -99,8 +121,29 @@ export default function DeviceDetail() {
// ── Data fetching ──────────────────────────────────────────────────────────
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('')
// 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 {
const d = await api.get(`/devices/${id}`)
setDevice(d)
@@ -109,14 +152,8 @@ export default function DeviceDetail() {
setLoading(false)
const sn = d.serial_number || d.device_id
if (sn) {
api.get('/mqtt/status').then(mqttData => {
if (mqttData?.devices) {
const match = mqttData.devices.find(s => s.device_serial === sn)
setMqttStatus(match || null)
}
}).catch(() => {})
}
const statusDone = statusPromise || (sn ? fetchStatus(sn) : Promise.resolve())
statusDone.finally(() => setRefreshing(false))
if (d.customer_id) {
api.get(`/devices/${id}/customer`).then(res => {
@@ -132,13 +169,28 @@ export default function DeviceDetail() {
}).catch(() => setDeviceUsers([])).finally(() => setUsersLoading(false))
} 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)
setRefreshing(false)
}
}, [id])
useEffect(() => { loadDevice() }, [loadDevice])
// Re-fetches the device without toggling the page-level loading spinner —
// used by background reconciliation (e.g. ClockTab/BellsTab silently
// correcting drift from a GET-config refresh) so it doesn't unmount/remount
// the active tab mid-sync.
const reloadDeviceSilent = useCallback(async () => {
try {
const d = await api.get(`/devices/${id}`)
setDevice(d)
} catch {
// Silent by design — a failed background refresh isn't worth surfacing.
}
}, [id])
const loadCmdHistory = useCallback(async () => {
const sn = device?.serial_number || device?.device_id
if (!sn) return
@@ -157,6 +209,66 @@ export default function DeviceDetail() {
if (activeTab === 'control' && device) loadCmdHistory()
}, [activeTab, device, loadCmdHistory])
// ── Command ack (live reply over WebSocket) ───────────────────────────────
// Send/ack-queue machinery lives in useDeviceCommand (shared with the
// onboarding wizard). Heartbeats aren't command acks, so they're handled
// here via onNonAckMessage — the hook forwards anything that isn't a
// 'control/ack' reply for this device instead of opening a second WS connection.
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) => {
// Live heartbeat — updates the online dot/RSSI without polling. The device
// publishes one every ~30s; we just reflect whatever lands here instead of
// waiting for the next page load / GET /mqtt/status round trip.
// v2 heartbeat payload is FLAT (no nested .payload wrapper) — see
// vesper_mqtt_topic_spec_v2.md. field names: fw_version, uptime_human.
if (msg.type !== 'status/heartbeat') return
// Retained replay = the device's LAST heartbeat, re-sent by the broker when
// the backend reconnects — not proof the device is alive now.
if (msg.retained) return
const hb = msg.payload || {}
// LWT / graceful-disconnect marker: the device just went away.
if (hb.state === 'offline') {
setMqttStatus(prev => prev ? { ...prev, online: false } : prev)
return
}
setMqttStatus(prev => ({
device_serial: deviceSerial,
online: true,
seconds_since_heartbeat: 0,
last_alert_event: prev?.last_alert_event ?? null,
last_heartbeat: {
...(prev?.last_heartbeat || {}),
device_id: hb.device_id ?? prev?.last_heartbeat?.device_id,
firmware_version: hb.fw_version ?? prev?.last_heartbeat?.firmware_version,
ip_address: hb.ip_address ?? prev?.last_heartbeat?.ip_address,
gateway: hb.gateway ?? prev?.last_heartbeat?.gateway,
uptime_ms: hb.uptime_ms ?? prev?.last_heartbeat?.uptime_ms,
uptime_display: hb.uptime_human ?? prev?.last_heartbeat?.uptime_display,
rssi: hb.rssi ?? prev?.last_heartbeat?.rssi,
free_heap: hb.free_heap ?? prev?.last_heartbeat?.free_heap,
state: hb.state ?? prev?.last_heartbeat?.state,
ok: hb.ok ?? prev?.last_heartbeat?.ok,
received_at: new Date().toISOString(),
},
}))
}, [deviceSerial])
// DeviceDetail additionally refreshes the Control tab's command history as
// soon as a command is accepted for sending — the shared hook doesn't know
// about that concern, so it's wired in via onCommandSent.
const { sendMqttCommand, sendMqttCommandSilent, sendingCmd } = useDeviceCommand({
deviceSerial,
onNonAckMessage: handleNonAckMessage,
onCommandSent: loadCmdHistory,
})
// ── Tab sync ───────────────────────────────────────────────────────────────
const handleTabChange = key => {
@@ -213,20 +325,19 @@ export default function DeviceDetail() {
}
}
const sendMqttCommand = async (cmd, contents = {}) => {
const deviceId = device?.device_id || device?.serial_number
if (!deviceId) return
setSendingCmd(cmd)
// Console-only friendly name — separate from device_name (the name the end
// user gave the device in the app). Saves optimistically into local state
// so the hero title updates immediately; a failed save reverts and toasts.
const handleSaveConsoleName = useCallback(async (newName) => {
const previous = device?.console_name || ''
setDevice(d => d ? { ...d, console_name: newName } : d)
try {
await api.post(`/mqtt/command/${deviceId}`, { cmd, contents })
toast.success('Sent', `Command "${cmd}" sent.`)
loadCmdHistory()
await api.put(`/devices/${id}`, { console_name: newName })
} catch (err) {
toast.danger('Error', err.message || 'Failed to send command.')
} finally {
setSendingCmd('')
setDevice(d => d ? { ...d, console_name: previous } : d)
toast({ variant: 'danger', title: 'Failed to rename device', description: err.message || 'Please try again.' })
}
}
}, [id, device, toast])
// ── Derived ────────────────────────────────────────────────────────────────
@@ -272,6 +383,7 @@ export default function DeviceDetail() {
stats,
sn,
isOnline,
mqttStatus,
tags,
setTags,
staffNotes,
@@ -284,14 +396,15 @@ export default function DeviceDetail() {
cmdHistoryLoading,
sendingCmd,
loadDevice,
reloadDeviceSilent,
loadCmdHistory,
sendMqttCommand,
sendMqttCommandSilent,
onShowDelete: () => setShowDelete(true),
onAssignCustomer: () => setShowAssignCustomer(true),
onUnassignCustomer: handleUnassignCustomer,
onEditLocation: () => setEditingLocation(true),
onEditAttributes: () => setEditingAttributes(true),
onEditLogging: () => setEditingLogging(true),
onEditMisc: () => setEditingMisc(true),
onEditBellOutputs: () => setEditingBellOutputs(true),
onEditClockSettings: () => setEditingClockSettings(true),
@@ -305,12 +418,54 @@ export default function DeviceDetail() {
// ── Render ─────────────────────────────────────────────────────────────────
return (
<div className="page-wrapper">
<div className="page-wrapper page-wrapper--capped">
<PageHeader
title={device.device_name || 'Unnamed Device'}
subtitle={sn}
title={
<span style={{ display: 'inline-flex', alignItems: 'center', gap: 'var(--space-4)' }}>
<span style={{
width: 48, height: 48,
borderRadius: 'var(--radius-xl)',
background: 'rgba(28, 32, 38, 0.30)',
backdropFilter: 'var(--blur-modal)',
WebkitBackdropFilter: 'var(--blur-modal)',
border: '1px solid var(--color-border)',
boxShadow: 'var(--shadow-card), var(--shadow-md)',
display: 'flex', alignItems: 'center', justifyContent: 'center',
flexShrink: 0,
}}>
<SignalIndicator rssi={mqttStatus?.last_heartbeat?.rssi} isOnline={isOnline} size="md" />
</span>
<span style={{ display: 'flex', flexDirection: 'column' }}>
<EditableText
value={device.console_name || ''}
placeholder={device.device_name || 'Unnamed Device'}
onSave={handleSaveConsoleName}
editable={canEdit}
inputAriaLabel="Edit console name"
/>
<CopyableSerial
serial={sn}
className="page-header-subtitle"
style={{ margin: 0, color: 'var(--color-text-muted)', fontSize: 'var(--font-size-base)', lineHeight: 'var(--line-height-base)' }}
/>
</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')}>
Ping Now
</Button>
{canEdit && (
<Button variant="secondary" onClick={() => navigate(`/devices/${id}/edit`)}>
Edit Device
@@ -326,6 +481,7 @@ export default function DeviceDetail() {
<div style={{ flex: 1, minWidth: 0 }}>
{activeTab === 'overview' && <OverviewTab {...tabProps} />}
{activeTab === 'health' && <HealthTab {...tabProps} />}
{activeTab === 'general' && <GeneralTab {...tabProps} />}
{activeTab === 'bells' && <BellsTab {...tabProps} />}
{activeTab === 'clock' && <ClockTab {...tabProps} />}
@@ -350,13 +506,6 @@ export default function DeviceDetail() {
attr={attr}
id={id}
/>
<EditLoggingModal
open={editingLogging}
onClose={() => setEditingLogging(false)}
onSaved={loadDevice}
attr={attr}
id={id}
/>
<EditMiscModal
open={editingMisc}
onClose={() => setEditingMisc(false)}
@@ -372,6 +521,7 @@ export default function DeviceDetail() {
attr={attr}
sub={sub}
id={id}
sendMqttCommand={sendMqttCommand}
/>
<EditClockSettingsModal
open={editingClockSettings}
@@ -380,6 +530,7 @@ export default function DeviceDetail() {
attr={attr}
sub={sub}
id={id}
sendMqttCommand={sendMqttCommand}
/>
<EditAlertsModal
open={editingAlerts}
@@ -388,6 +539,7 @@ export default function DeviceDetail() {
clock={clock}
attr={attr}
id={id}
sendMqttCommand={sendMqttCommand}
/>
<EditBacklightModal
open={editingBacklight}
@@ -397,6 +549,7 @@ export default function DeviceDetail() {
clock={clock}
sub={sub}
id={id}
sendMqttCommand={sendMqttCommand}
/>
<EditSubscriptionModal
open={editingSubscription}
@@ -422,7 +575,7 @@ export default function DeviceDetail() {
open={showDelete}
variant="danger"
title="Delete Device"
message={`Are you sure you want to delete "${device.device_name || sn}"? This action cannot be undone.`}
message={`Are you sure you want to delete "${device.console_name || device.device_name || sn}"? This action cannot be undone.`}
confirmLabel="Delete"
onConfirm={handleDelete}
onCancel={() => setShowDelete(false)}

Some files were not shown because too many files have changed in this diff Show More