feat: solar inverter monitor — FastAPI + SQLite backend, React PWA dashboard

Monitoring for the Refusol 020K inverters. The on-site poller POSTs each
60 s cycle to /api/readings; the dashboard answers first whether every
inverter is operating and whether one is producing far less than its peers
(string fuse / breaker problems).

- Backend: FastAPI + SQLite. Parameters defined once in fields.py (columns
  auto-added on start); unknown poller keys are kept in `extra` since the
  parameter map is still being researched. Idempotent ingest, daily energy
  rollup in site-local days, history downsampling, 2-year retention.
- Health: Offline vs Sleeping (sun elevation) vs No data (datalogger
  silent, detected via empty-batch heartbeats), Fault from error_code,
  underperformance vs fleet median (per kWp when sizes set), MPPT imbalance.
- Frontend: mobile-first React + Tailwind, installable PWA, comparison bars,
  24 h power / 30 day energy charts, detail page with all parameters.
- Docker: backend + frontend + nginx on one port for NPM, as in
  bellsystems-cp; deploy-host.sh pulls main and rebuilds.
- poller/backend_client.py: stdlib client with offline spool for
  refusol_poller.py; fake_poller.py simulates the site.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-21 07:42:48 +03:00
co-authored by Claude Opus 5.5
commit d4b584e364
59 changed files with 10849 additions and 0 deletions
+23
View File
@@ -0,0 +1,23 @@
import pytest
from fastapi.testclient import TestClient
KEY = "test-key"
@pytest.fixture
def client(tmp_path, monkeypatch):
monkeypatch.setenv("DB_PATH", str(tmp_path / "test.db"))
monkeypatch.setenv("API_KEY", KEY)
# Midday sun at this position so silent inverters count as offline
monkeypatch.setenv("SITE_LATITUDE", "0")
monkeypatch.setenv("SITE_LONGITUDE", "0")
monkeypatch.setenv("DAYLIGHT_MIN_ELEVATION", "-90")
from app.config import get_settings
get_settings.cache_clear()
from app.main import app
with TestClient(app) as c:
c.headers["X-API-Key"] = KEY
yield c
get_settings.cache_clear()
+102
View File
@@ -0,0 +1,102 @@
import time
from datetime import datetime, timezone
def reading(inv, ts, power, **kw):
return {
"inverter_id": inv,
"timestamp": datetime.fromtimestamp(ts, timezone.utc).isoformat(),
"ac_power_total_w": power,
"ac_voltage_l1_v": 230.5,
"dc_voltage_mppt1_v": 600.0,
"dc_current_mppt1_a": power / 1200,
"dc_voltage_mppt2_v": 600.0,
"dc_current_mppt2_a": power / 1200,
"daily_energy_wh": 1000 + power,
"total_energy_wh": 5_000_000,
**kw,
}
def test_rejects_missing_key(client):
r = client.post("/api/readings", json=[], headers={"X-API-Key": "nope"})
assert r.status_code == 401
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()["duplicates"] == 1
latest = client.get("/api/inverters/inv1/latest").json()
assert latest["ac_power_total_w"] == 10000
assert latest["extra"] == {"p_new_param": 42}
assert latest["dc_power_total_w"] == 10000
def test_summary_flags_weak_and_silent_inverters(client):
now = int(time.time())
batch = []
for t in (now - 120, now - 60, now):
batch += [reading("inv1", t, 15000), reading("inv2", t, 14500), reading("inv3", t, 6000)]
# MPPT2 dead on inv4
batch.append(reading("inv4", t, 7500, dc_current_mppt1_a=12.5, dc_current_mppt2_a=0))
batch.append(reading("inv5", now - 3600, 15000))
batch.append(reading("inv6", now, 15000, error_code=301, status_text="Isolation fault"))
client.post("/api/readings", json=batch)
s = client.get("/api/summary").json()
by_id = {x["inverter"]["id"]: x["health"] for x in s["inverters"]}
assert s["datalogger"]["online"] is True
assert by_id["inv1"]["state"] == "ok"
assert by_id["inv3"]["state"] == "warning"
assert by_id["inv3"]["issues"][0]["code"] == "underperforming"
assert "mppt_imbalance" in [i["code"] for i in by_id["inv4"]["issues"]]
assert by_id["inv5"]["state"] == "offline" and not by_id["inv5"]["online"]
assert by_id["inv6"]["state"] == "fault"
assert s["totals"]["online_count"] == 5
assert s["totals"]["ac_power_w"] == 15000 + 14500 + 6000 + 7500 + 15000
def test_per_kwp_comparison_uses_capacity(client):
now = int(time.time())
client.post("/api/readings", json=[reading("big", now, 16000), reading("small", now, 8000)])
client.patch("/api/inverters/big", json={"capacity_kwp": 20, "name": "Roof A"})
client.patch("/api/inverters/small", json={"capacity_kwp": 10})
s = client.get("/api/summary").json()
assert s["fleet_median_w_per_kwp"] == 800
assert all(x["health"]["state"] == "ok" for x in s["inverters"])
assert s["inverters"][0]["inverter"]["name"] == "Roof A"
def test_history_power_and_daily(client):
now = int(time.time())
batch = [reading("inv1", now - i * 60, 1000 + i) for i in range(30)]
client.post("/api/readings", json=batch)
h = client.get("/api/inverters/inv1/history", params={"bucket": 600}).json()
assert h["bucket"] == 600 and 3 <= len(h["points"]) <= 4
assert "dc_power_mppt1_w" in h["points"][0]
p = client.get("/api/power").json()
assert p["inverters"] == ["inv1"] and p["points"][-1]["inv1"] > 0
d = client.get("/api/energy/daily", params={"days": 7}).json()
assert len(d["days"]) == 7
assert d["days"][-1]["total_wh"] >= 1000
d1 = client.get("/api/inverters/inv1/daily", params={"days": 3}).json()
assert d1["days"][-1]["peak_power_w"] == 1029
def test_empty_batch_marks_datalogger_alive(client):
s = client.get("/api/summary").json()
assert s["datalogger"]["online"] is False
client.post("/api/readings", json=[])
assert client.get("/api/summary").json()["datalogger"]["online"] is True
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