Files
refusol-datalogging/backend/app/health.py
T
bonaminandClaude Opus 5.5 8029468fb1 feat(api): shared view settings, recent readings, last production run
Groundwork for the dashboard settings page and the five-inverter contract:

- GET/PUT /api/settings stores display options (comparison averaging,
  scale and reference, power chart range and smoothing, voltage display,
  default language) in the meta table. Shared by every viewer since there
  are no accounts; PUT needs the API key so a public visitor can't change
  everyone's view. Unknown keys are ignored, missing ones take defaults.
- /api/summary returns each inverter's last few readings (recent_power) so
  the comparison can average out one reading taken under a passing cloud.
- Offline is now judged per inverter: a couple of missed cycles at the
  unit's own cadence (INV5 is cloud-polled every ~5 min), never below
  ONLINE_WINDOW_SECONDS. Before, INV5 flapped offline between reports.
- /api/power?last_run=true covers the latest production run, split at
  night silences; units reporting 0 W overnight don't join runs.
- Issues carry params so clients can render them in Greek.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 17:59:33 +03:00

191 lines
8.3 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
# 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"
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)
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"] <= window(inv_id)
# 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"
silent_s = r["age_seconds"] if r else None
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",
"params": {"seconds": silent_s},
})
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}",
"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")
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",
"params": {"input": weak, "weak_w": round(lo), "strong_w": round(hi)},
})
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,
"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]
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,
}