diff --git a/backend/app/api.py b/backend/app/api.py index 218080d..cfe91d9 100644 --- a/backend/app/api.py +++ b/backend/app/api.py @@ -1,3 +1,4 @@ +import json import logging import secrets import sqlite3 @@ -5,11 +6,12 @@ from datetime import date, datetime, timedelta, timezone from typing import Annotated from fastapi import APIRouter, Body, Depends, Header, HTTPException, Query +from pydantic import ValidationError from . import fields, health, store from .config import get_settings -from .db import get_db, set_meta -from .schemas import IngestResult, Inverter, InverterUpdate, ReadingIn, Summary +from .db import get_db, get_meta, set_meta +from .schemas import IngestResult, Inverter, InverterUpdate, ReadingIn, Summary, ViewSettings log = logging.getLogger("solar") router = APIRouter(prefix="/api") @@ -88,9 +90,25 @@ def get_summary(conn: Db): @router.get("/power", tags=["dashboard"]) -def get_fleet_power(conn: Db, start: FromQ = None, end: ToQ = None, bucket: BucketQ = None): +def get_fleet_power( + conn: Db, + start: FromQ = None, + end: ToQ = None, + bucket: BucketQ = None, + last_run: Annotated[ + bool, + Query(description="Ignore from/to and cover the latest production run (since the inverters last woke up)"), + ] = False, +): """AC power of every inverter over time (default: last 24 h).""" - s, e = _range(start, end, timedelta(hours=24)) + run = store.last_production_run(conn) if last_run else None + if run: + # A little margin either side; up to now while still producing + now = store.now_ts() + s = run[0] - 900 + e = now if now - run[1] <= 900 else run[1] + 900 + else: + s, e = _range(start, end, timedelta(hours=24)) b = store.pick_bucket(s, e, bucket) return { "from": store.to_dt(s), @@ -101,6 +119,38 @@ def get_fleet_power(conn: Db, start: FromQ = None, end: ToQ = None, bucket: Buck } +# ---------------------------------------------------------------- settings + +SETTINGS_KEY = "view_settings" + + +def _load_view_settings(conn: sqlite3.Connection) -> ViewSettings: + raw = get_meta(conn, SETTINGS_KEY) + try: + return ViewSettings.model_validate(json.loads(raw) if raw else {}) + except (ValueError, ValidationError): + log.warning("Stored view settings are invalid; using defaults") + return ViewSettings() + + +@router.get("/settings", response_model=ViewSettings, tags=["settings"]) +def get_view_settings(conn: Db): + """Dashboard display options, shared by every viewer.""" + return _load_view_settings(conn) + + +@router.put( + "/settings", + response_model=ViewSettings, + dependencies=[Depends(require_api_key)], + tags=["settings"], +) +def put_view_settings(conn: Db, body: ViewSettings): + """Replace the display options for every viewer. Omitted keys reset to their default.""" + set_meta(conn, SETTINGS_KEY, body.model_dump_json()) + return body + + @router.get("/energy/daily", tags=["dashboard"]) def get_fleet_daily_energy( conn: Db, diff --git a/backend/app/health.py b/backend/app/health.py index cf6cb4d..5399e76 100644 --- a/backend/app/health.py +++ b/backend/app/health.py @@ -14,6 +14,15 @@ from .config import get_settings from .db import get_meta +# Recent readings per inverter: their spacing tells each unit's reporting +# cadence; the newest few let clients average out a passing cloud. +RECENT_SAMPLES = 8 +RECENT_LOOKBACK_SECONDS = 2 * 3600 +RECENT_POWER_COUNT = 5 +RECENT_POWER_SECONDS = 1800 +MAX_ONLINE_WINDOW_SECONDS = 1800 + + def _minutes(seconds: int) -> str: if seconds < 3600: return f"{seconds // 60} min" @@ -39,10 +48,21 @@ def summary(conn: sqlite3.Connection) -> dict: latest = store.latest_all(conn) averages = store.window_averages(conn, s.underperform_window_seconds) energy_today = store.today_energy(conn) + recent = store.recent_readings(conn, RECENT_SAMPLES, RECENT_LOOKBACK_SECONDS) + + def window(inv_id: str) -> int: + """Silence allowed before offline: a couple of missed cycles at the + unit's own cadence (60 s local, ~5 min cloud), never below the + configured window.""" + ts = [x["ts"] for x in recent.get(inv_id, [])] + gaps = [a - b for a, b in zip(ts, ts[1:]) if a > b] + if not gaps: + return s.online_window_seconds + return int(min(MAX_ONLINE_WINDOW_SECONDS, max(s.online_window_seconds, 2.5 * statistics.median(gaps)))) def is_online(inv_id: str) -> bool: r = latest.get(inv_id) - return r is not None and r["age_seconds"] <= s.online_window_seconds + return r is not None and r["age_seconds"] <= window(inv_id) # Fleet comparison: per kWp when every producing inverter has a capacity # set, raw watts otherwise (assumes similar arrays). @@ -74,6 +94,7 @@ def summary(conn: sqlite3.Connection) -> dict: if not online: since = f"for {_minutes(r['age_seconds'])}" if r else "yet" + silent_s = r["age_seconds"] if r else None if not datalogger_online: state = "unknown" issues.append({ @@ -89,6 +110,7 @@ def summary(conn: sqlite3.Connection) -> dict: "code": "not_responding", "severity": "critical", "message": f"Not responding {since} while the datalogger is online", + "params": {"seconds": silent_s}, }) else: if r.get("error_code"): @@ -98,12 +120,14 @@ def summary(conn: sqlite3.Connection) -> dict: "code": "error_code", "severity": "critical", "message": f"Inverter reports error code {r['error_code']}{text}", + "params": {"error_code": r["error_code"], "status_text": r.get("status_text")}, }) if compare and relative is not None and relative < s.underperform_ratio: issues.append({ "code": "underperforming", "severity": "warning", "message": f"Producing {relative:.0%} of the fleet median — check strings, fuses and breakers", + "params": {"relative": relative}, }) avg = averages.get(inv["id"], {}) m1, m2 = avg.get("mppt1_w"), avg.get("mppt2_w") @@ -115,6 +139,7 @@ def summary(conn: sqlite3.Connection) -> dict: "code": "mppt_imbalance", "severity": "warning", "message": f"{weak} at {lo:.0f} W vs {hi:.0f} W on the other input — check that string", + "params": {"input": weak, "weak_w": round(lo), "strong_w": round(hi)}, }) if state == "ok" and issues: state = "warning" @@ -131,9 +156,15 @@ def summary(conn: sqlite3.Connection) -> dict: "issues": issues, "avg_power_w": round(averages[inv["id"]]["ac_power_w"]) if online and averages.get(inv["id"], {}).get("ac_power_w") is not None else None, "relative_output": relative, + "online_window_seconds": window(inv["id"]), }, "energy_today": energy_today.get(inv["id"], {"wh": None, "estimated": False}), "latest": r, + "recent_power": [ + {"timestamp": store.to_dt(x["ts"]), "ac_power_total_w": x["w"]} + for x in recent.get(inv["id"], []) + if x["ts"] >= now - RECENT_POWER_SECONDS + ][:RECENT_POWER_COUNT], }) today_values = [e["wh"] for e in energy_today.values() if e["wh"] is not None] diff --git a/backend/app/schemas.py b/backend/app/schemas.py index b498df8..2af4b46 100644 --- a/backend/app/schemas.py +++ b/backend/app/schemas.py @@ -82,6 +82,10 @@ class Issue(BaseModel): code: str severity: Severity message: str + params: dict[str, Any] = Field( + default_factory=dict, + description="Values inside the message, so clients can render it in their own language", + ) class Health(BaseModel): @@ -95,6 +99,10 @@ class Health(BaseModel): relative_output: float | None = Field( description="Output vs fleet median (1.0 = median), per kWp when capacities are set" ) + online_window_seconds: int = Field( + description="Silence after which this inverter counts as offline: ONLINE_WINDOW_SECONDS, " + "stretched for units that report slowly (e.g. cloud-polled every 5 min)" + ) class EnergyToday(BaseModel): @@ -102,11 +110,20 @@ class EnergyToday(BaseModel): estimated: bool = Field(description="Integrated from AC power, not the inverter's own counter") +class RecentPower(BaseModel): + timestamp: datetime + ac_power_total_w: int | None + + class InverterStatus(BaseModel): inverter: Inverter health: Health energy_today: EnergyToday latest: dict[str, Any] | None + recent_power: list[RecentPower] = Field( + description="Up to the last 5 readings of the past 30 min, newest first — lets clients " + "average out a single reading taken while a cloud shaded one array" + ) class Totals(BaseModel): @@ -130,6 +147,42 @@ class Sun(BaseModel): daylight: bool | None +PowerRange = Literal["30m", "1h", "3h", "6h", "24h", "run", "3d", "7d", "30d"] + + +class ViewSettings(BaseModel): + """Dashboard display options. Shared by every viewer (there are no user + accounts); unknown keys are ignored and missing ones take the default, + so older and newer clients can coexist.""" + + model_config = ConfigDict(extra="ignore") + + # Output comparison + comparison_readings: Literal[1, 3, 5] = Field( + default=1, description="Average the last N readings per inverter (1 = latest only)" + ) + comparison_scale: Literal["auto", "max", "custom"] = Field( + default="auto", + description="Bar length: auto = rounded-up ceiling above the highest, " + "max = highest inverter is a full bar, custom = comparison_custom_kw is a full bar", + ) + comparison_custom_kw: float | None = Field(default=None, gt=0, le=1000) + comparison_reference: Literal["median", "best", "custom"] = Field( + default="median", description="What the percentage is relative to" + ) + + # Fleet power chart + power_range: PowerRange = "24h" + power_smoothing: Literal["off", "light", "strong"] = "off" + + # Display + voltage_display: Literal["phase", "line"] = Field( + default="phase", + description="phase = line-to-neutral as sent (~240 V); line = x√3, matches the inverter screen (~415 V)", + ) + default_language: Literal["en", "el"] = "el" + + class Summary(BaseModel): generated_at: datetime datalogger: Datalogger diff --git a/backend/app/store.py b/backend/app/store.py index 142a276..452aee8 100644 --- a/backend/app/store.py +++ b/backend/app/store.py @@ -259,6 +259,43 @@ def window_averages(conn: sqlite3.Connection, seconds: int) -> dict[str, dict]: return {r["inverter_id"]: dict(r) for r in rows} +def recent_readings(conn: sqlite3.Connection, n: int, seconds: int) -> dict[str, list[dict]]: + """{inverter_id: [{ts, w}, ...]} — up to the last n readings of the past + `seconds`, newest first.""" + rows = conn.execute( + """ + SELECT inverter_id, ts, w FROM ( + SELECT inverter_id, ts, ac_power_total_w AS w, + row_number() OVER (PARTITION BY inverter_id ORDER BY ts DESC) AS rn + FROM readings WHERE ts >= ? + ) WHERE rn <= ? ORDER BY inverter_id, ts DESC + """, + (now_ts() - seconds, n), + ).fetchall() + out: dict[str, list[dict]] = {} + for r in rows: + out.setdefault(r["inverter_id"], []).append({"ts": r["ts"], "w": r["w"]}) + return out + + +def last_production_run(conn: sqlite3.Connection, gap_seconds: int = 5400) -> tuple[int, int] | None: + """(start, end) of the most recent stretch in which some inverter produced + power, split at silences longer than `gap_seconds` (the night). A unit + that keeps reporting 0 W overnight (cloud-polled) doesn't join the runs.""" + rows = conn.execute( + "SELECT DISTINCT ts FROM readings WHERE ac_power_total_w > 0 AND ts >= ? ORDER BY ts DESC", + (now_ts() - 4 * 86400,), + ).fetchall() + if not rows: + return None + end = start = rows[0]["ts"] + for r in rows[1:]: + if start - r["ts"] > gap_seconds: + break + start = r["ts"] + return start, end + + # ---------------------------------------------------------------- history diff --git a/backend/tests/test_api.py b/backend/tests/test_api.py index 9d575bb..34fa477 100644 --- a/backend/tests/test_api.py +++ b/backend/tests/test_api.py @@ -189,3 +189,57 @@ def test_energy_survives_out_of_order_readings(client): e = client.get("/api/summary").json()["inverters"][0]["energy_today"] if e["wh"] is not None: assert 2900 <= e["wh"] <= 3000 + + +def test_view_settings_shared_defaults_and_auth(client): + s = client.get("/api/settings").json() + assert s["comparison_readings"] == 1 and s["power_range"] == "24h" + + body = {**s, "comparison_readings": 3, "comparison_scale": "custom", "comparison_custom_kw": 25, + "power_range": "run", "power_smoothing": "light", "future_option": True} + assert client.put("/api/settings", json=body, headers={"X-API-Key": "nope"}).status_code == 401 + saved = client.put("/api/settings", json=body).json() + assert saved["comparison_custom_kw"] == 25 and "future_option" not in saved + assert client.get("/api/settings").json()["power_range"] == "run" + + assert client.put("/api/settings", json={"comparison_readings": 4}).status_code == 422 + + +def test_recent_power_and_slow_unit_stays_online(client): + now = int(time.time()) + batch = [onsite_payload("INV1", now - i * 60, 6000 + i) for i in range(7)] + # Cloud-polled unit: every 5 min, last one 8 min ago — beyond the 5 min + # default window but only ~1.5 of its own cycles + batch += [onsite_payload("INV5", now - 480 - i * 300, 5000) for i in range(6)] + client.post("/api/readings", json=batch) + + by_id = {x["inverter"]["id"]: x for x in client.get("/api/summary").json()["inverters"]} + assert [p["ac_power_total_w"] for p in by_id["INV1"]["recent_power"]] == [6000, 6001, 6002, 6003, 6004] + assert by_id["INV1"]["health"]["online_window_seconds"] == 300 + assert by_id["INV5"]["health"]["online"] is True + assert by_id["INV5"]["health"]["online_window_seconds"] == 750 + assert len(by_id["INV5"]["recent_power"]) == 5 + + +def test_issue_params_for_translation(client): + now = int(time.time()) + client.post("/api/readings", json=[ + onsite_payload("INV1", now, 7000), onsite_payload("INV2", now, 7000), onsite_payload("INV4", now, 2000), + ]) + inv4 = client.get("/api/summary").json()["inverters"][2]["health"] + assert inv4["issues"][0]["params"]["relative"] < 0.75 + + +def test_power_last_production_run(client): + now = int(time.time()) + # Yesterday's run, a night of silence, then this morning's run; INV5 + # reports 0 W all night and must not glue the runs together + batch = [onsite_payload("INV1", now - 20 * 3600 + i * 600, 5000) for i in range(6)] + batch += [onsite_payload("INV5", now - 18 * 3600 + i * 1800, 0, status=1) for i in range(30)] + batch += [onsite_payload("INV1", now - 3 * 3600 + i * 600, 5000) for i in range(18)] + client.post("/api/readings", json=batch) + + p = client.get("/api/power", params={"last_run": True}).json() + start = datetime.fromisoformat(p["from"]).timestamp() + assert abs(start - (now - 3 * 3600 - 900)) < 5 + assert abs(datetime.fromisoformat(p["to"]).timestamp() - now) < 5