feat: match the verified on-site poller payload

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 <noreply@anthropic.com>
This commit is contained in:
2026-10-21 09:43:55 +03:00
co-authored by Claude Opus 5.5
parent 0b0e4b7d6d
commit d01cef991f
15 changed files with 401 additions and 82 deletions
+119 -25
View File
@@ -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, <inverter_id>: 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, <inverter_id>: 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}