Files
refusol-datalogging/backend/app/main.py
T
bonaminandClaude Opus 5.5 d4b584e364 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>
2026-10-21 07:42:48 +03:00

55 lines
1.2 KiB
Python

import asyncio
import logging
from contextlib import asynccontextmanager
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from . import store
from .api import router
from .config import get_settings
from .db import migrate, session
log = logging.getLogger("solar")
PURGE_INTERVAL_SECONDS = 6 * 3600
def purge_once() -> None:
with session() as conn:
deleted = store.purge(conn, get_settings().retention_days)
if deleted:
log.info("Retention: purged %d readings", deleted)
async def purge_loop() -> None:
while True:
try:
await asyncio.to_thread(purge_once)
except Exception:
log.exception("Retention purge failed")
await asyncio.sleep(PURGE_INTERVAL_SECONDS)
@asynccontextmanager
async def lifespan(app: FastAPI):
migrate()
task = asyncio.create_task(purge_loop())
yield
task.cancel()
app = FastAPI(
title="Refusol Solar Monitor",
lifespan=lifespan,
docs_url="/api/docs",
redoc_url=None,
openapi_url="/api/openapi.json",
)
app.add_middleware(
CORSMiddleware,
allow_origins=get_settings().cors_origins,
allow_methods=["*"],
allow_headers=["*"],
)
app.include_router(router)