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:
@@ -0,0 +1,219 @@
|
||||
import secrets
|
||||
import sqlite3
|
||||
from datetime import date, datetime, timedelta, timezone
|
||||
from typing import Annotated
|
||||
|
||||
from fastapi import APIRouter, Body, Depends, Header, HTTPException, Query
|
||||
|
||||
from . import fields, health, store
|
||||
from .config import get_settings
|
||||
from .db import get_db, set_meta
|
||||
from .schemas import IngestResult, Inverter, InverterUpdate, ReadingIn, Summary
|
||||
|
||||
router = APIRouter(prefix="/api")
|
||||
Db = Annotated[sqlite3.Connection, Depends(get_db)]
|
||||
|
||||
|
||||
def require_api_key(x_api_key: Annotated[str | None, Header()] = None) -> None:
|
||||
if not x_api_key or not secrets.compare_digest(x_api_key, get_settings().api_key):
|
||||
raise HTTPException(401, "Invalid or missing X-API-Key")
|
||||
|
||||
|
||||
def _range(start: datetime | None, end: datetime | None, default: timedelta) -> tuple[int, int]:
|
||||
def ts(d: datetime) -> int:
|
||||
return int((d if d.tzinfo else d.replace(tzinfo=timezone.utc)).timestamp())
|
||||
|
||||
e = ts(end) if end else store.now_ts()
|
||||
s = ts(start) if start else e - int(default.total_seconds())
|
||||
if s >= e:
|
||||
raise HTTPException(422, "'from' must be before 'to'")
|
||||
return s, e
|
||||
|
||||
|
||||
def _day_range(start: date | None, end: date | None, days: int) -> tuple[date, date]:
|
||||
last = end or store.today()
|
||||
first = start or last - timedelta(days=days - 1)
|
||||
if first > last:
|
||||
raise HTTPException(422, "'from' must not be after 'to'")
|
||||
if (last - first).days > 3660:
|
||||
raise HTTPException(422, "Range too long (max 10 years)")
|
||||
return first, last
|
||||
|
||||
|
||||
def _inverter_or_404(conn: sqlite3.Connection, inverter_id: str) -> dict:
|
||||
inv = store.get_inverter(conn, inverter_id)
|
||||
if not inv:
|
||||
raise HTTPException(404, f"Unknown inverter '{inverter_id}'")
|
||||
return inv
|
||||
|
||||
|
||||
FromQ = Annotated[datetime | None, Query(alias="from", description="ISO timestamp, UTC if no offset")]
|
||||
ToQ = Annotated[datetime | None, Query(alias="to", description="ISO timestamp, UTC if no offset")]
|
||||
BucketQ = Annotated[
|
||||
int | None,
|
||||
Query(ge=60, le=86400, description="Seconds per point. Omit to pick one giving ≤600 points."),
|
||||
]
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- ingest
|
||||
|
||||
|
||||
@router.post(
|
||||
"/readings",
|
||||
response_model=IngestResult,
|
||||
dependencies=[Depends(require_api_key)],
|
||||
tags=["ingest"],
|
||||
summary="Ingest one poll cycle (one object per inverter)",
|
||||
)
|
||||
def post_readings(conn: Db, readings: Annotated[list[ReadingIn], Body(max_length=200)]):
|
||||
"""Send an empty array when no inverter answered — it still tells the
|
||||
backend the datalogger is alive, which is how a dead inverter is told
|
||||
apart from a dead internet link."""
|
||||
stored, duplicates = store.ingest(conn, readings)
|
||||
set_meta(conn, "last_ingest_at", str(store.now_ts()))
|
||||
return {"received": len(readings), "stored": stored, "duplicates": duplicates}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- dashboard
|
||||
|
||||
|
||||
@router.get("/summary", response_model=Summary, tags=["dashboard"])
|
||||
def get_summary(conn: Db):
|
||||
"""Latest reading + health of every inverter, fleet totals."""
|
||||
return health.summary(conn)
|
||||
|
||||
|
||||
@router.get("/power", tags=["dashboard"])
|
||||
def get_fleet_power(conn: Db, start: FromQ = None, end: ToQ = None, bucket: BucketQ = None):
|
||||
"""AC power of every inverter over time (default: last 24 h)."""
|
||||
s, e = _range(start, end, timedelta(hours=24))
|
||||
b = store.pick_bucket(s, e, bucket)
|
||||
return {
|
||||
"from": store.to_dt(s),
|
||||
"to": store.to_dt(e),
|
||||
"bucket": b,
|
||||
"inverters": [i["id"] for i in store.list_inverters(conn)],
|
||||
"points": store.fleet_power(conn, s, e, b),
|
||||
}
|
||||
|
||||
|
||||
@router.get("/energy/daily", tags=["dashboard"])
|
||||
def get_fleet_daily_energy(
|
||||
conn: Db,
|
||||
start: Annotated[date | None, Query(alias="from")] = None,
|
||||
end: Annotated[date | None, Query(alias="to")] = None,
|
||||
days: Annotated[int, Query(ge=1, le=3660)] = 30,
|
||||
):
|
||||
"""Energy per local day for every inverter plus the total (default: last 30 days)."""
|
||||
first, last = _day_range(start, end, days)
|
||||
return {
|
||||
"inverters": [i["id"] for i in store.list_inverters(conn)],
|
||||
"days": store.daily_energy(conn, first, last),
|
||||
}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- inverters
|
||||
|
||||
|
||||
@router.get("/inverters", response_model=list[Inverter], tags=["inverters"])
|
||||
def get_inverters(conn: Db):
|
||||
return store.list_inverters(conn)
|
||||
|
||||
|
||||
@router.get("/inverters/{inverter_id}", response_model=Inverter, tags=["inverters"])
|
||||
def get_inverter(conn: Db, inverter_id: str):
|
||||
return _inverter_or_404(conn, inverter_id)
|
||||
|
||||
|
||||
@router.patch(
|
||||
"/inverters/{inverter_id}",
|
||||
response_model=Inverter,
|
||||
dependencies=[Depends(require_api_key)],
|
||||
tags=["inverters"],
|
||||
)
|
||||
def update_inverter(conn: Db, inverter_id: str, body: InverterUpdate):
|
||||
"""Set display name, array size (kWp, enables per-kWp comparison), MPPT count, order, notes."""
|
||||
_inverter_or_404(conn, inverter_id)
|
||||
changes = body.model_dump(exclude_unset=True)
|
||||
if changes:
|
||||
sets = ", ".join(f"{k} = ?" for k in changes)
|
||||
conn.execute(f"UPDATE inverters SET {sets} WHERE id = ?", [*changes.values(), inverter_id])
|
||||
return store.get_inverter(conn, inverter_id)
|
||||
|
||||
|
||||
@router.get("/inverters/{inverter_id}/latest", tags=["inverters"])
|
||||
def get_latest(conn: Db, inverter_id: str):
|
||||
_inverter_or_404(conn, inverter_id)
|
||||
r = store.latest(conn, inverter_id)
|
||||
if not r:
|
||||
raise HTTPException(404, "No readings yet")
|
||||
return r
|
||||
|
||||
|
||||
@router.get("/inverters/{inverter_id}/history", tags=["inverters"])
|
||||
def get_history(
|
||||
conn: Db,
|
||||
inverter_id: str,
|
||||
start: FromQ = None,
|
||||
end: ToQ = None,
|
||||
bucket: BucketQ = None,
|
||||
field: Annotated[list[str] | None, Query(description="Limit to these fields (repeatable)")] = None,
|
||||
):
|
||||
"""Readings over time, averaged per bucket (energy counters and codes use the max).
|
||||
Default: last 24 h."""
|
||||
_inverter_or_404(conn, inverter_id)
|
||||
s, e = _range(start, end, timedelta(hours=24))
|
||||
b = store.pick_bucket(s, e, bucket)
|
||||
return {
|
||||
"inverter_id": inverter_id,
|
||||
"from": store.to_dt(s),
|
||||
"to": store.to_dt(e),
|
||||
"bucket": b,
|
||||
"points": store.history(conn, inverter_id, s, e, b, field),
|
||||
}
|
||||
|
||||
|
||||
@router.get("/inverters/{inverter_id}/daily", tags=["inverters"])
|
||||
def get_inverter_daily(
|
||||
conn: Db,
|
||||
inverter_id: str,
|
||||
start: Annotated[date | None, Query(alias="from")] = None,
|
||||
end: Annotated[date | None, Query(alias="to")] = None,
|
||||
days: Annotated[int, Query(ge=1, le=3660)] = 365,
|
||||
):
|
||||
"""Energy and peak power per local day (default: last 365 days)."""
|
||||
_inverter_or_404(conn, inverter_id)
|
||||
first, last = _day_range(start, end, days)
|
||||
rows = store.daily_energy(conn, first, last, inverter_id)
|
||||
return {
|
||||
"inverter_id": inverter_id,
|
||||
"days": [
|
||||
{"day": r["day"], "energy_wh": r.get(inverter_id), "peak_power_w": r.get("peak_power_w")}
|
||||
for r in rows
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- meta
|
||||
|
||||
|
||||
@router.get("/meta/fields", tags=["meta"])
|
||||
def get_fields():
|
||||
"""Labels, units and groups of every reading parameter — render from this
|
||||
instead of hard-coding, so new parameters show up automatically."""
|
||||
return fields.describe()
|
||||
|
||||
|
||||
@router.get("/meta/config", tags=["meta"])
|
||||
def get_public_config():
|
||||
s = get_settings()
|
||||
return {
|
||||
"site_timezone": s.site_timezone,
|
||||
"online_window_seconds": s.online_window_seconds,
|
||||
"underperform_ratio": s.underperform_ratio,
|
||||
}
|
||||
|
||||
|
||||
@router.get("/health", tags=["meta"])
|
||||
def get_health():
|
||||
return {"status": "ok"}
|
||||
@@ -0,0 +1,57 @@
|
||||
from functools import lru_cache
|
||||
|
||||
from pydantic import field_validator
|
||||
from pydantic_settings import BaseSettings, SettingsConfigDict
|
||||
|
||||
|
||||
class Settings(BaseSettings):
|
||||
model_config = SettingsConfigDict(env_file=".env", extra="ignore")
|
||||
|
||||
# Shared secret the on-site poller sends in X-API-Key. Also guards the
|
||||
# inverter metadata edits (name, kWp, ...).
|
||||
api_key: str = "change-me"
|
||||
|
||||
db_path: str = "/app/data/solar.db"
|
||||
|
||||
# Local calendar of the installation — decides where "today" starts for
|
||||
# the daily-energy rollup and the charts.
|
||||
site_timezone: str = "Europe/Athens"
|
||||
# Used to compute the sun's elevation so an inverter that went quiet at
|
||||
# night shows as "sleeping" instead of raising an alarm. Leave empty to
|
||||
# treat every silent inverter as offline.
|
||||
site_latitude: float | None = None
|
||||
site_longitude: float | None = None
|
||||
# Below this sun elevation (degrees) inverters are expected to be off.
|
||||
daylight_min_elevation: float = 5.0
|
||||
|
||||
# A reading newer than this marks an inverter as Online.
|
||||
online_window_seconds: int = 300
|
||||
retention_days: int = 730
|
||||
|
||||
# Underperformance check: an inverter is flagged when its output (per kWp
|
||||
# if capacities are set, otherwise raw W) is below this fraction of the
|
||||
# fleet median over the last few minutes.
|
||||
underperform_ratio: float = 0.75
|
||||
underperform_window_seconds: int = 600
|
||||
# Skip the check while the fleet is barely producing (dawn, dusk, heavy
|
||||
# overcast) — differences there are noise.
|
||||
underperform_min_fleet_w_per_kwp: float = 50.0
|
||||
underperform_min_fleet_w: float = 1000.0
|
||||
|
||||
# One MPPT producing under this fraction of the other is flagged (only
|
||||
# for inverters with mppt_count = 2), once the stronger one exceeds
|
||||
# mppt_min_power_w.
|
||||
mppt_imbalance_ratio: float = 0.5
|
||||
mppt_min_power_w: float = 1000.0
|
||||
|
||||
cors_origins: list[str] = ["*"]
|
||||
|
||||
@field_validator("site_latitude", "site_longitude", mode="before")
|
||||
@classmethod
|
||||
def blank_is_none(cls, v):
|
||||
return None if isinstance(v, str) and not v.strip() else v
|
||||
|
||||
|
||||
@lru_cache
|
||||
def get_settings() -> Settings:
|
||||
return Settings()
|
||||
@@ -0,0 +1,94 @@
|
||||
import os
|
||||
import sqlite3
|
||||
from collections.abc import Iterator
|
||||
from contextlib import contextmanager
|
||||
|
||||
from .config import get_settings
|
||||
from .fields import FIELDS
|
||||
|
||||
SCHEMA = """
|
||||
CREATE TABLE IF NOT EXISTS inverters (
|
||||
id TEXT PRIMARY KEY,
|
||||
name TEXT,
|
||||
capacity_kwp REAL,
|
||||
mppt_count INTEGER NOT NULL DEFAULT 2,
|
||||
sort_order INTEGER NOT NULL DEFAULT 0,
|
||||
notes TEXT,
|
||||
first_seen INTEGER,
|
||||
last_seen INTEGER
|
||||
);
|
||||
|
||||
-- One row per inverter per poll cycle. ts = unix seconds, UTC.
|
||||
-- The per-parameter columns are added from fields.py by migrate().
|
||||
CREATE TABLE IF NOT EXISTS readings (
|
||||
inverter_id TEXT NOT NULL,
|
||||
ts INTEGER NOT NULL,
|
||||
extra TEXT,
|
||||
PRIMARY KEY (inverter_id, ts)
|
||||
) WITHOUT ROWID;
|
||||
CREATE INDEX IF NOT EXISTS readings_ts ON readings (ts);
|
||||
|
||||
-- Daily rollup, kept forever (readings are purged after the retention
|
||||
-- period). day is the local date at the site (SITE_TIMEZONE).
|
||||
CREATE TABLE IF NOT EXISTS daily_energy (
|
||||
inverter_id TEXT NOT NULL,
|
||||
day TEXT NOT NULL,
|
||||
daily_energy_wh INTEGER,
|
||||
total_min_wh INTEGER,
|
||||
total_max_wh INTEGER,
|
||||
peak_power_w INTEGER,
|
||||
PRIMARY KEY (inverter_id, day)
|
||||
) WITHOUT ROWID;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS meta (
|
||||
key TEXT PRIMARY KEY,
|
||||
value TEXT
|
||||
);
|
||||
"""
|
||||
|
||||
|
||||
def connect() -> sqlite3.Connection:
|
||||
path = get_settings().db_path
|
||||
os.makedirs(os.path.dirname(os.path.abspath(path)), exist_ok=True)
|
||||
conn = sqlite3.connect(path, timeout=30)
|
||||
conn.row_factory = sqlite3.Row
|
||||
conn.execute("PRAGMA journal_mode=WAL")
|
||||
conn.execute("PRAGMA synchronous=NORMAL")
|
||||
return conn
|
||||
|
||||
|
||||
@contextmanager
|
||||
def session() -> Iterator[sqlite3.Connection]:
|
||||
conn = connect()
|
||||
try:
|
||||
with conn:
|
||||
yield conn
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def get_db() -> Iterator[sqlite3.Connection]:
|
||||
with session() as conn:
|
||||
yield conn
|
||||
|
||||
|
||||
def migrate() -> None:
|
||||
with session() as conn:
|
||||
conn.executescript(SCHEMA)
|
||||
existing = {r["name"] for r in conn.execute("PRAGMA table_info(readings)")}
|
||||
for f in FIELDS:
|
||||
if f.key not in existing:
|
||||
conn.execute(f"ALTER TABLE readings ADD COLUMN {f.key} {f.sql_type}")
|
||||
|
||||
|
||||
def get_meta(conn: sqlite3.Connection, key: str) -> str | None:
|
||||
row = conn.execute("SELECT value FROM meta WHERE key = ?", (key,)).fetchone()
|
||||
return row["value"] if row else None
|
||||
|
||||
|
||||
def set_meta(conn: sqlite3.Connection, key: str, value: str) -> None:
|
||||
conn.execute(
|
||||
"INSERT INTO meta (key, value) VALUES (?, ?) "
|
||||
"ON CONFLICT(key) DO UPDATE SET value = excluded.value",
|
||||
(key, value),
|
||||
)
|
||||
@@ -0,0 +1,82 @@
|
||||
"""Single source of truth for the per-reading parameters.
|
||||
|
||||
Every field listed here gets its own column in `readings` (missing columns are
|
||||
added on startup), is accepted by POST /api/readings, and is described by
|
||||
GET /api/meta/fields so the dashboard and future apps can render it without a
|
||||
code change. Anything the poller sends that is NOT listed here is still kept,
|
||||
in the reading's `extra` JSON — promote it to this list once its meaning and
|
||||
scaling are confirmed.
|
||||
"""
|
||||
|
||||
from dataclasses import asdict, dataclass
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Field:
|
||||
key: str
|
||||
sql_type: str # REAL | INTEGER | TEXT
|
||||
label: str
|
||||
unit: str | None
|
||||
group: str # ac | dc | energy | device
|
||||
# How values combine when history is downsampled into buckets.
|
||||
agg: str = "avg" # avg | max | last
|
||||
decimals: int = 1
|
||||
|
||||
|
||||
FIELDS: list[Field] = [
|
||||
Field("ac_power_total_w", "INTEGER", "AC power", "W", "ac", decimals=0),
|
||||
Field("ac_voltage_l1_v", "REAL", "AC voltage L1", "V", "ac"),
|
||||
Field("ac_voltage_l2_v", "REAL", "AC voltage L2", "V", "ac"),
|
||||
Field("ac_voltage_l3_v", "REAL", "AC voltage L3", "V", "ac"),
|
||||
Field("ac_current_l1_a", "REAL", "AC current L1", "A", "ac", decimals=2),
|
||||
Field("ac_current_l2_a", "REAL", "AC current L2", "A", "ac", decimals=2),
|
||||
Field("ac_current_l3_a", "REAL", "AC current L3", "A", "ac", decimals=2),
|
||||
Field("grid_frequency_hz", "REAL", "Grid frequency", "Hz", "ac", decimals=2),
|
||||
Field("dc_voltage_mppt1_v", "REAL", "DC voltage MPPT1", "V", "dc"),
|
||||
Field("dc_voltage_mppt2_v", "REAL", "DC voltage MPPT2", "V", "dc"),
|
||||
Field("dc_current_mppt1_a", "REAL", "DC current MPPT1", "A", "dc"),
|
||||
Field("dc_current_mppt2_a", "REAL", "DC current MPPT2", "A", "dc"),
|
||||
Field("temperature_c", "INTEGER", "Temperature", "°C", "device", decimals=0),
|
||||
Field("status_code", "INTEGER", "Status code", None, "device", agg="last", decimals=0),
|
||||
Field("error_code", "INTEGER", "Error code", None, "device", agg="last", decimals=0),
|
||||
Field("status_text", "TEXT", "Status", None, "device", agg="last"),
|
||||
Field("daily_energy_wh", "INTEGER", "Energy today", "Wh", "energy", agg="max", decimals=0),
|
||||
Field("total_energy_wh", "INTEGER", "Lifetime energy", "Wh", "energy", agg="max", decimals=0),
|
||||
]
|
||||
|
||||
FIELD_KEYS = [f.key for f in FIELDS]
|
||||
FIELDS_BY_KEY = {f.key: f for f in FIELDS}
|
||||
NUMERIC_KEYS = [f.key for f in FIELDS if f.sql_type != "TEXT"]
|
||||
|
||||
# Values derived from the stored ones, shown alongside them.
|
||||
DERIVED: list[Field] = [
|
||||
Field("dc_power_mppt1_w", "REAL", "DC power MPPT1", "W", "dc", decimals=0),
|
||||
Field("dc_power_mppt2_w", "REAL", "DC power MPPT2", "W", "dc", decimals=0),
|
||||
Field("dc_power_total_w", "REAL", "DC power total", "W", "dc", decimals=0),
|
||||
Field("efficiency_pct", "REAL", "Conversion efficiency", "%", "dc", decimals=1),
|
||||
]
|
||||
|
||||
|
||||
def describe() -> list[dict]:
|
||||
return [asdict(f) | {"derived": False} for f in FIELDS] + [
|
||||
asdict(f) | {"derived": True} for f in DERIVED
|
||||
]
|
||||
|
||||
|
||||
def derive(r: dict) -> dict:
|
||||
"""Add DC power and efficiency to a reading dict (in place) and return it."""
|
||||
|
||||
def mul(v, a):
|
||||
return None if v is None or a is None else v * a
|
||||
|
||||
p1 = mul(r.get("dc_voltage_mppt1_v"), r.get("dc_current_mppt1_a"))
|
||||
p2 = mul(r.get("dc_voltage_mppt2_v"), r.get("dc_current_mppt2_a"))
|
||||
r["dc_power_mppt1_w"] = round(p1) if p1 is not None else None
|
||||
r["dc_power_mppt2_w"] = round(p2) if p2 is not None else None
|
||||
dc = None if p1 is None and p2 is None else (p1 or 0) + (p2 or 0)
|
||||
r["dc_power_total_w"] = round(dc) if dc is not None else None
|
||||
ac = r.get("ac_power_total_w")
|
||||
r["efficiency_pct"] = (
|
||||
round(ac / dc * 100, 1) if ac is not None and dc and dc > 200 else None
|
||||
)
|
||||
return r
|
||||
@@ -0,0 +1,147 @@
|
||||
"""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
|
||||
|
||||
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"
|
||||
|
||||
statuses.append({
|
||||
"inverter": inv,
|
||||
"health": {
|
||||
"online": online,
|
||||
"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,
|
||||
},
|
||||
"latest": r,
|
||||
})
|
||||
|
||||
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(energy_today.values()),
|
||||
"total_energy_wh": sum((r.get("total_energy_wh") or 0) for r in latest.values()),
|
||||
"inverter_count": len(inverters),
|
||||
"online_count": sum(1 for i in inverters if is_online(i["id"])),
|
||||
"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,
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
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)
|
||||
@@ -0,0 +1,124 @@
|
||||
from datetime import datetime
|
||||
from typing import Any, Literal
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
|
||||
InverterId = Field(min_length=1, max_length=64, pattern=r"^[A-Za-z0-9_.\-]+$")
|
||||
|
||||
|
||||
class ReadingIn(BaseModel):
|
||||
"""One inverter's values from one poll cycle.
|
||||
|
||||
Every parameter is optional — send what the poller could read. Unknown
|
||||
keys are accepted and stored in `extra` (as are keys of an explicit
|
||||
`extra` object), so new parameters can be logged before the backend
|
||||
knows about them.
|
||||
"""
|
||||
|
||||
model_config = ConfigDict(extra="allow")
|
||||
|
||||
inverter_id: str = InverterId
|
||||
timestamp: datetime | None = Field(
|
||||
default=None, description="UTC. Defaults to the time the backend receives it."
|
||||
)
|
||||
|
||||
ac_voltage_l1_v: float | None = None
|
||||
ac_voltage_l2_v: float | None = None
|
||||
ac_voltage_l3_v: float | None = None
|
||||
dc_voltage_mppt1_v: float | None = None
|
||||
dc_voltage_mppt2_v: float | None = None
|
||||
dc_current_mppt1_a: float | None = None
|
||||
dc_current_mppt2_a: float | None = None
|
||||
ac_current_l1_a: float | None = None
|
||||
ac_current_l2_a: float | None = None
|
||||
ac_current_l3_a: float | None = None
|
||||
ac_power_total_w: int | None = None
|
||||
grid_frequency_hz: float | None = None
|
||||
temperature_c: int | None = None
|
||||
daily_energy_wh: int | None = None
|
||||
total_energy_wh: int | None = None
|
||||
|
||||
status_code: int | None = Field(default=None, description="Raw inverter state, if known")
|
||||
error_code: int | None = Field(default=None, description="Non-zero = inverter reports a fault")
|
||||
status_text: str | None = Field(default=None, max_length=200)
|
||||
|
||||
extra: dict[str, Any] | None = None
|
||||
|
||||
|
||||
class IngestResult(BaseModel):
|
||||
received: int
|
||||
stored: int
|
||||
duplicates: int
|
||||
|
||||
|
||||
class InverterUpdate(BaseModel):
|
||||
name: str | None = Field(default=None, max_length=100)
|
||||
capacity_kwp: float | None = Field(default=None, ge=0, le=1000)
|
||||
mppt_count: int | None = Field(default=None, ge=1, le=4)
|
||||
sort_order: int | None = None
|
||||
notes: str | None = Field(default=None, max_length=2000)
|
||||
|
||||
|
||||
class Inverter(BaseModel):
|
||||
id: str
|
||||
name: str
|
||||
capacity_kwp: float | None
|
||||
mppt_count: int
|
||||
sort_order: int
|
||||
notes: str | None
|
||||
first_seen: datetime | None
|
||||
last_seen: datetime | None
|
||||
|
||||
|
||||
Severity = Literal["info", "warning", "critical"]
|
||||
State = Literal["ok", "warning", "fault", "offline", "sleeping", "unknown"]
|
||||
|
||||
|
||||
class Issue(BaseModel):
|
||||
code: str
|
||||
severity: Severity
|
||||
message: str
|
||||
|
||||
|
||||
class Health(BaseModel):
|
||||
online: bool = Field(description="A reading arrived within ONLINE_WINDOW_SECONDS")
|
||||
state: State
|
||||
issues: list[Issue]
|
||||
avg_power_w: float | None = Field(description="Mean AC power over the comparison window")
|
||||
relative_output: float | None = Field(
|
||||
description="Output vs fleet median (1.0 = median), per kWp when capacities are set"
|
||||
)
|
||||
|
||||
|
||||
class InverterStatus(BaseModel):
|
||||
inverter: Inverter
|
||||
health: Health
|
||||
latest: dict[str, Any] | None
|
||||
|
||||
|
||||
class Totals(BaseModel):
|
||||
ac_power_w: int
|
||||
daily_energy_wh: int
|
||||
total_energy_wh: int
|
||||
inverter_count: int
|
||||
online_count: int
|
||||
problem_count: int
|
||||
|
||||
|
||||
class Datalogger(BaseModel):
|
||||
online: bool
|
||||
last_ingest_at: datetime | None
|
||||
|
||||
|
||||
class Sun(BaseModel):
|
||||
elevation: float | None
|
||||
daylight: bool | None
|
||||
|
||||
|
||||
class Summary(BaseModel):
|
||||
generated_at: datetime
|
||||
datalogger: Datalogger
|
||||
sun: Sun
|
||||
totals: Totals
|
||||
fleet_median_w_per_kwp: float | None
|
||||
inverters: list[InverterStatus]
|
||||
@@ -0,0 +1,277 @@
|
||||
"""Database reads and writes. All timestamps in the DB are unix seconds (UTC)."""
|
||||
|
||||
import json
|
||||
import sqlite3
|
||||
import time
|
||||
from datetime import date, datetime, timedelta, timezone
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
from .config import get_settings
|
||||
from .fields import FIELD_KEYS, FIELDS_BY_KEY, NUMERIC_KEYS, derive
|
||||
from .schemas import ReadingIn
|
||||
|
||||
BUCKETS = [60, 300, 900, 1800, 3600, 3 * 3600, 6 * 3600, 86400]
|
||||
MAX_POINTS = 600
|
||||
|
||||
|
||||
def now_ts() -> int:
|
||||
return int(time.time())
|
||||
|
||||
|
||||
def to_dt(ts: int | None) -> datetime | None:
|
||||
return datetime.fromtimestamp(ts, timezone.utc) if ts is not None else None
|
||||
|
||||
|
||||
def site_tz() -> ZoneInfo:
|
||||
return ZoneInfo(get_settings().site_timezone)
|
||||
|
||||
|
||||
def local_day(ts: int) -> str:
|
||||
return datetime.fromtimestamp(ts, site_tz()).date().isoformat()
|
||||
|
||||
|
||||
def today() -> date:
|
||||
return datetime.now(site_tz()).date()
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- ingest
|
||||
|
||||
|
||||
def _ts_of(r: ReadingIn) -> int:
|
||||
if r.timestamp is None:
|
||||
return now_ts()
|
||||
t = r.timestamp
|
||||
if t.tzinfo is None:
|
||||
t = t.replace(tzinfo=timezone.utc)
|
||||
return int(t.timestamp())
|
||||
|
||||
|
||||
def ingest(conn: sqlite3.Connection, readings: list[ReadingIn]) -> tuple[int, int]:
|
||||
"""Store readings; returns (stored, duplicates). Re-sent readings (same
|
||||
inverter + timestamp) are ignored, so the poller can safely retry."""
|
||||
stored = 0
|
||||
cols = ["inverter_id", "ts", "extra", *FIELD_KEYS]
|
||||
insert_sql = (
|
||||
f"INSERT OR IGNORE INTO readings ({', '.join(cols)}) "
|
||||
f"VALUES ({', '.join('?' for _ in cols)})"
|
||||
)
|
||||
for r in readings:
|
||||
ts = _ts_of(r)
|
||||
values = r.model_dump(include=set(FIELD_KEYS))
|
||||
extra = {**(r.model_extra or {}), **(r.extra or {})}
|
||||
|
||||
conn.execute(
|
||||
"INSERT OR IGNORE INTO inverters (id, name, first_seen, last_seen) VALUES (?, ?, ?, ?)",
|
||||
(r.inverter_id, r.inverter_id, ts, ts),
|
||||
)
|
||||
conn.execute(
|
||||
"UPDATE inverters SET last_seen = max(coalesce(last_seen, 0), ?) WHERE id = ?",
|
||||
(ts, r.inverter_id),
|
||||
)
|
||||
cur = conn.execute(
|
||||
insert_sql,
|
||||
[r.inverter_id, ts, json.dumps(extra) if extra else None]
|
||||
+ [values[k] for k in FIELD_KEYS],
|
||||
)
|
||||
if cur.rowcount == 0:
|
||||
continue
|
||||
stored += 1
|
||||
|
||||
# max()/min() of two values where either may be NULL
|
||||
conn.execute(
|
||||
"""
|
||||
INSERT INTO daily_energy
|
||||
(inverter_id, day, daily_energy_wh, total_min_wh, total_max_wh, peak_power_w)
|
||||
VALUES (?, ?, ?, ?, ?, ?)
|
||||
ON CONFLICT (inverter_id, day) DO UPDATE SET
|
||||
daily_energy_wh = max(coalesce(daily_energy_wh, excluded.daily_energy_wh),
|
||||
coalesce(excluded.daily_energy_wh, daily_energy_wh)),
|
||||
total_min_wh = min(coalesce(total_min_wh, excluded.total_min_wh),
|
||||
coalesce(excluded.total_min_wh, total_min_wh)),
|
||||
total_max_wh = max(coalesce(total_max_wh, excluded.total_max_wh),
|
||||
coalesce(excluded.total_max_wh, total_max_wh)),
|
||||
peak_power_w = max(coalesce(peak_power_w, excluded.peak_power_w),
|
||||
coalesce(excluded.peak_power_w, peak_power_w))
|
||||
""",
|
||||
(
|
||||
r.inverter_id,
|
||||
local_day(ts),
|
||||
values["daily_energy_wh"],
|
||||
values["total_energy_wh"],
|
||||
values["total_energy_wh"],
|
||||
values["ac_power_total_w"],
|
||||
),
|
||||
)
|
||||
return stored, len(readings) - stored
|
||||
|
||||
|
||||
def purge(conn: sqlite3.Connection, retention_days: int) -> int:
|
||||
cutoff = now_ts() - retention_days * 86400
|
||||
return conn.execute("DELETE FROM readings WHERE ts < ?", (cutoff,)).rowcount
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- inverters
|
||||
|
||||
|
||||
def inverter_dict(row: sqlite3.Row) -> dict:
|
||||
d = dict(row)
|
||||
d["name"] = d["name"] or d["id"]
|
||||
d["first_seen"] = to_dt(d["first_seen"])
|
||||
d["last_seen"] = to_dt(d["last_seen"])
|
||||
return d
|
||||
|
||||
|
||||
def list_inverters(conn: sqlite3.Connection) -> list[dict]:
|
||||
rows = conn.execute("SELECT * FROM inverters ORDER BY sort_order, id").fetchall()
|
||||
return [inverter_dict(r) for r in rows]
|
||||
|
||||
|
||||
def get_inverter(conn: sqlite3.Connection, inverter_id: str) -> dict | None:
|
||||
row = conn.execute("SELECT * FROM inverters WHERE id = ?", (inverter_id,)).fetchone()
|
||||
return inverter_dict(row) if row else None
|
||||
|
||||
|
||||
def reading_dict(row: sqlite3.Row) -> dict:
|
||||
d = dict(row)
|
||||
ts = d.pop("ts")
|
||||
d["timestamp"] = to_dt(ts)
|
||||
d["age_seconds"] = now_ts() - ts
|
||||
d["extra"] = json.loads(d["extra"]) if d.get("extra") else {}
|
||||
return derive(d)
|
||||
|
||||
|
||||
def latest(conn: sqlite3.Connection, inverter_id: str) -> dict | None:
|
||||
row = conn.execute(
|
||||
"SELECT * FROM readings WHERE inverter_id = ? ORDER BY ts DESC LIMIT 1", (inverter_id,)
|
||||
).fetchone()
|
||||
return reading_dict(row) if row else None
|
||||
|
||||
|
||||
def latest_all(conn: sqlite3.Connection) -> dict[str, dict]:
|
||||
rows = conn.execute(
|
||||
"""
|
||||
SELECT r.* FROM readings r
|
||||
JOIN (SELECT inverter_id, max(ts) AS ts FROM readings GROUP BY inverter_id) m
|
||||
ON m.inverter_id = r.inverter_id AND m.ts = r.ts
|
||||
"""
|
||||
).fetchall()
|
||||
return {r["inverter_id"]: reading_dict(r) for r in rows}
|
||||
|
||||
|
||||
def window_averages(conn: sqlite3.Connection, seconds: int) -> dict[str, dict]:
|
||||
rows = conn.execute(
|
||||
"""
|
||||
SELECT inverter_id,
|
||||
avg(ac_power_total_w) AS ac_power_w,
|
||||
avg(dc_voltage_mppt1_v * dc_current_mppt1_a) AS mppt1_w,
|
||||
avg(dc_voltage_mppt2_v * dc_current_mppt2_a) AS mppt2_w
|
||||
FROM readings WHERE ts >= ? GROUP BY inverter_id
|
||||
""",
|
||||
(now_ts() - seconds,),
|
||||
).fetchall()
|
||||
return {r["inverter_id"]: dict(r) for r in rows}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- history
|
||||
|
||||
|
||||
def pick_bucket(start: int, end: int, requested: int | None) -> int:
|
||||
if requested:
|
||||
return max(60, requested)
|
||||
span = max(1, end - start)
|
||||
return next((b for b in BUCKETS if span / b <= MAX_POINTS), BUCKETS[-1])
|
||||
|
||||
|
||||
def _agg(key: str) -> str:
|
||||
fn = "max" if FIELDS_BY_KEY[key].agg in ("max", "last") else "avg"
|
||||
return f"{fn}({key}) AS {key}"
|
||||
|
||||
|
||||
def history(
|
||||
conn: sqlite3.Connection,
|
||||
inverter_id: str,
|
||||
start: int,
|
||||
end: int,
|
||||
bucket: int,
|
||||
fields: list[str] | None,
|
||||
) -> list[dict]:
|
||||
keys = [k for k in (fields or NUMERIC_KEYS) if k in NUMERIC_KEYS]
|
||||
# DC power is averaged per row (V*I), not as avg(V)*avg(I)
|
||||
sql = f"""
|
||||
SELECT (ts / :b) * :b AS t,
|
||||
{', '.join(_agg(k) for k in keys)},
|
||||
avg(dc_voltage_mppt1_v * dc_current_mppt1_a) AS dc_power_mppt1_w,
|
||||
avg(dc_voltage_mppt2_v * dc_current_mppt2_a) AS dc_power_mppt2_w
|
||||
FROM readings
|
||||
WHERE inverter_id = :id AND ts >= :start AND ts <= :end
|
||||
GROUP BY t ORDER BY t
|
||||
"""
|
||||
rows = conn.execute(sql, {"b": bucket, "id": inverter_id, "start": start, "end": end})
|
||||
out = []
|
||||
for r in rows:
|
||||
d = {"t": r["t"]}
|
||||
for k in r.keys()[1:]:
|
||||
v = r[k]
|
||||
if v is not None and k in FIELDS_BY_KEY:
|
||||
v = round(v, FIELDS_BY_KEY[k].decimals + 1)
|
||||
elif v is not None:
|
||||
v = round(v)
|
||||
d[k] = v
|
||||
out.append(d)
|
||||
return out
|
||||
|
||||
|
||||
def fleet_power(conn: sqlite3.Connection, start: int, end: int, bucket: int) -> list[dict]:
|
||||
"""AC power per inverter per bucket, pivoted: [{t, <inverter_id>: W, ...}]."""
|
||||
rows = conn.execute(
|
||||
"""
|
||||
SELECT (ts / :b) * :b AS t, inverter_id, avg(ac_power_total_w) AS w
|
||||
FROM readings WHERE ts >= :start AND ts <= :end
|
||||
GROUP BY t, inverter_id ORDER BY t
|
||||
""",
|
||||
{"b": bucket, "start": start, "end": end},
|
||||
)
|
||||
points: dict[int, dict] = {}
|
||||
for r in rows:
|
||||
p = points.setdefault(r["t"], {"t": r["t"]})
|
||||
p[r["inverter_id"]] = round(r["w"]) if r["w"] is not None else None
|
||||
return list(points.values())
|
||||
|
||||
|
||||
def daily_energy(
|
||||
conn: sqlite3.Connection, first: date, last: date, inverter_id: str | None = None
|
||||
) -> list[dict]:
|
||||
"""[{day, total_wh, <inverter_id>: Wh, ...}] for every day in range, oldest first.
|
||||
Uses the inverter's own daily counter, falling back to the lifetime
|
||||
counter's growth over the day when the daily counter wasn't reported."""
|
||||
sql = """
|
||||
SELECT day, inverter_id, peak_power_w,
|
||||
coalesce(daily_energy_wh, total_max_wh - total_min_wh) AS wh
|
||||
FROM daily_energy WHERE day >= ? AND day <= ?
|
||||
"""
|
||||
params: list = [first.isoformat(), last.isoformat()]
|
||||
if inverter_id:
|
||||
sql += " AND inverter_id = ?"
|
||||
params.append(inverter_id)
|
||||
by_day: dict[str, dict] = {}
|
||||
d = first
|
||||
while d <= last:
|
||||
by_day[d.isoformat()] = {"day": d.isoformat(), "total_wh": 0}
|
||||
d += timedelta(days=1)
|
||||
for r in conn.execute(sql, params):
|
||||
row = by_day[r["day"]]
|
||||
row[r["inverter_id"]] = r["wh"]
|
||||
row["total_wh"] += r["wh"] or 0
|
||||
if inverter_id:
|
||||
row["peak_power_w"] = r["peak_power_w"]
|
||||
return list(by_day.values())
|
||||
|
||||
|
||||
def today_energy(conn: sqlite3.Connection) -> dict[str, int]:
|
||||
rows = conn.execute(
|
||||
"SELECT inverter_id, coalesce(daily_energy_wh, total_max_wh - total_min_wh) AS wh "
|
||||
"FROM daily_energy WHERE day = ?",
|
||||
(today().isoformat(),),
|
||||
)
|
||||
return {r["inverter_id"]: r["wh"] or 0 for r in rows}
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
"""Sun elevation from date/time and position (NOAA approximation, ±0.5°)."""
|
||||
|
||||
import math
|
||||
from datetime import datetime, timezone
|
||||
|
||||
|
||||
def elevation(when: datetime, lat: float, lon: float) -> float:
|
||||
when = when.astimezone(timezone.utc)
|
||||
day_of_year = when.timetuple().tm_yday
|
||||
hours = when.hour + when.minute / 60 + when.second / 3600
|
||||
|
||||
g = 2 * math.pi / 365 * (day_of_year - 1 + (hours - 12) / 24)
|
||||
eq_time = 229.18 * (
|
||||
0.000075
|
||||
+ 0.001868 * math.cos(g)
|
||||
- 0.032077 * math.sin(g)
|
||||
- 0.014615 * math.cos(2 * g)
|
||||
- 0.040849 * math.sin(2 * g)
|
||||
)
|
||||
decl = (
|
||||
0.006918
|
||||
- 0.399912 * math.cos(g)
|
||||
+ 0.070257 * math.sin(g)
|
||||
- 0.006758 * math.cos(2 * g)
|
||||
+ 0.000907 * math.sin(2 * g)
|
||||
- 0.002697 * math.cos(3 * g)
|
||||
+ 0.00148 * math.sin(3 * g)
|
||||
)
|
||||
true_solar_minutes = hours * 60 + eq_time + 4 * lon
|
||||
hour_angle = math.radians(true_solar_minutes / 4 - 180)
|
||||
lat_r = math.radians(lat)
|
||||
cos_zenith = math.sin(lat_r) * math.sin(decl) + math.cos(lat_r) * math.cos(decl) * math.cos(
|
||||
hour_angle
|
||||
)
|
||||
return 90 - math.degrees(math.acos(max(-1.0, min(1.0, cos_zenith))))
|
||||
Reference in New Issue
Block a user