From d01cef991f3f0e2bbe06efed85d0238df257e3e5 Mon Sep 17 00:00:00 2001
From: bonamin
Date: Wed, 21 Oct 2026 09:43:55 +0300
Subject: [PATCH] feat: match the verified on-site poller payload
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
The on-site agent found that the DC (P052/P054/P05A/P05C) and energy (P063)
registers are static/frozen and ac_power_total_w is now computed V*I, so
the backend and dashboard have to cope with those fields being absent.
- Feeding/Standby from status_code (FEEDING_STATUS_CODES, default 7 and 8:
INV1's OEM board uses 7). Online but not feeding = Standby; a standby
inverter while peers produce is still caught by the underperformance
check. Missing error_code stays "no fault".
- Daily energy falls back to AC power integrated between readings, flagged
estimated (≈ in the UI); out-of-order (spooled) readings recompute the
day. Existing databases get the column and a rebuild on startup.
- Totals are null instead of 0 when there's no energy data; lifetime shows
"not available yet". Parameters the poller doesn't send are hidden on the
detail page, DC lines only drawn when DC data exists.
- Timestamps more than 5 min in the future are stored at receive time and
counted in clamped_future — the example payload carried local Athens time
labelled +00:00.
Co-Authored-By: Claude Opus 5.5
---
.env.example | 12 ++
backend/app/api.py | 18 ++-
backend/app/config.py | 13 ++
backend/app/db.py | 12 +-
backend/app/health.py | 16 ++-
backend/app/main.py | 4 +-
backend/app/schemas.py | 21 +++-
backend/app/store.py | 144 +++++++++++++++++++----
backend/tests/test_api.py | 91 +++++++++++++-
frontend/src/components/Charts.jsx | 9 ++
frontend/src/components/Health.jsx | 6 +-
frontend/src/components/Icon.jsx | 6 +
frontend/src/components/InverterCard.jsx | 31 +++--
frontend/src/pages/Dashboard.jsx | 35 ++++--
frontend/src/pages/InverterDetail.jsx | 65 ++++++----
15 files changed, 401 insertions(+), 82 deletions(-)
diff --git a/.env.example b/.env.example
index 71a881a..4d16f56 100644
--- a/.env.example
+++ b/.env.example
@@ -34,6 +34,18 @@ UNDERPERFORM_MIN_FLEET_W=1000
MPPT_IMBALANCE_RATIO=0.5
MPPT_MIN_POWER_W=1000
+# status_code values meaning "feeding the grid" (JSON list): 8 on the
+# standard units, 7 on INV1's OEM board. Any other code shows as Standby.
+FEEDING_STATUS_CODES=[7, 8]
+
+# Readings stamped more than this many seconds in the future (poller clock
+# wrong, or local time sent as UTC) are stored at the time they arrive.
+MAX_FUTURE_SKEW_SECONDS=300
+
+# Daily energy is estimated by integrating AC power while the energy counters
+# aren't decoded; gaps between readings longer than this aren't bridged.
+ENERGY_INTEGRATION_MAX_GAP_SECONDS=300
+
# Browser origins allowed to call the API directly (JSON list). The dashboard
# itself is same-origin and doesn't need this.
CORS_ORIGINS=["*"]
diff --git a/backend/app/api.py b/backend/app/api.py
index a359337..218080d 100644
--- a/backend/app/api.py
+++ b/backend/app/api.py
@@ -1,3 +1,4 @@
+import logging
import secrets
import sqlite3
from datetime import date, datetime, timedelta, timezone
@@ -10,6 +11,7 @@ from .config import get_settings
from .db import get_db, set_meta
from .schemas import IngestResult, Inverter, InverterUpdate, ReadingIn, Summary
+log = logging.getLogger("solar")
router = APIRouter(prefix="/api")
Db = Annotated[sqlite3.Connection, Depends(get_db)]
@@ -69,9 +71,11 @@ def post_readings(conn: Db, readings: Annotated[list[ReadingIn], Body(max_length
"""Send an empty array when no inverter answered — it still tells the
backend the datalogger is alive, which is how a dead inverter is told
apart from a dead internet link."""
- stored, duplicates = store.ingest(conn, readings)
+ stored, duplicates, clamped = store.ingest(conn, readings)
set_meta(conn, "last_ingest_at", str(store.now_ts()))
- return {"received": len(readings), "stored": stored, "duplicates": duplicates}
+ if clamped:
+ log.warning("%d readings had future timestamps (clock/timezone wrong on the poller?)", clamped)
+ return {"received": len(readings), "stored": stored, "duplicates": duplicates, "clamped_future": clamped}
# ---------------------------------------------------------------- dashboard
@@ -181,14 +185,20 @@ def get_inverter_daily(
end: Annotated[date | None, Query(alias="to")] = None,
days: Annotated[int, Query(ge=1, le=3660)] = 365,
):
- """Energy and peak power per local day (default: last 365 days)."""
+ """Energy and peak power per local day (default: last 365 days).
+ `estimated` days are integrated from AC power, not the inverter's counter."""
_inverter_or_404(conn, inverter_id)
first, last = _day_range(start, end, days)
rows = store.daily_energy(conn, first, last, inverter_id)
return {
"inverter_id": inverter_id,
"days": [
- {"day": r["day"], "energy_wh": r.get(inverter_id), "peak_power_w": r.get("peak_power_w")}
+ {
+ "day": r["day"],
+ "energy_wh": r.get(inverter_id),
+ "estimated": r["estimated"],
+ "peak_power_w": r.get("peak_power_w"),
+ }
for r in rows
],
}
diff --git a/backend/app/config.py b/backend/app/config.py
index 5daddb8..7376be5 100644
--- a/backend/app/config.py
+++ b/backend/app/config.py
@@ -44,6 +44,19 @@ class Settings(BaseSettings):
mppt_imbalance_ratio: float = 0.5
mppt_min_power_w: float = 1000.0
+ # status_code values that mean the inverter is feeding the grid
+ # (8 on the standard units, 7 on the OEM board in INV1). Any other
+ # reported code shows as Standby.
+ feeding_status_codes: list[int] = [7, 8]
+
+ # Readings stamped further than this in the future (wrong clock or local
+ # time sent as UTC) are stored at the time they were received instead.
+ max_future_skew_seconds: int = 300
+
+ # Energy is estimated by integrating AC power between consecutive
+ # readings; gaps longer than this are not bridged.
+ energy_integration_max_gap_seconds: int = 300
+
cors_origins: list[str] = ["*"]
@field_validator("site_latitude", "site_longitude", mode="before")
diff --git a/backend/app/db.py b/backend/app/db.py
index 107a092..6e4c945 100644
--- a/backend/app/db.py
+++ b/backend/app/db.py
@@ -37,6 +37,9 @@ CREATE TABLE IF NOT EXISTS daily_energy (
total_min_wh INTEGER,
total_max_wh INTEGER,
peak_power_w INTEGER,
+ -- AC power integrated over time: the fallback while the inverter's
+ -- own energy counters aren't decoded
+ integrated_wh REAL,
PRIMARY KEY (inverter_id, day)
) WITHOUT ROWID;
@@ -72,13 +75,20 @@ def get_db() -> Iterator[sqlite3.Connection]:
yield conn
-def migrate() -> None:
+def migrate() -> bool:
+ """Create/upgrade the schema. Returns True when the integrated-energy
+ column was just added and has to be rebuilt from existing readings."""
with session() as conn:
conn.executescript(SCHEMA)
existing = {r["name"] for r in conn.execute("PRAGMA table_info(readings)")}
for f in FIELDS:
if f.key not in existing:
conn.execute(f"ALTER TABLE readings ADD COLUMN {f.key} {f.sql_type}")
+ daily_cols = {r["name"] for r in conn.execute("PRAGMA table_info(daily_energy)")}
+ if "integrated_wh" not in daily_cols:
+ conn.execute("ALTER TABLE daily_energy ADD COLUMN integrated_wh REAL")
+ return True
+ return False
def get_meta(conn: sqlite3.Connection, key: str) -> str | None:
diff --git a/backend/app/health.py b/backend/app/health.py
index 3061225..cf6cb4d 100644
--- a/backend/app/health.py
+++ b/backend/app/health.py
@@ -69,6 +69,9 @@ def summary(conn: sqlite3.Connection) -> dict:
spec = specific(inv) if online else None
relative = round(spec / median, 3) if spec is not None and median else None
+ code = r.get("status_code") if r else None
+ feeding = None if code is None else code in s.feeding_status_codes
+
if not online:
since = f"for {_minutes(r['age_seconds'])}" if r else "yet"
if not datalogger_online:
@@ -115,25 +118,34 @@ def summary(conn: sqlite3.Connection) -> dict:
})
if state == "ok" and issues:
state = "warning"
+ elif state == "ok" and feeding is False:
+ # Awake but not feeding (low light, or a state not decoded yet)
+ state = "standby"
statuses.append({
"inverter": inv,
"health": {
"online": online,
+ "feeding": feeding if online else None,
"state": state,
"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,
},
+ "energy_today": energy_today.get(inv["id"], {"wh": None, "estimated": False}),
"latest": r,
})
+ today_values = [e["wh"] for e in energy_today.values() if e["wh"] is not None]
+ lifetime_values = [r["total_energy_wh"] for r in latest.values() if r.get("total_energy_wh") is not None]
totals = {
"ac_power_w": sum((latest[i["id"]].get("ac_power_total_w") or 0) for i in inverters if is_online(i["id"])),
- "daily_energy_wh": sum(energy_today.values()),
- "total_energy_wh": sum((r.get("total_energy_wh") or 0) for r in latest.values()),
+ "daily_energy_wh": sum(today_values) if today_values else None,
+ "daily_energy_estimated": any(e["estimated"] for e in energy_today.values() if e["wh"] is not None),
+ "total_energy_wh": sum(lifetime_values) if lifetime_values else None,
"inverter_count": len(inverters),
"online_count": sum(1 for i in inverters if is_online(i["id"])),
+ "feeding_count": sum(1 for st in statuses if st["health"]["feeding"]),
"problem_count": sum(1 for st in statuses if st["health"]["state"] in ("fault", "warning", "offline")),
}
diff --git a/backend/app/main.py b/backend/app/main.py
index ea1a426..ba503cd 100644
--- a/backend/app/main.py
+++ b/backend/app/main.py
@@ -32,7 +32,9 @@ async def purge_loop() -> None:
@asynccontextmanager
async def lifespan(app: FastAPI):
- migrate()
+ if migrate():
+ with session() as conn:
+ store.rebuild_integrated_energy(conn)
task = asyncio.create_task(purge_loop())
yield
task.cancel()
diff --git a/backend/app/schemas.py b/backend/app/schemas.py
index 4bd5060..b498df8 100644
--- a/backend/app/schemas.py
+++ b/backend/app/schemas.py
@@ -49,6 +49,10 @@ class IngestResult(BaseModel):
received: int
stored: int
duplicates: int
+ clamped_future: int = Field(
+ description="Readings stamped in the future (clock wrong, or local time sent as UTC); "
+ "stored at the time they were received instead"
+ )
class InverterUpdate(BaseModel):
@@ -71,7 +75,7 @@ class Inverter(BaseModel):
Severity = Literal["info", "warning", "critical"]
-State = Literal["ok", "warning", "fault", "offline", "sleeping", "unknown"]
+State = Literal["ok", "standby", "warning", "fault", "offline", "sleeping", "unknown"]
class Issue(BaseModel):
@@ -82,6 +86,9 @@ class Issue(BaseModel):
class Health(BaseModel):
online: bool = Field(description="A reading arrived within ONLINE_WINDOW_SECONDS")
+ feeding: bool | None = Field(
+ description="status_code is one of FEEDING_STATUS_CODES; null when no status_code is reported"
+ )
state: State
issues: list[Issue]
avg_power_w: float | None = Field(description="Mean AC power over the comparison window")
@@ -90,18 +97,26 @@ class Health(BaseModel):
)
+class EnergyToday(BaseModel):
+ wh: int | None
+ estimated: bool = Field(description="Integrated from AC power, not the inverter's own counter")
+
+
class InverterStatus(BaseModel):
inverter: Inverter
health: Health
+ energy_today: EnergyToday
latest: dict[str, Any] | None
class Totals(BaseModel):
ac_power_w: int
- daily_energy_wh: int
- total_energy_wh: int
+ daily_energy_wh: int | None
+ daily_energy_estimated: bool
+ total_energy_wh: int | None = Field(description="Null until the inverters report a lifetime counter")
inverter_count: int
online_count: int
+ feeding_count: int
problem_count: int
diff --git a/backend/app/store.py b/backend/app/store.py
index 57fe8eb..142a276 100644
--- a/backend/app/store.py
+++ b/backend/app/store.py
@@ -37,26 +37,76 @@ def today() -> date:
# ---------------------------------------------------------------- ingest
-def _ts_of(r: ReadingIn) -> int:
+def _ts_of(r: ReadingIn, received: int) -> tuple[int, bool]:
+ """Reading time in unix seconds, and whether it had to be clamped
+ because it lay in the future (bad clock / local time sent as UTC)."""
if r.timestamp is None:
- return now_ts()
+ return received, False
t = r.timestamp
if t.tzinfo is None:
t = t.replace(tzinfo=timezone.utc)
- return int(t.timestamp())
+ ts = int(t.timestamp())
+ if ts > received + get_settings().max_future_skew_seconds:
+ return received, True
+ return ts, False
-def ingest(conn: sqlite3.Connection, readings: list[ReadingIn]) -> tuple[int, int]:
- """Store readings; returns (stored, duplicates). Re-sent readings (same
- inverter + timestamp) are ignored, so the poller can safely retry."""
- stored = 0
+def _integrate(conn: sqlite3.Connection, inverter_id: str, ts: int, power: int | None) -> float | None:
+ """Wh produced since the previous reading (trapezoid rule), or None when
+ there's nothing to add (no power, first reading, gap too long)."""
+ if power is None:
+ return None
+ prev = conn.execute(
+ "SELECT ts, ac_power_total_w AS w FROM readings "
+ "WHERE inverter_id = ? AND ts < ? ORDER BY ts DESC LIMIT 1",
+ (inverter_id, ts),
+ ).fetchone()
+ if not prev or prev["w"] is None:
+ return None
+ dt = ts - prev["ts"]
+ if dt > get_settings().energy_integration_max_gap_seconds:
+ return None
+ return (prev["w"] + power) / 2 * dt / 3600
+
+
+def _integrated_for_day(conn: sqlite3.Connection, inverter_id: str, day: str) -> float:
+ """Integrated Wh for one inverter and local day, from scratch."""
+ tz = site_tz()
+ start = int(datetime.combine(date.fromisoformat(day), datetime.min.time(), tz).timestamp())
+ end = start + 2 * 86400 # covers DST days; filtered by local_day below
+ max_gap = get_settings().energy_integration_max_gap_seconds
+ rows = conn.execute(
+ "SELECT ts, ac_power_total_w AS w FROM readings "
+ "WHERE inverter_id = ? AND ts >= ? AND ts < ? ORDER BY ts",
+ (inverter_id, start - max_gap, end),
+ ).fetchall()
+ total, prev = 0.0, None
+ for r in rows:
+ if (
+ prev
+ and prev["w"] is not None
+ and r["w"] is not None
+ and r["ts"] - prev["ts"] <= max_gap
+ and local_day(r["ts"]) == day
+ ):
+ total += (prev["w"] + r["w"]) / 2 * (r["ts"] - prev["ts"]) / 3600
+ prev = r
+ return total
+
+
+def ingest(conn: sqlite3.Connection, readings: list[ReadingIn]) -> tuple[int, int, int]:
+ """Store readings; returns (stored, duplicates, clamped). Re-sent readings
+ (same inverter + timestamp) are ignored, so the poller can safely retry."""
+ stored = clamped = 0
+ received = now_ts()
cols = ["inverter_id", "ts", "extra", *FIELD_KEYS]
insert_sql = (
f"INSERT OR IGNORE INTO readings ({', '.join(cols)}) "
f"VALUES ({', '.join('?' for _ in cols)})"
)
for r in readings:
- ts = _ts_of(r)
+ ts, was_clamped = _ts_of(r, received)
+ clamped += was_clamped
values = r.model_dump(include=set(FIELD_KEYS))
extra = {**(r.model_extra or {}), **(r.extra or {})}
@@ -76,13 +126,21 @@ def ingest(conn: sqlite3.Connection, readings: list[ReadingIn]) -> tuple[int, in
if cur.rowcount == 0:
continue
stored += 1
+ # A reading arriving after a later one (re-sent from the poller's
+ # spool out of order) changes intervals already counted: recompute
+ # that day instead of adding to it.
+ out_of_order = conn.execute(
+ "SELECT 1 FROM readings WHERE inverter_id = ? AND ts > ? LIMIT 1", (r.inverter_id, ts)
+ ).fetchone() is not None
+ integrated_wh = None if out_of_order else _integrate(conn, r.inverter_id, ts, values["ac_power_total_w"])
# max()/min() of two values where either may be NULL
conn.execute(
"""
INSERT INTO daily_energy
- (inverter_id, day, daily_energy_wh, total_min_wh, total_max_wh, peak_power_w)
- VALUES (?, ?, ?, ?, ?, ?)
+ (inverter_id, day, daily_energy_wh, total_min_wh, total_max_wh, peak_power_w,
+ integrated_wh)
+ VALUES (?, ?, ?, ?, ?, ?, ?)
ON CONFLICT (inverter_id, day) DO UPDATE SET
daily_energy_wh = max(coalesce(daily_energy_wh, excluded.daily_energy_wh),
coalesce(excluded.daily_energy_wh, daily_energy_wh)),
@@ -91,7 +149,8 @@ def ingest(conn: sqlite3.Connection, readings: list[ReadingIn]) -> tuple[int, in
total_max_wh = max(coalesce(total_max_wh, excluded.total_max_wh),
coalesce(excluded.total_max_wh, total_max_wh)),
peak_power_w = max(coalesce(peak_power_w, excluded.peak_power_w),
- coalesce(excluded.peak_power_w, peak_power_w))
+ coalesce(excluded.peak_power_w, peak_power_w)),
+ integrated_wh = coalesce(integrated_wh, 0) + coalesce(excluded.integrated_wh, 0)
""",
(
r.inverter_id,
@@ -100,9 +159,37 @@ def ingest(conn: sqlite3.Connection, readings: list[ReadingIn]) -> tuple[int, in
values["total_energy_wh"],
values["total_energy_wh"],
values["ac_power_total_w"],
+ integrated_wh,
),
)
- return stored, len(readings) - stored
+ if out_of_order:
+ day = local_day(ts)
+ conn.execute(
+ "UPDATE daily_energy SET integrated_wh = ? WHERE inverter_id = ? AND day = ?",
+ (_integrated_for_day(conn, r.inverter_id, day), r.inverter_id, day),
+ )
+ return stored, len(readings) - stored, clamped
+
+
+def rebuild_integrated_energy(conn: sqlite3.Connection) -> None:
+ """Recompute daily integrated energy from the stored readings."""
+ max_gap = get_settings().energy_integration_max_gap_seconds
+ totals: dict[tuple[str, str], float] = {}
+ prev: dict[str, tuple[int, int | None]] = {}
+ for r in conn.execute(
+ "SELECT inverter_id, ts, ac_power_total_w AS w FROM readings ORDER BY inverter_id, ts"
+ ):
+ p = prev.get(r["inverter_id"])
+ if p and p[1] is not None and r["w"] is not None and r["ts"] - p[0] <= max_gap:
+ key = (r["inverter_id"], local_day(r["ts"]))
+ totals[key] = totals.get(key, 0) + (p[1] + r["w"]) / 2 * (r["ts"] - p[0]) / 3600
+ prev[r["inverter_id"]] = (r["ts"], r["w"])
+ conn.execute("UPDATE daily_energy SET integrated_wh = NULL")
+ for (inv, day), wh in totals.items():
+ conn.execute(
+ "UPDATE daily_energy SET integrated_wh = ? WHERE inverter_id = ? AND day = ?",
+ (wh, inv, day),
+ )
def purge(conn: sqlite3.Connection, retention_days: int) -> int:
@@ -238,15 +325,21 @@ def fleet_power(conn: sqlite3.Connection, start: int, end: int, bucket: int) ->
return list(points.values())
+# Best available energy for a day: the inverter's daily counter, else the
+# lifetime counter's growth, else AC power integrated over time (estimate).
+ENERGY_SQL = """
+ coalesce(daily_energy_wh, total_max_wh - total_min_wh, cast(round(integrated_wh) AS INTEGER)) AS wh,
+ (daily_energy_wh IS NULL AND total_max_wh IS NULL AND integrated_wh IS NOT NULL) AS estimated
+"""
+
+
def daily_energy(
conn: sqlite3.Connection, first: date, last: date, inverter_id: str | None = None
) -> list[dict]:
- """[{day, total_wh, : Wh, ...}] for every day in range, oldest first.
- Uses the inverter's own daily counter, falling back to the lifetime
- counter's growth over the day when the daily counter wasn't reported."""
- sql = """
- SELECT day, inverter_id, peak_power_w,
- coalesce(daily_energy_wh, total_max_wh - total_min_wh) AS wh
+ """[{day, total_wh, estimated, : Wh, ...}] for every day in
+ range, oldest first. Days with no data have total_wh null."""
+ sql = f"""
+ SELECT day, inverter_id, peak_power_w, {ENERGY_SQL}
FROM daily_energy WHERE day >= ? AND day <= ?
"""
params: list = [first.isoformat(), last.isoformat()]
@@ -256,22 +349,23 @@ def daily_energy(
by_day: dict[str, dict] = {}
d = first
while d <= last:
- by_day[d.isoformat()] = {"day": d.isoformat(), "total_wh": 0}
+ by_day[d.isoformat()] = {"day": d.isoformat(), "total_wh": None, "estimated": False}
d += timedelta(days=1)
for r in conn.execute(sql, params):
row = by_day[r["day"]]
row[r["inverter_id"]] = r["wh"]
- row["total_wh"] += r["wh"] or 0
+ if r["wh"] is not None:
+ row["total_wh"] = (row["total_wh"] or 0) + r["wh"]
+ row["estimated"] = row["estimated"] or bool(r["estimated"])
if inverter_id:
row["peak_power_w"] = r["peak_power_w"]
return list(by_day.values())
-def today_energy(conn: sqlite3.Connection) -> dict[str, int]:
+def today_energy(conn: sqlite3.Connection) -> dict[str, dict]:
+ """{inverter_id: {"wh": int | None, "estimated": bool}} for today."""
rows = conn.execute(
- "SELECT inverter_id, coalesce(daily_energy_wh, total_max_wh - total_min_wh) AS wh "
- "FROM daily_energy WHERE day = ?",
+ f"SELECT inverter_id, {ENERGY_SQL} FROM daily_energy WHERE day = ?",
(today().isoformat(),),
)
- return {r["inverter_id"]: r["wh"] or 0 for r in rows}
-
+ return {r["inverter_id"]: {"wh": r["wh"], "estimated": bool(r["estimated"])} for r in rows}
diff --git a/backend/tests/test_api.py b/backend/tests/test_api.py
index 5c5fd2c..9d575bb 100644
--- a/backend/tests/test_api.py
+++ b/backend/tests/test_api.py
@@ -26,7 +26,9 @@ def test_rejects_missing_key(client):
def test_ingest_is_idempotent_and_keeps_unknown_fields(client):
now = int(time.time())
batch = [reading("inv1", now, 10000, p_new_param=42)]
- assert client.post("/api/readings", json=batch).json() == {"received": 1, "stored": 1, "duplicates": 0}
+ assert client.post("/api/readings", json=batch).json() == {
+ "received": 1, "stored": 1, "duplicates": 0, "clamped_future": 0
+ }
assert client.post("/api/readings", json=batch).json()["duplicates"] == 1
latest = client.get("/api/inverters/inv1/latest").json()
@@ -100,3 +102,90 @@ def test_empty_batch_marks_datalogger_alive(client):
def test_fields_meta(client):
keys = [f["key"] for f in client.get("/api/meta/fields").json()]
assert "ac_power_total_w" in keys and "efficiency_pct" in keys
+
+
+def onsite_payload(inv, ts, power=6882, status=8):
+ """Exactly what the real on-site poller sends (2026-10-21)."""
+ return {
+ "timestamp": datetime.fromtimestamp(ts, timezone.utc).isoformat(),
+ "inverter_id": inv,
+ "ac_voltage_l1_v": 232.6, "ac_voltage_l2_v": 233.35, "ac_voltage_l3_v": 232.62,
+ "ac_current_l1_a": 11.75, "ac_current_l2_a": 9.16, "ac_current_l3_a": 8.95,
+ "ac_power_total_w": power, "grid_frequency_hz": 50.0, "temperature_c": 36,
+ "status_code": status, "status_text": "feeding" if status in (7, 8) else "standby/not feeding",
+ "p06d_raw_latched": 21450, "p052_static_v": 312.5, "p05a_static_a": 45.0,
+ "p063_ind0_raw": 1872,
+ }
+
+
+def test_onsite_payload_accepted_and_ok(client):
+ now = int(time.time())
+ batch = [onsite_payload("INV1", now, 6900, status=7), onsite_payload("INV2", now), onsite_payload("INV4", now, 6800)]
+ r = client.post("/api/readings", json=batch)
+ assert r.status_code == 200
+ assert r.json() == {"received": 3, "stored": 3, "duplicates": 0, "clamped_future": 0}
+
+ s = client.get("/api/summary").json()
+ for st in s["inverters"]:
+ assert st["health"]["state"] == "ok", st
+ assert st["health"]["feeding"] is True
+ latest = s["inverters"][1]["latest"]
+ assert latest["extra"]["p06d_raw_latched"] == 21450
+ assert latest["dc_power_total_w"] is None and latest["efficiency_pct"] is None
+ # No energy counters sent: lifetime unknown, today not yet integrated
+ assert s["totals"]["total_energy_wh"] is None
+ assert s["totals"]["feeding_count"] == 3
+
+
+def test_not_feeding_is_standby_and_flagged_when_peers_produce(client):
+ now = int(time.time())
+ client.post("/api/readings", json=[
+ onsite_payload("INV1", now, 6900), onsite_payload("INV2", now, 7000),
+ onsite_payload("INV4", now, 0, status=3),
+ ])
+ by_id = {x["inverter"]["id"]: x["health"] for x in client.get("/api/summary").json()["inverters"]}
+ assert by_id["INV4"]["feeding"] is False
+ assert by_id["INV4"]["state"] == "warning" # 0 W while the others make ~7 kW
+
+
+def test_all_idle_is_plain_standby(client):
+ # Everyone awake but not feeding (e.g. dusk): standby, no alarm
+ now = int(time.time())
+ client.post("/api/readings", json=[onsite_payload(i, now, 0, status=3) for i in ("INV1", "INV2", "INV4")])
+ states = {x["health"]["state"] for x in client.get("/api/summary").json()["inverters"]}
+ assert states == {"standby"}
+
+
+def test_heartbeat(client):
+ r = client.post("/api/readings", json=[])
+ assert r.status_code == 200 and r.json()["received"] == 0
+
+
+def test_future_timestamp_is_clamped(client):
+ now = int(time.time())
+ r = client.post("/api/readings", json=[onsite_payload("INV2", now + 3 * 3600)]).json()
+ assert r["clamped_future"] == 1
+ latest = client.get("/api/inverters/INV2/latest").json()
+ assert abs(latest["age_seconds"]) < 5
+
+
+def test_energy_integrated_from_power_when_no_counters(client):
+ now = int(time.time())
+ # 6 kW for 30 minutes at 60 s steps -> 3 kWh
+ client.post("/api/readings", json=[onsite_payload("INV1", now - 1800 + i * 60, 6000) for i in range(31)])
+ s = client.get("/api/summary").json()
+ e = s["inverters"][0]["energy_today"]
+ if e["wh"] is not None: # skip when the window straddles local midnight
+ assert e["estimated"] is True
+ assert 2900 <= e["wh"] <= 3000
+ assert s["totals"]["daily_energy_estimated"] is True
+
+
+def test_energy_survives_out_of_order_readings(client):
+ now = int(time.time())
+ # Latest reading arrives first, then the earlier ones (spool re-send)
+ client.post("/api/readings", json=[onsite_payload("INV1", now, 6000)])
+ client.post("/api/readings", json=[onsite_payload("INV1", now - 1800 + i * 60, 6000) for i in range(30)])
+ e = client.get("/api/summary").json()["inverters"][0]["energy_today"]
+ if e["wh"] is not None:
+ assert 2900 <= e["wh"] <= 3000
diff --git a/frontend/src/components/Charts.jsx b/frontend/src/components/Charts.jsx
index 2653ead..326d454 100644
--- a/frontend/src/components/Charts.jsx
+++ b/frontend/src/components/Charts.jsx
@@ -189,3 +189,12 @@ export function DayBars({ days, series, format, axisFormat, height = 220 }) {
)
}
+
+export function EnergyFootnote({ estimated }) {
+ return (
+
+ {estimated && '≈ Estimated from AC power readings until the energy counters are decoded'}
+ axis in kWh
+
- MPPT1 and MPPT2 should track each other when both carry similar strings — one dropping
- away from the other points at that string.
+ {hasDc
+ ? 'MPPT1 and MPPT2 should track each other when both carry similar strings — one dropping away from the other points at that string.'
+ : 'DC input (MPPT) values are not available yet.'}