Compare commits
86
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
db22abdb7d | ||
|
|
eff9e72681 | ||
|
|
565aca4d56 | ||
|
|
3636556ae7 | ||
|
|
fb35ace0c7 | ||
|
|
da83f2a1cd | ||
|
|
9deff308b6 | ||
|
|
2e3d7ba062 | ||
|
|
5ab87fa9f0 | ||
|
|
62be80c9d8 | ||
|
|
2a6f9697b8 | ||
|
|
fba5110cc0 | ||
|
|
cdf5fc79a0 | ||
|
|
e4ea43a079 | ||
|
|
8837eb1e70 | ||
|
|
d1799bd3b1 | ||
|
|
ca53d2e871 | ||
|
|
65ff2372ca | ||
|
|
c2767ca7e0 | ||
|
|
bbd356d846 | ||
|
|
18705aaefb | ||
|
|
f1a7c5a7ca | ||
|
|
82cf95a9af | ||
|
|
963516ece0 | ||
|
|
46c5c0a846 | ||
|
|
18e57c6e5f | ||
|
|
98dd16b597 | ||
|
|
36f9540a89 | ||
|
|
c1df3b5aa3 | ||
|
|
3f3d2cc63c | ||
|
|
e663b0a609 | ||
|
|
61e9bfab7c | ||
|
|
43102c617d | ||
|
|
ecfe00307a | ||
|
|
6ea7e9d2c5 | ||
|
|
f5db83f26c | ||
|
|
3acd89a2c6 | ||
|
|
81365eed89 | ||
|
|
1253ec155e | ||
|
|
8a668ca60f | ||
|
|
85bd2f7e51 | ||
|
|
79a87e48f1 | ||
|
|
017911bece | ||
|
|
c36e4c41f8 | ||
|
|
8b229e7fb3 | ||
|
|
9d9b46056a | ||
|
|
adec979182 | ||
|
|
99baec9fcf | ||
|
|
c56344a6dc | ||
|
|
0c0dd9d0e9 | ||
|
|
529e866fff | ||
|
|
c8ac0b78c5 | ||
|
|
80c0e955f0 | ||
|
|
ae5da6046f | ||
|
|
aad5f4b98c | ||
|
|
751cac72ce | ||
|
|
cef5e1f0f5 | ||
|
|
f036000769 | ||
|
|
d87925516a | ||
|
|
f54500a9d9 | ||
|
|
4737ab4306 | ||
|
|
6686faad6b | ||
|
|
b07bdafd85 | ||
|
|
dff1a35560 | ||
|
|
acd1896788 | ||
|
|
0d79a9f72c | ||
|
|
6e0a291228 | ||
|
|
8ec13947cb | ||
|
|
0bec4c4648 | ||
|
|
cc138e3d82 | ||
|
|
7c533b9245 | ||
|
|
e5d556fee1 | ||
|
|
38750ba951 | ||
|
|
7f6145ca35 | ||
|
|
2f7c5e859d | ||
|
|
883c0556dd | ||
|
|
1ce0137ba9 | ||
|
|
eaf92f1581 | ||
|
|
cc28ed880b | ||
|
|
44609352b2 | ||
|
|
70e0f9f734 | ||
|
|
a9b3b4e9b0 | ||
|
|
65ce446e44 | ||
|
|
bff90965bf | ||
|
|
3394716f8f | ||
|
|
abf3c3825b |
@@ -17,6 +17,10 @@ MOSQUITTO_PASSWORD_FILE=/etc/mosquitto/passwd
|
|||||||
MQTT_CLIENT_ID=bellsystems-admin-panel
|
MQTT_CLIENT_ID=bellsystems-admin-panel
|
||||||
# HMAC secret used to derive per-device MQTT passwords (must match firmware)
|
# HMAC secret used to derive per-device MQTT passwords (must match firmware)
|
||||||
MQTT_SECRET=change-me-in-production
|
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
|
# App
|
||||||
BACKEND_CORS_ORIGINS=["http://localhost:5173"]
|
BACKEND_CORS_ORIGINS=["http://localhost:5173"]
|
||||||
|
|||||||
+3
-1
@@ -40,4 +40,6 @@ Thumbs.db
|
|||||||
.project-vesper-plan.md
|
.project-vesper-plan.md
|
||||||
|
|
||||||
# claude
|
# claude
|
||||||
.claude/
|
.claude/
|
||||||
|
# Per-machine compose overrides (e.g. Windows Postgres volume)
|
||||||
|
docker-compose.override.yml
|
||||||
|
|||||||
@@ -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
|
- **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 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.
|
- **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 |
|
| `StatusBadge` | `@/components/ui/StatusBadge` | Coloured status pills |
|
||||||
| `FormField` | `@/components/ui/FormField` | Every text/email/password/textarea input |
|
| `FormField` | `@/components/ui/FormField` | Every text/email/password/textarea input |
|
||||||
| `Select` | `@/components/ui/Select` | Custom dropdown (used inside FormField type="select") |
|
| `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 |
|
| `Modal` | `@/components/ui/Modal` | All overlay dialogs |
|
||||||
| `ConfirmDialog` | `@/components/ui/ConfirmDialog` | Destructive / confirmation prompts |
|
| `ConfirmDialog` | `@/components/ui/ConfirmDialog` | Destructive / confirmation prompts |
|
||||||
| `DataTable` | `@/components/ui/DataTable` | All tabular data with sorting/selection |
|
| `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
|
## API Client
|
||||||
|
|
||||||
```js
|
```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/`.
|
These are the ONLY two files permitted to import from `_archive/auth/`.
|
||||||
All other files use `@/hooks/useAuth`.
|
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.
|
||||||
|
|||||||
@@ -39,6 +39,20 @@ bellsystems-admin/
|
|||||||
└── .env
|
└── .env
|
||||||
```
|
```
|
||||||
|
|
||||||
|
## Shared data contract (Firestore schema v1)
|
||||||
|
|
||||||
|
Firestore is shared with the BellSystems tablet and phone apps (FlutterFlow). Device
|
||||||
|
documents must follow the schema in the **bellsystems-schema** repo
|
||||||
|
(`v1/firestore.schema.json`) — one wrongly typed field makes the apps silently hide the
|
||||||
|
device from its users.
|
||||||
|
|
||||||
|
- All device writes go through `backend/devices/firestore_v1.py`.
|
||||||
|
- Adding or changing a shared field: update the schema repo first, then every app and this
|
||||||
|
console in the same release.
|
||||||
|
- Check production data: `node tools/audit.js <service-account.json>` in the schema repo.
|
||||||
|
|
||||||
|
Details: the "Firestore Schema v1" section of `CLAUDE.md`.
|
||||||
|
|
||||||
## Documentation
|
## Documentation
|
||||||
|
|
||||||
See `BellSystems_AdminPanel_Strategy.md` for the full architecture and build plan.
|
See `BellSystems_AdminPanel_Strategy.md` for the full architecture and build plan.
|
||||||
@@ -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")
|
||||||
@@ -19,6 +19,9 @@ class Settings(BaseSettings):
|
|||||||
mqtt_admin_username: str = "admin"
|
mqtt_admin_username: str = "admin"
|
||||||
mqtt_admin_password: str = ""
|
mqtt_admin_password: str = ""
|
||||||
mqtt_secret: str = "change-me-in-production"
|
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"
|
mosquitto_password_file: str = "/etc/mosquitto/passwd"
|
||||||
mqtt_client_id: str = "bellsystems-admin-panel"
|
mqtt_client_id: str = "bellsystems-admin-panel"
|
||||||
|
|
||||||
@@ -32,6 +35,9 @@ class Settings(BaseSettings):
|
|||||||
# Local file storage
|
# Local file storage
|
||||||
built_melodies_storage_path: str = "./storage/built_melodies"
|
built_melodies_storage_path: str = "./storage/built_melodies"
|
||||||
firmware_storage_path: str = "./storage/firmware"
|
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"
|
flash_assets_storage_path: str = "./storage/flash_assets"
|
||||||
melody_binaries_storage_path: str = "./storage/melody_binaries"
|
melody_binaries_storage_path: str = "./storage/melody_binaries"
|
||||||
melody_download_base_url: str = "http://melodies.bellsystems.net/download"
|
melody_download_base_url: str = "http://melodies.bellsystems.net/download"
|
||||||
|
|||||||
@@ -12,10 +12,40 @@ from database.pg_mqtt import (
|
|||||||
get_heartbeats,
|
get_heartbeats,
|
||||||
get_commands,
|
get_commands,
|
||||||
get_latest_heartbeats,
|
get_latest_heartbeats,
|
||||||
|
get_latest_heartbeat,
|
||||||
|
warm_latest_cache,
|
||||||
get_pending_command,
|
get_pending_command,
|
||||||
upsert_alert,
|
upsert_alert,
|
||||||
delete_alert,
|
delete_alert,
|
||||||
get_alerts,
|
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,
|
partition_manager_loop,
|
||||||
ensure_current_partitions,
|
ensure_current_partitions,
|
||||||
)
|
)
|
||||||
@@ -38,10 +68,40 @@ __all__ = [
|
|||||||
"get_heartbeats",
|
"get_heartbeats",
|
||||||
"get_commands",
|
"get_commands",
|
||||||
"get_latest_heartbeats",
|
"get_latest_heartbeats",
|
||||||
|
"get_latest_heartbeat",
|
||||||
|
"warm_latest_cache",
|
||||||
"get_pending_command",
|
"get_pending_command",
|
||||||
"upsert_alert",
|
"upsert_alert",
|
||||||
"delete_alert",
|
"delete_alert",
|
||||||
"get_alerts",
|
"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",
|
"partition_manager_loop",
|
||||||
"ensure_current_partitions",
|
"ensure_current_partitions",
|
||||||
]
|
]
|
||||||
|
|||||||
@@ -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]
|
||||||
+954
-38
File diff suppressed because it is too large
Load Diff
@@ -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
@@ -1,7 +1,12 @@
|
|||||||
from pydantic import BaseModel, Field
|
from pydantic import BaseModel, ConfigDict, Field
|
||||||
from typing import Any, Dict, List, Optional
|
from typing import Any, Dict, List, Optional
|
||||||
from enum import Enum
|
from enum import Enum
|
||||||
|
|
||||||
|
# Field names and types follow Firestore schema v1 (bellsystems-schema repo,
|
||||||
|
# v1/firestore.schema.json) — the shape the shipped tablet/phone apps read.
|
||||||
|
# Timestamps travel through the API as ISO 8601 strings and are unset as None
|
||||||
|
# (never ""); devices/firestore_v1.py converts to/from Firestore.
|
||||||
|
|
||||||
|
|
||||||
# --- Enums ---
|
# --- Enums ---
|
||||||
|
|
||||||
@@ -30,12 +35,14 @@ class DeviceTiers(str, Enum):
|
|||||||
|
|
||||||
class DeviceNetworkSettings(BaseModel):
|
class DeviceNetworkSettings(BaseModel):
|
||||||
hostname: str = ""
|
hostname: str = ""
|
||||||
useStaticIP: bool = False
|
usesStaticIP: bool = False
|
||||||
ipAddress: Any = []
|
# Dotted strings ("10.0.0.5"); "" = not set. The firmware's network.set_config
|
||||||
gateway: Any = []
|
# MQTT command uses its own names (useStaticIP / ip) — convert at that boundary.
|
||||||
subnet: Any = []
|
ipAddress: str = ""
|
||||||
dns1: Any = []
|
gateway: str = ""
|
||||||
dns2: Any = []
|
subnet: str = ""
|
||||||
|
dns1: str = ""
|
||||||
|
dns2: str = ""
|
||||||
|
|
||||||
|
|
||||||
class DeviceClockSettings(BaseModel):
|
class DeviceClockSettings(BaseModel):
|
||||||
@@ -49,14 +56,18 @@ class DeviceClockSettings(BaseModel):
|
|||||||
quarterAlertsBell: int = 0
|
quarterAlertsBell: int = 0
|
||||||
isDaySilenceOn: bool = False
|
isDaySilenceOn: bool = False
|
||||||
isNightSilenceOn: bool = False
|
isNightSilenceOn: bool = False
|
||||||
daySilenceFrom: str = ""
|
# Time of day carried in a Timestamp (v1 quirk); only the UTC time part matters.
|
||||||
daySilenceTo: str = ""
|
daySilenceFrom: Optional[str] = None
|
||||||
nightSilenceFrom: str = ""
|
daySilenceTo: Optional[str] = None
|
||||||
nightSilenceTo: str = ""
|
nightSilenceFrom: Optional[str] = None
|
||||||
backlightTurnOnTime: str = ""
|
nightSilenceTo: Optional[str] = None
|
||||||
backlightTurnOffTime: str = ""
|
backlightTurnOnTime: Optional[str] = None
|
||||||
|
backlightTurnOffTime: Optional[str] = None
|
||||||
isBacklightAutomationOn: bool = False
|
isBacklightAutomationOn: bool = False
|
||||||
backlightOutput: int = 0
|
backlightOutput: int = 0
|
||||||
|
# Firmware 3.2.0+ face sync policy (clock.set_config face_sync_mode / smart_max_wait_min)
|
||||||
|
faceSyncMode: str = "force"
|
||||||
|
smartMaxWaitMin: int = 61
|
||||||
|
|
||||||
|
|
||||||
class DeviceAttributes(BaseModel):
|
class DeviceAttributes(BaseModel):
|
||||||
@@ -67,9 +78,9 @@ class DeviceAttributes(BaseModel):
|
|||||||
bellOutputs: List[int] = []
|
bellOutputs: List[int] = []
|
||||||
hammerTimings: List[int] = []
|
hammerTimings: List[int] = []
|
||||||
bellGuardOn: bool = False
|
bellGuardOn: bool = False
|
||||||
bellGuardSafetyOn: bool = False
|
bellguardSafetyOn: bool = False # lower-case g: the exact key the apps read
|
||||||
warningsOn: bool = False
|
warningsOn: bool = False
|
||||||
towerClockTime: str = ""
|
towerClockTime: Optional[str] = None
|
||||||
clockSettings: DeviceClockSettings = DeviceClockSettings()
|
clockSettings: DeviceClockSettings = DeviceClockSettings()
|
||||||
deviceLocale: HelperMelodyTypes = HelperMelodyTypes.all
|
deviceLocale: HelperMelodyTypes = HelperMelodyTypes.all
|
||||||
networkSettings: DeviceNetworkSettings = DeviceNetworkSettings()
|
networkSettings: DeviceNetworkSettings = DeviceNetworkSettings()
|
||||||
@@ -80,7 +91,7 @@ class DeviceAttributes(BaseModel):
|
|||||||
|
|
||||||
class DeviceSubInformation(BaseModel):
|
class DeviceSubInformation(BaseModel):
|
||||||
subscrTier: DeviceTiers = DeviceTiers.basic
|
subscrTier: DeviceTiers = DeviceTiers.basic
|
||||||
subscrStart: str = ""
|
subscrStart: Optional[str] = None
|
||||||
subscrDuration: int = 0
|
subscrDuration: int = 0
|
||||||
maxUsers: int = 0
|
maxUsers: int = 0
|
||||||
maxOutputs: int = 0
|
maxOutputs: int = 0
|
||||||
@@ -92,32 +103,74 @@ class DeviceStatistics(BaseModel):
|
|||||||
perBellStrikes: List[int] = []
|
perBellStrikes: List[int] = []
|
||||||
totalWarningsGiven: int = 0
|
totalWarningsGiven: int = 0
|
||||||
warrantyActive: bool = False
|
warrantyActive: bool = False
|
||||||
warrantyStart: str = ""
|
warrantyStart: Optional[str] = None
|
||||||
warrantyPeriod: int = 0
|
warrantyPeriod: int = 0
|
||||||
maintainedOn: str = ""
|
maintainedOn: Optional[str] = None
|
||||||
maintainancePeriod: int = 0
|
maintainancePeriod: int = 0 # misspelled in v1 on purpose: the apps read this key
|
||||||
|
|
||||||
|
|
||||||
|
class HealthThresholdTier(BaseModel):
|
||||||
|
"""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):
|
class MelodyMainItem(BaseModel):
|
||||||
"""Mirrors the Melody schema used in the melodies collection."""
|
"""One melody as stored inside devices.device_melodies_all (v1 MelodyMainItem).
|
||||||
information: dict = {}
|
|
||||||
default_settings: dict = {}
|
NOT the melodies/{id} document shape: the apps read camelCase keys here
|
||||||
type: str = ""
|
(mainInformation / defaultSettings / settings / binaryUrl / melodyReference).
|
||||||
url: str = ""
|
Extra keys are kept so a read-modify-write never drops data.
|
||||||
|
"""
|
||||||
|
model_config = ConfigDict(extra="allow")
|
||||||
|
|
||||||
|
melodyReference: Optional[str] = None # path "melodies/{id}" in the API
|
||||||
uid: str = ""
|
uid: str = ""
|
||||||
pid: str = ""
|
pid: str = ""
|
||||||
|
mainInformation: Dict[str, Any] = {}
|
||||||
|
defaultSettings: Dict[str, Any] = {}
|
||||||
|
settings: Dict[str, Any] = {}
|
||||||
|
binaryUrl: str = ""
|
||||||
|
|
||||||
|
|
||||||
# --- Request / Response schemas ---
|
# --- Request / Response schemas ---
|
||||||
|
|
||||||
class DeviceCreate(BaseModel):
|
class DeviceCreate(BaseModel):
|
||||||
device_name: str = ""
|
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_photo: str = ""
|
||||||
device_location: str = ""
|
device_location: str = ""
|
||||||
is_Online: bool = False
|
is_Online: bool = False
|
||||||
device_attributes: DeviceAttributes = DeviceAttributes()
|
device_attributes: DeviceAttributes = DeviceAttributes()
|
||||||
device_subscription: DeviceSubInformation = DeviceSubInformation()
|
device_subscription: DeviceSubInformation = DeviceSubInformation()
|
||||||
device_stats: DeviceStatistics = DeviceStatistics()
|
device_stats: DeviceStatistics = DeviceStatistics()
|
||||||
|
device_health_settings: DeviceHealthSettings = DeviceHealthSettings()
|
||||||
events_on: bool = False
|
events_on: bool = False
|
||||||
device_location_coordinates: Any = None # GeoPoint dict {lat, lng} or legacy str
|
device_location_coordinates: Any = None # GeoPoint dict {lat, lng} or legacy str
|
||||||
device_melodies_all: List[MelodyMainItem] = []
|
device_melodies_all: List[MelodyMainItem] = []
|
||||||
@@ -136,6 +189,7 @@ class DeviceCreate(BaseModel):
|
|||||||
|
|
||||||
class DeviceUpdate(BaseModel):
|
class DeviceUpdate(BaseModel):
|
||||||
device_name: Optional[str] = None
|
device_name: Optional[str] = None
|
||||||
|
console_name: Optional[str] = None
|
||||||
device_photo: Optional[str] = None
|
device_photo: Optional[str] = None
|
||||||
device_location: Optional[str] = None
|
device_location: Optional[str] = None
|
||||||
is_Online: Optional[bool] = None
|
is_Online: Optional[bool] = None
|
||||||
@@ -143,6 +197,7 @@ class DeviceUpdate(BaseModel):
|
|||||||
device_attributes: Optional[Dict[str, Any]] = None
|
device_attributes: Optional[Dict[str, Any]] = None
|
||||||
device_subscription: Optional[Dict[str, Any]] = None
|
device_subscription: Optional[Dict[str, Any]] = None
|
||||||
device_stats: 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
|
events_on: Optional[bool] = None
|
||||||
device_location_coordinates: Optional[Any] = None # dict {lat, lng} or legacy str
|
device_location_coordinates: Optional[Any] = None # dict {lat, lng} or legacy str
|
||||||
device_melodies_all: Optional[List[MelodyMainItem]] = None
|
device_melodies_all: Optional[List[MelodyMainItem]] = None
|
||||||
@@ -179,7 +234,7 @@ class DeviceNoteUpdate(BaseModel):
|
|||||||
|
|
||||||
|
|
||||||
class DeviceUserInfo(BaseModel):
|
class DeviceUserInfo(BaseModel):
|
||||||
"""User info resolved from device_users sub-collection or user_list."""
|
"""User info resolved from the device's user_list (role from the device_users mirror)."""
|
||||||
user_id: str = ""
|
user_id: str = ""
|
||||||
display_name: str = ""
|
display_name: str = ""
|
||||||
email: str = ""
|
email: str = ""
|
||||||
@@ -190,3 +245,39 @@ class DeviceUserInfo(BaseModel):
|
|||||||
class DeviceUsersResponse(BaseModel):
|
class DeviceUsersResponse(BaseModel):
|
||||||
users: List[DeviceUserInfo]
|
users: List[DeviceUserInfo]
|
||||||
total: int
|
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
@@ -10,8 +10,10 @@ from devices.models import (
|
|||||||
DeviceCreate, DeviceUpdate, DeviceInDB, DeviceListResponse,
|
DeviceCreate, DeviceUpdate, DeviceInDB, DeviceListResponse,
|
||||||
DeviceUsersResponse, DeviceUserInfo,
|
DeviceUsersResponse, DeviceUserInfo,
|
||||||
DeviceNoteCreate, DeviceNoteUpdate,
|
DeviceNoteCreate, DeviceNoteUpdate,
|
||||||
|
ResetStatsRequest, ResetStatsResult,
|
||||||
)
|
)
|
||||||
from devices import service
|
from devices import service
|
||||||
|
from users import service as users_service
|
||||||
import database as mqtt_db
|
import database as mqtt_db
|
||||||
from mqtt.models import DeviceAlertEntry, DeviceAlertsResponse
|
from mqtt.models import DeviceAlertEntry, DeviceAlertsResponse
|
||||||
from shared.firebase import get_db as get_firestore
|
from shared.firebase import get_db as get_firestore
|
||||||
@@ -25,7 +27,7 @@ CRM_COLLECTION = "crm_customers"
|
|||||||
|
|
||||||
|
|
||||||
@router.get("", response_model=DeviceListResponse)
|
@router.get("", response_model=DeviceListResponse)
|
||||||
async def list_devices(
|
def list_devices(
|
||||||
search: Optional[str] = Query(None),
|
search: Optional[str] = Query(None),
|
||||||
online: Optional[bool] = Query(None),
|
online: Optional[bool] = Query(None),
|
||||||
tier: Optional[str] = Query(None),
|
tier: Optional[str] = Query(None),
|
||||||
@@ -40,7 +42,7 @@ async def list_devices(
|
|||||||
|
|
||||||
|
|
||||||
@router.get("/{device_id}", response_model=DeviceInDB)
|
@router.get("/{device_id}", response_model=DeviceInDB)
|
||||||
async def get_device(
|
def get_device(
|
||||||
device_id: str,
|
device_id: str,
|
||||||
_user: TokenPayload = Depends(require_permission("devices", "view")),
|
_user: TokenPayload = Depends(require_permission("devices", "view")),
|
||||||
):
|
):
|
||||||
@@ -48,7 +50,7 @@ async def get_device(
|
|||||||
|
|
||||||
|
|
||||||
@router.get("/{device_id}/users", response_model=DeviceUsersResponse)
|
@router.get("/{device_id}/users", response_model=DeviceUsersResponse)
|
||||||
async def get_device_users(
|
def get_device_users(
|
||||||
device_id: str,
|
device_id: str,
|
||||||
_user: TokenPayload = Depends(require_permission("devices", "view")),
|
_user: TokenPayload = Depends(require_permission("devices", "view")),
|
||||||
):
|
):
|
||||||
@@ -65,7 +67,7 @@ async def create_device(
|
|||||||
):
|
):
|
||||||
device = service.create_device(body)
|
device = service.create_device(body)
|
||||||
await log_action(db, _user.sub, _user.name or _user.email, "CREATE", "device",
|
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
|
return device
|
||||||
|
|
||||||
|
|
||||||
@@ -87,7 +89,7 @@ async def update_device(
|
|||||||
if "tags" in body.model_fields_set and (old.tags or []) != (device.tags or []):
|
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 [])}
|
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",
|
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
|
return device
|
||||||
|
|
||||||
|
|
||||||
@@ -117,7 +119,7 @@ async def get_device_alerts(
|
|||||||
# ─────────────────────────────────────────────────────────────────────────────
|
# ─────────────────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
@router.get("/{device_id}/notes")
|
@router.get("/{device_id}/notes")
|
||||||
async def list_device_notes(
|
def list_device_notes(
|
||||||
device_id: str,
|
device_id: str,
|
||||||
_user: TokenPayload = Depends(require_permission("devices", "view")),
|
_user: TokenPayload = Depends(require_permission("devices", "view")),
|
||||||
):
|
):
|
||||||
@@ -137,7 +139,7 @@ async def list_device_notes(
|
|||||||
|
|
||||||
|
|
||||||
@router.post("/{device_id}/notes", status_code=201)
|
@router.post("/{device_id}/notes", status_code=201)
|
||||||
async def create_device_note(
|
def create_device_note(
|
||||||
device_id: str,
|
device_id: str,
|
||||||
body: DeviceNoteCreate,
|
body: DeviceNoteCreate,
|
||||||
_user: TokenPayload = Depends(require_permission("devices", "edit")),
|
_user: TokenPayload = Depends(require_permission("devices", "edit")),
|
||||||
@@ -161,7 +163,7 @@ async def create_device_note(
|
|||||||
|
|
||||||
|
|
||||||
@router.put("/{device_id}/notes/{note_id}")
|
@router.put("/{device_id}/notes/{note_id}")
|
||||||
async def update_device_note(
|
def update_device_note(
|
||||||
device_id: str,
|
device_id: str,
|
||||||
note_id: str,
|
note_id: str,
|
||||||
body: DeviceNoteUpdate,
|
body: DeviceNoteUpdate,
|
||||||
@@ -185,7 +187,7 @@ async def update_device_note(
|
|||||||
|
|
||||||
|
|
||||||
@router.delete("/{device_id}/notes/{note_id}", status_code=204)
|
@router.delete("/{device_id}/notes/{note_id}", status_code=204)
|
||||||
async def delete_device_note(
|
def delete_device_note(
|
||||||
device_id: str,
|
device_id: str,
|
||||||
note_id: str,
|
note_id: str,
|
||||||
_user: TokenPayload = Depends(require_permission("devices", "edit")),
|
_user: TokenPayload = Depends(require_permission("devices", "edit")),
|
||||||
@@ -208,7 +210,7 @@ class TagsUpdate(BaseModel):
|
|||||||
|
|
||||||
|
|
||||||
@router.put("/{device_id}/tags", response_model=DeviceInDB)
|
@router.put("/{device_id}/tags", response_model=DeviceInDB)
|
||||||
async def update_device_tags(
|
def update_device_tags(
|
||||||
device_id: str,
|
device_id: str,
|
||||||
body: TagsUpdate,
|
body: TagsUpdate,
|
||||||
_user: TokenPayload = Depends(require_permission("devices", "edit")),
|
_user: TokenPayload = Depends(require_permission("devices", "edit")),
|
||||||
@@ -234,7 +236,7 @@ class AssignCustomerBody(BaseModel):
|
|||||||
|
|
||||||
|
|
||||||
@router.get("/{device_id}/customer-search")
|
@router.get("/{device_id}/customer-search")
|
||||||
async def search_customers_for_device(
|
def search_customers_for_device(
|
||||||
device_id: str,
|
device_id: str,
|
||||||
q: str = Query(""),
|
q: str = Query(""),
|
||||||
_user: TokenPayload = Depends(require_permission("devices", "view")),
|
_user: TokenPayload = Depends(require_permission("devices", "view")),
|
||||||
@@ -355,7 +357,7 @@ async def unassign_device_from_customer(
|
|||||||
# ─────────────────────────────────────────────────────────────────────────────
|
# ─────────────────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
@router.get("/{device_id}/customer")
|
@router.get("/{device_id}/customer")
|
||||||
async def get_device_customer(
|
def get_device_customer(
|
||||||
device_id: str,
|
device_id: str,
|
||||||
_user: TokenPayload = Depends(require_permission("devices", "view")),
|
_user: TokenPayload = Depends(require_permission("devices", "view")),
|
||||||
):
|
):
|
||||||
@@ -397,7 +399,7 @@ class UserSearchResult(BaseModel):
|
|||||||
|
|
||||||
|
|
||||||
@router.get("/{device_id}/user-search")
|
@router.get("/{device_id}/user-search")
|
||||||
async def search_users_for_device(
|
def search_users_for_device(
|
||||||
device_id: str,
|
device_id: str,
|
||||||
q: str = Query(""),
|
q: str = Query(""),
|
||||||
_user: TokenPayload = Depends(require_permission("devices", "view")),
|
_user: TokenPayload = Depends(require_permission("devices", "view")),
|
||||||
@@ -437,14 +439,14 @@ async def add_user_to_device(
|
|||||||
db: AsyncSession = Depends(get_pg_session),
|
db: AsyncSession = Depends(get_pg_session),
|
||||||
):
|
):
|
||||||
"""Add a user reference to the device's user_list field."""
|
"""Add a user reference to the device's user_list field."""
|
||||||
db = get_firestore()
|
fs = get_firestore()
|
||||||
device_ref = db.collection("devices").document(device_id)
|
device_ref = fs.collection("devices").document(device_id)
|
||||||
device_doc = device_ref.get()
|
device_doc = device_ref.get()
|
||||||
if not device_doc.exists:
|
if not device_doc.exists:
|
||||||
raise HTTPException(status_code=404, detail="Device not found")
|
raise HTTPException(status_code=404, detail="Device not found")
|
||||||
|
|
||||||
# Verify user exists
|
# 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:
|
if not user_doc.exists:
|
||||||
raise HTTPException(status_code=404, detail="User not found")
|
raise HTTPException(status_code=404, detail="User not found")
|
||||||
|
|
||||||
@@ -460,10 +462,17 @@ async def add_user_to_device(
|
|||||||
elif isinstance(entry, str):
|
elif isinstance(entry, str):
|
||||||
existing_ids.add(entry.split("/")[-1])
|
existing_ids.add(entry.split("/")[-1])
|
||||||
|
|
||||||
|
# user_list, 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:
|
if body.user_id not in existing_ids:
|
||||||
user_ref = db.collection("users").document(body.user_id)
|
|
||||||
user_list.append(user_ref)
|
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",
|
await log_action(db, _user.sub, _user.name or _user.email, "UPDATE", "device",
|
||||||
device_id, device_id, meta={"action_detail": "user_added",
|
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),
|
db: AsyncSession = Depends(get_pg_session),
|
||||||
):
|
):
|
||||||
"""Remove a user reference from the device's user_list field."""
|
"""Remove a user reference from the device's user_list field."""
|
||||||
db = get_firestore()
|
fs = get_firestore()
|
||||||
device_ref = db.collection("devices").document(device_id)
|
device_ref = fs.collection("devices").document(device_id)
|
||||||
device_doc = device_ref.get()
|
device_doc = device_ref.get()
|
||||||
if not device_doc.exists:
|
if not device_doc.exists:
|
||||||
raise HTTPException(status_code=404, detail="Device not found")
|
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)
|
# 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)]
|
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",
|
await log_action(db, _user.sub, _user.name or _user.email, "UPDATE", "device",
|
||||||
device_id, device_id, meta={"action_detail": "user_removed",
|
device_id, device_id, meta={"action_detail": "user_removed",
|
||||||
"user_id": user_id})
|
"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
@@ -1,11 +1,12 @@
|
|||||||
import secrets
|
import secrets
|
||||||
import string
|
import string
|
||||||
|
|
||||||
from datetime import datetime
|
from google.cloud.firestore_v1 import DocumentReference
|
||||||
from google.cloud.firestore_v1 import GeoPoint, DocumentReference
|
from google.cloud.firestore_v1.field_path import FieldPath
|
||||||
|
|
||||||
from shared.firebase import get_db
|
from shared.firebase import get_db
|
||||||
from shared.exceptions import NotFoundError
|
from shared.exceptions import NotFoundError
|
||||||
|
from devices import firestore_v1
|
||||||
from devices.models import DeviceCreate, DeviceUpdate, DeviceInDB
|
from devices.models import DeviceCreate, DeviceUpdate, DeviceInDB
|
||||||
|
|
||||||
COLLECTION = "devices"
|
COLLECTION = "devices"
|
||||||
@@ -14,34 +15,6 @@ COLLECTION = "devices"
|
|||||||
SN_CHARS = string.ascii_uppercase + string.digits
|
SN_CHARS = string.ascii_uppercase + string.digits
|
||||||
SN_SEGMENT_LEN = 4
|
SN_SEGMENT_LEN = 4
|
||||||
|
|
||||||
# Clock/silence/backlight fields stored as Firestore Timestamps (written as datetime)
|
|
||||||
_TIMESTAMP_FIELD_NAMES = {
|
|
||||||
"daySilenceFrom", "daySilenceTo",
|
|
||||||
"nightSilenceFrom", "nightSilenceTo",
|
|
||||||
"backlightTurnOnTime", "backlightTurnOffTime",
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
def _restore_timestamps(d: dict) -> dict:
|
|
||||||
"""Recursively convert ISO 8601 strings for known timestamp fields to datetime objects.
|
|
||||||
|
|
||||||
Firestore stores Python datetime objects as native Timestamps, which Flutter
|
|
||||||
reads as DateTime. Plain strings would break the Flutter app.
|
|
||||||
"""
|
|
||||||
result = {}
|
|
||||||
for k, v in d.items():
|
|
||||||
if isinstance(v, dict):
|
|
||||||
result[k] = _restore_timestamps(v)
|
|
||||||
elif isinstance(v, str) and k in _TIMESTAMP_FIELD_NAMES:
|
|
||||||
try:
|
|
||||||
result[k] = datetime.fromisoformat(v.replace("Z", "+00:00"))
|
|
||||||
except ValueError:
|
|
||||||
result[k] = v
|
|
||||||
else:
|
|
||||||
result[k] = v
|
|
||||||
return result
|
|
||||||
|
|
||||||
|
|
||||||
def _generate_serial_number() -> str:
|
def _generate_serial_number() -> str:
|
||||||
"""Generate a unique serial number in the format BS-XXXX-XXXX."""
|
"""Generate a unique serial number in the format BS-XXXX-XXXX."""
|
||||||
seg1 = "".join(secrets.choice(SN_CHARS) for _ in range(SN_SEGMENT_LEN))
|
seg1 = "".join(secrets.choice(SN_CHARS) for _ in range(SN_SEGMENT_LEN))
|
||||||
@@ -66,36 +39,6 @@ def _ensure_unique_serial(db) -> str:
|
|||||||
raise RuntimeError("Could not generate a unique serial number after 100 attempts")
|
raise RuntimeError("Could not generate a unique serial number after 100 attempts")
|
||||||
|
|
||||||
|
|
||||||
def _convert_firestore_value(val):
|
|
||||||
"""Convert Firestore-specific types (Timestamp, GeoPoint, DocumentReference) to strings."""
|
|
||||||
if isinstance(val, datetime):
|
|
||||||
# Firestore DatetimeWithNanoseconds is a datetime subclass
|
|
||||||
return val.strftime("%d %B %Y at %H:%M:%S UTC%z")
|
|
||||||
if isinstance(val, GeoPoint):
|
|
||||||
return {"lat": val.latitude, "lng": val.longitude}
|
|
||||||
if isinstance(val, DocumentReference):
|
|
||||||
# Store the document path (e.g. "users/abc123")
|
|
||||||
return val.path
|
|
||||||
return val
|
|
||||||
|
|
||||||
|
|
||||||
def _sanitize_dict(d: dict) -> dict:
|
|
||||||
"""Recursively convert Firestore-native types in a dict to plain strings."""
|
|
||||||
result = {}
|
|
||||||
for k, v in d.items():
|
|
||||||
if isinstance(v, dict):
|
|
||||||
result[k] = _sanitize_dict(v)
|
|
||||||
elif isinstance(v, list):
|
|
||||||
result[k] = [
|
|
||||||
_sanitize_dict(item) if isinstance(item, dict)
|
|
||||||
else _convert_firestore_value(item)
|
|
||||||
for item in v
|
|
||||||
]
|
|
||||||
else:
|
|
||||||
result[k] = _convert_firestore_value(v)
|
|
||||||
return result
|
|
||||||
|
|
||||||
|
|
||||||
def _auto_upgrade_claimed(doc_ref, data: dict) -> dict:
|
def _auto_upgrade_claimed(doc_ref, data: dict) -> dict:
|
||||||
"""If the device has entries in user_list and isn't already claimed/decommissioned,
|
"""If the device has entries in user_list and isn't already claimed/decommissioned,
|
||||||
upgrade mfg_status to 'claimed' automatically and return the updated data dict."""
|
upgrade mfg_status to 'claimed' automatically and return the updated data dict."""
|
||||||
@@ -117,7 +60,7 @@ def _doc_to_device(doc) -> DeviceInDB:
|
|||||||
"""
|
"""
|
||||||
raw = doc.to_dict()
|
raw = doc.to_dict()
|
||||||
raw = _auto_upgrade_claimed(doc.reference, raw)
|
raw = _auto_upgrade_claimed(doc.reference, raw)
|
||||||
data = _sanitize_dict(raw)
|
data = firestore_v1.to_api(raw)
|
||||||
return DeviceInDB(id=doc.id, **data)
|
return DeviceInDB(id=doc.id, **data)
|
||||||
|
|
||||||
|
|
||||||
@@ -158,9 +101,10 @@ def list_devices(
|
|||||||
if search:
|
if search:
|
||||||
search_lower = search.lower()
|
search_lower = search.lower()
|
||||||
name_match = search_lower in (device.device_name or "").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()
|
location_match = search_lower in (device.device_location or "").lower()
|
||||||
sn_match = search_lower in (device.serial_number 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
|
continue
|
||||||
|
|
||||||
results.append(device)
|
results.append(device)
|
||||||
@@ -185,22 +129,31 @@ def create_device(data: DeviceCreate) -> DeviceInDB:
|
|||||||
serial_number = _ensure_unique_serial(db)
|
serial_number = _ensure_unique_serial(db)
|
||||||
|
|
||||||
doc_data = data.model_dump()
|
doc_data = data.model_dump()
|
||||||
doc_data["device_id"] = serial_number
|
doc_data["serial_number"] = serial_number # D1: canonical id; to_firestore mirrors it to device_id
|
||||||
|
doc_data.pop("device_id", None)
|
||||||
|
doc_data = firestore_v1.to_firestore(doc_data, db)
|
||||||
|
|
||||||
_, doc_ref = db.collection(COLLECTION).add(doc_data)
|
_, doc_ref = db.collection(COLLECTION).add(doc_data)
|
||||||
|
|
||||||
return DeviceInDB(id=doc_ref.id, **doc_data)
|
return _doc_to_device(doc_ref.get())
|
||||||
|
|
||||||
|
|
||||||
def _deep_merge(base: dict, overrides: dict) -> dict:
|
def _leaf_field_paths(value: dict, prefix: tuple = ()) -> dict:
|
||||||
"""Recursively merge overrides into base, preserving unmentioned nested keys."""
|
"""Flatten a nested map into {firestore field path: leaf value}.
|
||||||
result = dict(base)
|
|
||||||
for k, v in overrides.items():
|
Lists and scalars are leaves; a non-empty map is descended into, so writing
|
||||||
if isinstance(v, dict) and isinstance(result.get(k), dict):
|
{"device_attributes": {"hasBells": True}} touches ONLY
|
||||||
result[k] = _deep_merge(result[k], v)
|
device_attributes.hasBells — never the sibling fields of the parent map.
|
||||||
|
An empty map is kept as a leaf (it explicitly sets that map to {}).
|
||||||
|
"""
|
||||||
|
out: dict = {}
|
||||||
|
for k, v in value.items():
|
||||||
|
path = prefix + (k,)
|
||||||
|
if isinstance(v, dict) and v:
|
||||||
|
out.update(_leaf_field_paths(v, path))
|
||||||
else:
|
else:
|
||||||
result[k] = v
|
out[FieldPath(*path).to_api_repr()] = v
|
||||||
return result
|
return out
|
||||||
|
|
||||||
|
|
||||||
def update_device(device_doc_id: str, data: DeviceUpdate) -> DeviceInDB:
|
def update_device(device_doc_id: str, data: DeviceUpdate) -> DeviceInDB:
|
||||||
@@ -211,34 +164,122 @@ def update_device(device_doc_id: str, data: DeviceUpdate) -> DeviceInDB:
|
|||||||
if not doc.exists:
|
if not doc.exists:
|
||||||
raise NotFoundError("Device")
|
raise NotFoundError("Device")
|
||||||
|
|
||||||
update_data = data.model_dump(exclude_none=True)
|
# Top-level None still means "not sent" (unchanged API behaviour). Inside the
|
||||||
|
# nested maps an explicit null is kept: it clears that field, e.g. a silence
|
||||||
|
# time being switched off — the v1 way to say "unset" (never "").
|
||||||
|
sent = data.model_dump(exclude_unset=True)
|
||||||
|
update_data = firestore_v1.to_firestore({k: v for k, v in sent.items() if v is not None}, db)
|
||||||
|
|
||||||
# Convert {lat, lng} dict to a Firestore GeoPoint
|
# Nested structs are written field-by-field (dotted paths), so only the
|
||||||
coords = update_data.get("device_location_coordinates")
|
# exact leaves the caller sent are touched. Rewriting the whole parent map
|
||||||
if isinstance(coords, dict) and "lat" in coords and "lng" in coords:
|
# (the old read-merge-write) clobbered sibling fields whenever two writes
|
||||||
update_data["device_location_coordinates"] = GeoPoint(coords["lat"], coords["lng"])
|
# raced, or the FlutterFlow apps wrote in between our read and our write.
|
||||||
|
|
||||||
# Deep-merge nested structs so unmentioned sub-fields are preserved
|
|
||||||
existing = doc.to_dict()
|
existing = doc.to_dict()
|
||||||
nested_keys = (
|
nested_keys = (
|
||||||
"device_attributes", "device_subscription", "device_stats",
|
"device_attributes", "device_subscription", "device_stats", "device_health_settings",
|
||||||
)
|
)
|
||||||
for key in nested_keys:
|
for key in nested_keys:
|
||||||
if key in update_data and isinstance(existing.get(key), dict):
|
if isinstance(update_data.get(key), dict) and update_data[key]:
|
||||||
update_data[key] = _deep_merge(existing[key], update_data[key])
|
update_data.update(_leaf_field_paths(update_data.pop(key), (key,)))
|
||||||
|
|
||||||
update_data = _restore_timestamps(update_data)
|
if "user_list" not in update_data:
|
||||||
doc_ref.update(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()
|
updated_doc = doc_ref.get()
|
||||||
return _doc_to_device(updated_doc)
|
return _doc_to_device(updated_doc)
|
||||||
|
|
||||||
|
|
||||||
def get_device_users(device_doc_id: str) -> list[dict]:
|
def user_list_entry_id(entry) -> str:
|
||||||
"""Get users assigned to a device from the device_users sub-collection.
|
"""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()
|
db = get_db()
|
||||||
doc_ref = db.collection(COLLECTION).document(device_doc_id)
|
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:
|
if not doc.exists:
|
||||||
raise NotFoundError("Device")
|
raise NotFoundError("Device")
|
||||||
|
|
||||||
# Try sub-collection first
|
roles = {
|
||||||
sub_docs = list(doc_ref.collection("device_users").stream())
|
uid: (snaps[0].to_dict() or {}).get("role", "")
|
||||||
|
for uid, snaps in device_users_by_user(doc_ref).items()
|
||||||
|
}
|
||||||
|
|
||||||
users = []
|
users = []
|
||||||
|
seen = set()
|
||||||
if sub_docs:
|
for entry in (doc.to_dict() or {}).get("user_list") or []:
|
||||||
for sub_doc in sub_docs:
|
uid = user_list_entry_id(entry)
|
||||||
sub_data = sub_doc.to_dict()
|
if not uid or uid in seen:
|
||||||
role = sub_data.get("role", "")
|
continue
|
||||||
user_ref = sub_data.get("user_reference")
|
seen.add(uid)
|
||||||
|
try:
|
||||||
# Resolve user reference
|
user_doc = db.collection("users").document(uid).get()
|
||||||
user_id = ""
|
except Exception as e:
|
||||||
display_name = ""
|
print(f"[devices] Error resolving user_list entry {uid}: {e}")
|
||||||
email = ""
|
continue
|
||||||
photo_url = ""
|
if not user_doc.exists:
|
||||||
|
continue
|
||||||
if isinstance(user_ref, DocumentReference):
|
user_data = user_doc.to_dict() or {}
|
||||||
try:
|
users.append({
|
||||||
user_doc = user_ref.get()
|
"user_id": user_doc.id,
|
||||||
if user_doc.exists:
|
"display_name": user_data.get("display_name", ""),
|
||||||
user_data = user_doc.to_dict()
|
"email": user_data.get("email", ""),
|
||||||
user_id = user_doc.id
|
"role": roles.get(uid, ""),
|
||||||
display_name = user_data.get("display_name", "")
|
"photo_url": user_data.get("photo_url", ""),
|
||||||
email = user_data.get("email", "")
|
})
|
||||||
photo_url = user_data.get("photo_url", "")
|
|
||||||
except Exception as e:
|
|
||||||
print(f"[devices] Error resolving user reference: {e}")
|
|
||||||
continue
|
|
||||||
elif isinstance(user_ref, str):
|
|
||||||
# String path like "users/abc123"
|
|
||||||
try:
|
|
||||||
ref_doc = db.document(user_ref).get()
|
|
||||||
if ref_doc.exists:
|
|
||||||
user_data = ref_doc.to_dict()
|
|
||||||
user_id = ref_doc.id
|
|
||||||
display_name = user_data.get("display_name", "")
|
|
||||||
email = user_data.get("email", "")
|
|
||||||
photo_url = user_data.get("photo_url", "")
|
|
||||||
except Exception as e:
|
|
||||||
print(f"[devices] Error resolving user path: {e}")
|
|
||||||
continue
|
|
||||||
|
|
||||||
users.append({
|
|
||||||
"user_id": user_id,
|
|
||||||
"display_name": display_name,
|
|
||||||
"email": email,
|
|
||||||
"role": role,
|
|
||||||
"photo_url": photo_url,
|
|
||||||
})
|
|
||||||
else:
|
|
||||||
# Fallback to user_list field
|
|
||||||
device_data = doc.to_dict()
|
|
||||||
user_list = device_data.get("user_list", [])
|
|
||||||
for entry in user_list:
|
|
||||||
try:
|
|
||||||
if isinstance(entry, DocumentReference):
|
|
||||||
user_doc = entry.get()
|
|
||||||
elif isinstance(entry, str) and entry.strip():
|
|
||||||
# Could be a path like "users/abc" or a raw doc ID
|
|
||||||
if "/" in entry:
|
|
||||||
user_doc = db.document(entry).get()
|
|
||||||
else:
|
|
||||||
user_doc = db.collection("users").document(entry).get()
|
|
||||||
else:
|
|
||||||
continue
|
|
||||||
|
|
||||||
if user_doc.exists:
|
|
||||||
user_data = user_doc.to_dict()
|
|
||||||
users.append({
|
|
||||||
"user_id": user_doc.id,
|
|
||||||
"display_name": user_data.get("display_name", ""),
|
|
||||||
"email": user_data.get("email", ""),
|
|
||||||
"role": "",
|
|
||||||
"photo_url": user_data.get("photo_url", ""),
|
|
||||||
})
|
|
||||||
except Exception as e:
|
|
||||||
print(f"[devices] Error resolving user_list entry: {e}")
|
|
||||||
|
|
||||||
return users
|
return users
|
||||||
|
|
||||||
|
|||||||
@@ -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():
|
if device_id and isinstance(device_id, str) and device_id.strip():
|
||||||
device_doc = db.collection("devices").document(device_id.strip()).get()
|
device_doc = db.collection("devices").document(device_id.strip()).get()
|
||||||
if device_doc.exists:
|
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():
|
if user_id and isinstance(user_id, str) and user_id.strip():
|
||||||
user_doc = db.collection("users").document(user_id.strip()).get()
|
user_doc = db.collection("users").document(user_id.strip()).get()
|
||||||
|
|||||||
@@ -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
|
||||||
@@ -8,7 +8,7 @@ from sqlalchemy.ext.asyncio import AsyncSession
|
|||||||
from auth.models import TokenPayload
|
from auth.models import TokenPayload
|
||||||
from auth.dependencies import require_permission
|
from auth.dependencies import require_permission
|
||||||
from firmware.models import FirmwareVersion, FirmwareListResponse, FirmwareMetadataResponse, UpdateType
|
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 database.postgres import get_pg_session
|
||||||
from shared.audit import log_action
|
from shared.audit import log_action
|
||||||
|
|
||||||
@@ -29,10 +29,15 @@ async def upload_firmware(
|
|||||||
release_note: Optional[str] = Form(None),
|
release_note: Optional[str] = Form(None),
|
||||||
bespoke_uid: Optional[str] = Form(None),
|
bespoke_uid: Optional[str] = Form(None),
|
||||||
file: UploadFile = File(...),
|
file: UploadFile = File(...),
|
||||||
|
elf_file: Optional[UploadFile] = File(None),
|
||||||
_user: TokenPayload = Depends(require_permission("manufacturing", "add")),
|
_user: TokenPayload = Depends(require_permission("manufacturing", "add")),
|
||||||
db: AsyncSession = Depends(get_pg_session),
|
db: AsyncSession = Depends(get_pg_session),
|
||||||
):
|
):
|
||||||
file_bytes = await file.read()
|
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(
|
fw = service.upload_firmware(
|
||||||
hw_type=hw_type,
|
hw_type=hw_type,
|
||||||
channel=channel,
|
channel=channel,
|
||||||
@@ -44,11 +49,48 @@ async def upload_firmware(
|
|||||||
release_note=release_note,
|
release_note=release_note,
|
||||||
bespoke_uid=bespoke_uid,
|
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",
|
await log_action(db, _user.sub, _user.name or _user.email, "CREATE", "firmware",
|
||||||
fw.id, f"{hw_type} v{version} ({channel})")
|
fw.id, f"{hw_type} v{version} ({channel})")
|
||||||
return fw
|
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)
|
@router.get("", response_model=FirmwareListResponse)
|
||||||
def list_firmware(
|
def list_firmware(
|
||||||
hw_type: Optional[str] = Query(None),
|
hw_type: Optional[str] = Query(None),
|
||||||
@@ -114,10 +156,14 @@ async def edit_firmware(
|
|||||||
release_note: Optional[str] = Form(None),
|
release_note: Optional[str] = Form(None),
|
||||||
bespoke_uid: Optional[str] = Form(None),
|
bespoke_uid: Optional[str] = Form(None),
|
||||||
file: Optional[UploadFile] = File(None),
|
file: Optional[UploadFile] = File(None),
|
||||||
|
elf_file: Optional[UploadFile] = File(None),
|
||||||
_user: TokenPayload = Depends(require_permission("manufacturing", "add")),
|
_user: TokenPayload = Depends(require_permission("manufacturing", "add")),
|
||||||
db: AsyncSession = Depends(get_pg_session),
|
db: AsyncSession = Depends(get_pg_session),
|
||||||
):
|
):
|
||||||
file_bytes = await file.read() if file and file.filename else None
|
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(
|
fw = service.edit_firmware(
|
||||||
doc_id=firmware_id,
|
doc_id=firmware_id,
|
||||||
channel=channel,
|
channel=channel,
|
||||||
@@ -129,6 +175,10 @@ async def edit_firmware(
|
|||||||
bespoke_uid=bespoke_uid,
|
bespoke_uid=bespoke_uid,
|
||||||
file_bytes=file_bytes,
|
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",
|
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)
|
firmware_id, f"{fw.hw_type} v{fw.version} ({fw.channel})" if fw else firmware_id)
|
||||||
return fw
|
return fw
|
||||||
|
|||||||
@@ -50,7 +50,8 @@ def _resolve_device_name(db, device_id: str) -> str:
|
|||||||
try:
|
try:
|
||||||
doc = db.collection("devices").document(device_id.strip()).get()
|
doc = db.collection("devices").document(device_id.strip()).get()
|
||||||
if doc.exists:
|
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:
|
except Exception as e:
|
||||||
print(f"[helpdesk] Error resolving device name: {e}")
|
print(f"[helpdesk] Error resolving device name: {e}")
|
||||||
return ""
|
return ""
|
||||||
|
|||||||
@@ -29,6 +29,7 @@ from notes.router import router as notes_router
|
|||||||
from tickets.router import router as tickets_router
|
from tickets.router import router as tickets_router
|
||||||
from audit.router import router as audit_router
|
from audit.router import router as audit_router
|
||||||
from search.router import router as search_router
|
from search.router import router as search_router
|
||||||
|
from timezones.router import router as timezones_router
|
||||||
from crm.nextcloud import close_client as close_nextcloud_client, keepalive_ping as nextcloud_keepalive
|
from crm.nextcloud import close_client as close_nextcloud_client, keepalive_ping as nextcloud_keepalive
|
||||||
from crm.mail_accounts import get_mail_accounts
|
from crm.mail_accounts import get_mail_accounts
|
||||||
from mqtt.client import mqtt_manager
|
from mqtt.client import mqtt_manager
|
||||||
@@ -78,6 +79,7 @@ app.include_router(notes_router)
|
|||||||
app.include_router(tickets_router)
|
app.include_router(tickets_router)
|
||||||
app.include_router(audit_router)
|
app.include_router(audit_router)
|
||||||
app.include_router(search_router)
|
app.include_router(search_router)
|
||||||
|
app.include_router(timezones_router)
|
||||||
|
|
||||||
|
|
||||||
async def nextcloud_keepalive_loop():
|
async def nextcloud_keepalive_loop():
|
||||||
@@ -114,8 +116,13 @@ async def startup():
|
|||||||
await sqlite_init_db()
|
await sqlite_init_db()
|
||||||
await melody_service.migrate_from_firestore()
|
await melody_service.migrate_from_firestore()
|
||||||
mqtt_manager.start(asyncio.get_event_loop())
|
mqtt_manager.start(asyncio.get_event_loop())
|
||||||
|
# Seed the in-memory latest-status cache in the background so the first
|
||||||
|
# device list / detail load after a restart doesn't pay for the slow
|
||||||
|
# fleet-wide DISTINCT ON scans (see database/latest_cache.py).
|
||||||
|
asyncio.create_task(db.warm_latest_cache())
|
||||||
asyncio.create_task(db.partition_manager_loop())
|
asyncio.create_task(db.partition_manager_loop())
|
||||||
asyncio.create_task(db.purge_loop())
|
asyncio.create_task(db.purge_loop())
|
||||||
|
asyncio.create_task(mqtt_manager.ping_loop())
|
||||||
asyncio.create_task(nextcloud_keepalive_loop())
|
asyncio.create_task(nextcloud_keepalive_loop())
|
||||||
asyncio.create_task(crm_poll_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")]
|
sync_accounts = [a for a in get_mail_accounts() if a.get("sync_inbound") and a.get("imap_host")]
|
||||||
|
|||||||
@@ -80,20 +80,33 @@ class BatchResponse(BaseModel):
|
|||||||
created_at: str
|
created_at: str
|
||||||
|
|
||||||
|
|
||||||
|
class DeviceUserSummary(BaseModel):
|
||||||
|
user_id: str
|
||||||
|
display_name: str = ""
|
||||||
|
email: str = ""
|
||||||
|
|
||||||
|
|
||||||
class DeviceInventoryItem(BaseModel):
|
class DeviceInventoryItem(BaseModel):
|
||||||
id: str
|
id: str
|
||||||
serial_number: str
|
serial_number: str
|
||||||
hw_type: str
|
hw_family: str # board family code (BoardType value or bespoke UID) = firmware NVS "hw_family"
|
||||||
hw_version: str
|
hw_revision: str # hardware revision, e.g. "1.0" = firmware NVS "hw_revision"
|
||||||
mfg_status: str
|
mfg_status: str
|
||||||
mfg_batch_id: Optional[str] = None
|
mfg_batch_id: Optional[str] = None
|
||||||
created_at: Optional[str] = None
|
created_at: Optional[str] = None
|
||||||
owner: Optional[str] = None
|
owner: Optional[str] = None
|
||||||
assigned_to: Optional[str] = None
|
assigned_to: Optional[str] = None
|
||||||
device_name: 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
|
lifecycle_history: Optional[List["LifecycleEntry"]] = None
|
||||||
customer_id: Optional[str] = None
|
customer_id: Optional[str] = None
|
||||||
|
customer_name: Optional[str] = None
|
||||||
user_list: Optional[List[str]] = None
|
user_list: Optional[List[str]] = None
|
||||||
|
users: Optional[List[DeviceUserSummary]] = None
|
||||||
|
|
||||||
|
|
||||||
class DeviceInventoryListResponse(BaseModel):
|
class DeviceInventoryListResponse(BaseModel):
|
||||||
@@ -121,7 +134,7 @@ class CustomerSearchResult(BaseModel):
|
|||||||
|
|
||||||
class RecentActivityItem(BaseModel):
|
class RecentActivityItem(BaseModel):
|
||||||
serial_number: str
|
serial_number: str
|
||||||
hw_type: str
|
hw_family: str
|
||||||
mfg_status: str
|
mfg_status: str
|
||||||
owner: Optional[str] = None
|
owner: Optional[str] = None
|
||||||
updated_at: Optional[str] = None
|
updated_at: Optional[str] = None
|
||||||
|
|||||||
@@ -71,7 +71,9 @@ async def create_batch(
|
|||||||
@router.get("/devices", response_model=DeviceInventoryListResponse)
|
@router.get("/devices", response_model=DeviceInventoryListResponse)
|
||||||
def list_devices(
|
def list_devices(
|
||||||
status: Optional[str] = Query(None),
|
status: Optional[str] = Query(None),
|
||||||
hw_type: Optional[str] = Query(None),
|
hw_family: Optional[str] = Query(None),
|
||||||
|
hw_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),
|
search: Optional[str] = Query(None),
|
||||||
limit: int = Query(100, ge=1, le=500),
|
limit: int = Query(100, ge=1, le=500),
|
||||||
offset: int = Query(0, ge=0),
|
offset: int = Query(0, ge=0),
|
||||||
@@ -79,7 +81,9 @@ def list_devices(
|
|||||||
):
|
):
|
||||||
items = service.list_devices(
|
items = service.list_devices(
|
||||||
status=status,
|
status=status,
|
||||||
hw_type=hw_type,
|
hw_family=hw_family,
|
||||||
|
hw_families=hw_families,
|
||||||
|
has_users=has_users,
|
||||||
search=search,
|
search=search,
|
||||||
limit=limit,
|
limit=limit,
|
||||||
offset=offset,
|
offset=offset,
|
||||||
@@ -601,7 +605,7 @@ def download_bootloader(
|
|||||||
):
|
):
|
||||||
"""Return the bootloader.bin for this device's hw_type (flashed at 0x1000)."""
|
"""Return the bootloader.bin for this device's hw_type (flashed at 0x1000)."""
|
||||||
item = service.get_device_by_sn(sn)
|
item = service.get_device_by_sn(sn)
|
||||||
hw_type = hw_type_override or item.hw_type
|
hw_type = hw_type_override or item.hw_family
|
||||||
try:
|
try:
|
||||||
data = service.get_flash_asset(hw_type, "bootloader.bin")
|
data = service.get_flash_asset(hw_type, "bootloader.bin")
|
||||||
except NotFoundError as e:
|
except NotFoundError as e:
|
||||||
@@ -621,7 +625,7 @@ def download_partitions(
|
|||||||
):
|
):
|
||||||
"""Return the partitions.bin for this device's hw_type (flashed at 0x8000)."""
|
"""Return the partitions.bin for this device's hw_type (flashed at 0x8000)."""
|
||||||
item = service.get_device_by_sn(sn)
|
item = service.get_device_by_sn(sn)
|
||||||
hw_type = hw_type_override or item.hw_type
|
hw_type = hw_type_override or item.hw_family
|
||||||
try:
|
try:
|
||||||
data = service.get_flash_asset(hw_type, "partitions.bin")
|
data = service.get_flash_asset(hw_type, "partitions.bin")
|
||||||
except NotFoundError as e:
|
except NotFoundError as e:
|
||||||
|
|||||||
@@ -11,9 +11,11 @@ from shared.firebase import get_db
|
|||||||
from shared.exceptions import NotFoundError
|
from shared.exceptions import NotFoundError
|
||||||
from utils.serial_number import generate_serial
|
from utils.serial_number import generate_serial
|
||||||
from utils.nvs_generator import generate as generate_nvs_binary
|
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"
|
COLLECTION = "devices"
|
||||||
|
CRM_COLLECTION = "crm_customers"
|
||||||
|
USERS_COLLECTION = "users"
|
||||||
_BATCH_ID_CHARS = string.ascii_uppercase + string.digits
|
_BATCH_ID_CHARS = string.ascii_uppercase + string.digits
|
||||||
|
|
||||||
|
|
||||||
@@ -45,7 +47,7 @@ def _resolve_user_list(raw_list: list) -> list[str]:
|
|||||||
return result
|
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 {}
|
data = doc.to_dict() or {}
|
||||||
created_raw = data.get("created_at")
|
created_raw = data.get("created_at")
|
||||||
if isinstance(created_raw, datetime):
|
if isinstance(created_raw, datetime):
|
||||||
@@ -53,23 +55,68 @@ def _doc_to_inventory_item(doc) -> DeviceInventoryItem:
|
|||||||
else:
|
else:
|
||||||
created_str = str(created_raw) if created_raw else None
|
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(
|
return DeviceInventoryItem(
|
||||||
id=doc.id,
|
id=doc.id,
|
||||||
serial_number=data.get("serial_number", ""),
|
serial_number=data.get("serial_number", ""),
|
||||||
hw_type=data.get("hw_type", ""),
|
# hw_type / hw_version: names used before 2026-11-08 (kept as read fallback)
|
||||||
hw_version=data.get("hw_version", ""),
|
hw_family=data.get("hw_family") or data.get("hw_type", ""),
|
||||||
|
hw_revision=data.get("hw_revision") or data.get("hw_version", ""),
|
||||||
mfg_status=data.get("mfg_status", "manufactured"),
|
mfg_status=data.get("mfg_status", "manufactured"),
|
||||||
mfg_batch_id=data.get("mfg_batch_id"),
|
mfg_batch_id=data.get("mfg_batch_id"),
|
||||||
created_at=created_str,
|
created_at=created_str,
|
||||||
owner=data.get("owner"),
|
owner=data.get("owner"),
|
||||||
assigned_to=data.get("assigned_to"),
|
assigned_to=data.get("assigned_to"),
|
||||||
device_name=data.get("device_name") or None,
|
device_name=data.get("device_name") or None,
|
||||||
|
console_name=data.get("console_name") or None,
|
||||||
lifecycle_history=data.get("lifecycle_history") or [],
|
lifecycle_history=data.get("lifecycle_history") or [],
|
||||||
customer_id=data.get("customer_id"),
|
customer_id=customer_id,
|
||||||
user_list=_resolve_user_list(data.get("user_list") or []),
|
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:
|
def create_batch(data: BatchCreate) -> BatchResponse:
|
||||||
db = get_db()
|
db = get_db()
|
||||||
existing_sns = _get_existing_sns(db)
|
existing_sns = _get_existing_sns(db)
|
||||||
@@ -88,8 +135,11 @@ def create_batch(data: BatchCreate) -> BatchResponse:
|
|||||||
|
|
||||||
db.collection(COLLECTION).add({
|
db.collection(COLLECTION).add({
|
||||||
"serial_number": sn,
|
"serial_number": sn,
|
||||||
"hw_type": data.board_type.value,
|
"device_id": sn, # schema v1 / D1: both apps connect over MQTT with device_id
|
||||||
"hw_version": data.board_version,
|
|
||||||
|
# Same names as the firmware NVS keys.
|
||||||
|
"hw_family": data.board_type.value,
|
||||||
|
"hw_revision": data.board_version,
|
||||||
"mfg_status": "manufactured",
|
"mfg_status": "manufactured",
|
||||||
"mfg_batch_id": batch_id,
|
"mfg_batch_id": batch_id,
|
||||||
"created_at": now,
|
"created_at": now,
|
||||||
@@ -122,7 +172,9 @@ def create_batch(data: BatchCreate) -> BatchResponse:
|
|||||||
|
|
||||||
def list_devices(
|
def list_devices(
|
||||||
status: str | None = None,
|
status: str | None = None,
|
||||||
hw_type: str | None = None,
|
hw_family: str | None = None,
|
||||||
|
hw_families: list[str] | None = None,
|
||||||
|
has_users: bool | None = None,
|
||||||
search: str | None = None,
|
search: str | None = None,
|
||||||
limit: int = 100,
|
limit: int = 100,
|
||||||
offset: int = 0,
|
offset: int = 0,
|
||||||
@@ -132,11 +184,28 @@ def list_devices(
|
|||||||
|
|
||||||
if status:
|
if status:
|
||||||
query = query.where("mfg_status", "==", status)
|
query = query.where("mfg_status", "==", status)
|
||||||
if hw_type:
|
if hw_family:
|
||||||
query = query.where("hw_type", "==", hw_type)
|
query = query.where("hw_family", "==", hw_family)
|
||||||
|
|
||||||
docs = list(query.stream())
|
docs = list(query.stream())
|
||||||
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:
|
if search:
|
||||||
search_lower = search.lower()
|
search_lower = search.lower()
|
||||||
@@ -145,6 +214,10 @@ def list_devices(
|
|||||||
if search_lower in (item.serial_number or "").lower()
|
if search_lower in (item.serial_number or "").lower()
|
||||||
or search_lower in (item.owner 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.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]
|
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())
|
docs = list(db.collection(COLLECTION).where("serial_number", "==", sn).limit(1).stream())
|
||||||
if not docs:
|
if not docs:
|
||||||
raise NotFoundError("Device")
|
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:
|
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)
|
item = get_device_by_sn(sn)
|
||||||
return generate_nvs_binary(
|
return generate_nvs_binary(
|
||||||
serial_number=item.serial_number,
|
serial_number=item.serial_number,
|
||||||
hw_family=hw_type_override if hw_type_override else item.hw_type,
|
hw_family=hw_type_override if hw_type_override else item.hw_family,
|
||||||
hw_revision=hw_revision_override if hw_revision_override else item.hw_version,
|
hw_revision=hw_revision_override if hw_revision_override else item.hw_revision,
|
||||||
legacy=legacy,
|
legacy=legacy,
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -260,7 +335,7 @@ def assign_device(sn: str, data: DeviceAssign) -> DeviceInventoryItem:
|
|||||||
for item in owned_items
|
for item in owned_items
|
||||||
)
|
)
|
||||||
if not already_assigned:
|
if not already_assigned:
|
||||||
device_name = doc_data.get("device_name") or BOARD_TYPE_LABELS.get(doc_data.get("hw_type", ""), sn)
|
device_name = doc_data.get("device_name") or BOARD_TYPE_LABELS.get(doc_data.get("hw_family") or doc_data.get("hw_type", ""), sn)
|
||||||
owned_items.append({
|
owned_items.append({
|
||||||
"type": "console_device",
|
"type": "console_device",
|
||||||
"console_device": {
|
"console_device": {
|
||||||
@@ -330,7 +405,7 @@ def get_stats() -> ManufacturingStats:
|
|||||||
|
|
||||||
activity_candidates.append(RecentActivityItem(
|
activity_candidates.append(RecentActivityItem(
|
||||||
serial_number=data.get("serial_number", ""),
|
serial_number=data.get("serial_number", ""),
|
||||||
hw_type=data.get("hw_type", ""),
|
hw_family=data.get("hw_family") or data.get("hw_type", ""),
|
||||||
mfg_status=status,
|
mfg_status=status,
|
||||||
owner=data.get("owner"),
|
owner=data.get("owner"),
|
||||||
updated_at=ts_str,
|
updated_at=ts_str,
|
||||||
@@ -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."""
|
"""Return the FastAPI download URL for the latest stable firmware for this device's hw_type."""
|
||||||
from firmware.service import get_latest
|
from firmware.service import get_latest
|
||||||
item = get_device_by_sn(sn)
|
item = get_device_by_sn(sn)
|
||||||
hw_type = item.hw_type.lower()
|
latest = get_latest(item.hw_family.lower(), "stable")
|
||||||
latest = get_latest(hw_type, "stable")
|
|
||||||
# download_url is a relative path like /api/firmware/vs/stable/1.4.2/firmware.bin
|
# download_url is a relative path like /api/firmware/vs/stable/1.4.2/firmware.bin
|
||||||
return latest.download_url
|
return latest.download_url
|
||||||
|
|||||||
@@ -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
@@ -9,8 +9,10 @@ Password strategy: HMAC-SHA256(MQTT_SECRET, username)[:32]
|
|||||||
- Deterministic: no storage needed, re-derive on every auth check
|
- Deterministic: no storage needed, re-derive on every auth check
|
||||||
- Rotating MQTT_SECRET invalidates all passwords at once if needed
|
- Rotating MQTT_SECRET invalidates all passwords at once if needed
|
||||||
|
|
||||||
Transition support: during rollout, the legacy password "vesper" is also
|
Transition support: while MQTT_ALLOW_LEGACY_PASSWORD is on (default), the
|
||||||
accepted so that devices still on old firmware stay connected.
|
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:
|
User types handled:
|
||||||
- Device users (e.g. "PV25L22BP01R01", "PV-26A18-BC02R-X7KQA"):
|
- Device users (e.g. "PV25L22BP01R01", "PV-26A18-BC02R-X7KQA"):
|
||||||
@@ -18,21 +20,49 @@ User types handled:
|
|||||||
- Kiosk users (e.g. "PV25L22BP01R01-kiosk"):
|
- Kiosk users (e.g. "PV25L22BP01R01-kiosk"):
|
||||||
Same HMAC auth derived from the full kiosk username.
|
Same HMAC auth derived from the full kiosk username.
|
||||||
ACL: allowed to access topics of their base device (suffix stripped).
|
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:
|
- admin, bonamin, NodeRED, and other non-device users:
|
||||||
These connect via the passwd file backend (go-auth file backend).
|
These connect via the passwd file backend (go-auth file backend).
|
||||||
They never reach this HTTP backend — go-auth resolves them first.
|
They never reach this HTTP backend — go-auth resolves them first.
|
||||||
The ACL endpoint below handles them defensively anyway (superuser list).
|
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 hmac
|
||||||
import hashlib
|
import hashlib
|
||||||
|
import logging
|
||||||
|
import re
|
||||||
|
import threading
|
||||||
|
import time
|
||||||
|
|
||||||
from fastapi import APIRouter, Form, Response
|
from fastapi import APIRouter, Form, Response
|
||||||
|
from firebase_admin import auth as firebase_auth
|
||||||
|
|
||||||
from config import settings
|
from config import settings
|
||||||
|
from mqtt import app_users
|
||||||
|
|
||||||
|
logger = logging.getLogger("mqtt.auth")
|
||||||
|
|
||||||
router = APIRouter(prefix="/mqtt/auth", tags=["mqtt-auth"])
|
router = APIRouter(prefix="/mqtt/auth", tags=["mqtt-auth"])
|
||||||
|
|
||||||
LEGACY_PASSWORD = "vesper"
|
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).
|
# Users authenticated via passwd file (go-auth file backend).
|
||||||
# If they somehow reach the HTTP ACL endpoint, grant full access.
|
# If they somehow reach the HTTP ACL endpoint, grant full access.
|
||||||
SUPERUSERS = {"admin", "bonamin", "NodeRED"}
|
SUPERUSERS = {"admin", "bonamin", "NodeRED"}
|
||||||
@@ -47,18 +77,44 @@ def _derive_password(username: str) -> str:
|
|||||||
).hexdigest()[:32]
|
).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:
|
def _is_valid_password(username: str, password: str) -> bool:
|
||||||
"""
|
"""
|
||||||
Accept the password if it matches either:
|
Accept the password if it matches either:
|
||||||
- The HMAC-derived password (new firmware)
|
- The HMAC-derived password (new firmware)
|
||||||
- The legacy hardcoded "vesper" password (old firmware, transition period)
|
- The legacy hardcoded "vesper" password (old firmware, transition period),
|
||||||
|
only when MQTT_ALLOW_LEGACY_PASSWORD is on and the username is
|
||||||
Remove the legacy check in Stage 7 once all devices are on new firmware.
|
device-shaped (never app_ users or unknown shapes).
|
||||||
"""
|
"""
|
||||||
expected = _derive_password(username)
|
expected = _derive_password(username)
|
||||||
hmac_ok = hmac.compare_digest(expected, password)
|
if hmac.compare_digest(expected, password):
|
||||||
legacy_ok = hmac.compare_digest(LEGACY_PASSWORD, password)
|
return True
|
||||||
return hmac_ok or legacy_ok
|
|
||||||
|
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:
|
def _base_sn(username: str) -> str:
|
||||||
@@ -72,8 +128,52 @@ def _base_sn(username: str) -> str:
|
|||||||
return username
|
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")
|
@router.post("/user")
|
||||||
async def mqtt_auth_user(
|
def mqtt_auth_user(
|
||||||
username: str = Form(...),
|
username: str = Form(...),
|
||||||
password: str = Form(...),
|
password: str = Form(...),
|
||||||
clientid: str = Form(default=""),
|
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")
|
Username = device SN (new format: "PV-26A18-BC02R-X7KQA", old format: "PV25L22BP01R01")
|
||||||
or kiosk variant: "PV25L22BP01R01-kiosk"
|
or kiosk variant: "PV25L22BP01R01-kiosk"
|
||||||
|
or app user: "app_<firebase_uid>"
|
||||||
Password = HMAC-derived (new firmware) or "vesper" (legacy firmware)
|
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
|
Note: admin, bonamin and NodeRED authenticate via the go-auth passwd file backend
|
||||||
and never reach this endpoint.
|
and never reach this endpoint.
|
||||||
"""
|
"""
|
||||||
|
if username.startswith(APP_USER_PREFIX):
|
||||||
|
return _auth_app_user(username, password)
|
||||||
|
|
||||||
if _is_valid_password(username, password):
|
if _is_valid_password(username, password):
|
||||||
return Response(status_code=200)
|
return Response(status_code=200)
|
||||||
|
|
||||||
return Response(status_code=403)
|
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")
|
@router.post("/acl")
|
||||||
async def mqtt_auth_acl(
|
def mqtt_auth_acl(
|
||||||
username: str = Form(...),
|
username: str = Form(...),
|
||||||
topic: str = Form(...),
|
topic: str = Form(...),
|
||||||
clientid: str = Form(default=""),
|
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.
|
Returns 200 to allow, 403 to deny.
|
||||||
|
|
||||||
Topic pattern: vesper/{sn}/...
|
Topic pattern: vesper/{sn}/...
|
||||||
- Device users: may only access their own SN segment
|
- Device users: may only access their own SN segment
|
||||||
- Kiosk users: stripped of -kiosk suffix, then same rule applies
|
- 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 (bonamin, NodeRED): full access
|
||||||
"""
|
"""
|
||||||
# Superusers get full access (shouldn't reach here but handled defensively)
|
# Superusers get full access (shouldn't reach here but handled defensively)
|
||||||
if username in SUPERUSERS:
|
if username in SUPERUSERS:
|
||||||
return Response(status_code=200)
|
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)
|
# Derive the base SN (handles -kiosk suffix)
|
||||||
base = _base_sn(username)
|
base = _base_sn(username)
|
||||||
|
|
||||||
|
|||||||
+68
-9
@@ -1,12 +1,19 @@
|
|||||||
import json
|
import json
|
||||||
import logging
|
import logging
|
||||||
import asyncio
|
import asyncio
|
||||||
|
import time
|
||||||
from typing import Set
|
from typing import Set
|
||||||
import paho.mqtt.client as paho_mqtt
|
import paho.mqtt.client as paho_mqtt
|
||||||
from config import settings
|
from config import settings
|
||||||
|
|
||||||
logger = logging.getLogger("mqtt.client")
|
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:
|
class MqttManager:
|
||||||
"""Singleton MQTT client manager."""
|
"""Singleton MQTT client manager."""
|
||||||
@@ -61,12 +68,17 @@ class MqttManager:
|
|||||||
if reason_code == 0:
|
if reason_code == 0:
|
||||||
self._connected = True
|
self._connected = True
|
||||||
logger.info("MQTT connected, subscribing to topics")
|
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([
|
client.subscribe([
|
||||||
("vesper/+/data", 1),
|
("vesper/+/control/ack", 1),
|
||||||
|
("vesper/+/control/reports", 1),
|
||||||
("vesper/+/status/heartbeat", 1),
|
("vesper/+/status/heartbeat", 1),
|
||||||
("vesper/+/status/alerts", 1),
|
("vesper/+/status/playback", 1),
|
||||||
("vesper/+/status/info", 0),
|
("vesper/+/system/alerts", 1),
|
||||||
("vesper/+/logs", 1),
|
("vesper/+/system/info", 1),
|
||||||
|
("vesper/+/system/logs", 0),
|
||||||
|
("vesper/+/system/metrics", 0),
|
||||||
])
|
])
|
||||||
else:
|
else:
|
||||||
logger.error(f"MQTT connection failed: {reason_code}")
|
logger.error(f"MQTT connection failed: {reason_code}")
|
||||||
@@ -87,10 +99,17 @@ class MqttManager:
|
|||||||
|
|
||||||
serial = parts[1]
|
serial = parts[1]
|
||||||
topic_type = "/".join(parts[2:])
|
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():
|
if self._loop and self._loop.is_running():
|
||||||
asyncio.run_coroutine_threadsafe(
|
asyncio.run_coroutine_threadsafe(
|
||||||
self._process_message(serial, topic_type, payload, topic),
|
self._process_message(serial, topic_type, payload, topic, retained),
|
||||||
self._loop,
|
self._loop,
|
||||||
)
|
)
|
||||||
except json.JSONDecodeError:
|
except json.JSONDecodeError:
|
||||||
@@ -99,15 +118,16 @@ class MqttManager:
|
|||||||
logger.error(f"Error processing MQTT message: {e}")
|
logger.error(f"Error processing MQTT message: {e}")
|
||||||
|
|
||||||
async def _process_message(self, serial: str, topic_type: str,
|
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
|
from mqtt.logger import handle_message
|
||||||
await handle_message(serial, topic_type, payload)
|
await handle_message(serial, topic_type, payload, retained=retained)
|
||||||
|
|
||||||
ws_data = {
|
ws_data = {
|
||||||
"type": topic_type,
|
"type": topic_type,
|
||||||
"device_serial": serial,
|
"device_serial": serial,
|
||||||
"payload": payload,
|
"payload": payload,
|
||||||
"topic": raw_topic,
|
"topic": raw_topic,
|
||||||
|
"retained": retained,
|
||||||
}
|
}
|
||||||
await self._broadcast_ws(ws_data)
|
await self._broadcast_ws(ws_data)
|
||||||
|
|
||||||
@@ -132,10 +152,49 @@ class MqttManager:
|
|||||||
if not self._client or not self._connected:
|
if not self._client or not self._connected:
|
||||||
return False
|
return False
|
||||||
|
|
||||||
topic = f"vesper/{device_serial}/control"
|
topic = f"vesper/{device_serial}/control/command"
|
||||||
payload = json.dumps({"cmd": cmd, "contents": contents})
|
payload = json.dumps({"v": 2, "cmd": cmd, "contents": contents})
|
||||||
result = self._client.publish(topic, payload, qos=1)
|
result = self._client.publish(topic, payload, qos=1)
|
||||||
return result.rc == paho_mqtt.MQTT_ERR_SUCCESS
|
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()
|
mqtt_manager = MqttManager()
|
||||||
|
|||||||
@@ -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
@@ -1,5 +1,7 @@
|
|||||||
import logging
|
import logging
|
||||||
|
import time
|
||||||
import database as db
|
import database as db
|
||||||
|
from mqtt import presence
|
||||||
|
|
||||||
logger = logging.getLogger("mqtt.logger")
|
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:
|
try:
|
||||||
|
# v2 topic set — see project-vesper's vesper_mqtt_topic_spec_v2.md.
|
||||||
if topic_type == "status/heartbeat":
|
if topic_type == "status/heartbeat":
|
||||||
await _handle_heartbeat(serial, payload)
|
await _handle_heartbeat(serial, payload, retained)
|
||||||
elif topic_type == "status/alerts":
|
elif topic_type == "system/alerts":
|
||||||
await _handle_alerts(serial, payload)
|
await _handle_alerts(serial, payload, retained)
|
||||||
elif topic_type == "status/info":
|
elif topic_type == "system/info":
|
||||||
await _handle_info(serial, payload)
|
await _handle_info(serial, payload, retained)
|
||||||
elif topic_type == "logs":
|
elif topic_type == "system/logs":
|
||||||
await _handle_log(serial, payload)
|
await _handle_log(serial, payload)
|
||||||
elif topic_type == "data":
|
elif topic_type == "system/metrics":
|
||||||
await _handle_data_response(serial, payload)
|
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:
|
else:
|
||||||
logger.debug(f"Unhandled topic type: {topic_type} for {serial}")
|
logger.debug(f"Unhandled topic type: {topic_type} for {serial}")
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(f"Error handling {topic_type} for {serial}: {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.
|
# Store silently — do not log as a visible event.
|
||||||
# The console surfaces an alert only when the device goes silent (no heartbeat for 90s).
|
# 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(
|
await db.insert_heartbeat(
|
||||||
device_serial=serial,
|
device_serial=serial,
|
||||||
device_id=inner.get("device_id", ""),
|
device_id=payload.get("device_id", ""),
|
||||||
firmware_version=inner.get("firmware_version", ""),
|
firmware_version=payload.get("fw_version", ""),
|
||||||
ip_address=inner.get("ip_address", ""),
|
ip_address=payload.get("ip_address", ""),
|
||||||
gateway=inner.get("gateway", ""),
|
gateway=payload.get("gateway", ""),
|
||||||
uptime_ms=inner.get("uptime_ms", 0),
|
uptime_ms=payload.get("uptime_ms", 0),
|
||||||
uptime_display=inner.get("timestamp", ""),
|
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,
|
level=level,
|
||||||
message=message,
|
message=message,
|
||||||
device_timestamp=device_timestamp,
|
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", "")
|
subsystem = payload.get("subsystem", "")
|
||||||
state = payload.get("state", "")
|
state = payload.get("state", "")
|
||||||
if not subsystem or not state:
|
if not subsystem or not state:
|
||||||
@@ -71,24 +108,161 @@ async def _handle_alerts(serial: str, payload: dict):
|
|||||||
if state == "CLEARED":
|
if state == "CLEARED":
|
||||||
await db.delete_alert(serial, subsystem)
|
await db.delete_alert(serial, subsystem)
|
||||||
else:
|
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", "")
|
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", {})
|
data = payload.get("payload", {})
|
||||||
|
|
||||||
if event_type == "playback_started":
|
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":
|
elif event_type == "playback_stopped":
|
||||||
logger.debug(f"{serial}: playback stopped")
|
message = "Playback stopped"
|
||||||
else:
|
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", "")
|
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)
|
pending = await db.get_pending_command(serial)
|
||||||
if pending:
|
if pending:
|
||||||
cmd_status = "success" if status == "SUCCESS" else "error"
|
cmd_status = "success" if status == "SUCCESS" else "error"
|
||||||
@@ -98,4 +272,4 @@ async def _handle_data_response(serial: str, payload: dict):
|
|||||||
response_payload=payload,
|
response_payload=payload,
|
||||||
)
|
)
|
||||||
else:
|
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")
|
||||||
|
|||||||
@@ -27,6 +27,7 @@ class DeviceLogEntry(BaseModel):
|
|||||||
level: str
|
level: str
|
||||||
message: str
|
message: str
|
||||||
device_timestamp: Optional[int] = None
|
device_timestamp: Optional[int] = None
|
||||||
|
source: str = "log"
|
||||||
received_at: str
|
received_at: str
|
||||||
|
|
||||||
|
|
||||||
@@ -39,6 +40,10 @@ class HeartbeatEntry(BaseModel):
|
|||||||
gateway: Optional[str] = None
|
gateway: Optional[str] = None
|
||||||
uptime_ms: Optional[int] = None
|
uptime_ms: Optional[int] = None
|
||||||
uptime_display: Optional[str] = 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
|
received_at: str
|
||||||
|
|
||||||
|
|
||||||
@@ -53,11 +58,21 @@ class CommandEntry(BaseModel):
|
|||||||
responded_at: Optional[str] = None
|
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):
|
class DeviceMqttStatus(BaseModel):
|
||||||
device_serial: str
|
device_serial: str
|
||||||
online: bool
|
online: bool
|
||||||
last_heartbeat: Optional[HeartbeatEntry] = None
|
last_heartbeat: Optional[HeartbeatEntry] = None
|
||||||
seconds_since_heartbeat: Optional[int] = None
|
seconds_since_heartbeat: Optional[int] = None
|
||||||
|
last_alert_event: Optional[AlertEventEntry] = None
|
||||||
|
|
||||||
|
|
||||||
class MqttStatusResponse(BaseModel):
|
class MqttStatusResponse(BaseModel):
|
||||||
@@ -96,3 +111,125 @@ class DeviceAlertEntry(BaseModel):
|
|||||||
|
|
||||||
class DeviceAlertsResponse(BaseModel):
|
class DeviceAlertsResponse(BaseModel):
|
||||||
alerts: List[DeviceAlertEntry]
|
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]
|
||||||
|
|||||||
@@ -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
@@ -1,48 +1,90 @@
|
|||||||
from fastapi import APIRouter, Depends, Query, WebSocket, WebSocketDisconnect
|
from fastapi import APIRouter, Depends, HTTPException, Query, WebSocket, WebSocketDisconnect
|
||||||
from typing import Optional
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
from typing import Optional, List
|
||||||
from auth.models import TokenPayload
|
from auth.models import TokenPayload
|
||||||
from auth.dependencies import require_permission
|
from auth.dependencies import require_permission
|
||||||
from mqtt.models import (
|
from mqtt.models import (
|
||||||
MqttCommandRequest, CommandSendResponse, MqttStatusResponse,
|
MqttCommandRequest, CommandSendResponse, MqttStatusResponse,
|
||||||
DeviceMqttStatus, LogListResponse, HeartbeatListResponse,
|
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.client import mqtt_manager
|
||||||
|
from mqtt import presence
|
||||||
import database as db
|
import database as db
|
||||||
|
from database.postgres import get_pg_session
|
||||||
|
from shared.audit import log_action
|
||||||
from datetime import datetime, timezone
|
from datetime import datetime, timezone
|
||||||
|
|
||||||
router = APIRouter(prefix="/api/mqtt", tags=["mqtt"])
|
router = APIRouter(prefix="/api/mqtt", tags=["mqtt"])
|
||||||
|
|
||||||
|
|
||||||
|
def _device_status(hb: dict, alert_event: dict | None, now: datetime) -> DeviceMqttStatus:
|
||||||
|
try:
|
||||||
|
received = datetime.fromisoformat(hb["received_at"])
|
||||||
|
if received.tzinfo is None:
|
||||||
|
received = received.replace(tzinfo=timezone.utc)
|
||||||
|
seconds_ago = int((now - received).total_seconds())
|
||||||
|
except (ValueError, TypeError):
|
||||||
|
seconds_ago = 9999
|
||||||
|
return DeviceMqttStatus(
|
||||||
|
device_serial=hb["device_serial"],
|
||||||
|
online=seconds_ago < 90 and not presence.is_marked_offline(hb["device_serial"]),
|
||||||
|
last_heartbeat=HeartbeatEntry(**hb),
|
||||||
|
seconds_since_heartbeat=seconds_ago,
|
||||||
|
last_alert_event=AlertEventEntry(**alert_event) if alert_event else None,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
@router.get("/status", response_model=MqttStatusResponse)
|
@router.get("/status", response_model=MqttStatusResponse)
|
||||||
async def get_all_device_status(
|
async def get_all_device_status(
|
||||||
_user: TokenPayload = Depends(require_permission("mqtt", "view")),
|
_user: TokenPayload = Depends(require_permission("mqtt", "view")),
|
||||||
):
|
):
|
||||||
|
# Both reads come from database/latest_cache.py (kept current by the MQTT
|
||||||
|
# ingest), so this answers instantly instead of scanning history tables.
|
||||||
heartbeats = await db.get_latest_heartbeats()
|
heartbeats = await db.get_latest_heartbeats()
|
||||||
|
alert_events = await db.get_latest_alert_events()
|
||||||
|
alert_by_serial = {a["device_serial"]: a for a in alert_events}
|
||||||
now = datetime.now(timezone.utc)
|
now = datetime.now(timezone.utc)
|
||||||
devices = []
|
|
||||||
for hb in heartbeats:
|
|
||||||
received_str = hb["received_at"]
|
|
||||||
try:
|
|
||||||
received = datetime.fromisoformat(received_str)
|
|
||||||
if received.tzinfo is None:
|
|
||||||
received = received.replace(tzinfo=timezone.utc)
|
|
||||||
seconds_ago = int((now - received).total_seconds())
|
|
||||||
except (ValueError, TypeError):
|
|
||||||
seconds_ago = 9999
|
|
||||||
|
|
||||||
devices.append(DeviceMqttStatus(
|
|
||||||
device_serial=hb["device_serial"],
|
|
||||||
online=seconds_ago < 90,
|
|
||||||
last_heartbeat=HeartbeatEntry(**hb),
|
|
||||||
seconds_since_heartbeat=seconds_ago,
|
|
||||||
))
|
|
||||||
return MqttStatusResponse(
|
return MqttStatusResponse(
|
||||||
devices=devices,
|
devices=[_device_status(hb, alert_by_serial.get(hb["device_serial"]), now) for hb in heartbeats],
|
||||||
broker_connected=mqtt_manager.connected,
|
broker_connected=mqtt_manager.connected,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/status/{device_serial}", response_model=Optional[DeviceMqttStatus])
|
||||||
|
async def get_device_status(
|
||||||
|
device_serial: str,
|
||||||
|
_user: TokenPayload = Depends(require_permission("mqtt", "view")),
|
||||||
|
):
|
||||||
|
"""One device's live status — what DeviceDetail needs, without shipping
|
||||||
|
the whole fleet. null when the device has never sent a heartbeat."""
|
||||||
|
hb = await db.get_latest_heartbeat(device_serial)
|
||||||
|
if not hb:
|
||||||
|
return None
|
||||||
|
alert_event = await db.get_latest_alert_event(device_serial)
|
||||||
|
return _device_status(hb, alert_event, datetime.now(timezone.utc))
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/latest-metrics", response_model=LatestMetricsResponse)
|
||||||
|
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)
|
@router.post("/command/{device_serial}", response_model=CommandSendResponse)
|
||||||
async def send_command(
|
async def send_command(
|
||||||
device_serial: str,
|
device_serial: str,
|
||||||
@@ -81,27 +123,58 @@ async def send_command(
|
|||||||
async def get_device_logs(
|
async def get_device_logs(
|
||||||
device_serial: str,
|
device_serial: str,
|
||||||
level: Optional[str] = Query(None, description="Filter: INFO, WARN, ERROR"),
|
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),
|
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),
|
limit: int = Query(100, ge=1, le=1000),
|
||||||
offset: int = Query(0, ge=0),
|
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")),
|
_user: TokenPayload = Depends(require_permission("mqtt", "view")),
|
||||||
):
|
):
|
||||||
logs, total = await db.get_logs(
|
logs, total = await db.get_logs(
|
||||||
device_serial, level=level, search=search,
|
device_serial, level=level, search=search, source=source,
|
||||||
limit=limit, offset=offset,
|
min_level=min_level, limit=limit, offset=offset, since=since, until=until,
|
||||||
)
|
)
|
||||||
return LogListResponse(logs=logs, total=total)
|
return LogListResponse(logs=logs, total=total)
|
||||||
|
|
||||||
|
|
||||||
|
@router.delete("/logs/{device_serial}")
|
||||||
|
async def delete_device_logs(
|
||||||
|
device_serial: str,
|
||||||
|
source: Optional[List[str]] = Query(None, description="Only these sources: log, info. Repeat param for several. Omit for all."),
|
||||||
|
level: Optional[List[str]] = Query(None, description="Only these levels: INFO, WARN, ERROR. Repeat param for several. Omit for all."),
|
||||||
|
until: Optional[datetime] = Query(None, description="Only rows at/before this ISO timestamp"),
|
||||||
|
_user: TokenPayload = Depends(require_permission("devices", "edit")),
|
||||||
|
pg: AsyncSession = Depends(get_pg_session),
|
||||||
|
):
|
||||||
|
"""Delete console-stored log rows for one device (Health tab → Logs →
|
||||||
|
Delete Logs). Narrowed by source/level/time when given. Heartbeats,
|
||||||
|
alert history and commands are cleared through the existing
|
||||||
|
POST /api/devices/{id}/reset-stats instead."""
|
||||||
|
bad_sources = [s for s in (source or []) if s not in ("log", "info")]
|
||||||
|
bad_levels = [l for l in (level or []) if l not in ("INFO", "WARN", "ERROR")]
|
||||||
|
if bad_sources or bad_levels:
|
||||||
|
raise HTTPException(status_code=400, detail=f"Invalid filter: {bad_sources + bad_levels}")
|
||||||
|
deleted = await db.delete_device_logs_filtered(device_serial, sources=source, levels=level, until=until)
|
||||||
|
await log_action(pg, _user.sub, _user.name or _user.email, "DELETE", "device_logs",
|
||||||
|
device_serial, device_serial,
|
||||||
|
meta={"sources": source, "levels": level,
|
||||||
|
"until": until.isoformat() if until else None, "deleted": deleted})
|
||||||
|
return {"deleted": deleted}
|
||||||
|
|
||||||
|
|
||||||
@router.get("/heartbeats/{device_serial}", response_model=HeartbeatListResponse)
|
@router.get("/heartbeats/{device_serial}", response_model=HeartbeatListResponse)
|
||||||
async def get_device_heartbeats(
|
async def get_device_heartbeats(
|
||||||
device_serial: str,
|
device_serial: str,
|
||||||
limit: int = Query(100, ge=1, le=1000),
|
limit: int = Query(100, ge=1, le=5000),
|
||||||
offset: int = Query(0, ge=0),
|
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")),
|
_user: TokenPayload = Depends(require_permission("mqtt", "view")),
|
||||||
):
|
):
|
||||||
heartbeats, total = await db.get_heartbeats(
|
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)
|
return HeartbeatListResponse(heartbeats=heartbeats, total=total)
|
||||||
|
|
||||||
@@ -119,6 +192,93 @@ async def get_device_commands(
|
|||||||
return CommandListResponse(commands=commands, total=total)
|
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")
|
@router.websocket("/ws")
|
||||||
async def mqtt_websocket(websocket: WebSocket):
|
async def mqtt_websocket(websocket: WebSocket):
|
||||||
"""Live MQTT data stream. Auth via query param: ?token=JWT"""
|
"""Live MQTT data stream. Auth via query param: ?token=JWT"""
|
||||||
|
|||||||
@@ -109,9 +109,9 @@ async def validate_serial(serial_number: str):
|
|||||||
device = get_device_by_sn(sn)
|
device = get_device_by_sn(sn)
|
||||||
return SerialValidationResult(
|
return SerialValidationResult(
|
||||||
valid=True,
|
valid=True,
|
||||||
hw_type=device.hw_type,
|
hw_type=device.hw_family,
|
||||||
hw_type_label=HW_TYPE_LABELS.get(device.hw_type, device.hw_type.replace("_", " ").title()),
|
hw_type_label=HW_TYPE_LABELS.get(device.hw_family, device.hw_family.replace("_", " ").title()),
|
||||||
hw_version=device.hw_version,
|
hw_version=device.hw_revision,
|
||||||
)
|
)
|
||||||
except Exception:
|
except Exception:
|
||||||
return SerialValidationResult(valid=False)
|
return SerialValidationResult(valid=False)
|
||||||
|
|||||||
@@ -17,4 +17,6 @@ Pillow>=10.0.0
|
|||||||
pdf2image>=1.17.0
|
pdf2image>=1.17.0
|
||||||
asyncpg==0.30.0
|
asyncpg==0.30.0
|
||||||
sqlalchemy[asyncio]==2.0.36
|
sqlalchemy[asyncio]==2.0.36
|
||||||
alembic==1.14.0
|
alembic==1.14.0
|
||||||
|
# IANA tz database for the device timezone table (timezones/). Bump to pick up new DST rules.
|
||||||
|
tzdata==2026.6
|
||||||
|
|||||||
@@ -0,0 +1,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())
|
||||||
@@ -26,8 +26,9 @@ def _search_devices(q: str) -> list[dict]:
|
|||||||
return []
|
return []
|
||||||
out = []
|
out = []
|
||||||
for d in results[:LIMIT]:
|
for d in results[:LIMIT]:
|
||||||
label = d.device_name or d.serial_number or d.device_id or d.id
|
display_name = d.console_name or d.device_name
|
||||||
sublabel = d.serial_number if d.device_name else None
|
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({
|
out.append({
|
||||||
"type": "device",
|
"type": "device",
|
||||||
"id": d.id,
|
"id": d.id,
|
||||||
|
|||||||
@@ -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
|
||||||
@@ -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
|
||||||
@@ -4,8 +4,10 @@ from auth.dependencies import require_permission, require_roles
|
|||||||
from auth.models import Role
|
from auth.models import Role
|
||||||
from settings.models import MelodySettings, MelodySettingsUpdate
|
from settings.models import MelodySettings, MelodySettingsUpdate
|
||||||
from settings.public_features_models import PublicFeaturesSettings, PublicFeaturesSettingsUpdate
|
from settings.public_features_models import PublicFeaturesSettings, PublicFeaturesSettingsUpdate
|
||||||
|
from settings.log_retention_models import LogRetentionSettings, LogRetentionSettingsUpdate
|
||||||
from settings import service
|
from settings import service
|
||||||
from settings import public_features_service
|
from settings import public_features_service
|
||||||
|
from settings import log_retention_service
|
||||||
|
|
||||||
router = APIRouter(prefix="/api/settings", tags=["settings"])
|
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)),
|
_user: TokenPayload = Depends(require_roles(Role.sysadmin, Role.admin)),
|
||||||
):
|
):
|
||||||
return public_features_service.update_public_features(body)
|
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)
|
||||||
|
|||||||
@@ -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))
|
||||||
@@ -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() == []
|
||||||
@@ -0,0 +1,190 @@
|
|||||||
|
"""
|
||||||
|
Device writes must match Firestore schema v1 (bellsystems-schema/v1). One wrongly
|
||||||
|
typed field makes the FlutterFlow apps silently drop the whole device, so these
|
||||||
|
cover the exact shapes found corrupting production data on 2026-11-08.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from google.cloud.firestore_v1 import DocumentReference, GeoPoint
|
||||||
|
|
||||||
|
from devices import firestore_v1 as v1
|
||||||
|
from devices.models import DeviceCreate
|
||||||
|
from shared.exceptions import ValidationError
|
||||||
|
|
||||||
|
|
||||||
|
class _FakeDb:
|
||||||
|
"""Just enough of a Firestore client to build DocumentReferences."""
|
||||||
|
|
||||||
|
def collection(self, name):
|
||||||
|
db = self
|
||||||
|
|
||||||
|
class _Col:
|
||||||
|
def document(self, doc_id):
|
||||||
|
return DocumentReference(name, doc_id, client=db)
|
||||||
|
|
||||||
|
return _Col()
|
||||||
|
|
||||||
|
|
||||||
|
DB = _FakeDb()
|
||||||
|
T = datetime(2026, 1, 15, 22, 1, tzinfo=timezone.utc)
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------- timestamps
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("value", ["", None])
|
||||||
|
def test_unset_timestamp_becomes_null_never_empty_string(value):
|
||||||
|
out = v1.to_firestore({"device_attributes": {"towerClockTime": value,
|
||||||
|
"clockSettings": {"daySilenceFrom": value}}})
|
||||||
|
assert out["device_attributes"]["towerClockTime"] is None
|
||||||
|
assert out["device_attributes"]["clockSettings"]["daySilenceFrom"] is None
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("value", [
|
||||||
|
"2026-01-15T22:01:00Z",
|
||||||
|
"2026-01-15T22:01:00+00:00",
|
||||||
|
"15 January 2026 at 22:01:00 UTC+0000", # the format the API used to serve
|
||||||
|
])
|
||||||
|
def test_timestamp_strings_become_datetimes(value):
|
||||||
|
out = v1.to_firestore({"device_stats": {"maintainedOn": value}})
|
||||||
|
assert out["device_stats"]["maintainedOn"] == T
|
||||||
|
|
||||||
|
|
||||||
|
def test_unparseable_timestamp_is_rejected_not_stored():
|
||||||
|
with pytest.raises(ValidationError):
|
||||||
|
v1.to_firestore({"device_subscription": {"subscrStart": "next tuesday"}})
|
||||||
|
|
||||||
|
|
||||||
|
def test_timestamp_round_trip_is_lossless():
|
||||||
|
stored = {"device_attributes": {"clockSettings": {"nightSilenceTo": T}}}
|
||||||
|
api = v1.to_api(stored)
|
||||||
|
assert api["device_attributes"]["clockSettings"]["nightSilenceTo"] == "2026-01-15T22:01:00Z"
|
||||||
|
again = v1.to_firestore(api)
|
||||||
|
assert again["device_attributes"]["clockSettings"]["nightSilenceTo"] == T
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------- IP addresses
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("value, expected", [
|
||||||
|
(["10", "0", "0", "5"], "10.0.0.5"),
|
||||||
|
([10, 0, 0, 5], "10.0.0.5"),
|
||||||
|
([], ""),
|
||||||
|
("192.168.1.102", "192.168.1.102"),
|
||||||
|
("", ""),
|
||||||
|
])
|
||||||
|
def test_ip_addresses_are_dotted_strings(value, expected):
|
||||||
|
out = v1.to_firestore({"device_attributes": {"networkSettings": {"ipAddress": value}}})
|
||||||
|
assert out["device_attributes"]["networkSettings"]["ipAddress"] == expected
|
||||||
|
|
||||||
|
|
||||||
|
def test_invalid_ip_is_rejected():
|
||||||
|
with pytest.raises(ValidationError):
|
||||||
|
v1.to_firestore({"device_attributes": {"networkSettings": {"gateway": "10.0.0"}}})
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------- key spelling
|
||||||
|
|
||||||
|
def test_legacy_keys_are_renamed():
|
||||||
|
out = v1.to_firestore({"device_attributes": {
|
||||||
|
"bellGuardSafetyOn": True,
|
||||||
|
"networkSettings": {"useStaticIP": True},
|
||||||
|
}})
|
||||||
|
attrs = out["device_attributes"]
|
||||||
|
assert attrs == {"bellguardSafetyOn": True, "networkSettings": {"usesStaticIP": True}}
|
||||||
|
|
||||||
|
|
||||||
|
def test_v1_key_wins_over_legacy_duplicate():
|
||||||
|
out = v1.to_firestore({"device_attributes": {
|
||||||
|
"bellguardSafetyOn": False, "bellGuardSafetyOn": True,
|
||||||
|
"networkSettings": {"usesStaticIP": True, "useStaticIP": False},
|
||||||
|
}})
|
||||||
|
attrs = out["device_attributes"]
|
||||||
|
assert attrs["bellguardSafetyOn"] is False and "bellGuardSafetyOn" not in attrs
|
||||||
|
assert attrs["networkSettings"] == {"usesStaticIP": True}
|
||||||
|
|
||||||
|
|
||||||
|
def test_legacy_hw_names_become_firmware_names():
|
||||||
|
out = v1.to_firestore({"hw_type": "vesper_plus", "hw_version": "1.0"})
|
||||||
|
assert out == {"hw_family": "vesper_plus", "hw_revision": "1.0"}
|
||||||
|
assert v1.to_api({"hw_type": "agnus", "hw_version": "1.0"}) == {"hw_family": "agnus", "hw_revision": "1.0"}
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("label", ["Bell Plus", "Bell Core", "vesper plus"])
|
||||||
|
def test_hw_family_display_labels_are_rejected(label):
|
||||||
|
with pytest.raises(ValidationError):
|
||||||
|
v1.to_firestore({"hw_family": label})
|
||||||
|
|
||||||
|
|
||||||
|
def test_retired_users_list_is_dropped():
|
||||||
|
assert "users_list" not in v1.to_firestore({"users_list": [], "device_name": "x"})
|
||||||
|
|
||||||
|
|
||||||
|
def test_read_folds_legacy_keys_and_repairs_values():
|
||||||
|
api = v1.to_api({"device_attributes": {
|
||||||
|
"bellGuardSafetyOn": True,
|
||||||
|
"towerClockTime": "",
|
||||||
|
"networkSettings": {"useStaticIP": True, "dns1": ["10", "0", "0", "1"]},
|
||||||
|
}})
|
||||||
|
attrs = api["device_attributes"]
|
||||||
|
assert attrs["bellguardSafetyOn"] is True and "bellGuardSafetyOn" not in attrs
|
||||||
|
assert attrs["towerClockTime"] is None
|
||||||
|
assert attrs["networkSettings"] == {"usesStaticIP": True, "dns1": "10.0.0.1"}
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------- identifiers (D1)
|
||||||
|
|
||||||
|
def test_serial_number_is_mirrored_to_device_id():
|
||||||
|
out = v1.to_firestore({"serial_number": "BSVSPR-26C20B-STD10R-2KCDPH"})
|
||||||
|
assert out["device_id"] == out["serial_number"] == "BSVSPR-26C20B-STD10R-2KCDPH"
|
||||||
|
|
||||||
|
|
||||||
|
def test_conflicting_ids_are_rejected():
|
||||||
|
with pytest.raises(ValidationError):
|
||||||
|
v1.to_firestore({"serial_number": "BSVSPR-A", "device_id": "PV25K29BP01R01"})
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------- references
|
||||||
|
|
||||||
|
def test_user_list_entries_become_references():
|
||||||
|
out = v1.to_firestore({"user_list": ["users/alice", "bob", "users/alice"]}, DB)
|
||||||
|
assert [r.path for r in out["user_list"]] == ["users/alice", "users/bob"]
|
||||||
|
assert all(isinstance(r, DocumentReference) for r in out["user_list"])
|
||||||
|
|
||||||
|
|
||||||
|
def test_coordinates_become_geopoint():
|
||||||
|
out = v1.to_firestore({"device_location_coordinates": {"lat": 40.6, "lng": 22.9}})
|
||||||
|
assert isinstance(out["device_location_coordinates"], GeoPoint)
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------- melodies
|
||||||
|
|
||||||
|
def test_device_melody_in_melodies_collection_shape_is_rejected():
|
||||||
|
with pytest.raises(ValidationError):
|
||||||
|
v1.to_firestore({"device_melodies_all": [{"information": {}, "default_settings": {}, "url": "x"}]})
|
||||||
|
|
||||||
|
|
||||||
|
def test_device_melody_reference_becomes_reference():
|
||||||
|
out = v1.to_firestore({"device_melodies_all": [
|
||||||
|
{"melodyReference": "melodies/m1", "mainInformation": {"name": "x"}},
|
||||||
|
]}, DB)
|
||||||
|
ref = out["device_melodies_all"][0]["melodyReference"]
|
||||||
|
assert isinstance(ref, DocumentReference) and ref.path == "melodies/m1"
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------- new devices
|
||||||
|
|
||||||
|
def test_new_device_defaults_are_v1_valid():
|
||||||
|
"""create_device writes DeviceCreate() defaults — they must not break the apps."""
|
||||||
|
doc = v1.to_firestore({**DeviceCreate().model_dump(), "serial_number": "BS-AAAA-BBBB"}, DB)
|
||||||
|
attrs = doc["device_attributes"]
|
||||||
|
for key in ("daySilenceFrom", "daySilenceTo", "nightSilenceFrom", "nightSilenceTo",
|
||||||
|
"backlightTurnOnTime", "backlightTurnOffTime"):
|
||||||
|
assert attrs["clockSettings"][key] is None
|
||||||
|
assert attrs["towerClockTime"] is None
|
||||||
|
assert attrs["networkSettings"]["ipAddress"] == ""
|
||||||
|
assert "useStaticIP" not in attrs["networkSettings"] and "usesStaticIP" in attrs["networkSettings"]
|
||||||
|
assert "bellguardSafetyOn" in attrs and "bellGuardSafetyOn" not in attrs
|
||||||
|
assert doc["device_stats"]["maintainedOn"] is None
|
||||||
|
assert doc["device_subscription"]["subscrStart"] is None
|
||||||
|
assert doc["device_id"] == "BS-AAAA-BBBB"
|
||||||
@@ -0,0 +1,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
|
||||||
@@ -0,0 +1,117 @@
|
|||||||
|
"""
|
||||||
|
Timezone table for device clock setup (timezones/). Pure tzdata — no Firestore, no MQTT.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
import tzdata
|
||||||
|
from fastapi import FastAPI
|
||||||
|
from fastapi.testclient import TestClient
|
||||||
|
|
||||||
|
from timezones import service
|
||||||
|
from timezones.router import router
|
||||||
|
|
||||||
|
SUMMER = datetime(2026, 7, 15, 12, tzinfo=timezone.utc)
|
||||||
|
WINTER = datetime(2026, 1, 15, 12, tzinfo=timezone.utc)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("posix, expected", [
|
||||||
|
("EET-2EEST,M3.5.0/3,M10.5.0/4", (120, 60, True)),
|
||||||
|
("EST5EDT,M3.2.0,M11.1.0", (-300, 60, True)),
|
||||||
|
("IST-5:30", (330, 0, False)),
|
||||||
|
("<+0545>-5:45", (345, 0, False)),
|
||||||
|
("<-03>3", (-180, 0, False)),
|
||||||
|
("IST-1GMT0,M10.5.0,M3.5.0/1", (60, -60, True)), # Dublin: negative DST
|
||||||
|
("<+1030>-10:30<+11>-11,M10.1.0,M4.1.0", (630, 30, True)), # Lord Howe: 30 min DST
|
||||||
|
("<+1245>-12:45<+1345>,M9.5.0/2:45,M4.1.0/3:45", (765, 60, True)), # Chatham
|
||||||
|
("IST-2IDT,M3.4.4/26,M10.5.0", (120, 60, True)), # Israel extended hours
|
||||||
|
])
|
||||||
|
def test_posix_offsets(posix, expected):
|
||||||
|
assert service.posix_offsets(posix) == expected
|
||||||
|
|
||||||
|
|
||||||
|
def test_posix_offsets_rejects_garbage():
|
||||||
|
with pytest.raises(ValueError):
|
||||||
|
service.posix_offsets("not a rule")
|
||||||
|
|
||||||
|
|
||||||
|
def test_table_shape_and_version():
|
||||||
|
table = service.get_table(now=WINTER)
|
||||||
|
assert table["tzdata_version"] == tzdata.IANA_VERSION
|
||||||
|
countries = table["countries"]
|
||||||
|
assert len(countries) > 200
|
||||||
|
assert [c["name"] for c in countries] == sorted(c["name"] for c in countries)
|
||||||
|
zone_count = 0
|
||||||
|
for country in countries:
|
||||||
|
assert country["zones"], country["code"]
|
||||||
|
for zone in country["zones"]:
|
||||||
|
zone_count += 1
|
||||||
|
assert zone["posix"] and len(zone["posix"]) < 64 # firmware POSIX_MAX_LEN
|
||||||
|
assert len(zone["name"]) < 48 # firmware NAME_MAX_LEN
|
||||||
|
assert country["code"] in zone["countries"]
|
||||||
|
assert zone_count > 300
|
||||||
|
|
||||||
|
|
||||||
|
def test_greece_and_australia():
|
||||||
|
gr = service.get_table("gr", now=SUMMER)["countries"]
|
||||||
|
assert len(gr) == 1 and gr[0]["name"] == "Greece"
|
||||||
|
athens = gr[0]["zones"][0]
|
||||||
|
assert athens["name"] == "Europe/Athens"
|
||||||
|
assert athens["posix"] == "EET-2EEST,M3.5.0/3,M10.5.0/4"
|
||||||
|
assert (athens["std_offset_min"], athens["dst_offset_min"], athens["has_dst"]) == (120, 60, True)
|
||||||
|
assert athens["current_offset_min"] == 180 and athens["current_dst"] is True
|
||||||
|
assert athens["display"] == "(UTC+03:00) Athens"
|
||||||
|
|
||||||
|
au = {z["name"]: z for z in service.get_table("AU", now=SUMMER)["countries"][0]["zones"]}
|
||||||
|
assert au["Australia/Sydney"]["current_offset_min"] == 600 # southern winter
|
||||||
|
assert au["Australia/Brisbane"]["has_dst"] is False
|
||||||
|
assert au["Australia/Lord_Howe"]["dst_offset_min"] == 30
|
||||||
|
|
||||||
|
|
||||||
|
def test_current_offset_follows_dst():
|
||||||
|
athens = service.get_zone("Europe/Athens", now=WINTER)
|
||||||
|
assert athens["current_offset_min"] == 120 and athens["current_dst"] is False
|
||||||
|
|
||||||
|
|
||||||
|
def test_rule_offsets_match_zoneinfo_once_rules_are_settled():
|
||||||
|
# By 2030 every zone runs on its POSIX footer, so the offset in force must be
|
||||||
|
# either the standard offset or standard + DST from that rule.
|
||||||
|
table = service.get_table()
|
||||||
|
for when in (datetime(2030, 1, 15, 12, tzinfo=timezone.utc), datetime(2030, 7, 15, 12, tzinfo=timezone.utc)):
|
||||||
|
for country in table["countries"]:
|
||||||
|
for zone in country["zones"]:
|
||||||
|
current = service.get_zone(zone["name"], now=when)["current_offset_min"]
|
||||||
|
allowed = {zone["std_offset_min"], zone["std_offset_min"] + zone["dst_offset_min"]}
|
||||||
|
assert current in allowed, (zone["name"], when, current, allowed)
|
||||||
|
|
||||||
|
|
||||||
|
def test_unknown_country_and_zone():
|
||||||
|
assert service.get_table("XX") is None
|
||||||
|
assert service.get_zone("Nowhere/Town") is None
|
||||||
|
assert service.get_zone("../../etc/passwd") is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_alias_not_in_zone_tab_resolves():
|
||||||
|
zone = service.get_zone("Asia/Calcutta")
|
||||||
|
assert zone["posix"] == "IST-5:30" and zone["countries"] == []
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def client():
|
||||||
|
app = FastAPI()
|
||||||
|
app.include_router(router)
|
||||||
|
return TestClient(app)
|
||||||
|
|
||||||
|
|
||||||
|
def test_routes(client):
|
||||||
|
r = client.get("/api/public/timezones", params={"country": "GR"})
|
||||||
|
assert r.status_code == 200
|
||||||
|
assert r.json()["countries"][0]["zones"][0]["name"] == "Europe/Athens"
|
||||||
|
|
||||||
|
assert client.get("/api/public/timezones", params={"country": "XX"}).status_code == 404
|
||||||
|
|
||||||
|
r = client.get("/api/public/timezones/zone", params={"name": "Australia/Sydney"})
|
||||||
|
assert r.status_code == 200 and r.json()["posix"] == "AEST-10AEDT,M10.1.0,M4.1.0/3"
|
||||||
|
|
||||||
|
assert client.get("/api/public/timezones/zone", params={"name": "Nowhere/Town"}).status_code == 404
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
"""
|
||||||
|
Public (no-auth) timezone table for device clock setup — see timezones/service.py.
|
||||||
|
|
||||||
|
Public on purpose: it is IANA data, and the phone app (Firebase auth, MQTT) and the tablet
|
||||||
|
bundle export both need it without console credentials.
|
||||||
|
"""
|
||||||
|
from fastapi import APIRouter, HTTPException, Query
|
||||||
|
|
||||||
|
from timezones import service
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/api/public/timezones", tags=["timezones"])
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("")
|
||||||
|
async def list_timezones(country: str | None = Query(None, description="ISO 3166 alpha-2 code, e.g. GR")):
|
||||||
|
"""All countries with their IANA zones, POSIX rules and current offsets.
|
||||||
|
|
||||||
|
The response is also the file the tablet app bundles (save it as-is; `tzdata_version`
|
||||||
|
tells which IANA release it came from).
|
||||||
|
"""
|
||||||
|
table = service.get_table(country)
|
||||||
|
if table is None:
|
||||||
|
raise HTTPException(status_code=404, detail=f"Unknown country code: {country}")
|
||||||
|
return table
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/zone")
|
||||||
|
async def get_timezone(name: str = Query(..., description="IANA zone name, e.g. Europe/Athens")):
|
||||||
|
"""One zone by IANA name — e.g. to turn a phone's own timezone into a device rule."""
|
||||||
|
zone = service.get_zone(name)
|
||||||
|
if zone is None:
|
||||||
|
raise HTTPException(status_code=404, detail=f"Unknown timezone: {name}")
|
||||||
|
return zone
|
||||||
@@ -0,0 +1,170 @@
|
|||||||
|
"""
|
||||||
|
IANA timezone table for the device clock (firmware 3.0.0+, timezone mode "auto").
|
||||||
|
|
||||||
|
Devices evaluate a POSIX TZ rule string (e.g. "EET-2EEST,M3.5.0/3,M10.5.0/4"), not the
|
||||||
|
IANA database, so whoever sets a device's timezone has to send the rule. This module is the
|
||||||
|
single source of those rules for the console and the phone app (GET /api/public/timezones);
|
||||||
|
the tablet app, which only talks to devices over local WebSocket, bundles a saved copy of
|
||||||
|
the same response.
|
||||||
|
|
||||||
|
Everything comes from the `tzdata` package pinned in requirements.txt (IANA release in
|
||||||
|
`tzdata.IANA_VERSION`): the POSIX rule is the footer of each zone's TZif file, zone →
|
||||||
|
country from zone.tab, country names from iso3166.tab. To pick up new DST rules, bump the
|
||||||
|
pin — nothing is generated or committed by hand.
|
||||||
|
|
||||||
|
The firmware side is project-vesper src/TimeKeeper/TimeZone.cpp; its host tests check that
|
||||||
|
it evaluates every one of these rules the same way as CPython's zoneinfo.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import importlib.resources
|
||||||
|
import re
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
from functools import lru_cache
|
||||||
|
from zoneinfo import ZoneInfo
|
||||||
|
|
||||||
|
import tzdata
|
||||||
|
|
||||||
|
# POSIX TZ: std offset [dst [offset] [,rule]] — only the offsets are needed here.
|
||||||
|
_NAME = r"(?:<[^>]+>|[A-Za-z]{3,})"
|
||||||
|
_OFFSET = r"([+-]?\d{1,3}(?::\d{1,2}){0,2})"
|
||||||
|
_POSIX_RE = re.compile(rf"^{_NAME}{_OFFSET}(?:({_NAME}){_OFFSET}?(?:,.*)?)?$")
|
||||||
|
|
||||||
|
|
||||||
|
def _tzdata_file(name: str):
|
||||||
|
return importlib.resources.files("tzdata.zoneinfo").joinpath(*name.split("/"))
|
||||||
|
|
||||||
|
|
||||||
|
def _hms_to_min(text: str) -> int:
|
||||||
|
sign = -1 if text.startswith("-") else 1
|
||||||
|
parts = [int(p) for p in text.lstrip("+-").split(":")]
|
||||||
|
parts += [0] * (3 - len(parts))
|
||||||
|
return sign * (parts[0] * 60 + parts[1] + (1 if parts[2] >= 30 else 0))
|
||||||
|
|
||||||
|
|
||||||
|
def posix_offsets(posix: str) -> tuple[int, int, bool]:
|
||||||
|
"""(std_offset_min, dst_offset_min, has_dst), east-positive minutes.
|
||||||
|
|
||||||
|
POSIX offsets are west-positive ("EET-2" is UTC+2). dst_offset_min is the DST
|
||||||
|
*amount* (DST total - standard), default one hour, matching the firmware's
|
||||||
|
tz::makeAuto(). It can be negative (Europe/Dublin models winter as negative DST).
|
||||||
|
"""
|
||||||
|
m = _POSIX_RE.match(posix)
|
||||||
|
if not m:
|
||||||
|
raise ValueError(f"unparseable POSIX TZ rule: {posix!r}")
|
||||||
|
std = -_hms_to_min(m.group(1))
|
||||||
|
if not m.group(2):
|
||||||
|
return std, 0, False
|
||||||
|
total = -_hms_to_min(m.group(3)) if m.group(3) else std + 60
|
||||||
|
return std, total - std, True
|
||||||
|
|
||||||
|
|
||||||
|
def posix_rule(name: str) -> str | None:
|
||||||
|
"""POSIX TZ footer of a zone's TZif (v2+) file, or None."""
|
||||||
|
try:
|
||||||
|
data = _tzdata_file(name).read_bytes()
|
||||||
|
except (FileNotFoundError, IsADirectoryError, OSError):
|
||||||
|
return None
|
||||||
|
if not data.startswith(b"TZif") or data[4:5] < b"2":
|
||||||
|
return None
|
||||||
|
footer = data.rstrip(b"\n").rsplit(b"\n", 1)[-1].decode("ascii", "replace")
|
||||||
|
return footer or None
|
||||||
|
|
||||||
|
|
||||||
|
def _format_offset(minutes: int) -> str:
|
||||||
|
sign = "+" if minutes >= 0 else "-"
|
||||||
|
return f"UTC{sign}{abs(minutes) // 60:02d}:{abs(minutes) % 60:02d}"
|
||||||
|
|
||||||
|
|
||||||
|
@lru_cache(maxsize=1)
|
||||||
|
def _static_table() -> tuple[list[dict], dict[str, dict]]:
|
||||||
|
"""Countries (sorted by name) with their zones in zone.tab order, plus a name index.
|
||||||
|
Only the parts that never change at runtime; offsets "now" are added per request."""
|
||||||
|
countries_by_code = {}
|
||||||
|
for line in _tzdata_file("iso3166.tab").read_text(encoding="utf-8").splitlines():
|
||||||
|
if line and not line.startswith("#"):
|
||||||
|
code, name = line.split("\t", 1)
|
||||||
|
countries_by_code[code] = {"code": code, "name": name.strip(), "zones": []}
|
||||||
|
|
||||||
|
zones_by_name: dict[str, dict] = {}
|
||||||
|
for line in _tzdata_file("zone.tab").read_text(encoding="utf-8").splitlines():
|
||||||
|
if not line or line.startswith("#"):
|
||||||
|
continue
|
||||||
|
fields = line.split("\t")
|
||||||
|
code, name = fields[0], fields[2]
|
||||||
|
comment = fields[3].strip() if len(fields) > 3 else ""
|
||||||
|
posix = posix_rule(name)
|
||||||
|
country = countries_by_code.get(code)
|
||||||
|
if not posix or country is None:
|
||||||
|
continue
|
||||||
|
std, dst, has_dst = posix_offsets(posix)
|
||||||
|
zone = zones_by_name.get(name)
|
||||||
|
if zone is None:
|
||||||
|
zone = {
|
||||||
|
"name": name,
|
||||||
|
"city": name.rsplit("/", 1)[-1].replace("_", " "),
|
||||||
|
"comment": comment,
|
||||||
|
"posix": posix,
|
||||||
|
"std_offset_min": std,
|
||||||
|
"dst_offset_min": dst,
|
||||||
|
"has_dst": has_dst,
|
||||||
|
"countries": [],
|
||||||
|
}
|
||||||
|
zones_by_name[name] = zone
|
||||||
|
zone["countries"].append(code)
|
||||||
|
country["zones"].append(zone)
|
||||||
|
|
||||||
|
countries = sorted((c for c in countries_by_code.values() if c["zones"]), key=lambda c: c["name"])
|
||||||
|
return countries, zones_by_name
|
||||||
|
|
||||||
|
|
||||||
|
def _with_current(zone: dict, now: datetime) -> dict:
|
||||||
|
local = now.astimezone(ZoneInfo(zone["name"]))
|
||||||
|
offset = int(local.utcoffset().total_seconds() // 60)
|
||||||
|
out = {k: v for k, v in zone.items() if k != "countries"}
|
||||||
|
out["countries"] = list(zone["countries"])
|
||||||
|
out["current_offset_min"] = offset
|
||||||
|
out["current_dst"] = bool(local.dst())
|
||||||
|
out["display"] = f"({_format_offset(offset)}) {zone['city']}" + (f" — {zone['comment']}" if zone["comment"] else "")
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def tzdata_version() -> str:
|
||||||
|
return tzdata.IANA_VERSION
|
||||||
|
|
||||||
|
|
||||||
|
def get_table(country: str | None = None, now: datetime | None = None) -> dict | None:
|
||||||
|
"""Full table, or one country's (ISO 3166 alpha-2, case-insensitive). None if unknown."""
|
||||||
|
now = now or datetime.now(timezone.utc)
|
||||||
|
countries, _ = _static_table()
|
||||||
|
if country:
|
||||||
|
countries = [c for c in countries if c["code"] == country.upper()]
|
||||||
|
if not countries:
|
||||||
|
return None
|
||||||
|
return {
|
||||||
|
"tzdata_version": tzdata_version(),
|
||||||
|
"generated_at": now.isoformat(timespec="seconds"),
|
||||||
|
"countries": [
|
||||||
|
{"code": c["code"], "name": c["name"], "zones": [_with_current(z, now) for z in c["zones"]]}
|
||||||
|
for c in countries
|
||||||
|
],
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def get_zone(name: str, now: datetime | None = None) -> dict | None:
|
||||||
|
"""One zone. Also resolves IANA names that zone.tab doesn't list (aliases such as
|
||||||
|
"Asia/Calcutta", or "UTC") — phones may report those as their own timezone."""
|
||||||
|
_, zones = _static_table()
|
||||||
|
zone = zones.get(name)
|
||||||
|
if zone is None:
|
||||||
|
posix = posix_rule(name) if re.fullmatch(r"[A-Za-z0-9_+\-]+(/[A-Za-z0-9_+\-]+)*", name) else None
|
||||||
|
if posix is None:
|
||||||
|
return None
|
||||||
|
std, dst, has_dst = posix_offsets(posix)
|
||||||
|
zone = {"name": name, "city": name.rsplit("/", 1)[-1].replace("_", " "), "comment": "",
|
||||||
|
"posix": posix, "std_offset_min": std, "dst_offset_min": dst, "has_dst": has_dst,
|
||||||
|
"countries": []}
|
||||||
|
result = _with_current(zone, now or datetime.now(timezone.utc))
|
||||||
|
result["tzdata_version"] = tzdata_version()
|
||||||
|
return result
|
||||||
@@ -4,7 +4,7 @@ from typing import List, Optional
|
|||||||
|
|
||||||
# --- Request / Response schemas ---
|
# --- Request / Response schemas ---
|
||||||
|
|
||||||
class UserCreate(BaseModel):
|
class UserProfile(BaseModel):
|
||||||
email: str = ""
|
email: str = ""
|
||||||
display_name: str = ""
|
display_name: str = ""
|
||||||
photo_url: str = ""
|
photo_url: str = ""
|
||||||
@@ -17,6 +17,10 @@ class UserCreate(BaseModel):
|
|||||||
quickSettingsPIN: str = ""
|
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):
|
class UserUpdate(BaseModel):
|
||||||
email: Optional[str] = None
|
email: Optional[str] = None
|
||||||
display_name: Optional[str] = None
|
display_name: Optional[str] = None
|
||||||
@@ -29,7 +33,7 @@ class UserUpdate(BaseModel):
|
|||||||
quickSettingsPIN: Optional[str] = None
|
quickSettingsPIN: Optional[str] = None
|
||||||
|
|
||||||
|
|
||||||
class UserInDB(UserCreate):
|
class UserInDB(UserProfile):
|
||||||
id: str
|
id: str
|
||||||
created_time: str = ""
|
created_time: str = ""
|
||||||
lastActive: str = ""
|
lastActive: str = ""
|
||||||
|
|||||||
+133
-54
@@ -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 firebase_admin import auth as firebase_auth
|
||||||
from shared.firebase import get_db, get_bucket
|
from shared.firebase import get_db, get_bucket
|
||||||
@@ -9,6 +9,37 @@ from users.models import UserCreate, UserUpdate, UserInDB
|
|||||||
|
|
||||||
COLLECTION = "users"
|
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):
|
def _convert_firestore_value(val):
|
||||||
"""Convert Firestore-specific types (Timestamp, DocumentReference) to strings."""
|
"""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:
|
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()
|
db = get_db()
|
||||||
doc_data = data.model_dump()
|
doc_data = data.model_dump(exclude={"password"})
|
||||||
|
doc_data["email"] = email
|
||||||
doc_data["friendsList"] = []
|
doc_data["friendsList"] = []
|
||||||
doc_data["friendsInvited"] = []
|
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:
|
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)
|
update_data = data.model_dump(exclude_none=True)
|
||||||
doc_ref.update(update_data)
|
doc_ref.update(update_data)
|
||||||
|
invalidate_mqtt_acl_cache(doc.to_dict()) # status may have changed
|
||||||
|
|
||||||
updated_doc = doc_ref.get()
|
updated_doc = doc_ref.get()
|
||||||
return _doc_to_user(updated_doc)
|
return _doc_to_user(updated_doc)
|
||||||
|
|
||||||
|
|
||||||
def delete_user(user_doc_id: str) -> None:
|
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()
|
db = get_db()
|
||||||
doc_ref = db.collection(COLLECTION).document(user_doc_id)
|
doc_ref = db.collection(COLLECTION).document(user_doc_id)
|
||||||
doc = doc_ref.get()
|
doc = doc_ref.get()
|
||||||
if not doc.exists:
|
if not doc.exists:
|
||||||
raise NotFoundError("User")
|
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()
|
doc_ref.delete()
|
||||||
|
invalidate_mqtt_acl_cache(doc.to_dict())
|
||||||
|
|
||||||
|
|
||||||
def block_user(user_doc_id: str) -> UserInDB:
|
def block_user(user_doc_id: str) -> UserInDB:
|
||||||
@@ -130,6 +201,7 @@ def block_user(user_doc_id: str) -> UserInDB:
|
|||||||
raise NotFoundError("User")
|
raise NotFoundError("User")
|
||||||
|
|
||||||
doc_ref.update({"status": "blocked"})
|
doc_ref.update({"status": "blocked"})
|
||||||
|
invalidate_mqtt_acl_cache(doc.to_dict())
|
||||||
updated_doc = doc_ref.get()
|
updated_doc = doc_ref.get()
|
||||||
return _doc_to_user(updated_doc)
|
return _doc_to_user(updated_doc)
|
||||||
|
|
||||||
@@ -143,6 +215,7 @@ def unblock_user(user_doc_id: str) -> UserInDB:
|
|||||||
raise NotFoundError("User")
|
raise NotFoundError("User")
|
||||||
|
|
||||||
doc_ref.update({"status": "active"})
|
doc_ref.update({"status": "active"})
|
||||||
|
invalidate_mqtt_acl_cache(doc.to_dict())
|
||||||
updated_doc = doc_ref.get()
|
updated_doc = doc_ref.get()
|
||||||
return _doc_to_user(updated_doc)
|
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:
|
if not device_doc.exists:
|
||||||
raise NotFoundError("Device")
|
raise NotFoundError("Device")
|
||||||
|
|
||||||
# Add user path to device's user_list if not already there
|
from devices import service as devices_service
|
||||||
|
|
||||||
|
# Add a user reference to device's user_list if not already there.
|
||||||
|
# Stored as a DocumentReference, the format the FlutterFlow app writes.
|
||||||
device_data = device_doc.to_dict()
|
device_data = device_doc.to_dict()
|
||||||
user_list = device_data.get("user_list", [])
|
user_list = device_data.get("user_list", []) or []
|
||||||
user_path = f"users/{user_doc_id}"
|
already_assigned = any(devices_service.user_list_entry_id(e) == user_doc_id for e in user_list)
|
||||||
|
|
||||||
# Check if already assigned (handle both string paths and DocumentReferences)
|
|
||||||
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
|
|
||||||
|
|
||||||
|
# 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:
|
if not already_assigned:
|
||||||
user_list.append(user_path)
|
user_list.append(user_ref)
|
||||||
device_ref.update({"user_list": user_list})
|
batch.update(device_ref, {"user_list": user_list})
|
||||||
|
stage_device_serial_link(batch, user_ref, device_serial_of(device_data), linked=True)
|
||||||
|
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())
|
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:
|
if not device_doc.exists:
|
||||||
raise NotFoundError("Device")
|
raise NotFoundError("Device")
|
||||||
|
|
||||||
# Remove user from device's user_list
|
from devices import service as devices_service
|
||||||
|
|
||||||
|
# Remove user from device's user_list (any entry format)
|
||||||
device_data = device_doc.to_dict()
|
device_data = device_doc.to_dict()
|
||||||
user_list = device_data.get("user_list", [])
|
user_list = device_data.get("user_list", []) or []
|
||||||
user_path = f"users/{user_doc_id}"
|
new_list = [e for e in user_list if devices_service.user_list_entry_id(e) != user_doc_id]
|
||||||
|
|
||||||
new_list = []
|
batch = db.batch()
|
||||||
for entry in user_list:
|
batch.update(device_ref, {"user_list": new_list})
|
||||||
if isinstance(entry, DocumentReference):
|
stage_device_serial_link(batch, user_ref, device_serial_of(device_data), linked=False)
|
||||||
if entry.path != user_path:
|
devices_service.stage_device_users_mirror(batch, device_ref, user_ref, linked=False)
|
||||||
new_list.append(entry)
|
batch.commit()
|
||||||
elif entry != user_path:
|
invalidate_mqtt_acl_cache(user_doc.to_dict())
|
||||||
new_list.append(entry)
|
|
||||||
|
|
||||||
device_ref.update({"user_list": new_list})
|
|
||||||
|
|
||||||
return _doc_to_user(user_ref.get())
|
return _doc_to_user(user_ref.get())
|
||||||
|
|
||||||
|
|
||||||
def get_user_devices(user_doc_id: str) -> list[dict]:
|
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()
|
db = get_db()
|
||||||
|
|
||||||
# Verify user exists
|
# Verify user exists
|
||||||
@@ -230,25 +302,32 @@ def get_user_devices(user_doc_id: str) -> list[dict]:
|
|||||||
if not user_doc.exists:
|
if not user_doc.exists:
|
||||||
raise NotFoundError("User")
|
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 = []
|
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()
|
data = doc.to_dict()
|
||||||
user_list = data.get("user_list", [])
|
devices.append({
|
||||||
|
"id": doc.id,
|
||||||
for entry in user_list:
|
"device_name": data.get("device_name", ""),
|
||||||
entry_path = entry.path if isinstance(entry, DocumentReference) else entry
|
"device_id": data.get("device_id", ""),
|
||||||
if entry_path == user_path:
|
"device_location": data.get("device_location", ""),
|
||||||
devices.append({
|
"is_Online": data.get("is_Online", False),
|
||||||
"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
|
|
||||||
|
|
||||||
return devices
|
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:
|
def set_password(user_doc_id: str, new_password: str) -> None:
|
||||||
"""Set a Firebase Auth password for a user via their Firestore document ID.
|
"""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.
|
automatically for users who registered via the Flutter app.
|
||||||
"""
|
"""
|
||||||
if not new_password or len(new_password) < 6:
|
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", "")
|
uid = doc.to_dict().get("uid", "")
|
||||||
if not 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:
|
try:
|
||||||
firebase_auth.update_user(uid, password=new_password)
|
firebase_auth.update_user(uid, password=new_password)
|
||||||
|
|||||||
@@ -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
|
||||||
@@ -2,6 +2,7 @@ services:
|
|||||||
backend:
|
backend:
|
||||||
build: ./backend
|
build: ./backend
|
||||||
container_name: bellsystems-backend
|
container_name: bellsystems-backend
|
||||||
|
restart: unless-stopped
|
||||||
env_file: .env
|
env_file: .env
|
||||||
volumes:
|
volumes:
|
||||||
- ./backend:/app
|
- ./backend:/app
|
||||||
@@ -22,12 +23,14 @@ services:
|
|||||||
frontend:
|
frontend:
|
||||||
build: ./frontend
|
build: ./frontend
|
||||||
container_name: bellsystems-frontend
|
container_name: bellsystems-frontend
|
||||||
|
restart: unless-stopped
|
||||||
networks:
|
networks:
|
||||||
- internal
|
- internal
|
||||||
|
|
||||||
nginx:
|
nginx:
|
||||||
image: nginx:alpine
|
image: nginx:alpine
|
||||||
container_name: bellsystems-nginx
|
container_name: bellsystems-nginx
|
||||||
|
restart: unless-stopped
|
||||||
ports:
|
ports:
|
||||||
- "90:80" # access v2 on localhost:8001
|
- "90:80" # access v2 on localhost:8001
|
||||||
volumes:
|
volumes:
|
||||||
@@ -47,6 +50,9 @@ services:
|
|||||||
POSTGRES_USER: ${POSTGRES_USER}
|
POSTGRES_USER: ${POSTGRES_USER}
|
||||||
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}
|
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}
|
||||||
volumes:
|
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
|
- ./data/postgres:/var/lib/postgresql/data
|
||||||
networks:
|
networks:
|
||||||
- internal
|
- internal
|
||||||
|
|||||||
@@ -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
|
||||||
|
```
|
||||||
@@ -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.
|
||||||
@@ -9,6 +9,7 @@ import { Link, useLocation, useNavigate } from 'react-router-dom'
|
|||||||
import { useAuth } from '@/hooks/useAuth'
|
import { useAuth } from '@/hooks/useAuth'
|
||||||
import api from '@/lib/api'
|
import api from '@/lib/api'
|
||||||
import HeaderSearch from '@/components/ui/HeaderSearch'
|
import HeaderSearch from '@/components/ui/HeaderSearch'
|
||||||
|
import { getLocalizedValue } from '@/lib/melodyUtils'
|
||||||
|
|
||||||
// ─── Breadcrumb config ────────────────────────────────────────────────────────
|
// ─── 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 },
|
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 },
|
products: { path: (id) => `/crm/products/${id}`, label: (d) => d.name || null },
|
||||||
quotations: { path: (id) => `/crm/quotations/${id}`, label: (d) => d.quotation_number || 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 },
|
orders: { path: (id) => `/crm/orders/${id}`, label: (d) => d.order_number || null },
|
||||||
melodies: { path: (id) => `/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) => d.name || 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 },
|
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 },
|
notes: { path: (id) => `/equipment/notes/${id}`, label: (d) => d.title || d.subject || null },
|
||||||
staff: { path: (id) => `/staff/${id}`, label: (d) => d.name || null },
|
staff: { path: (id) => `/staff/${id}`, label: (d) => d.name || null },
|
||||||
@@ -292,6 +293,16 @@ const SETTINGS_ITEMS = [
|
|||||||
</svg>
|
</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',
|
to: '/settings/pages',
|
||||||
label: 'Page Settings',
|
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>,
|
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} />,
|
blackBox: () => <SvgIcon Component={IcoBlackbox} />,
|
||||||
deviceSettings: () => <SvgIcon Component={IcoMelodySettings} />,
|
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>,
|
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} />,
|
melodies: () => <SvgIcon Component={IcoMelodies} />,
|
||||||
library: () => <SvgIcon Component={IcoMelodiesEditor} />,
|
library: () => <SvgIcon Component={IcoMelodiesEditor} />,
|
||||||
@@ -132,6 +133,7 @@ const navSections = [
|
|||||||
{ to: '/mqtt/commands', label: 'Command Center', icon: 'commandCenter' },
|
{ to: '/mqtt/commands', label: 'Command Center', icon: 'commandCenter' },
|
||||||
{ to: '/equipment/notes', label: 'BlackBox', icon: 'blackBox' },
|
{ to: '/equipment/notes', label: 'BlackBox', icon: 'blackBox' },
|
||||||
{ to: '/devices/settings', label: 'Device Settings', icon: 'deviceSettings', placeholder: true },
|
{ 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' },
|
{ 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 & 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>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -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>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -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>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -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>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -16,6 +16,7 @@
|
|||||||
|
|
||||||
import { useState, useRef, useEffect, Children, isValidElement } from 'react'
|
import { useState, useRef, useEffect, Children, isValidElement } from 'react'
|
||||||
import { createPortal } from 'react-dom'
|
import { createPortal } from 'react-dom'
|
||||||
|
import { computeFloatingMenuPosition } from '@/lib/floatingMenuPosition'
|
||||||
|
|
||||||
// Parse React <option> children into a flat [{value, label, disabled}] array
|
// Parse React <option> children into a flat [{value, label, disabled}] array
|
||||||
function parseOptions(children) {
|
function parseOptions(children) {
|
||||||
@@ -46,7 +47,7 @@ export default function Select({
|
|||||||
...props
|
...props
|
||||||
}) {
|
}) {
|
||||||
const [open, setOpen] = useState(false)
|
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 triggerRef = useRef(null)
|
||||||
const menuRef = useRef(null)
|
const menuRef = useRef(null)
|
||||||
|
|
||||||
@@ -105,8 +106,7 @@ export default function Select({
|
|||||||
function openMenu() {
|
function openMenu() {
|
||||||
if (disabled) return
|
if (disabled) return
|
||||||
if (triggerRef.current) {
|
if (triggerRef.current) {
|
||||||
const r = triggerRef.current.getBoundingClientRect()
|
setMenuPos(computeFloatingMenuPosition(triggerRef.current.getBoundingClientRect()))
|
||||||
setMenuPos({ top: r.bottom + 4, left: r.left, width: r.width })
|
|
||||||
}
|
}
|
||||||
setOpen(true)
|
setOpen(true)
|
||||||
}
|
}
|
||||||
@@ -130,7 +130,7 @@ export default function Select({
|
|||||||
<div
|
<div
|
||||||
ref={menuRef}
|
ref={menuRef}
|
||||||
className="select-menu"
|
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"
|
role="listbox"
|
||||||
aria-label="Options"
|
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 })}
|
||||||
|
/>
|
||||||
|
</>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -12,8 +12,9 @@
|
|||||||
// Each toast auto-dismisses after `duration` ms (default 4000).
|
// Each toast auto-dismisses after `duration` ms (default 4000).
|
||||||
// ToastProvider renders the stack itself via a portal — no extra component needed.
|
// 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 { createPortal } from 'react-dom'
|
||||||
|
import Spinner from '@/components/ui/Spinner'
|
||||||
|
|
||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
// Context
|
// Context
|
||||||
@@ -49,7 +50,7 @@ function ToastIcon({ variant }) {
|
|||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
// Single Toast item
|
// 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 [exiting, setExiting] = useState(false)
|
||||||
|
|
||||||
const dismiss = useCallback(() => {
|
const dismiss = useCallback(() => {
|
||||||
@@ -57,15 +58,21 @@ function ToastItem({ id, variant = 'info', title, message, duration = 4000, onDi
|
|||||||
setTimeout(() => onDismiss(id), 300)
|
setTimeout(() => onDismiss(id), 300)
|
||||||
}, [id, onDismiss])
|
}, [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 timerRef = useRef(null)
|
||||||
const startTimer = () => {
|
const startTimer = () => {
|
||||||
|
if (pending) return
|
||||||
timerRef.current = setTimeout(dismiss, duration)
|
timerRef.current = setTimeout(dismiss, duration)
|
||||||
}
|
}
|
||||||
const clearTimer = () => clearTimeout(timerRef.current)
|
const clearTimer = () => clearTimeout(timerRef.current)
|
||||||
|
|
||||||
// Start timer on mount
|
// (Re)start the timer whenever `pending` resolves to false, or on mount if already resolved
|
||||||
useState(() => { startTimer() })
|
useEffect(() => {
|
||||||
|
clearTimer()
|
||||||
|
startTimer()
|
||||||
|
return clearTimer
|
||||||
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
|
}, [pending, duration])
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
@@ -76,7 +83,7 @@ function ToastItem({ id, variant = 'info', title, message, duration = 4000, onDi
|
|||||||
onMouseLeave={startTimer}
|
onMouseLeave={startTimer}
|
||||||
>
|
>
|
||||||
<div className="toast-icon">
|
<div className="toast-icon">
|
||||||
<ToastIcon variant={variant} />
|
{pending ? <Spinner size="sm" /> : <ToastIcon variant={variant} />}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="toast-content">
|
<div className="toast-content">
|
||||||
@@ -94,11 +101,13 @@ function ToastItem({ id, variant = 'info', title, message, duration = 4000, onDi
|
|||||||
</svg>
|
</svg>
|
||||||
</button>
|
</button>
|
||||||
|
|
||||||
{/* Progress bar — shrinks over duration */}
|
{/* Progress bar — shrinks over duration. Hidden while pending (no timeout running). */}
|
||||||
<div
|
{!pending && (
|
||||||
className="toast-progress"
|
<div
|
||||||
style={{ animationDuration: `${duration}ms` }}
|
className="toast-progress"
|
||||||
/>
|
style={{ animationDuration: `${duration}ms` }}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -111,9 +120,9 @@ let _nextId = 1
|
|||||||
export function ToastProvider({ children }) {
|
export function ToastProvider({ children }) {
|
||||||
const [toasts, setToasts] = useState([])
|
const [toasts, setToasts] = useState([])
|
||||||
|
|
||||||
const addToast = useCallback((variant, title, message, duration) => {
|
const addToast = useCallback((variant, title, message, duration, pending = false) => {
|
||||||
const id = _nextId++
|
const id = _nextId++
|
||||||
setToasts((prev) => [...prev, { id, variant, title, message, duration }])
|
setToasts((prev) => [...prev, { id, variant, title, message, duration, pending }])
|
||||||
return id
|
return id
|
||||||
}, [])
|
}, [])
|
||||||
|
|
||||||
@@ -121,11 +130,20 @@ export function ToastProvider({ children }) {
|
|||||||
setToasts((prev) => prev.filter((t) => t.id !== id))
|
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 = {
|
const toast = {
|
||||||
success: (title, message, duration) => addToast('success', title, message, duration),
|
success: (title, message, duration) => addToast('success', title, message, duration),
|
||||||
danger: (title, message, duration) => addToast('danger', title, message, duration),
|
danger: (title, message, duration) => addToast('danger', title, message, duration),
|
||||||
warning: (title, message, duration) => addToast('warning', title, message, duration),
|
warning: (title, message, duration) => addToast('warning', title, message, duration),
|
||||||
info: (title, message, duration) => addToast('info', 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,
|
dismiss,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -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
|
||||||
@@ -1,2 +1,61 @@
|
|||||||
// TODO: implement
|
// frontend/src/hooks/useMqttWebSocket.js
|
||||||
export function useMqttWebSocket() {}
|
// 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
|
||||||
|
|||||||
@@ -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
|
||||||
@@ -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)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
@@ -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'
|
||||||
|
}
|
||||||
@@ -0,0 +1,113 @@
|
|||||||
|
// frontend/src/lib/deviceCache.js
|
||||||
|
// Last-known device data for stale-while-revalidate rendering.
|
||||||
|
//
|
||||||
|
// DeviceList and DeviceDetail paint instantly from whatever was fetched last
|
||||||
|
// (in this tab, or earlier in this browser session), then revalidate in the
|
||||||
|
// background and swap in fresh data silently. The backend's MQTT ingest keeps
|
||||||
|
// status current every ~30s, so the cached copy is almost always right; the
|
||||||
|
// background fetch just confirms it.
|
||||||
|
//
|
||||||
|
// Kept in memory (survives in-app navigation) and mirrored to sessionStorage
|
||||||
|
// (survives a page reload in the same tab). Storage can be unavailable or
|
||||||
|
// full — every access is wrapped so the cache silently degrades to memory-only.
|
||||||
|
|
||||||
|
const STORAGE_KEY = 'bs.deviceCache.v1'
|
||||||
|
|
||||||
|
function load() {
|
||||||
|
try {
|
||||||
|
const raw = sessionStorage.getItem(STORAGE_KEY)
|
||||||
|
if (raw) return JSON.parse(raw)
|
||||||
|
} catch { /* unavailable / corrupt — start empty */ }
|
||||||
|
return {}
|
||||||
|
}
|
||||||
|
|
||||||
|
const state = {
|
||||||
|
devicesByQuery: {}, // list query string -> devices[]
|
||||||
|
deviceById: {}, // firestore doc id -> device
|
||||||
|
statusMap: null, // serial -> /mqtt/status entry
|
||||||
|
diagMap: null, // serial -> latest diagnostics (list columns)
|
||||||
|
pingMap: null, // serial -> latest ping sample (list columns)
|
||||||
|
healthByKey: {}, // `${sn}|${rangeKey}` -> Health overview datasets
|
||||||
|
...load(),
|
||||||
|
}
|
||||||
|
|
||||||
|
let persistTimer = null
|
||||||
|
function persist() {
|
||||||
|
// Coalesce bursts (e.g. a heartbeat per device) into one write.
|
||||||
|
if (persistTimer) return
|
||||||
|
persistTimer = setTimeout(() => {
|
||||||
|
persistTimer = null
|
||||||
|
try {
|
||||||
|
// Health datasets can be thousands of rows — memory only.
|
||||||
|
const { healthByKey, ...rest } = state
|
||||||
|
sessionStorage.setItem(STORAGE_KEY, JSON.stringify(rest))
|
||||||
|
} catch { /* quota / unavailable — memory cache still works */ }
|
||||||
|
}, 500)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Device list ──────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
export function getCachedDevices(query) {
|
||||||
|
return state.devicesByQuery[query] || null
|
||||||
|
}
|
||||||
|
|
||||||
|
export function setCachedDevices(query, devices) {
|
||||||
|
state.devicesByQuery[query] = devices
|
||||||
|
for (const d of devices) if (d?.id) state.deviceById[d.id] = d
|
||||||
|
persist()
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Single device ────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
export function getCachedDevice(id) {
|
||||||
|
return state.deviceById[id] || null
|
||||||
|
}
|
||||||
|
|
||||||
|
export function setCachedDevice(device) {
|
||||||
|
if (!device?.id) return
|
||||||
|
state.deviceById[device.id] = device
|
||||||
|
persist()
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── MQTT status ──────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
export function getCachedStatusMap() {
|
||||||
|
return state.statusMap
|
||||||
|
}
|
||||||
|
|
||||||
|
export function setCachedStatusMap(map) {
|
||||||
|
state.statusMap = map
|
||||||
|
persist()
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getCachedStatus(serial) {
|
||||||
|
return (serial && state.statusMap?.[serial]) || null
|
||||||
|
}
|
||||||
|
|
||||||
|
export function setCachedStatus(serial, status) {
|
||||||
|
if (!serial) return
|
||||||
|
state.statusMap = { ...(state.statusMap || {}), [serial]: status }
|
||||||
|
persist()
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Latest metrics (list columns) ────────────────────────────────────────────
|
||||||
|
|
||||||
|
export function getCachedMetrics() {
|
||||||
|
return { diagMap: state.diagMap, pingMap: state.pingMap }
|
||||||
|
}
|
||||||
|
|
||||||
|
export function setCachedMetrics(diagMap, pingMap) {
|
||||||
|
state.diagMap = diagMap
|
||||||
|
state.pingMap = pingMap
|
||||||
|
persist()
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Health overview datasets ─────────────────────────────────────────────────
|
||||||
|
|
||||||
|
export function getCachedHealth(key) {
|
||||||
|
return state.healthByKey[key] || null
|
||||||
|
}
|
||||||
|
|
||||||
|
export function setCachedHealth(key, data) {
|
||||||
|
state.healthByKey[key] = data
|
||||||
|
}
|
||||||
@@ -0,0 +1,324 @@
|
|||||||
|
// frontend/src/lib/deviceConfigDiff.js
|
||||||
|
// Compares what the console has SAVED (Firestore) against what the device
|
||||||
|
// actually has STORED (its *.get_config replies), setting by setting.
|
||||||
|
//
|
||||||
|
// Every builder returns rows for the ConfigConflictModal:
|
||||||
|
// { key, label, group, saved, device, differs, patch }
|
||||||
|
// saved / device — display strings for each side
|
||||||
|
// differs — true when the two sides really disagree
|
||||||
|
// patch — device_attributes fragment that makes Firestore match the
|
||||||
|
// device for THIS row only ("Keep device version")
|
||||||
|
//
|
||||||
|
// Nothing here writes anything — callers decide what to do with the rows.
|
||||||
|
|
||||||
|
// ─── Shared helpers ───────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
const onOff = (v) => (v ? 'Enabled' : 'Disabled')
|
||||||
|
|
||||||
|
function row(key, label, group, savedVal, deviceVal, fmt, patch) {
|
||||||
|
return {
|
||||||
|
key,
|
||||||
|
label,
|
||||||
|
group,
|
||||||
|
saved: fmt(savedVal),
|
||||||
|
device: fmt(deviceVal),
|
||||||
|
differs: savedVal !== deviceVal,
|
||||||
|
patch,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function isPlainObject(v) {
|
||||||
|
return v !== null && typeof v === 'object' && !Array.isArray(v)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Merge row patches into one device_attributes object (later rows win per leaf). */
|
||||||
|
export function mergePatches(rows) {
|
||||||
|
const out = {}
|
||||||
|
const merge = (target, src) => {
|
||||||
|
for (const [k, v] of Object.entries(src)) {
|
||||||
|
if (isPlainObject(v)) {
|
||||||
|
if (!isPlainObject(target[k])) target[k] = {}
|
||||||
|
merge(target[k], v)
|
||||||
|
} else {
|
||||||
|
target[k] = v
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
rows.forEach((r) => r.patch && merge(out, r.patch))
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── Bells ────────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
// 0 and 65535 (the firmware's uint16 "unset") both mean "no output assigned".
|
||||||
|
const normOutput = (o) => {
|
||||||
|
const n = Number(o)
|
||||||
|
return !Number.isFinite(n) || n === 65535 ? 0 : n
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The device keeps a fixed set of bell channels (typically 16). Bell index is
|
||||||
|
* meaningful (melodies map notes to bell numbers), so channels are compared
|
||||||
|
* index-by-index — never compacted.
|
||||||
|
*/
|
||||||
|
export function bellDeviceView(data) {
|
||||||
|
const outputs = data?.outputs || {}
|
||||||
|
const durations = data?.durations || {}
|
||||||
|
const indexes = [...Object.keys(outputs), ...Object.keys(durations)]
|
||||||
|
.map(Number)
|
||||||
|
.filter(Number.isInteger)
|
||||||
|
const channels = indexes.length ? Math.max(...indexes) + 1 : 0
|
||||||
|
let lastAssigned = -1
|
||||||
|
for (let i = 0; i < channels; i++) if (normOutput(outputs[i]) > 0) lastAssigned = i
|
||||||
|
return {
|
||||||
|
enabled: !!data?.bells_enabled,
|
||||||
|
channels,
|
||||||
|
lastAssigned,
|
||||||
|
output: (i) => normOutput(outputs[i]),
|
||||||
|
duration: (i) => (durations[i] != null ? Number(durations[i]) : null),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function bellSaved(attr) {
|
||||||
|
const outputs = (attr?.bellOutputs || []).map(normOutput)
|
||||||
|
const timings = attr?.hammerTimings || []
|
||||||
|
return {
|
||||||
|
count: outputs.length,
|
||||||
|
output: (i) => (i < outputs.length ? outputs[i] : 0),
|
||||||
|
timing: (i) => (timings[i] != null ? Number(timings[i]) : null),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const bellLabel = (output, ms) =>
|
||||||
|
output === 0 ? 'Disabled' : `Output ${output} · ${ms != null ? `${ms} ms` : '—'}`
|
||||||
|
|
||||||
|
/** How many bell rows to compare: every saved bell + every bell the device has wired. */
|
||||||
|
export function bellRowCount(attr, data) {
|
||||||
|
return Math.max(bellSaved(attr).count, bellDeviceView(data).lastAssigned + 1)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function buildBellRows(attr, data) {
|
||||||
|
const dev = bellDeviceView(data)
|
||||||
|
const saved = bellSaved(attr)
|
||||||
|
const count = bellRowCount(attr, data)
|
||||||
|
|
||||||
|
// Firestore stores the bells as whole lists, so "keep device" for any bell
|
||||||
|
// rewrites those lists (and only those) from the device's channels.
|
||||||
|
const listsPatch = {
|
||||||
|
totalBells: count,
|
||||||
|
bellOutputs: Array.from({ length: count }, (_, i) => dev.output(i)),
|
||||||
|
hammerTimings: Array.from({ length: count }, (_, i) => dev.duration(i) ?? saved.timing(i) ?? 90),
|
||||||
|
}
|
||||||
|
|
||||||
|
const rows = [
|
||||||
|
row('hasBells', 'Bell Commander', 'commander', !!attr?.hasBells, dev.enabled, onOff, { hasBells: dev.enabled }),
|
||||||
|
]
|
||||||
|
for (let i = 0; i < count; i++) {
|
||||||
|
const so = saved.output(i)
|
||||||
|
const st = saved.timing(i)
|
||||||
|
const dout = dev.output(i)
|
||||||
|
const dt = dev.duration(i)
|
||||||
|
rows.push({
|
||||||
|
key: `bell-${i}`,
|
||||||
|
label: `Bell ${i + 1}`,
|
||||||
|
group: 'bells',
|
||||||
|
saved: i < saved.count ? bellLabel(so, st) : 'Not configured',
|
||||||
|
device: bellLabel(dout, dt),
|
||||||
|
// Timing only matters for a bell that's actually wired on both sides.
|
||||||
|
differs: so !== dout || (so > 0 && dout > 0 && st !== dt),
|
||||||
|
patch: listsPatch,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
return rows
|
||||||
|
}
|
||||||
|
|
||||||
|
/** relay.set_config contents that make the device match the saved bells. */
|
||||||
|
export function bellPushContents(attr, data) {
|
||||||
|
const dev = bellDeviceView(data)
|
||||||
|
const saved = bellSaved(attr)
|
||||||
|
// relay.set_config is a partial update: every channel past the saved list
|
||||||
|
// must be sent explicitly as 0, or a stale output stays wired on the device.
|
||||||
|
const channels = Math.max(dev.channels, saved.count)
|
||||||
|
const outputs = {}
|
||||||
|
const durations = {}
|
||||||
|
for (let i = 0; i < channels; i++) {
|
||||||
|
outputs[i] = saved.output(i)
|
||||||
|
const t = saved.timing(i)
|
||||||
|
if (i < saved.count && Number.isFinite(t)) durations[i] = t
|
||||||
|
}
|
||||||
|
return { outputs, durations }
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── Clock ────────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
/** "HH:MM" from a stored timestamp / time string, or null. */
|
||||||
|
export function extractTime(tsStr) {
|
||||||
|
if (!tsStr) return null
|
||||||
|
const d = new Date(
|
||||||
|
String(tsStr).replace(' at ', ' ').replace('UTC+0000', 'UTC').replace(/UTC\+(\d{4})/, 'UTC')
|
||||||
|
)
|
||||||
|
if (!isNaN(d.getTime())) {
|
||||||
|
return `${d.getUTCHours().toString().padStart(2, '0')}:${d.getUTCMinutes().toString().padStart(2, '0')}`
|
||||||
|
}
|
||||||
|
const match = String(tsStr).match(/(\d{1,2}):(\d{2})/)
|
||||||
|
return match ? `${match[1].padStart(2, '0')}:${match[2]}` : null
|
||||||
|
}
|
||||||
|
|
||||||
|
const timeToIso = (hhmm) => (hhmm ? `2000-01-01T${hhmm}:00Z` : null)
|
||||||
|
const deviceTime = (v) => (v ? extractTime(v) : null)
|
||||||
|
|
||||||
|
const ALERT_FROM_FW = { OFF: 'disabled', SINGLE: 'single', HOURS: 'multi' }
|
||||||
|
export const ALERT_TO_FW = { disabled: 'OFF', single: 'SINGLE', multi: 'HOURS' }
|
||||||
|
const ALERT_LABEL = { disabled: 'Disabled', single: 'Single strike', multi: 'Hour indicating' }
|
||||||
|
const FACE_SYNC_LABEL = { force: 'Force', smart: 'Smart' }
|
||||||
|
|
||||||
|
const fwBell = (v) => (v === 255 ? 0 : Number(v) || 0)
|
||||||
|
export const toFwBell = (n) => (n === 0 ? 255 : n)
|
||||||
|
|
||||||
|
const fmtOutput = (o) => (o ? `Output ${o}` : 'None')
|
||||||
|
const fmtBell = (b) => (b ? `Bell ${b}` : 'None')
|
||||||
|
const fmtMs = (ms) => (ms ? `${ms} ms` : '—')
|
||||||
|
const fmtTime = (t) => t || '—'
|
||||||
|
|
||||||
|
export function buildClockRows(attr, clock, data) {
|
||||||
|
const c = clock || {}
|
||||||
|
const d = data || {}
|
||||||
|
const rows = []
|
||||||
|
|
||||||
|
// ── Clock mechanism (clock.set_config) ──
|
||||||
|
const devC1 = Number(d.c1output) || 0
|
||||||
|
const devC2 = Number(d.c2output) || 0
|
||||||
|
const devPulse = Number(d.pulse_duration) || 0
|
||||||
|
const devPause = Number(d.pause_duration) || 0
|
||||||
|
// Positional (odd, even) — never filtered, or an unassigned odd output would
|
||||||
|
// shift the even one into its slot and the two would never compare equal.
|
||||||
|
const outputsPatch = { clockSettings: { clockOutputs: [devC1, devC2] } }
|
||||||
|
const timingsPatch = { clockSettings: { clockTimings: [devPulse, devPause] } }
|
||||||
|
|
||||||
|
rows.push(row('hasClock', 'Clock', 'config', !!attr?.hasClock, !!d.enabled, onOff, { hasClock: !!d.enabled }))
|
||||||
|
rows.push(row('c1', 'Odd output', 'config', Number(c.clockOutputs?.[0]) || 0, devC1, fmtOutput, outputsPatch))
|
||||||
|
rows.push(row('c2', 'Even output', 'config', Number(c.clockOutputs?.[1]) || 0, devC2, fmtOutput, outputsPatch))
|
||||||
|
rows.push(row('pulse', 'Run pulse', 'config', Number(c.clockTimings?.[0]) || 0, devPulse, fmtMs, timingsPatch))
|
||||||
|
rows.push(row('pause', 'Pause', 'config', Number(c.clockTimings?.[1]) || 0, devPause, fmtMs, timingsPatch))
|
||||||
|
if (d.face_sync_mode != null) {
|
||||||
|
rows.push(row('faceSync', 'Face sync mode', 'config', c.faceSyncMode || 'force', d.face_sync_mode,
|
||||||
|
(v) => FACE_SYNC_LABEL[v] || v, { clockSettings: { faceSyncMode: d.face_sync_mode } }))
|
||||||
|
}
|
||||||
|
if (d.smart_max_wait_min != null) {
|
||||||
|
rows.push(row('maxWait', 'Smart sync max wait', 'config', c.smartMaxWaitMin ?? 61, d.smart_max_wait_min,
|
||||||
|
(v) => `${v} min`, { clockSettings: { smartMaxWaitMin: d.smart_max_wait_min } }))
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Alerts & silence (clock.set_alerts_config) ──
|
||||||
|
const savedAlert = c.ringAlerts || 'disabled'
|
||||||
|
const devAlert = ALERT_FROM_FW[d.alert_type] ?? 'disabled'
|
||||||
|
rows.push(row('ringAlerts', 'Alerts', 'alerts', savedAlert, devAlert,
|
||||||
|
(v) => ALERT_LABEL[v] || v, { clockSettings: { ringAlerts: devAlert } }))
|
||||||
|
if (savedAlert === 'multi' || devAlert === 'multi') {
|
||||||
|
rows.push(row('ringIntervals', 'Alert tempo', 'alerts', c.ringIntervals ?? null, d.alert_interval ?? null,
|
||||||
|
fmtMs, { clockSettings: { ringIntervals: d.alert_interval ?? null } }))
|
||||||
|
}
|
||||||
|
rows.push(row('hourBell', 'Hour bell', 'alerts', Number(c.hourAlertsBell) || 0, fwBell(d.hour_bell),
|
||||||
|
fmtBell, { clockSettings: { hourAlertsBell: fwBell(d.hour_bell) } }))
|
||||||
|
rows.push(row('halfBell', 'Half-hour bell', 'alerts', Number(c.halfhourAlertsBell) || 0, fwBell(d.half_bell),
|
||||||
|
fmtBell, { clockSettings: { halfhourAlertsBell: fwBell(d.half_bell) } }))
|
||||||
|
rows.push(row('quarterBell', 'Quarter bell', 'alerts', Number(c.quarterAlertsBell) || 0, fwBell(d.quarter_bell),
|
||||||
|
fmtBell, { clockSettings: { quarterAlertsBell: fwBell(d.quarter_bell) } }))
|
||||||
|
|
||||||
|
const silence = (prefix, label, savedOn, devOn, savedFrom, savedTo, devFrom, devTo, keys) => {
|
||||||
|
rows.push(row(`${prefix}On`, label, 'alerts', !!savedOn, !!devOn, onOff, { clockSettings: { [keys.on]: !!devOn } }))
|
||||||
|
// Window times only matter while the silence is on (on either side).
|
||||||
|
if (savedOn || devOn) {
|
||||||
|
rows.push(row(`${prefix}From`, `${label} from`, 'alerts', extractTime(savedFrom), deviceTime(devFrom),
|
||||||
|
fmtTime, { clockSettings: { [keys.from]: timeToIso(deviceTime(devFrom)) } }))
|
||||||
|
rows.push(row(`${prefix}To`, `${label} until`, 'alerts', extractTime(savedTo), deviceTime(devTo),
|
||||||
|
fmtTime, { clockSettings: { [keys.to]: timeToIso(deviceTime(devTo)) } }))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
silence('day', 'Day silence', c.isDaySilenceOn, d.daytime_silence, c.daySilenceFrom, c.daySilenceTo,
|
||||||
|
d.daytime_on, d.daytime_off, { on: 'isDaySilenceOn', from: 'daySilenceFrom', to: 'daySilenceTo' })
|
||||||
|
silence('night', 'Night silence', c.isNightSilenceOn, d.night_silence, c.nightSilenceFrom, c.nightSilenceTo,
|
||||||
|
d.night_on, d.night_off, { on: 'isNightSilenceOn', from: 'nightSilenceFrom', to: 'nightSilenceTo' })
|
||||||
|
|
||||||
|
// ── Backlight (clock.set_backlight) ──
|
||||||
|
const savedBl = !!c.isBacklightAutomationOn
|
||||||
|
const devBl = !!d.backlight
|
||||||
|
rows.push(row('backlight', 'Backlight automation', 'backlight', savedBl, devBl, onOff,
|
||||||
|
{ clockSettings: { isBacklightAutomationOn: devBl } }))
|
||||||
|
rows.push(row('backlightOutput', 'Backlight output', 'backlight', Number(c.backlightOutput) || 0,
|
||||||
|
fwBell(d.backlight_output), fmtOutput, { clockSettings: { backlightOutput: fwBell(d.backlight_output) } }))
|
||||||
|
if (savedBl || devBl) {
|
||||||
|
rows.push(row('backlightOn', 'Backlight on at', 'backlight', extractTime(c.backlightTurnOnTime),
|
||||||
|
deviceTime(d.backlight_on), fmtTime, { clockSettings: { backlightTurnOnTime: timeToIso(deviceTime(d.backlight_on)) } }))
|
||||||
|
rows.push(row('backlightOff', 'Backlight off at', 'backlight', extractTime(c.backlightTurnOffTime),
|
||||||
|
deviceTime(d.backlight_off), fmtTime, { clockSettings: { backlightTurnOffTime: timeToIso(deviceTime(d.backlight_off)) } }))
|
||||||
|
}
|
||||||
|
|
||||||
|
return rows
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The device commands that push the SAVED clock settings, one per differing group. */
|
||||||
|
export function clockPushCommands(attr, clock, differingGroups) {
|
||||||
|
const c = clock || {}
|
||||||
|
const cmds = []
|
||||||
|
if (differingGroups.has('config')) {
|
||||||
|
const faceSync = c.faceSyncMode || 'force'
|
||||||
|
const pulse = Number(c.clockTimings?.[0]) || 0
|
||||||
|
const pause = Number(c.clockTimings?.[1]) || 0
|
||||||
|
cmds.push(['clock.set_config', {
|
||||||
|
enabled: !!attr?.hasClock,
|
||||||
|
c1: Number(c.clockOutputs?.[0]) || 0,
|
||||||
|
c2: Number(c.clockOutputs?.[1]) || 0,
|
||||||
|
...(pulse ? { pulse_duration: pulse } : {}),
|
||||||
|
...(pause ? { pause_duration: pause } : {}),
|
||||||
|
face_sync_mode: faceSync,
|
||||||
|
...(faceSync === 'smart' ? { smart_max_wait_min: c.smartMaxWaitMin ?? 61 } : {}),
|
||||||
|
}])
|
||||||
|
}
|
||||||
|
if (differingGroups.has('alerts')) {
|
||||||
|
const alert = c.ringAlerts || 'disabled'
|
||||||
|
const dayOn = !!c.isDaySilenceOn
|
||||||
|
const nightOn = !!c.isNightSilenceOn
|
||||||
|
cmds.push(['clock.set_alerts_config', {
|
||||||
|
alert_type: ALERT_TO_FW[alert],
|
||||||
|
alert_interval: alert === 'multi' ? c.ringIntervals : undefined,
|
||||||
|
hour_bell: toFwBell(Number(c.hourAlertsBell) || 0),
|
||||||
|
half_bell: toFwBell(Number(c.halfhourAlertsBell) || 0),
|
||||||
|
quarter_bell: toFwBell(Number(c.quarterAlertsBell) || 0),
|
||||||
|
daytime_silence: dayOn,
|
||||||
|
daytime_on: dayOn ? extractTime(c.daySilenceFrom) ?? undefined : undefined,
|
||||||
|
daytime_off: dayOn ? extractTime(c.daySilenceTo) ?? undefined : undefined,
|
||||||
|
night_silence: nightOn,
|
||||||
|
night_on: nightOn ? extractTime(c.nightSilenceFrom) ?? undefined : undefined,
|
||||||
|
night_off: nightOn ? extractTime(c.nightSilenceTo) ?? undefined : undefined,
|
||||||
|
}])
|
||||||
|
}
|
||||||
|
if (differingGroups.has('backlight')) {
|
||||||
|
const on = !!c.isBacklightAutomationOn
|
||||||
|
cmds.push(['clock.set_backlight', {
|
||||||
|
backlight: on,
|
||||||
|
backlight_output: Number(c.backlightOutput) || 0,
|
||||||
|
backlight_on: on ? extractTime(c.backlightTurnOnTime) ?? undefined : undefined,
|
||||||
|
backlight_off: on ? extractTime(c.backlightTurnOffTime) ?? undefined : undefined,
|
||||||
|
}])
|
||||||
|
}
|
||||||
|
return cmds
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── Log levels ───────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
const LOG_LEVEL_NAMES = ['Disabled', 'Error', 'Warning', 'Info', 'Debug', 'Verbose']
|
||||||
|
const fmtLevel = (l) => `${LOG_LEVEL_NAMES[l] ?? l} (${l})`
|
||||||
|
|
||||||
|
export const LOG_FIELDS = [
|
||||||
|
{ key: 'serial', label: 'Serial log', attr: 'serialLogLevel', device: 'serial_level', cmd: 'log.set_serial' },
|
||||||
|
{ key: 'sd', label: 'SD storage', attr: 'sdLogLevel', device: 'sd_level', cmd: 'log.set_sd' },
|
||||||
|
{ key: 'mqtt', label: 'MQTT sync', attr: 'mqttLogLevel', device: 'mqtt_level', cmd: 'log.set_mqtt' },
|
||||||
|
]
|
||||||
|
|
||||||
|
export function buildLogRows(attr, data) {
|
||||||
|
return LOG_FIELDS
|
||||||
|
.filter((f) => data?.[f.device] != null)
|
||||||
|
.map((f) => row(f.key, f.label, f.key, Number(attr?.[f.attr] ?? 0), Number(data[f.device]),
|
||||||
|
fmtLevel, { [f.attr]: Number(data[f.device]) }))
|
||||||
|
}
|
||||||
@@ -0,0 +1,120 @@
|
|||||||
|
// frontend/src/lib/deviceTimezone.js
|
||||||
|
// Helpers for device clock timezones (firmware 3.0.0+, project-vesper F-079).
|
||||||
|
//
|
||||||
|
// The device RTC holds UTC; a timezone object tells it how to show local time:
|
||||||
|
// { mode: 'auto', name, posix } — DST switches by itself
|
||||||
|
// { mode: 'manual', name, std_offset_min, dst_offset_min, dst_start, dst_end } — one DST season
|
||||||
|
// { mode: 'fixed', name, std_offset_min, dst_offset_min } — never switches
|
||||||
|
// { mode: 'local' } — offset 0, no NTP
|
||||||
|
// Offsets are minutes EAST of UTC. dst_start / dst_end are UTC epoch seconds.
|
||||||
|
// The rule list comes from the backend (GET /api/public/timezones, docs/device-timezones.md).
|
||||||
|
|
||||||
|
import api from '@/lib/api'
|
||||||
|
import { fmtUtcOffset } from '@/lib/formatters'
|
||||||
|
|
||||||
|
export const TZ_MODES = [
|
||||||
|
{ value: 'auto', label: 'Automatic' },
|
||||||
|
{ value: 'manual', label: 'Manual DST' },
|
||||||
|
{ value: 'fixed', label: 'Fixed offset' },
|
||||||
|
{ value: 'local', label: 'Local only' },
|
||||||
|
]
|
||||||
|
|
||||||
|
export const TZ_MODE_LABELS = Object.fromEntries(TZ_MODES.map(m => [m.value, m.label]))
|
||||||
|
|
||||||
|
// UTC-12:00 … UTC+14:00 in 15-minute steps (covers Nepal +5:45, Chatham +12:45)
|
||||||
|
export const STD_OFFSET_OPTIONS = Array.from({ length: (840 + 720) / 15 + 1 }, (_, i) => {
|
||||||
|
const value = -720 + i * 15
|
||||||
|
return { value, label: fmtUtcOffset(value) }
|
||||||
|
})
|
||||||
|
|
||||||
|
export const DST_AMOUNT_OPTIONS = [
|
||||||
|
{ value: 30, label: '+30 min' },
|
||||||
|
{ value: 60, label: '+1 hour' },
|
||||||
|
{ value: 120, label: '+2 hours' },
|
||||||
|
]
|
||||||
|
|
||||||
|
export const MONTHS = ['January', 'February', 'March', 'April', 'May', 'June', 'July',
|
||||||
|
'August', 'September', 'October', 'November', 'December']
|
||||||
|
export const WEEKS = [
|
||||||
|
{ value: 1, label: '1st' }, { value: 2, label: '2nd' }, { value: 3, label: '3rd' },
|
||||||
|
{ value: 4, label: '4th' }, { value: 5, label: 'Last' },
|
||||||
|
]
|
||||||
|
export const WEEKDAYS = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']
|
||||||
|
|
||||||
|
// ── Timezone table (cached for the session) ───────────────────────────────────
|
||||||
|
|
||||||
|
let tablePromise = null
|
||||||
|
|
||||||
|
/** { tzdata_version, countries: [{ code, name, zones: [...] }] } — fetched once. */
|
||||||
|
export function loadTimezoneTable() {
|
||||||
|
if (!tablePromise) {
|
||||||
|
tablePromise = api.get('/public/timezones').catch(err => {
|
||||||
|
tablePromise = null // allow a retry after a failure
|
||||||
|
throw err
|
||||||
|
})
|
||||||
|
}
|
||||||
|
return tablePromise
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The country containing an IANA zone, or null. */
|
||||||
|
export function findCountryOfZone(table, zoneName) {
|
||||||
|
return table?.countries.find(c => c.zones.some(z => z.name === zoneName)) || null
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── POSIX rule builder (custom recurring DST) ─────────────────────────────────
|
||||||
|
|
||||||
|
// POSIX offsets are WEST-positive h[:mm] — the opposite sign of our minutes-east values.
|
||||||
|
function posixOffset(minutesEast) {
|
||||||
|
const west = -minutesEast
|
||||||
|
const sign = west < 0 ? '-' : ''
|
||||||
|
const abs = Math.abs(west)
|
||||||
|
const mm = abs % 60
|
||||||
|
return `${sign}${Math.floor(abs / 60)}${mm ? `:${String(mm).padStart(2, '0')}` : ''}`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Abbreviation for a numeric offset: "<+02>", "<+0545>", "<-03>"
|
||||||
|
function posixName(minutesEast) {
|
||||||
|
const sign = minutesEast < 0 ? '-' : '+'
|
||||||
|
const abs = Math.abs(minutesEast)
|
||||||
|
const mm = abs % 60
|
||||||
|
return `<${sign}${String(Math.floor(abs / 60)).padStart(2, '0')}${mm ? String(mm).padStart(2, '0') : ''}>`
|
||||||
|
}
|
||||||
|
|
||||||
|
// "HH:MM" → "/H" or "/H:MM"
|
||||||
|
function posixTime(hhmm) {
|
||||||
|
const [h, m] = hhmm.split(':').map(Number)
|
||||||
|
return `/${h}${m ? `:${String(m).padStart(2, '0')}` : ''}`
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Builds a POSIX TZ rule for a recurring DST schedule, e.g. std +120, DST +60,
|
||||||
|
* last Sunday of March 03:00 → last Sunday of October 04:00:
|
||||||
|
* "<+02>-2<+03>,M3.5.0/3,M10.5.0/4"
|
||||||
|
* `start.time` is local standard time, `end.time` local DST time (POSIX convention).
|
||||||
|
* dstAmountMin 0 → no DST part.
|
||||||
|
*/
|
||||||
|
export function buildPosixRule({ stdOffsetMin, dstAmountMin, start, end }) {
|
||||||
|
const std = `${posixName(stdOffsetMin)}${posixOffset(stdOffsetMin)}`
|
||||||
|
if (!dstAmountMin) return std
|
||||||
|
const total = stdOffsetMin + dstAmountMin
|
||||||
|
const dst = `${posixName(total)}${dstAmountMin === 60 ? '' : posixOffset(total)}`
|
||||||
|
const date = r => `M${r.month}.${r.week}.${r.weekday}${posixTime(r.time)}`
|
||||||
|
return `${std}${dst},${date(start)},${date(end)}`
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Wall-clock helpers ────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
/** "2026-03-29T03:00[:SS]" → epoch seconds, read as if it were UTC (no browser timezone). */
|
||||||
|
export function wallClockToEpoch(value) {
|
||||||
|
if (!value) return null
|
||||||
|
const ms = Date.parse(`${value.length === 16 ? `${value}:00` : value}Z`)
|
||||||
|
return Number.isNaN(ms) ? null : Math.floor(ms / 1000)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Epoch seconds → "YYYY-MM-DDTHH:MM" wall clock at the given offset (for datetime-local inputs). */
|
||||||
|
export function epochToWallClock(utcSeconds, offsetMin) {
|
||||||
|
if (!utcSeconds) return ''
|
||||||
|
// toISOString() is intentional here: the epoch is already shifted to the device's wall
|
||||||
|
// clock, so reading it back as UTC gives exactly those fields (no browser timezone involved).
|
||||||
|
return new Date((utcSeconds + offsetMin * 60) * 1000).toISOString().slice(0, 16)
|
||||||
|
}
|
||||||
@@ -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 }),
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -110,6 +110,14 @@ export function fmtTime24(iso) {
|
|||||||
return d.toLocaleTimeString(LOCALE_LONG, { hour: '2-digit', minute: '2-digit', second: '2-digit', hour12: false })
|
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. */
|
/** Relative time: "just now", "5 minutes ago", "3 days ago", etc. */
|
||||||
export function fmtRelative(iso) {
|
export function fmtRelative(iso) {
|
||||||
const d = safeDate(iso)
|
const d = safeDate(iso)
|
||||||
@@ -167,3 +175,35 @@ export function fmtEuro(n) {
|
|||||||
const f = parseFloat(n) || 0
|
const f = parseFloat(n) || 0
|
||||||
return f.toLocaleString('el-GR', { minimumFractionDigits: 2, maximumFractionDigits: 2 }) + ' €'
|
return f.toLocaleString('el-GR', { minimumFractionDigits: 2, maximumFractionDigits: 2 }) + ' €'
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ─── Device wall-clock time ──────────────────────────────────────────────────
|
||||||
|
// A device's local time is in the DEVICE's timezone, not the browser's. These never
|
||||||
|
// convert through the browser timezone: they format wall-clock values as devices report
|
||||||
|
// them (firmware 3.0.0+: "local": "2026-10-28T14:05:00", or a UTC epoch + offset).
|
||||||
|
|
||||||
|
// Formats in UTC so the wall-clock fields come out untouched
|
||||||
|
const WALL_DATETIME = new Intl.DateTimeFormat(LOCALE_LONG, {
|
||||||
|
day: 'numeric', month: 'short', year: 'numeric',
|
||||||
|
hour: '2-digit', minute: '2-digit', hour12: false, timeZone: 'UTC',
|
||||||
|
})
|
||||||
|
|
||||||
|
/** "28 Oct 2026, 14:05" — a device wall-clock string "2026-10-28T14:05:00" */
|
||||||
|
export function fmtWallClock(localIso) {
|
||||||
|
if (!localIso) return '—'
|
||||||
|
const d = safeDate(`${localIso}Z`)
|
||||||
|
return d ? WALL_DATETIME.format(d) : '—'
|
||||||
|
}
|
||||||
|
|
||||||
|
/** "28 Oct 2026, 14:05" — a UTC epoch (seconds) shown in a device's local time */
|
||||||
|
export function fmtDeviceDateTime(utcSeconds, offsetMin) {
|
||||||
|
if (!utcSeconds) return '—'
|
||||||
|
return WALL_DATETIME.format(new Date((utcSeconds + (offsetMin || 0) * 60) * 1000))
|
||||||
|
}
|
||||||
|
|
||||||
|
/** "UTC+02:00" / "UTC-03:30" — minutes east of UTC */
|
||||||
|
export function fmtUtcOffset(minutes) {
|
||||||
|
if (minutes == null) return '—'
|
||||||
|
const sign = minutes >= 0 ? '+' : '-'
|
||||||
|
const abs = Math.abs(minutes)
|
||||||
|
return `UTC${sign}${String(Math.floor(abs / 60)).padStart(2, '0')}:${String(abs % 60).padStart(2, '0')}`
|
||||||
|
}
|
||||||
|
|||||||
@@ -0,0 +1,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 */}
|
{/* 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 ? (
|
{loading ? (
|
||||||
<div style={{ display: 'flex', justifyContent: 'center', padding: 'var(--space-6)' }}>
|
<div style={{ display: 'flex', justifyContent: 'center', padding: 'var(--space-6)' }}>
|
||||||
<Spinner size="sm" />
|
<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't match what the console has saved
|
||||||
|
— <strong style={{ color: 'var(--color-warning)' }}>
|
||||||
|
{diffCount} {diffCount === 1 ? 'difference' : 'differences'}
|
||||||
|
</strong>. Choose which version to keep. Nothing changes until you pick one.
|
||||||
|
</p>
|
||||||
|
|
||||||
|
{/* Two columns, rows aligned across them (one shared grid). */}
|
||||||
|
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', columnGap: 'var(--space-4)' }}>
|
||||||
|
<ColumnHeader icon="dashboard" title="Saved in Console" subtitle="What the database holds" />
|
||||||
|
<ColumnHeader icon="devices" title="Stored on Device" subtitle="Read from the device just now" />
|
||||||
|
|
||||||
|
{visible.map((r, i) => [
|
||||||
|
<Cell key={`${r.key}-s`} label={r.label} value={r.saved} differs={r.differs} last={i === visible.length - 1} />,
|
||||||
|
<Cell key={`${r.key}-d`} label={r.label} value={r.device} differs={r.differs} last={i === visible.length - 1} />,
|
||||||
|
])}
|
||||||
|
|
||||||
|
{canEdit ? (
|
||||||
|
<>
|
||||||
|
<ColumnFooter hint="Pushes these settings to the device. The database is already correct.">
|
||||||
|
<Button
|
||||||
|
variant="primary"
|
||||||
|
icon={<Icon name="upload" size={14} />}
|
||||||
|
loading={busy === 'console'}
|
||||||
|
disabled={!!busy}
|
||||||
|
onClick={run('console', onKeepConsole)}
|
||||||
|
>
|
||||||
|
Keep Console version
|
||||||
|
</Button>
|
||||||
|
</ColumnFooter>
|
||||||
|
<ColumnFooter hint="Saves only the differing values to the database. The device is not touched.">
|
||||||
|
<Button
|
||||||
|
variant="primary"
|
||||||
|
icon={<Icon name="download" size={14} />}
|
||||||
|
loading={busy === 'device'}
|
||||||
|
disabled={!!busy}
|
||||||
|
onClick={run('device', onKeepDevice)}
|
||||||
|
>
|
||||||
|
Keep Device version
|
||||||
|
</Button>
|
||||||
|
</ColumnFooter>
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<ColumnFooter hint="You don't have permission to change device settings." />
|
||||||
|
<ColumnFooter hint="You don't have permission to change device settings." />
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{error && (
|
||||||
|
<p style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-danger)', margin: 0 }}>{error}</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</Modal>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,175 @@
|
|||||||
|
// frontend/src/modals/bellcloud/devices/DeleteDeviceLogsModal.jsx
|
||||||
|
// Health tab → Logs → "Delete Logs…". Permanently deletes console-stored log
|
||||||
|
// history for one device, filtered by log type (and by level for the text
|
||||||
|
// channels). Unlike ResetStatsModal this never touches the device itself,
|
||||||
|
// Firestore stats, boot history or ping/diagnostics data — just the log
|
||||||
|
// channels shown in the Logs explorer.
|
||||||
|
//
|
||||||
|
// Device Logs / Info → DELETE /mqtt/logs/{serial}?source=…&level=…
|
||||||
|
// Alerts / Heartbeats / Commands → POST /devices/{id}/reset-stats (existing)
|
||||||
|
|
||||||
|
import { useState } from 'react'
|
||||||
|
import Modal from '@/components/ui/Modal'
|
||||||
|
import Button from '@/components/ui/Button'
|
||||||
|
import PressHoldButton from '@/components/ui/PressHoldButton'
|
||||||
|
import Icon from '@/components/ui/Icon'
|
||||||
|
import api from '@/lib/api'
|
||||||
|
import { useToast } from '@/components/ui/Toast'
|
||||||
|
|
||||||
|
const TYPES = [
|
||||||
|
{ key: 'log', label: 'Device Logs', description: 'Debug log lines the firmware streams over MQTT.', leveled: true },
|
||||||
|
{ key: 'info', label: 'Info events', description: 'System info events (playback started, config changes, …).', leveled: true },
|
||||||
|
{ key: 'alert_history', label: 'Alert history', description: 'Past alert transitions. Current active alerts are kept.' },
|
||||||
|
{ key: 'heartbeats', label: 'Heartbeats', description: 'Heartbeat history — also empties the RSSI and free-heap charts on Overview.' },
|
||||||
|
{ key: 'commands', label: 'Commands', description: 'Sent-command history (also shown in the Control tab).' },
|
||||||
|
]
|
||||||
|
|
||||||
|
const LEVELS = ['INFO', 'WARN', 'ERROR']
|
||||||
|
|
||||||
|
function CheckRow({ label, description, checked, onChange, disabled }) {
|
||||||
|
return (
|
||||||
|
<label style={{
|
||||||
|
display: 'flex', alignItems: 'flex-start', gap: 'var(--space-3)',
|
||||||
|
padding: 'var(--space-2) 0', cursor: disabled ? 'default' : 'pointer',
|
||||||
|
opacity: disabled ? 0.5 : 1,
|
||||||
|
}}>
|
||||||
|
<input
|
||||||
|
type="checkbox"
|
||||||
|
checked={checked}
|
||||||
|
onChange={onChange}
|
||||||
|
disabled={disabled}
|
||||||
|
style={{ accentColor: 'var(--color-danger)', flexShrink: 0, marginTop: 3 }}
|
||||||
|
/>
|
||||||
|
<div style={{ flex: 1, minWidth: 0 }}>
|
||||||
|
<p style={{ fontSize: 'var(--font-size-sm)', fontWeight: 'var(--font-weight-medium)', color: 'var(--color-text-primary)' }}>
|
||||||
|
{label}
|
||||||
|
</p>
|
||||||
|
{description && (
|
||||||
|
<p style={{ fontSize: 'var(--font-size-xs)', color: 'var(--color-text-muted)', marginTop: 2 }}>
|
||||||
|
{description}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</label>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function DeleteDeviceLogsModal({ open, onClose, onDeleted, deviceId, serial }) {
|
||||||
|
const { toast } = useToast()
|
||||||
|
const [types, setTypes] = useState({ log: true, info: true, alert_history: false, heartbeats: false, commands: false })
|
||||||
|
const [levels, setLevels] = useState({ INFO: true, WARN: true, ERROR: true })
|
||||||
|
const [running, setRunning] = useState(false)
|
||||||
|
|
||||||
|
const textSources = ['log', 'info'].filter(k => types[k])
|
||||||
|
const selectedLevels = LEVELS.filter(l => levels[l])
|
||||||
|
const allLevels = selectedLevels.length === LEVELS.length
|
||||||
|
const tableKeys = ['alert_history', 'heartbeats', 'commands'].filter(k => types[k])
|
||||||
|
const canRun = (textSources.length > 0 && selectedLevels.length > 0) || tableKeys.length > 0
|
||||||
|
|
||||||
|
const handleClose = () => { if (!running) onClose() }
|
||||||
|
|
||||||
|
const run = async () => {
|
||||||
|
setRunning(true)
|
||||||
|
const done = []
|
||||||
|
const failed = []
|
||||||
|
if (textSources.length > 0 && selectedLevels.length > 0) {
|
||||||
|
const params = new URLSearchParams()
|
||||||
|
textSources.forEach(s => params.append('source', s))
|
||||||
|
if (!allLevels) selectedLevels.forEach(l => params.append('level', l))
|
||||||
|
try {
|
||||||
|
const res = await api.delete(`/mqtt/logs/${encodeURIComponent(serial)}?${params}`)
|
||||||
|
done.push(`${res?.deleted ?? 0} log line(s)`)
|
||||||
|
} catch (err) {
|
||||||
|
failed.push(`logs: ${err.message || 'failed'}`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (tableKeys.length > 0) {
|
||||||
|
const body = Object.fromEntries(tableKeys.map(k => [k, true]))
|
||||||
|
try {
|
||||||
|
const res = await api.post(`/devices/${deviceId}/reset-stats`, body)
|
||||||
|
for (const k of tableKeys) {
|
||||||
|
const label = TYPES.find(t => t.key === k).label.toLowerCase()
|
||||||
|
done.push(`${res?.[k] ?? 0} ${label}`)
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
failed.push(`${tableKeys.join(', ')}: ${err.message || 'failed'}`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
setRunning(false)
|
||||||
|
if (failed.length === 0) {
|
||||||
|
toast.success('Logs deleted', `Removed ${done.join(', ')}.`)
|
||||||
|
} else {
|
||||||
|
toast.danger('Delete incomplete', failed.join(' · '))
|
||||||
|
}
|
||||||
|
onDeleted?.()
|
||||||
|
onClose()
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Modal open={open} onClose={handleClose} title="Delete Device Logs" size="md" persistent={running}>
|
||||||
|
<div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-5)' }}>
|
||||||
|
<div style={{
|
||||||
|
display: 'flex', alignItems: 'flex-start', gap: 'var(--space-2)',
|
||||||
|
padding: 'var(--space-3) var(--space-4)', borderRadius: 'var(--radius-md)',
|
||||||
|
backgroundColor: 'var(--color-danger-bg)', border: '1px solid var(--color-danger)',
|
||||||
|
fontSize: 'var(--font-size-sm)', color: 'var(--color-danger)',
|
||||||
|
}}>
|
||||||
|
<Icon name="warning" size={16} color="var(--color-danger)" style={{ flexShrink: 0, marginTop: 1 }} />
|
||||||
|
<span>
|
||||||
|
Permanently deletes the selected history for <strong>{serial}</strong> from the console database. The device's own SD-card logs are not affected. <strong>This cannot be undone.</strong>
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<span style={{ fontSize: 'var(--font-size-xs)', fontWeight: 'var(--font-weight-semibold)', color: 'var(--color-text-muted)', letterSpacing: 'var(--tracking-wide)', textTransform: 'uppercase' }}>
|
||||||
|
Log types
|
||||||
|
</span>
|
||||||
|
<div style={{ borderTop: '1px solid var(--color-border)', marginTop: 'var(--space-2)' }}>
|
||||||
|
{TYPES.map(t => (
|
||||||
|
<CheckRow
|
||||||
|
key={t.key}
|
||||||
|
label={t.label}
|
||||||
|
description={t.description}
|
||||||
|
checked={!!types[t.key]}
|
||||||
|
onChange={() => setTypes(prev => ({ ...prev, [t.key]: !prev[t.key] }))}
|
||||||
|
disabled={running}
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{textSources.length > 0 && (
|
||||||
|
<div>
|
||||||
|
<span style={{ fontSize: 'var(--font-size-xs)', fontWeight: 'var(--font-weight-semibold)', color: 'var(--color-text-muted)', letterSpacing: 'var(--tracking-wide)', textTransform: 'uppercase' }}>
|
||||||
|
Levels (Device Logs & Info)
|
||||||
|
</span>
|
||||||
|
<div style={{ display: 'flex', gap: 'var(--space-6)', borderTop: '1px solid var(--color-border)', marginTop: 'var(--space-2)', flexWrap: 'wrap' }}>
|
||||||
|
{LEVELS.map(l => (
|
||||||
|
<CheckRow
|
||||||
|
key={l}
|
||||||
|
label={l}
|
||||||
|
checked={!!levels[l]}
|
||||||
|
onChange={() => setLevels(prev => ({ ...prev, [l]: !prev[l] }))}
|
||||||
|
disabled={running}
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<div style={{ display: 'flex', justifyContent: 'flex-end', gap: 'var(--space-3)', paddingTop: 'var(--space-2)', borderTop: '1px solid var(--color-border)', flexWrap: 'wrap' }}>
|
||||||
|
<Button variant="ghost" onClick={handleClose} disabled={running}>Cancel</Button>
|
||||||
|
<PressHoldButton
|
||||||
|
variant="danger"
|
||||||
|
holdMs={2000}
|
||||||
|
disabled={running || !canRun}
|
||||||
|
holdingLabel="Keep holding to delete…"
|
||||||
|
onConfirm={run}
|
||||||
|
>
|
||||||
|
{running ? 'Deleting…' : 'Hold to Delete'}
|
||||||
|
</PressHoldButton>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</Modal>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -3,7 +3,7 @@ import Modal from '@/components/ui/Modal'
|
|||||||
import Button from '@/components/ui/Button'
|
import Button from '@/components/ui/Button'
|
||||||
|
|
||||||
export default function DeleteDeviceModal({ device, onConfirm, onCancel, error }) {
|
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
|
const serial = device?.serial_number || device?.device_id
|
||||||
|
|
||||||
return (
|
return (
|
||||||
|
|||||||
@@ -20,7 +20,7 @@ function extractTime(tsStr) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function timeToIso(hhmm) {
|
function timeToIso(hhmm) {
|
||||||
if (!hhmm) return ''
|
if (!hhmm) return null
|
||||||
return `2000-01-01T${hhmm}:00Z`
|
return `2000-01-01T${hhmm}:00Z`
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -112,8 +112,23 @@ function SilenceBlock({ title, isOn, onToggle, from, onFromChange, to, onToChang
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
export default function EditAlertsModal({ open, onClose, onSaved, clock, attr, id }) {
|
// Console UI uses alertType 'disabled'|'single'|'multi'; firmware uses
|
||||||
const totalBells = attr?.totalBells || 8
|
// 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 [alertType, setAlertType] = useState(clock?.ringAlerts || 'disabled')
|
||||||
const [ringIntervals, setRingIntervals] = useState(clock?.ringIntervals ?? 1000)
|
const [ringIntervals, setRingIntervals] = useState(clock?.ringIntervals ?? 1000)
|
||||||
@@ -141,28 +156,44 @@ export default function EditAlertsModal({ open, onClose, onSaved, clock, attr, i
|
|||||||
setSaving(true)
|
setSaving(true)
|
||||||
setError('')
|
setError('')
|
||||||
try {
|
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}`, {
|
await api.put(`/devices/${id}`, {
|
||||||
device_attributes: {
|
device_attributes: {
|
||||||
clockSettings: {
|
clockSettings: {
|
||||||
...clock,
|
|
||||||
ringAlerts: alertType,
|
ringAlerts: alertType,
|
||||||
ringAlertsMasterOn: alertType !== 'disabled',
|
|
||||||
ringIntervals: alertType === 'multi' ? ringIntervals : clock?.ringIntervals,
|
ringIntervals: alertType === 'multi' ? ringIntervals : clock?.ringIntervals,
|
||||||
hourAlertsBell: Number(hourBell),
|
hourAlertsBell: Number(hourBell),
|
||||||
halfhourAlertsBell: Number(halfBell),
|
halfhourAlertsBell: Number(halfBell),
|
||||||
quarterAlertsBell: Number(quarterBell),
|
quarterAlertsBell: Number(quarterBell),
|
||||||
isDaySilenceOn: isDayOn,
|
isDaySilenceOn: isDayOn,
|
||||||
daySilenceFrom: isDayOn && daySilenceFrom ? timeToIso(daySilenceFrom) : (clock?.daySilenceFrom || ''),
|
daySilenceFrom: isDayOn && daySilenceFrom ? timeToIso(daySilenceFrom) : (clock?.daySilenceFrom ?? null),
|
||||||
daySilenceTo: isDayOn && daySilenceTo ? timeToIso(daySilenceTo) : (clock?.daySilenceTo || ''),
|
daySilenceTo: isDayOn && daySilenceTo ? timeToIso(daySilenceTo) : (clock?.daySilenceTo ?? null),
|
||||||
isNightSilenceOn: isNightOn,
|
isNightSilenceOn: isNightOn,
|
||||||
nightSilenceFrom: isNightOn && nightFrom ? timeToIso(nightFrom) : (clock?.nightSilenceFrom || ''),
|
nightSilenceFrom: isNightOn && nightFrom ? timeToIso(nightFrom) : (clock?.nightSilenceFrom ?? null),
|
||||||
nightSilenceTo: isNightOn && nightTo ? timeToIso(nightTo) : (clock?.nightSilenceTo || ''),
|
nightSilenceTo: isNightOn && nightTo ? timeToIso(nightTo) : (clock?.nightSilenceTo ?? null),
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
await onSaved()
|
await onSaved()
|
||||||
onClose()
|
onClose()
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
|
// sendMqttCommand already surfaced a failure toast if the device rejected it.
|
||||||
setError(err.message || 'Failed to save.')
|
setError(err.message || 'Failed to save.')
|
||||||
} finally {
|
} finally {
|
||||||
setSaving(false)
|
setSaving(false)
|
||||||
@@ -171,7 +202,7 @@ export default function EditAlertsModal({ open, onClose, onSaved, clock, attr, i
|
|||||||
|
|
||||||
const bellOptions = [
|
const bellOptions = [
|
||||||
{ value: '0', label: 'Disabled' },
|
{ 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 (
|
return (
|
||||||
|
|||||||
@@ -9,10 +9,8 @@ const toBool = (v) => v === 'true' || v === true
|
|||||||
|
|
||||||
export default function EditAttributesModal({ open, onClose, onSaved, attr, id }) {
|
export default function EditAttributesModal({ open, onClose, onSaved, attr, id }) {
|
||||||
const [bellGuardOn, setBellGuardOn] = useState(String(attr?.bellGuardOn ?? false))
|
const [bellGuardOn, setBellGuardOn] = useState(String(attr?.bellGuardOn ?? false))
|
||||||
const [bellGuardSafetyOn, setBellGuardSafetyOn] = useState(String(attr?.bellGuardSafetyOn ?? false))
|
const [bellGuardSafetyOn, setBellGuardSafetyOn] = useState(String(attr?.bellguardSafetyOn ?? false))
|
||||||
const [warningsOn, setWarningsOn] = useState(String(attr?.warningsOn ?? false))
|
const [warningsOn, setWarningsOn] = useState(String(attr?.warningsOn ?? false))
|
||||||
const [hasBells, setHasBells] = useState(String(attr?.hasBells ?? false))
|
|
||||||
const [hasClock, setHasClock] = useState(String(attr?.hasClock ?? false))
|
|
||||||
const [saving, setSaving] = useState(false)
|
const [saving, setSaving] = useState(false)
|
||||||
const [error, setError] = useState('')
|
const [error, setError] = useState('')
|
||||||
|
|
||||||
@@ -20,13 +18,12 @@ export default function EditAttributesModal({ open, onClose, onSaved, attr, id }
|
|||||||
setSaving(true)
|
setSaving(true)
|
||||||
setError('')
|
setError('')
|
||||||
try {
|
try {
|
||||||
|
// App-only settings — no device-side equivalent, Firestore is the source of truth.
|
||||||
await api.put(`/devices/${id}`, {
|
await api.put(`/devices/${id}`, {
|
||||||
device_attributes: {
|
device_attributes: {
|
||||||
bellGuardOn: toBool(bellGuardOn),
|
bellGuardOn: toBool(bellGuardOn),
|
||||||
warningsOn: toBool(warningsOn),
|
warningsOn: toBool(warningsOn),
|
||||||
bellGuardSafetyOn: toBool(bellGuardSafetyOn),
|
bellguardSafetyOn: toBool(bellGuardSafetyOn),
|
||||||
hasBells: toBool(hasBells),
|
|
||||||
hasClock: toBool(hasClock),
|
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
await onSaved()
|
await onSaved()
|
||||||
@@ -42,7 +39,7 @@ export default function EditAttributesModal({ open, onClose, onSaved, attr, id }
|
|||||||
<Modal
|
<Modal
|
||||||
open={open}
|
open={open}
|
||||||
onClose={onClose}
|
onClose={onClose}
|
||||||
title="Edit Basic Attributes"
|
title="Edit Safety Settings"
|
||||||
size="sm"
|
size="sm"
|
||||||
footer={
|
footer={
|
||||||
<div style={{ display: 'flex', justifyContent: 'flex-end', gap: 'var(--space-3)' }}>
|
<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="true">Active</option>
|
||||||
<option value="false">Disabled</option>
|
<option value="false">Disabled</option>
|
||||||
</FormField>
|
</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 && (
|
{error && (
|
||||||
<p style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-danger)' }}>{error}</p>
|
<p style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-danger)' }}>{error}</p>
|
||||||
)}
|
)}
|
||||||
|
|||||||
@@ -17,13 +17,13 @@ function extractTime(tsStr) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function timeToIso(hhmm) {
|
function timeToIso(hhmm) {
|
||||||
if (!hhmm) return ''
|
if (!hhmm) return null
|
||||||
return `2000-01-01T${hhmm}:00Z`
|
return `2000-01-01T${hhmm}:00Z`
|
||||||
}
|
}
|
||||||
|
|
||||||
const toBool = (v) => v === 'true' || v === true
|
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 maxOutputs = sub?.maxOutputs || 8
|
||||||
const bellOutputsUsed = (attr?.bellOutputs || []).filter((o) => o > 0)
|
const bellOutputsUsed = (attr?.bellOutputs || []).filter((o) => o > 0)
|
||||||
const clockOutputsUsed = (clock?.clockOutputs || []).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)
|
setSaving(true)
|
||||||
setError('')
|
setError('')
|
||||||
try {
|
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}`, {
|
await api.put(`/devices/${id}`, {
|
||||||
device_attributes: {
|
device_attributes: {
|
||||||
clockSettings: {
|
clockSettings: {
|
||||||
...clock,
|
isBacklightAutomationOn: enabled,
|
||||||
isBacklightAutomationOn: toBool(isOn),
|
|
||||||
backlightOutput: Number(output),
|
backlightOutput: Number(output),
|
||||||
backlightTurnOnTime: toBool(isOn) && onTime ? timeToIso(onTime) : '',
|
backlightTurnOnTime: enabled && onTime ? timeToIso(onTime) : null,
|
||||||
backlightTurnOffTime: toBool(isOn) && offTime ? timeToIso(offTime) : '',
|
backlightTurnOffTime: enabled && offTime ? timeToIso(offTime) : null,
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
await onSaved()
|
await onSaved()
|
||||||
onClose()
|
onClose()
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
|
// sendMqttCommand already surfaced a failure toast if the device rejected it.
|
||||||
setError(err.message || 'Failed to save.')
|
setError(err.message || 'Failed to save.')
|
||||||
} finally {
|
} finally {
|
||||||
setSaving(false)
|
setSaving(false)
|
||||||
|
|||||||
@@ -17,7 +17,7 @@ const TIMING_LABELS = {
|
|||||||
140: 'Max — 140ms',
|
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 maxOutputs = sub?.maxOutputs || 8
|
||||||
const existingCount = attr?.totalBells || 0
|
const existingCount = attr?.totalBells || 0
|
||||||
const existingOutputs = attr?.bellOutputs || []
|
const existingOutputs = attr?.bellOutputs || []
|
||||||
@@ -25,10 +25,15 @@ export default function EditBellOutputsModal({ open, onClose, onSaved, attr, sub
|
|||||||
|
|
||||||
const [activeBells, setActiveBells] = useState(existingCount)
|
const [activeBells, setActiveBells] = useState(existingCount)
|
||||||
const [rows, setRows] = useState(() =>
|
const [rows, setRows] = useState(() =>
|
||||||
Array.from({ length: maxOutputs }, (_, i) => ({
|
Array.from({ length: maxOutputs }, (_, i) => {
|
||||||
output: existingOutputs[i] ?? 0,
|
// 65535 is the firmware's uint16 "unset" sentinel — treat it like 0 (Disabled)
|
||||||
timing: existingTimings[i] ?? 90,
|
// 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 [saving, setSaving] = useState(false)
|
||||||
const [error, setError] = useState('')
|
const [error, setError] = useState('')
|
||||||
@@ -43,6 +48,25 @@ export default function EditBellOutputsModal({ open, onClose, onSaved, attr, sub
|
|||||||
setSaving(true)
|
setSaving(true)
|
||||||
setError('')
|
setError('')
|
||||||
try {
|
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}`, {
|
await api.put(`/devices/${id}`, {
|
||||||
device_attributes: {
|
device_attributes: {
|
||||||
totalBells: activeBells,
|
totalBells: activeBells,
|
||||||
@@ -53,6 +77,7 @@ export default function EditBellOutputsModal({ open, onClose, onSaved, attr, sub
|
|||||||
await onSaved()
|
await onSaved()
|
||||||
onClose()
|
onClose()
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
|
// sendMqttCommand already surfaced a failure toast if the device rejected it.
|
||||||
setError(err.message || 'Failed to save.')
|
setError(err.message || 'Failed to save.')
|
||||||
} finally {
|
} finally {
|
||||||
setSaving(false)
|
setSaving(false)
|
||||||
|
|||||||
@@ -1,10 +1,13 @@
|
|||||||
// frontend/src/modals/bellcloud/devices/EditClockSettingsModal.jsx
|
// frontend/src/modals/bellcloud/devices/EditClockSettingsModal.jsx
|
||||||
// Edits: master switch, ODD/EVEN outputs, pulse and pause durations (sliders).
|
// Edits: master switch, ODD/EVEN outputs, pulse and pause durations (sliders), and the
|
||||||
|
// face sync policy (firmware 3.2.0+: force = run a full lap when the face is ahead,
|
||||||
|
// smart = wait if it is at most N minutes ahead).
|
||||||
|
|
||||||
import { useState } from 'react'
|
import { useState } from 'react'
|
||||||
import Modal from '@/components/ui/Modal'
|
import Modal from '@/components/ui/Modal'
|
||||||
import Button from '@/components/ui/Button'
|
import Button from '@/components/ui/Button'
|
||||||
import FormField from '@/components/ui/FormField'
|
import FormField from '@/components/ui/FormField'
|
||||||
|
import SegmentedControl from '@/components/ui/SegmentedControl'
|
||||||
import api from '@/lib/api'
|
import api from '@/lib/api'
|
||||||
|
|
||||||
// Pulse options in milliseconds — shown as sliders with labelled steps
|
// Pulse options in milliseconds — shown as sliders with labelled steps
|
||||||
@@ -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 clock = attr?.clockSettings || {}
|
||||||
const maxOutputs = sub?.maxOutputs || 8
|
const maxOutputs = sub?.maxOutputs || 8
|
||||||
const bellOutputsUsed = (attr?.bellOutputs || []).filter(o => o > 0)
|
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 [clockOut2, setClockOut2] = useState(String(existingClockOutputs[1] ?? 0))
|
||||||
const [runPulse, setRunPulse] = useState(existingTimings[0] || PULSE_STEPS[3]) // default 500ms
|
const [runPulse, setRunPulse] = useState(existingTimings[0] || PULSE_STEPS[3]) // default 500ms
|
||||||
const [pauseMs, setPauseMs] = useState(existingTimings[1] || PAUSE_STEPS[1]) // default 1000ms
|
const [pauseMs, setPauseMs] = useState(existingTimings[1] || PAUSE_STEPS[1]) // default 1000ms
|
||||||
|
const [faceSync, setFaceSync] = useState(clock.faceSyncMode || 'force')
|
||||||
|
const [maxWait, setMaxWait] = useState(String(clock.smartMaxWaitMin ?? 61))
|
||||||
const [saving, setSaving] = useState(false)
|
const [saving, setSaving] = useState(false)
|
||||||
const [error, setError] = useState('')
|
const [error, setError] = useState('')
|
||||||
|
|
||||||
@@ -78,26 +83,44 @@ export default function EditClockSettingsModal({ open, onClose, onSaved, attr, s
|
|||||||
const validationMsg = hasClock && (out1 === 0 || out2 === 0)
|
const validationMsg = hasClock && (out1 === 0 || out2 === 0)
|
||||||
? 'Both outputs must be assigned when the clock is enabled.'
|
? 'Both outputs must be assigned when the clock is enabled.'
|
||||||
: null
|
: null
|
||||||
const canSave = !conflictMsg && !validationMsg
|
const maxWaitNum = Number(maxWait)
|
||||||
|
const maxWaitMsg = faceSync === 'smart' && (!Number.isInteger(maxWaitNum) || maxWaitNum < 1 || maxWaitNum > 359)
|
||||||
|
? 'Maximum wait must be 1–359 minutes.'
|
||||||
|
: null
|
||||||
|
const canSave = !conflictMsg && !validationMsg && !maxWaitMsg
|
||||||
|
|
||||||
const handleSave = async () => {
|
const handleSave = async () => {
|
||||||
if (!canSave) return
|
if (!canSave) return
|
||||||
setSaving(true)
|
setSaving(true)
|
||||||
setError('')
|
setError('')
|
||||||
try {
|
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}`, {
|
await api.put(`/devices/${id}`, {
|
||||||
device_attributes: {
|
device_attributes: {
|
||||||
hasClock,
|
hasClock,
|
||||||
clockSettings: {
|
clockSettings: {
|
||||||
...clock,
|
|
||||||
clockOutputs: [out1, out2].filter(o => o > 0),
|
clockOutputs: [out1, out2].filter(o => o > 0),
|
||||||
clockTimings: [runPulse, pauseMs],
|
clockTimings: [runPulse, pauseMs],
|
||||||
|
faceSyncMode: faceSync,
|
||||||
|
...(faceSync === 'smart' ? { smartMaxWaitMin: maxWaitNum } : {}),
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
await onSaved()
|
await onSaved()
|
||||||
onClose()
|
onClose()
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
|
// sendMqttCommand already surfaced a failure toast if the device rejected it.
|
||||||
setError(err.message || 'Failed to save.')
|
setError(err.message || 'Failed to save.')
|
||||||
} finally {
|
} finally {
|
||||||
setSaving(false)
|
setSaving(false)
|
||||||
@@ -217,10 +240,42 @@ export default function EditClockSettingsModal({ open, onClose, onSaved, attr, s
|
|||||||
onChange={setPauseMs}
|
onChange={setPauseMs}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
|
<div style={{ height: 1, backgroundColor: 'var(--color-border)' }} />
|
||||||
|
|
||||||
|
{/* Face sync policy */}
|
||||||
|
<div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-3)' }}>
|
||||||
|
<div>
|
||||||
|
<p style={{ fontSize: 'var(--font-size-base)', fontWeight: 'var(--font-weight-semibold)', color: 'var(--color-text-primary)' }}>
|
||||||
|
Face Ahead of Real Time
|
||||||
|
</p>
|
||||||
|
<p style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-text-muted)', marginTop: 2 }}>
|
||||||
|
The hands only move forward. When they are ahead (e.g. after DST ends), Force runs a full
|
||||||
|
lap to catch up; Smart stops them until real time catches up.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<SegmentedControl
|
||||||
|
options={[{ value: 'force', label: 'Force (full lap)' }, { value: 'smart', label: 'Smart (wait)' }]}
|
||||||
|
value={faceSync}
|
||||||
|
onChange={setFaceSync}
|
||||||
|
size="sm"
|
||||||
|
/>
|
||||||
|
{faceSync === 'smart' && (
|
||||||
|
<FormField
|
||||||
|
label="Wait if ahead by at most (minutes)"
|
||||||
|
name="smartMaxWait"
|
||||||
|
type="number"
|
||||||
|
value={maxWait}
|
||||||
|
onChange={e => setMaxWait(e.target.value)}
|
||||||
|
inputProps={{ min: 1, max: 359, step: 1 }}
|
||||||
|
hint="Default 61 covers the DST change. Further ahead than this, the face runs the lap."
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
{/* Errors / warnings */}
|
{/* Errors / warnings */}
|
||||||
{(conflictMsg || validationMsg) && (
|
{(conflictMsg || validationMsg || maxWaitMsg) && (
|
||||||
<p style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-warning)', backgroundColor: 'var(--color-warning-bg)', padding: 'var(--space-2) var(--space-3)', borderRadius: 'var(--radius-sm)' }}>
|
<p style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-warning)', backgroundColor: 'var(--color-warning-bg)', padding: 'var(--space-2) var(--space-3)', borderRadius: 'var(--radius-sm)' }}>
|
||||||
{conflictMsg || validationMsg}
|
{conflictMsg || validationMsg || maxWaitMsg}
|
||||||
</p>
|
</p>
|
||||||
)}
|
)}
|
||||||
{error && (
|
{error && (
|
||||||
|
|||||||
@@ -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's current time (as UTC). The device shows it in {tzLabel}.
|
||||||
|
</p>
|
||||||
|
) : (
|
||||||
|
<FormField
|
||||||
|
label="Local time on the device"
|
||||||
|
name="deviceLocalTime"
|
||||||
|
type="datetime-local"
|
||||||
|
value={local}
|
||||||
|
onChange={e => setLocal(e.target.value)}
|
||||||
|
inputProps={{ step: 1 }}
|
||||||
|
hint={`Wall-clock time in ${tzLabel}.`}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{ntpWillCorrect && (
|
||||||
|
<p style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-warning)', backgroundColor: 'var(--color-warning-bg)', padding: 'var(--space-2) var(--space-3)', borderRadius: 'var(--radius-sm)' }}>
|
||||||
|
Automatic NTP is on: if this differs from real time, the device corrects it at its next sync
|
||||||
|
{timezone?.mode === 'fixed' ? ' (by up to 5 minutes in fixed mode)' : ''}.
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
{error && <p style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-danger)' }}>{error}</p>}
|
||||||
|
</div>
|
||||||
|
</Modal>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -1,67 +1,118 @@
|
|||||||
// frontend/src/modals/bellcloud/devices/SyncClockModal.jsx
|
// frontend/src/modals/bellcloud/devices/SyncClockModal.jsx
|
||||||
// Placeholder — clock sync UI to be implemented when MQTT sync protocol is defined.
|
// Corrects where the device thinks the clocktower's hands are (clock.set_face).
|
||||||
|
// Flow: pause the clock (clock.pause) so the hands stop while someone reads them, enter what
|
||||||
|
// the face shows, then save (clock.set_face) and resume (clock.resume). The device then moves
|
||||||
|
// the hands to the real time — forward only; with face sync "smart" it waits instead of a full
|
||||||
|
// lap when the face is slightly ahead. Closing without saving resumes the clock.
|
||||||
|
|
||||||
|
import { useEffect, useState } from 'react'
|
||||||
import Modal from '@/components/ui/Modal'
|
import Modal from '@/components/ui/Modal'
|
||||||
import Button from '@/components/ui/Button'
|
import Button from '@/components/ui/Button'
|
||||||
import Icon from '@/components/ui/Icon'
|
import FormField from '@/components/ui/FormField'
|
||||||
|
|
||||||
export default function SyncClockModal({ open, onClose, device }) {
|
const HOURS = Array.from({ length: 12 }, (_, i) => i + 1)
|
||||||
const sn = device?.serial_number || device?.device_id
|
const MINUTES = Array.from({ length: 60 }, (_, i) => i)
|
||||||
|
const pad = n => String(n).padStart(2, '0')
|
||||||
|
|
||||||
|
export default function SyncClockModal({ open, onClose, face, sendMqttCommand, onSaved }) {
|
||||||
|
const [paused, setPaused] = useState(false)
|
||||||
|
const [pausing, setPausing] = useState(false)
|
||||||
|
const [hour, setHour] = useState(12)
|
||||||
|
const [minute, setMinute] = useState(0)
|
||||||
|
const [saving, setSaving] = useState(false)
|
||||||
|
const [error, setError] = useState('')
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!open) return
|
||||||
|
setPaused(false)
|
||||||
|
setError('')
|
||||||
|
setHour(face?.clock_hour || 12)
|
||||||
|
setMinute(face?.clock_minute || 0)
|
||||||
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
|
}, [open])
|
||||||
|
|
||||||
|
const handleClose = async () => {
|
||||||
|
if (paused) {
|
||||||
|
try { await sendMqttCommand('clock.resume') } catch { /* toast already shown */ }
|
||||||
|
}
|
||||||
|
onClose()
|
||||||
|
}
|
||||||
|
|
||||||
|
const handlePause = async () => {
|
||||||
|
setPausing(true)
|
||||||
|
setError('')
|
||||||
|
try {
|
||||||
|
await sendMqttCommand('clock.pause')
|
||||||
|
setPaused(true)
|
||||||
|
} catch (err) {
|
||||||
|
setError(err.message || 'Failed to pause the clock.')
|
||||||
|
} finally {
|
||||||
|
setPausing(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleSave = async () => {
|
||||||
|
setSaving(true)
|
||||||
|
setError('')
|
||||||
|
try {
|
||||||
|
await sendMqttCommand('clock.set_face', { hour, minute })
|
||||||
|
await sendMqttCommand('clock.resume')
|
||||||
|
setPaused(false)
|
||||||
|
onSaved?.()
|
||||||
|
onClose()
|
||||||
|
} catch (err) {
|
||||||
|
setError(err.message || 'Failed to set the clocktower time.')
|
||||||
|
} finally {
|
||||||
|
setSaving(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Modal
|
<Modal
|
||||||
open={open}
|
open={open}
|
||||||
onClose={onClose}
|
onClose={handleClose}
|
||||||
title="Sync Clocktower"
|
title="Sync Clocktower"
|
||||||
size="sm"
|
size="sm"
|
||||||
|
persistent={paused}
|
||||||
footer={
|
footer={
|
||||||
<div style={{ display: 'flex', justifyContent: 'flex-end', gap: 'var(--space-3)' }}>
|
<div style={{ display: 'flex', justifyContent: 'flex-end', gap: 'var(--space-3)' }}>
|
||||||
<Button variant="ghost" onClick={onClose}>Close</Button>
|
<Button variant="ghost" onClick={handleClose}>{paused ? 'Cancel & Resume' : 'Cancel'}</Button>
|
||||||
<Button variant="primary" disabled>
|
<Button variant="primary" loading={saving} onClick={handleSave}>Save & Resume</Button>
|
||||||
Sync (Coming Soon)
|
|
||||||
</Button>
|
|
||||||
</div>
|
</div>
|
||||||
}
|
}
|
||||||
>
|
>
|
||||||
<div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 'var(--space-5)', padding: 'var(--space-4) 0', textAlign: 'center' }}>
|
<div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-5)' }}>
|
||||||
<div style={{
|
<p style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-text-muted)' }}>
|
||||||
width: 64,
|
The device thinks the clocktower shows{' '}
|
||||||
height: 64,
|
<span style={{ fontFamily: 'var(--font-family-mono)', color: 'var(--color-text-primary)' }}>
|
||||||
borderRadius: 'var(--radius-full)',
|
{face ? `${pad(face.clock_hour)}:${pad(face.clock_minute)}` : '—'}
|
||||||
backgroundColor: 'var(--color-primary-subtle)',
|
</span>
|
||||||
display: 'flex',
|
. If the hands show something else, enter what they really show.
|
||||||
alignItems: 'center',
|
|
||||||
justifyContent: 'center',
|
|
||||||
}}>
|
|
||||||
<Icon name="refresh" size={28} color="var(--color-primary)" />
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<p style={{ fontSize: 'var(--font-size-base)', fontWeight: 'var(--font-weight-semibold)', color: 'var(--color-text-primary)', marginBottom: 'var(--space-2)' }}>
|
|
||||||
Clock Synchronisation
|
|
||||||
</p>
|
|
||||||
<p style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-text-muted)', maxWidth: 340 }}>
|
|
||||||
This will send an MQTT command to correct the clocktower's mechanical position
|
|
||||||
if it has drifted from the master time reference.
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
{sn && (
|
|
||||||
<div style={{
|
|
||||||
padding: 'var(--space-3) var(--space-4)',
|
|
||||||
borderRadius: 'var(--radius-md)',
|
|
||||||
backgroundColor: 'var(--color-bg-elevated)',
|
|
||||||
border: '1px solid var(--color-border)',
|
|
||||||
width: '100%',
|
|
||||||
}}>
|
|
||||||
<span style={{ fontSize: 'var(--font-size-xs)', color: 'var(--color-text-muted)', textTransform: 'uppercase', letterSpacing: 'var(--tracking-wide)' }}>
|
|
||||||
Target device
|
|
||||||
</span>
|
|
||||||
<p style={{ fontFamily: 'var(--font-family-mono)', fontSize: 'var(--font-size-sm)', color: 'var(--color-text-primary)', marginTop: 'var(--space-1)' }}>
|
|
||||||
{sn}
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
<p style={{ fontSize: 'var(--font-size-xs)', color: 'var(--color-text-muted)', fontStyle: 'italic' }}>
|
|
||||||
Full sync implementation coming soon — MQTT protocol pending.
|
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
|
<div style={{ display: 'flex', alignItems: 'center', gap: 'var(--space-3)' }}>
|
||||||
|
<Button variant="secondary" size="sm" loading={pausing} disabled={paused} onClick={handlePause}>
|
||||||
|
{paused ? 'Clock paused' : 'Pause clock'}
|
||||||
|
</Button>
|
||||||
|
<span style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-text-muted)' }}>
|
||||||
|
Optional — stops the hands while you read them.
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 'var(--space-3)' }}>
|
||||||
|
<FormField label="Hour on the face" name="faceHour" type="select" value={String(hour)} onChange={e => setHour(Number(e.target.value))}>
|
||||||
|
{HOURS.map(h => <option key={h} value={String(h)}>{h}</option>)}
|
||||||
|
</FormField>
|
||||||
|
<FormField label="Minute on the face" name="faceMinute" type="select" value={String(minute)} onChange={e => setMinute(Number(e.target.value))}>
|
||||||
|
{MINUTES.map(m => <option key={m} value={String(m)}>{pad(m)}</option>)}
|
||||||
|
</FormField>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<p style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-text-muted)' }}>
|
||||||
|
After saving, the hands move forward to the real time. If the face is slightly ahead, the
|
||||||
|
face sync setting decides: Force runs a full lap, Smart waits.
|
||||||
|
</p>
|
||||||
|
{error && <p style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-danger)' }}>{error}</p>}
|
||||||
</div>
|
</div>
|
||||||
</Modal>
|
</Modal>
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -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
|
// frontend/src/pages/bellcloud/devices/DeviceDetail.jsx
|
||||||
// Parent shell — data fetching, tab routing, modals. Tab content lives in tabs/
|
// Parent shell — data fetching, tab routing, modals. Tab content lives in tabs/
|
||||||
|
|
||||||
import { useState, useEffect, useCallback } from 'react'
|
import { useState, useEffect, useCallback, useRef } from 'react'
|
||||||
import { useParams, useNavigate, useSearchParams } from 'react-router-dom'
|
import { useParams, useNavigate, useSearchParams } from 'react-router-dom'
|
||||||
import api from '@/lib/api'
|
import api from '@/lib/api'
|
||||||
|
import { getCachedDevice, setCachedDevice, getCachedStatus, setCachedStatus } from '@/lib/deviceCache'
|
||||||
import { useAuth } from '@/hooks/useAuth'
|
import { useAuth } from '@/hooks/useAuth'
|
||||||
import { useToast } from '@/components/ui/Toast'
|
import { useToast } from '@/components/ui/Toast'
|
||||||
|
import { useDeviceCommand } from '@/hooks/useDeviceCommand'
|
||||||
import PageHeader from '@/components/ui/PageHeader'
|
import PageHeader from '@/components/ui/PageHeader'
|
||||||
import Button from '@/components/ui/Button'
|
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 Tabs from '@/components/ui/Tabs'
|
||||||
import Spinner from '@/components/ui/Spinner'
|
import Spinner from '@/components/ui/Spinner'
|
||||||
import ConfirmDialog from '@/components/ui/ConfirmDialog'
|
import ConfirmDialog from '@/components/ui/ConfirmDialog'
|
||||||
|
|
||||||
import EditLocationModal from '@/modals/bellcloud/devices/EditLocationModal'
|
import EditLocationModal from '@/modals/bellcloud/devices/EditLocationModal'
|
||||||
import EditAttributesModal from '@/modals/bellcloud/devices/EditAttributesModal'
|
import EditAttributesModal from '@/modals/bellcloud/devices/EditAttributesModal'
|
||||||
import EditLoggingModal from '@/modals/bellcloud/devices/EditLoggingModal'
|
|
||||||
import EditMiscModal from '@/modals/bellcloud/devices/EditMiscModal'
|
import EditMiscModal from '@/modals/bellcloud/devices/EditMiscModal'
|
||||||
import EditBellOutputsModal from '@/modals/bellcloud/devices/EditBellOutputsModal'
|
import EditBellOutputsModal from '@/modals/bellcloud/devices/EditBellOutputsModal'
|
||||||
import EditClockSettingsModal from '@/modals/bellcloud/devices/EditClockSettingsModal'
|
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 WarrantyTab from '@/pages/bellcloud/devices/tabs/WarrantyTab'
|
||||||
import ManageTab from '@/pages/bellcloud/devices/tabs/ManageTab'
|
import ManageTab from '@/pages/bellcloud/devices/tabs/ManageTab'
|
||||||
import ControlTab from '@/pages/bellcloud/devices/tabs/ControlTab'
|
import ControlTab from '@/pages/bellcloud/devices/tabs/ControlTab'
|
||||||
|
import HealthTab from '@/pages/bellcloud/devices/tabs/HealthTab'
|
||||||
|
|
||||||
// ─── Tab config ───────────────────────────────────────────────────────────────
|
// ─── Tab config ───────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
const TABS = [
|
const TABS = [
|
||||||
{ key: 'overview', label: 'Overview' },
|
{ key: 'overview', label: 'Overview' },
|
||||||
|
{ key: 'health', label: 'Health' },
|
||||||
{ key: 'general', label: 'General' },
|
{ key: 'general', label: 'General' },
|
||||||
{ key: 'bells', label: 'Bell Mechanisms' },
|
{ key: 'bells', label: 'Bell Mechanisms' },
|
||||||
{ key: 'clock', label: 'Clock & Alerts' },
|
{ key: 'clock', label: 'Clock & Alerts' },
|
||||||
@@ -44,10 +51,15 @@ const TABS = [
|
|||||||
{ key: 'control', label: 'Control' },
|
{ 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) {
|
function resolveInitialTab(searchParams) {
|
||||||
const raw = searchParams.get('tab')
|
const raw = searchParams.get('tab')?.toLowerCase()
|
||||||
if (!raw) return 'overview'
|
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'
|
return match ? match.key : 'overview'
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -62,10 +74,19 @@ export default function DeviceDetail() {
|
|||||||
const canEdit = hasPermission('devices', 'edit')
|
const canEdit = hasPermission('devices', 'edit')
|
||||||
|
|
||||||
// ── State ──────────────────────────────────────────────────────────────────
|
// ── State ──────────────────────────────────────────────────────────────────
|
||||||
const [device, setDevice] = useState(null)
|
// Seeded from the last-known cache (lib/deviceCache — filled by DeviceList
|
||||||
const [loading, setLoading] = useState(true)
|
// and by earlier visits) so the page renders instantly; loadDevice() then
|
||||||
|
// revalidates in the background and `refreshing` drives the Syncing hint.
|
||||||
|
const [device, setDevice] = useState(() => getCachedDevice(id))
|
||||||
|
const [loading, setLoading] = useState(() => !getCachedDevice(id))
|
||||||
|
const [refreshing, setRefreshing] = useState(false)
|
||||||
const [error, setError] = useState('')
|
const [error, setError] = useState('')
|
||||||
const [mqttStatus, setMqttStatus] = useState(null)
|
const [mqttStatus, setMqttStatus] = useState(() => {
|
||||||
|
const d = getCachedDevice(id)
|
||||||
|
return getCachedStatus(d?.serial_number || d?.device_id)
|
||||||
|
})
|
||||||
|
const deviceRef = useRef(device)
|
||||||
|
deviceRef.current = device
|
||||||
const [activeTab, setActiveTab] = useState(() => resolveInitialTab(searchParams))
|
const [activeTab, setActiveTab] = useState(() => resolveInitialTab(searchParams))
|
||||||
|
|
||||||
const [deviceUsers, setDeviceUsers] = useState([])
|
const [deviceUsers, setDeviceUsers] = useState([])
|
||||||
@@ -73,20 +94,21 @@ export default function DeviceDetail() {
|
|||||||
const [ownerCustomer, setOwnerCustomer] = useState(null)
|
const [ownerCustomer, setOwnerCustomer] = useState(null)
|
||||||
const [assigningCustomer, setAssigningCustomer] = useState(false)
|
const [assigningCustomer, setAssigningCustomer] = useState(false)
|
||||||
|
|
||||||
const [tags, setTags] = useState([])
|
const [tags, setTags] = useState(() => {
|
||||||
const [staffNotes, setStaffNotes] = useState('')
|
const t = getCachedDevice(id)?.tags
|
||||||
|
return Array.isArray(t) ? t : []
|
||||||
|
})
|
||||||
|
const [staffNotes, setStaffNotes] = useState(() => getCachedDevice(id)?.staffNotes || '')
|
||||||
|
|
||||||
const [showDelete, setShowDelete] = useState(false)
|
const [showDelete, setShowDelete] = useState(false)
|
||||||
const [deleting, setDeleting] = useState(false)
|
const [deleting, setDeleting] = useState(false)
|
||||||
|
|
||||||
const [cmdHistory, setCmdHistory] = useState([])
|
const [cmdHistory, setCmdHistory] = useState([])
|
||||||
const [cmdHistoryLoading, setCmdHistoryLoading] = useState(false)
|
const [cmdHistoryLoading, setCmdHistoryLoading] = useState(false)
|
||||||
const [sendingCmd, setSendingCmd] = useState('')
|
|
||||||
|
|
||||||
// Modal open flags
|
// Modal open flags
|
||||||
const [editingLocation, setEditingLocation] = useState(false)
|
const [editingLocation, setEditingLocation] = useState(false)
|
||||||
const [editingAttributes, setEditingAttributes] = useState(false)
|
const [editingAttributes, setEditingAttributes] = useState(false)
|
||||||
const [editingLogging, setEditingLogging] = useState(false)
|
|
||||||
const [editingMisc, setEditingMisc] = useState(false)
|
const [editingMisc, setEditingMisc] = useState(false)
|
||||||
const [editingBellOutputs, setEditingBellOutputs] = useState(false)
|
const [editingBellOutputs, setEditingBellOutputs] = useState(false)
|
||||||
const [editingClockSettings, setEditingClockSettings] = useState(false)
|
const [editingClockSettings, setEditingClockSettings] = useState(false)
|
||||||
@@ -99,8 +121,29 @@ export default function DeviceDetail() {
|
|||||||
// ── Data fetching ──────────────────────────────────────────────────────────
|
// ── Data fetching ──────────────────────────────────────────────────────────
|
||||||
|
|
||||||
const loadDevice = useCallback(async () => {
|
const loadDevice = useCallback(async () => {
|
||||||
setLoading(true)
|
// Already showing this device (e.g. reload after a modal save) → refresh
|
||||||
|
// in place. Navigated here → seed from cache if we have it. Only a device
|
||||||
|
// we've never seen shows the full-page spinner.
|
||||||
|
const current = deviceRef.current?.id === id ? deviceRef.current : null
|
||||||
|
const seed = current || getCachedDevice(id)
|
||||||
|
if (!current) {
|
||||||
|
setDevice(seed)
|
||||||
|
setMqttStatus(seed ? getCachedStatus(seed.serial_number || seed.device_id) : null)
|
||||||
|
if (seed?.staffNotes) setStaffNotes(seed.staffNotes)
|
||||||
|
if (Array.isArray(seed?.tags)) setTags(seed.tags)
|
||||||
|
}
|
||||||
|
setLoading(!seed)
|
||||||
|
setRefreshing(true)
|
||||||
setError('')
|
setError('')
|
||||||
|
|
||||||
|
// Live status for just this device. Started right away when the serial
|
||||||
|
// is already known, in parallel with the device fetch.
|
||||||
|
const fetchStatus = sn => api.get(`/mqtt/status/${encodeURIComponent(sn)}`)
|
||||||
|
.then(st => setMqttStatus(st || null))
|
||||||
|
.catch(() => {})
|
||||||
|
const seedSn = seed?.serial_number || seed?.device_id
|
||||||
|
const statusPromise = seedSn ? fetchStatus(seedSn) : null
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const d = await api.get(`/devices/${id}`)
|
const d = await api.get(`/devices/${id}`)
|
||||||
setDevice(d)
|
setDevice(d)
|
||||||
@@ -109,14 +152,8 @@ export default function DeviceDetail() {
|
|||||||
setLoading(false)
|
setLoading(false)
|
||||||
|
|
||||||
const sn = d.serial_number || d.device_id
|
const sn = d.serial_number || d.device_id
|
||||||
if (sn) {
|
const statusDone = statusPromise || (sn ? fetchStatus(sn) : Promise.resolve())
|
||||||
api.get('/mqtt/status').then(mqttData => {
|
statusDone.finally(() => setRefreshing(false))
|
||||||
if (mqttData?.devices) {
|
|
||||||
const match = mqttData.devices.find(s => s.device_serial === sn)
|
|
||||||
setMqttStatus(match || null)
|
|
||||||
}
|
|
||||||
}).catch(() => {})
|
|
||||||
}
|
|
||||||
|
|
||||||
if (d.customer_id) {
|
if (d.customer_id) {
|
||||||
api.get(`/devices/${id}/customer`).then(res => {
|
api.get(`/devices/${id}/customer`).then(res => {
|
||||||
@@ -132,13 +169,28 @@ export default function DeviceDetail() {
|
|||||||
}).catch(() => setDeviceUsers([])).finally(() => setUsersLoading(false))
|
}).catch(() => setDeviceUsers([])).finally(() => setUsersLoading(false))
|
||||||
|
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
setError(err.message || 'Failed to load device.')
|
// Cached data on screen → keep it and stay quiet; otherwise show the error.
|
||||||
|
if (!seed) setError(err.message || 'Failed to load device.')
|
||||||
setLoading(false)
|
setLoading(false)
|
||||||
|
setRefreshing(false)
|
||||||
}
|
}
|
||||||
}, [id])
|
}, [id])
|
||||||
|
|
||||||
useEffect(() => { loadDevice() }, [loadDevice])
|
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 loadCmdHistory = useCallback(async () => {
|
||||||
const sn = device?.serial_number || device?.device_id
|
const sn = device?.serial_number || device?.device_id
|
||||||
if (!sn) return
|
if (!sn) return
|
||||||
@@ -157,6 +209,66 @@ export default function DeviceDetail() {
|
|||||||
if (activeTab === 'control' && device) loadCmdHistory()
|
if (activeTab === 'control' && device) loadCmdHistory()
|
||||||
}, [activeTab, 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 ───────────────────────────────────────────────────────────────
|
// ── Tab sync ───────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
const handleTabChange = key => {
|
const handleTabChange = key => {
|
||||||
@@ -213,20 +325,19 @@ export default function DeviceDetail() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const sendMqttCommand = async (cmd, contents = {}) => {
|
// Console-only friendly name — separate from device_name (the name the end
|
||||||
const deviceId = device?.device_id || device?.serial_number
|
// user gave the device in the app). Saves optimistically into local state
|
||||||
if (!deviceId) return
|
// so the hero title updates immediately; a failed save reverts and toasts.
|
||||||
setSendingCmd(cmd)
|
const handleSaveConsoleName = useCallback(async (newName) => {
|
||||||
|
const previous = device?.console_name || ''
|
||||||
|
setDevice(d => d ? { ...d, console_name: newName } : d)
|
||||||
try {
|
try {
|
||||||
await api.post(`/mqtt/command/${deviceId}`, { cmd, contents })
|
await api.put(`/devices/${id}`, { console_name: newName })
|
||||||
toast.success('Sent', `Command "${cmd}" sent.`)
|
|
||||||
loadCmdHistory()
|
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
toast.danger('Error', err.message || 'Failed to send command.')
|
setDevice(d => d ? { ...d, console_name: previous } : d)
|
||||||
} finally {
|
toast({ variant: 'danger', title: 'Failed to rename device', description: err.message || 'Please try again.' })
|
||||||
setSendingCmd('')
|
|
||||||
}
|
}
|
||||||
}
|
}, [id, device, toast])
|
||||||
|
|
||||||
// ── Derived ────────────────────────────────────────────────────────────────
|
// ── Derived ────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
@@ -272,6 +383,7 @@ export default function DeviceDetail() {
|
|||||||
stats,
|
stats,
|
||||||
sn,
|
sn,
|
||||||
isOnline,
|
isOnline,
|
||||||
|
mqttStatus,
|
||||||
tags,
|
tags,
|
||||||
setTags,
|
setTags,
|
||||||
staffNotes,
|
staffNotes,
|
||||||
@@ -284,14 +396,15 @@ export default function DeviceDetail() {
|
|||||||
cmdHistoryLoading,
|
cmdHistoryLoading,
|
||||||
sendingCmd,
|
sendingCmd,
|
||||||
loadDevice,
|
loadDevice,
|
||||||
|
reloadDeviceSilent,
|
||||||
loadCmdHistory,
|
loadCmdHistory,
|
||||||
sendMqttCommand,
|
sendMqttCommand,
|
||||||
|
sendMqttCommandSilent,
|
||||||
onShowDelete: () => setShowDelete(true),
|
onShowDelete: () => setShowDelete(true),
|
||||||
onAssignCustomer: () => setShowAssignCustomer(true),
|
onAssignCustomer: () => setShowAssignCustomer(true),
|
||||||
onUnassignCustomer: handleUnassignCustomer,
|
onUnassignCustomer: handleUnassignCustomer,
|
||||||
onEditLocation: () => setEditingLocation(true),
|
onEditLocation: () => setEditingLocation(true),
|
||||||
onEditAttributes: () => setEditingAttributes(true),
|
onEditAttributes: () => setEditingAttributes(true),
|
||||||
onEditLogging: () => setEditingLogging(true),
|
|
||||||
onEditMisc: () => setEditingMisc(true),
|
onEditMisc: () => setEditingMisc(true),
|
||||||
onEditBellOutputs: () => setEditingBellOutputs(true),
|
onEditBellOutputs: () => setEditingBellOutputs(true),
|
||||||
onEditClockSettings: () => setEditingClockSettings(true),
|
onEditClockSettings: () => setEditingClockSettings(true),
|
||||||
@@ -305,12 +418,54 @@ export default function DeviceDetail() {
|
|||||||
// ── Render ─────────────────────────────────────────────────────────────────
|
// ── Render ─────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="page-wrapper">
|
<div className="page-wrapper page-wrapper--capped">
|
||||||
|
|
||||||
<PageHeader
|
<PageHeader
|
||||||
title={device.device_name || 'Unnamed Device'}
|
title={
|
||||||
subtitle={sn}
|
<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 && (
|
{canEdit && (
|
||||||
<Button variant="secondary" onClick={() => navigate(`/devices/${id}/edit`)}>
|
<Button variant="secondary" onClick={() => navigate(`/devices/${id}/edit`)}>
|
||||||
Edit Device
|
Edit Device
|
||||||
@@ -326,6 +481,7 @@ export default function DeviceDetail() {
|
|||||||
|
|
||||||
<div style={{ flex: 1, minWidth: 0 }}>
|
<div style={{ flex: 1, minWidth: 0 }}>
|
||||||
{activeTab === 'overview' && <OverviewTab {...tabProps} />}
|
{activeTab === 'overview' && <OverviewTab {...tabProps} />}
|
||||||
|
{activeTab === 'health' && <HealthTab {...tabProps} />}
|
||||||
{activeTab === 'general' && <GeneralTab {...tabProps} />}
|
{activeTab === 'general' && <GeneralTab {...tabProps} />}
|
||||||
{activeTab === 'bells' && <BellsTab {...tabProps} />}
|
{activeTab === 'bells' && <BellsTab {...tabProps} />}
|
||||||
{activeTab === 'clock' && <ClockTab {...tabProps} />}
|
{activeTab === 'clock' && <ClockTab {...tabProps} />}
|
||||||
@@ -350,13 +506,6 @@ export default function DeviceDetail() {
|
|||||||
attr={attr}
|
attr={attr}
|
||||||
id={id}
|
id={id}
|
||||||
/>
|
/>
|
||||||
<EditLoggingModal
|
|
||||||
open={editingLogging}
|
|
||||||
onClose={() => setEditingLogging(false)}
|
|
||||||
onSaved={loadDevice}
|
|
||||||
attr={attr}
|
|
||||||
id={id}
|
|
||||||
/>
|
|
||||||
<EditMiscModal
|
<EditMiscModal
|
||||||
open={editingMisc}
|
open={editingMisc}
|
||||||
onClose={() => setEditingMisc(false)}
|
onClose={() => setEditingMisc(false)}
|
||||||
@@ -372,6 +521,7 @@ export default function DeviceDetail() {
|
|||||||
attr={attr}
|
attr={attr}
|
||||||
sub={sub}
|
sub={sub}
|
||||||
id={id}
|
id={id}
|
||||||
|
sendMqttCommand={sendMqttCommand}
|
||||||
/>
|
/>
|
||||||
<EditClockSettingsModal
|
<EditClockSettingsModal
|
||||||
open={editingClockSettings}
|
open={editingClockSettings}
|
||||||
@@ -380,6 +530,7 @@ export default function DeviceDetail() {
|
|||||||
attr={attr}
|
attr={attr}
|
||||||
sub={sub}
|
sub={sub}
|
||||||
id={id}
|
id={id}
|
||||||
|
sendMqttCommand={sendMqttCommand}
|
||||||
/>
|
/>
|
||||||
<EditAlertsModal
|
<EditAlertsModal
|
||||||
open={editingAlerts}
|
open={editingAlerts}
|
||||||
@@ -388,6 +539,7 @@ export default function DeviceDetail() {
|
|||||||
clock={clock}
|
clock={clock}
|
||||||
attr={attr}
|
attr={attr}
|
||||||
id={id}
|
id={id}
|
||||||
|
sendMqttCommand={sendMqttCommand}
|
||||||
/>
|
/>
|
||||||
<EditBacklightModal
|
<EditBacklightModal
|
||||||
open={editingBacklight}
|
open={editingBacklight}
|
||||||
@@ -397,6 +549,7 @@ export default function DeviceDetail() {
|
|||||||
clock={clock}
|
clock={clock}
|
||||||
sub={sub}
|
sub={sub}
|
||||||
id={id}
|
id={id}
|
||||||
|
sendMqttCommand={sendMqttCommand}
|
||||||
/>
|
/>
|
||||||
<EditSubscriptionModal
|
<EditSubscriptionModal
|
||||||
open={editingSubscription}
|
open={editingSubscription}
|
||||||
@@ -422,7 +575,7 @@ export default function DeviceDetail() {
|
|||||||
open={showDelete}
|
open={showDelete}
|
||||||
variant="danger"
|
variant="danger"
|
||||||
title="Delete Device"
|
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"
|
confirmLabel="Delete"
|
||||||
onConfirm={handleDelete}
|
onConfirm={handleDelete}
|
||||||
onCancel={() => setShowDelete(false)}
|
onCancel={() => setShowDelete(false)}
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user