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
+60
View File
@@ -0,0 +1,60 @@
# On-site poller
`refusol_poller.py` (not in this repo yet) reads the inverters over USS/TCP
(port 21062, USS address 0). It sends each cycle to the backend through
`backend_client.py` — copy that file next to the poller.
## Wiring it into `refusol_poller.py`
At the top of the file:
```python
from backend_client import BackendClient
BACKEND_URL = "https://solar.bonamin.net"
API_KEY = "same value as API_KEY in the server's .env"
backend = BackendClient(BACKEND_URL, API_KEY)
```
At the end of every poll cycle, one dict per inverter that answered:
```python
readings = []
for inverter_id, values in polled.items(): # however the poller holds them
readings.append({"inverter_id": inverter_id, **values})
backend.send(readings) # also call it when the list is empty
```
Each dict uses the keys below (all optional — send what was read). Anything
else you include (e.g. a newly discovered parameter as `"p0xx_raw": 1234`) is
stored too and shows under "Other (unmapped)" on the inverter page.
| key | unit | source |
|---|---|---|
| `ac_voltage_l1_v` / `_l2_v` / `_l3_v` | V | P050 / P05B / P064 raw / 40 |
| `dc_voltage_mppt1_v` / `_mppt2_v` | V | P052 / P054 raw / 40 |
| `dc_current_mppt1_a` / `_mppt2_a` | A | P05A / P05C raw / 10 |
| `ac_current_l1_a` / `_l2_a` / `_l3_a` | A | P068 / P069 / P06A raw / 100 |
| `ac_power_total_w` | W | P06D raw |
| `grid_frequency_hz` | Hz | P06C raw / 20 |
| `temperature_c` | °C | P070 raw >> 16 |
| `daily_energy_wh` | Wh | P063 IND=0 raw × 10 |
| `total_energy_wh` | Wh | P063 IND=11 raw |
| `status_code` | – | inverter state, once identified |
| `error_code` | – | non-zero = fault (shows the inverter as **Fault**) |
| `status_text` | – | optional human text for the code |
`send()` stamps each reading with the current UTC time, buffers to
`unsent_readings.jsonl` when the internet is down and re-sends later, and
never raises — a backend problem can't stop the polling loop.
**Call `send([])` even when no inverter answered.** That's the heartbeat that
lets the dashboard say "inverter not responding" (site online) instead of
"datalogger offline" (site/internet down).
## Trying the dashboard without the site
```bash
python fake_poller.py --url http://localhost:8090 --key change-me --backfill-days 30
```
+119
View File
@@ -0,0 +1,119 @@
"""Sends each poll cycle's readings to the Solar Monitor backend.
Standard library only — nothing to pip install on the site laptop.
from backend_client import BackendClient
client = BackendClient(BACKEND_URL, API_KEY)
...
client.send(readings) # once per poll cycle, list of dicts (may be empty)
- Every reading gets a UTC `timestamp` at the moment `send()` is called,
unless it already has one.
- If the backend can't be reached, readings are kept in a local spool file
and re-sent (oldest first) on later cycles, so an internet outage leaves no
gap in the history. The backend ignores duplicates, so re-sending is safe.
- Call `send([])` when no inverter answered: it still tells the backend the
datalogger is alive, which is how the dashboard tells a dead inverter apart
from a dead internet link.
"""
import json
import logging
import os
import urllib.error
import urllib.request
from datetime import datetime, timezone
log = logging.getLogger("backend_client")
BATCH_LIMIT = 200 # backend accepts up to 200 readings per POST
class BackendClient:
def __init__(
self,
backend_url: str,
api_key: str,
spool_path: str = "unsent_readings.jsonl",
max_spooled: int = 50_000, # ~1 week for 5 inverters at 1/min
timeout: float = 15,
):
self.url = backend_url.rstrip("/") + "/api/readings"
self.api_key = api_key
self.spool_path = spool_path
self.max_spooled = max_spooled
self.timeout = timeout
def send(self, readings: list[dict]) -> bool:
"""POST this cycle's readings (plus anything spooled). Never raises.
Returns True when everything was delivered."""
now = datetime.now(timezone.utc).isoformat(timespec="seconds")
readings = [{"timestamp": now, **r} for r in readings]
pending = self._load_spool()
if pending:
log.info("Re-sending %d spooled readings", len(pending))
queue = pending + readings
if not queue:
# Heartbeat: nothing to send, but the backend should know we're alive
return self._post([]) is not None
sent = 0
try:
while sent < len(queue):
chunk = queue[sent : sent + BATCH_LIMIT]
if self._post(chunk) is None:
break
sent += len(chunk)
finally:
self._save_spool(queue[sent:])
return sent == len(queue)
def _post(self, chunk: list[dict]) -> dict | None:
req = urllib.request.Request(
self.url,
data=json.dumps(chunk).encode(),
method="POST",
headers={"Content-Type": "application/json", "X-API-Key": self.api_key},
)
try:
with urllib.request.urlopen(req, timeout=self.timeout) as res:
return json.loads(res.read() or b"{}")
except urllib.error.HTTPError as e:
body = e.read().decode(errors="replace")[:300]
if e.code in (400, 422):
# The backend rejected the data itself — retrying won't help.
log.error("Backend rejected readings (%s): %s — dropping them", e.code, body)
return {}
log.warning("Backend error %s: %s", e.code, body)
except (urllib.error.URLError, TimeoutError, OSError) as e:
log.warning("Backend unreachable: %s", e)
return None
def _load_spool(self) -> list[dict]:
if not os.path.exists(self.spool_path):
return []
out = []
with open(self.spool_path, encoding="utf-8") as f:
for line in f:
line = line.strip()
if line:
try:
out.append(json.loads(line))
except json.JSONDecodeError:
pass
return out
def _save_spool(self, readings: list[dict]) -> None:
if len(readings) > self.max_spooled:
log.warning("Spool full — dropping %d oldest readings", len(readings) - self.max_spooled)
readings = readings[-self.max_spooled :]
if not readings:
if os.path.exists(self.spool_path):
os.remove(self.spool_path)
return
tmp = self.spool_path + ".tmp"
with open(tmp, "w", encoding="utf-8") as f:
for r in readings:
f.write(json.dumps(r) + "\n")
os.replace(tmp, self.spool_path)
+99
View File
@@ -0,0 +1,99 @@
"""Simulated inverters for trying the dashboard without the real site.
python fake_poller.py --url http://localhost:8090 --key change-me --backfill-days 30
--backfill-days first loads that many days of history (one reading per
5 minutes), then it posts live readings every --interval seconds. Inverter
INV3 runs with a dead MPPT2 string so the warnings show up.
"""
import argparse
import math
import random
import time
from datetime import datetime, timedelta, timezone
from backend_client import BackendClient
INVERTERS = ["INV1", "INV2", "INV3", "INV4", "INV5"]
PEAK_W = 18_000
def sun_factor(t: datetime) -> float:
# Rough local solar day 06:30–19:30 UTC+3, sine shaped
hour = (t.hour + 3 + t.minute / 60) % 24
x = (hour - 6.5) / 13
return max(0.0, math.sin(math.pi * x)) if 0 < x < 1 else 0.0
def reading(inv: str, t: datetime, state: dict) -> dict | None:
f = sun_factor(t) * random.uniform(0.93, 1.0)
if f <= 0.01:
return None # inverter asleep at night, doesn't answer
dead_mppt2 = inv == "INV3"
p_dc1 = PEAK_W / 2 * f
p_dc2 = 0 if dead_mppt2 else PEAK_W / 2 * f
v1, v2 = 560 + 60 * f, 560 + 60 * f
ac = int((p_dc1 + p_dc2) * 0.97)
day = t.date()
if state.get((inv, "day")) != day:
state[(inv, "day")] = day
state[(inv, "daily")] = 0
state[(inv, "daily")] += ac * state["step"] / 3600
state[(inv, "total")] = state.get((inv, "total"), 40_000_000) + ac * state["step"] / 3600
i_ac = ac / 3 / 230
return {
"inverter_id": inv,
"timestamp": t.isoformat(timespec="seconds"),
"ac_voltage_l1_v": round(random.uniform(228, 236), 1),
"ac_voltage_l2_v": round(random.uniform(228, 236), 1),
"ac_voltage_l3_v": round(random.uniform(228, 236), 1),
"dc_voltage_mppt1_v": round(v1, 1),
"dc_voltage_mppt2_v": round(v2 if not dead_mppt2 else 30.0, 1),
"dc_current_mppt1_a": round(p_dc1 / v1, 1),
"dc_current_mppt2_a": round(p_dc2 / v2, 1),
"ac_current_l1_a": round(i_ac, 2),
"ac_current_l2_a": round(i_ac, 2),
"ac_current_l3_a": round(i_ac, 2),
"ac_power_total_w": ac,
"grid_frequency_hz": round(random.uniform(49.95, 50.05), 2),
"temperature_c": int(30 + 25 * f),
"daily_energy_wh": int(state[(inv, "daily")] // 10 * 10),
"total_energy_wh": int(state[(inv, "total")]),
}
def main() -> None:
ap = argparse.ArgumentParser()
ap.add_argument("--url", default="http://localhost:8090")
ap.add_argument("--key", default="change-me")
ap.add_argument("--backfill-days", type=int, default=0)
ap.add_argument("--interval", type=int, default=60)
args = ap.parse_args()
client = BackendClient(args.url, args.key, spool_path="fake_unsent.jsonl")
state: dict = {}
if args.backfill_days:
state["step"] = 300
t = datetime.now(timezone.utc) - timedelta(days=args.backfill_days)
batch: list[dict] = []
while t < datetime.now(timezone.utc):
batch += [r for inv in INVERTERS if (r := reading(inv, t, state))]
if len(batch) >= 1000:
client.send(batch)
batch = []
t += timedelta(minutes=5)
client.send(batch)
print(f"Backfilled {args.backfill_days} days")
state["step"] = args.interval
while True:
now = datetime.now(timezone.utc)
batch = [r for inv in INVERTERS if (r := reading(inv, now, state))]
ok = client.send(batch)
print(f"{now:%H:%M:%S} sent {len(batch)} readings, ok={ok}")
time.sleep(args.interval)
if __name__ == "__main__":
main()