Files
refusol-datalogging/backend/app/health.py
T
bonaminandClaude Opus 5.5 d01cef991f 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>
2026-10-21 09:43:55 +03:00

160 lines
6.8 KiB
Python

"""Answers the two questions that matter most:
1. Is inverter X operational, or has it failed?
2. Is inverter X producing as much as its peers? A big gap usually means a
string fuse, breaker or connector problem on that array.
"""
import sqlite3
import statistics
from datetime import datetime, timezone
from . import store, sun
from .config import get_settings
from .db import get_meta
def _minutes(seconds: int) -> str:
if seconds < 3600:
return f"{seconds // 60} min"
if seconds < 86400:
return f"{seconds / 3600:.1f} h"
return f"{seconds / 86400:.1f} days"
def summary(conn: sqlite3.Connection) -> dict:
s = get_settings()
now = store.now_ts()
last_ingest = get_meta(conn, "last_ingest_at")
last_ingest = int(last_ingest) if last_ingest else None
datalogger_online = last_ingest is not None and now - last_ingest <= s.online_window_seconds
elevation = daylight = None
if s.site_latitude is not None and s.site_longitude is not None:
elevation = round(sun.elevation(datetime.now(timezone.utc), s.site_latitude, s.site_longitude), 1)
daylight = elevation >= s.daylight_min_elevation
inverters = store.list_inverters(conn)
latest = store.latest_all(conn)
averages = store.window_averages(conn, s.underperform_window_seconds)
energy_today = store.today_energy(conn)
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
# Fleet comparison: per kWp when every producing inverter has a capacity
# set, raw watts otherwise (assumes similar arrays).
producing = [i for i in inverters if is_online(i["id"]) and averages.get(i["id"], {}).get("ac_power_w") is not None]
per_kwp = bool(producing) and all(i["capacity_kwp"] for i in producing)
def specific(inv: dict) -> float | None:
w = averages.get(inv["id"], {}).get("ac_power_w")
if w is None:
return None
return w / inv["capacity_kwp"] if per_kwp else w
specs = [v for v in (specific(i) for i in producing) if v is not None]
median = statistics.median(specs) if len(specs) >= 2 else None
min_fleet = s.underperform_min_fleet_w_per_kwp if per_kwp else s.underperform_min_fleet_w
compare = median is not None and median >= min_fleet
statuses = []
for inv in inverters:
r = latest.get(inv["id"])
online = is_online(inv["id"])
issues: list[dict] = []
state = "ok"
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:
state = "unknown"
issues.append({
"code": "datalogger_offline",
"severity": "info",
"message": "No data from the site datalogger — inverter state unknown",
})
elif daylight is False:
state = "sleeping"
else:
state = "offline"
issues.append({
"code": "not_responding",
"severity": "critical",
"message": f"Not responding {since} while the datalogger is online",
})
else:
if r.get("error_code"):
state = "fault"
text = f" ({r['status_text']})" if r.get("status_text") else ""
issues.append({
"code": "error_code",
"severity": "critical",
"message": f"Inverter reports error code {r['error_code']}{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",
})
avg = averages.get(inv["id"], {})
m1, m2 = avg.get("mppt1_w"), avg.get("mppt2_w")
if inv["mppt_count"] >= 2 and m1 is not None and m2 is not None:
hi, lo = max(m1, m2), min(m1, m2)
if hi >= s.mppt_min_power_w and lo < hi * s.mppt_imbalance_ratio:
weak = "MPPT1" if m1 < m2 else "MPPT2"
issues.append({
"code": "mppt_imbalance",
"severity": "warning",
"message": f"{weak} at {lo:.0f} W vs {hi:.0f} W on the other input — check that string",
})
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(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")),
}
return {
"generated_at": datetime.now(timezone.utc),
"datalogger": {"online": datalogger_online, "last_ingest_at": store.to_dt(last_ingest)},
"sun": {"elevation": elevation, "daylight": daylight},
"totals": totals,
"fleet_median_w_per_kwp": round(median, 1) if median is not None and per_kwp else None,
"inverters": statuses,
}