diff --git a/.env.example b/.env.example
index 71a881a..4d16f56 100644
--- a/.env.example
+++ b/.env.example
@@ -34,6 +34,18 @@ UNDERPERFORM_MIN_FLEET_W=1000
MPPT_IMBALANCE_RATIO=0.5
MPPT_MIN_POWER_W=1000
+# status_code values meaning "feeding the grid" (JSON list): 8 on the
+# standard units, 7 on INV1's OEM board. Any other code shows as Standby.
+FEEDING_STATUS_CODES=[7, 8]
+
+# Readings stamped more than this many seconds in the future (poller clock
+# wrong, or local time sent as UTC) are stored at the time they arrive.
+MAX_FUTURE_SKEW_SECONDS=300
+
+# Daily energy is estimated by integrating AC power while the energy counters
+# aren't decoded; gaps between readings longer than this aren't bridged.
+ENERGY_INTEGRATION_MAX_GAP_SECONDS=300
+
# Browser origins allowed to call the API directly (JSON list). The dashboard
# itself is same-origin and doesn't need this.
CORS_ORIGINS=["*"]
diff --git a/backend/app/api.py b/backend/app/api.py
index a359337..218080d 100644
--- a/backend/app/api.py
+++ b/backend/app/api.py
@@ -1,3 +1,4 @@
+import logging
import secrets
import sqlite3
from datetime import date, datetime, timedelta, timezone
@@ -10,6 +11,7 @@ from .config import get_settings
from .db import get_db, set_meta
from .schemas import IngestResult, Inverter, InverterUpdate, ReadingIn, Summary
+log = logging.getLogger("solar")
router = APIRouter(prefix="/api")
Db = Annotated[sqlite3.Connection, Depends(get_db)]
@@ -69,9 +71,11 @@ def post_readings(conn: Db, readings: Annotated[list[ReadingIn], Body(max_length
"""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)
+ stored, duplicates, clamped = store.ingest(conn, readings)
set_meta(conn, "last_ingest_at", str(store.now_ts()))
- return {"received": len(readings), "stored": stored, "duplicates": duplicates}
+ if clamped:
+ log.warning("%d readings had future timestamps (clock/timezone wrong on the poller?)", clamped)
+ return {"received": len(readings), "stored": stored, "duplicates": duplicates, "clamped_future": clamped}
# ---------------------------------------------------------------- dashboard
@@ -181,14 +185,20 @@ def get_inverter_daily(
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)."""
+ """Energy and peak power per local day (default: last 365 days).
+ `estimated` days are integrated from AC power, not the inverter's counter."""
_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")}
+ {
+ "day": r["day"],
+ "energy_wh": r.get(inverter_id),
+ "estimated": r["estimated"],
+ "peak_power_w": r.get("peak_power_w"),
+ }
for r in rows
],
}
diff --git a/backend/app/config.py b/backend/app/config.py
index 5daddb8..7376be5 100644
--- a/backend/app/config.py
+++ b/backend/app/config.py
@@ -44,6 +44,19 @@ class Settings(BaseSettings):
mppt_imbalance_ratio: float = 0.5
mppt_min_power_w: float = 1000.0
+ # status_code values that mean the inverter is feeding the grid
+ # (8 on the standard units, 7 on the OEM board in INV1). Any other
+ # reported code shows as Standby.
+ feeding_status_codes: list[int] = [7, 8]
+
+ # Readings stamped further than this in the future (wrong clock or local
+ # time sent as UTC) are stored at the time they were received instead.
+ max_future_skew_seconds: int = 300
+
+ # Energy is estimated by integrating AC power between consecutive
+ # readings; gaps longer than this are not bridged.
+ energy_integration_max_gap_seconds: int = 300
+
cors_origins: list[str] = ["*"]
@field_validator("site_latitude", "site_longitude", mode="before")
diff --git a/backend/app/db.py b/backend/app/db.py
index 107a092..6e4c945 100644
--- a/backend/app/db.py
+++ b/backend/app/db.py
@@ -37,6 +37,9 @@ CREATE TABLE IF NOT EXISTS daily_energy (
total_min_wh INTEGER,
total_max_wh INTEGER,
peak_power_w INTEGER,
+ -- AC power integrated over time: the fallback while the inverter's
+ -- own energy counters aren't decoded
+ integrated_wh REAL,
PRIMARY KEY (inverter_id, day)
) WITHOUT ROWID;
@@ -72,13 +75,20 @@ def get_db() -> Iterator[sqlite3.Connection]:
yield conn
-def migrate() -> None:
+def migrate() -> bool:
+ """Create/upgrade the schema. Returns True when the integrated-energy
+ column was just added and has to be rebuilt from existing readings."""
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}")
+ daily_cols = {r["name"] for r in conn.execute("PRAGMA table_info(daily_energy)")}
+ if "integrated_wh" not in daily_cols:
+ conn.execute("ALTER TABLE daily_energy ADD COLUMN integrated_wh REAL")
+ return True
+ return False
def get_meta(conn: sqlite3.Connection, key: str) -> str | None:
diff --git a/backend/app/health.py b/backend/app/health.py
index 3061225..cf6cb4d 100644
--- a/backend/app/health.py
+++ b/backend/app/health.py
@@ -69,6 +69,9 @@ def summary(conn: sqlite3.Connection) -> dict:
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"
if not datalogger_online:
@@ -115,25 +118,34 @@ def summary(conn: sqlite3.Connection) -> dict:
})
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,
},
+ "energy_today": energy_today.get(inv["id"], {"wh": None, "estimated": False}),
"latest": r,
})
+ 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(energy_today.values()),
- "total_energy_wh": sum((r.get("total_energy_wh") or 0) for r in latest.values()),
+ "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")),
}
diff --git a/backend/app/main.py b/backend/app/main.py
index ea1a426..ba503cd 100644
--- a/backend/app/main.py
+++ b/backend/app/main.py
@@ -32,7 +32,9 @@ async def purge_loop() -> None:
@asynccontextmanager
async def lifespan(app: FastAPI):
- migrate()
+ if migrate():
+ with session() as conn:
+ store.rebuild_integrated_energy(conn)
task = asyncio.create_task(purge_loop())
yield
task.cancel()
diff --git a/backend/app/schemas.py b/backend/app/schemas.py
index 4bd5060..b498df8 100644
--- a/backend/app/schemas.py
+++ b/backend/app/schemas.py
@@ -49,6 +49,10 @@ class IngestResult(BaseModel):
received: int
stored: int
duplicates: int
+ clamped_future: int = Field(
+ description="Readings stamped in the future (clock wrong, or local time sent as UTC); "
+ "stored at the time they were received instead"
+ )
class InverterUpdate(BaseModel):
@@ -71,7 +75,7 @@ class Inverter(BaseModel):
Severity = Literal["info", "warning", "critical"]
-State = Literal["ok", "warning", "fault", "offline", "sleeping", "unknown"]
+State = Literal["ok", "standby", "warning", "fault", "offline", "sleeping", "unknown"]
class Issue(BaseModel):
@@ -82,6 +86,9 @@ class Issue(BaseModel):
class Health(BaseModel):
online: bool = Field(description="A reading arrived within ONLINE_WINDOW_SECONDS")
+ feeding: bool | None = Field(
+ description="status_code is one of FEEDING_STATUS_CODES; null when no status_code is reported"
+ )
state: State
issues: list[Issue]
avg_power_w: float | None = Field(description="Mean AC power over the comparison window")
@@ -90,18 +97,26 @@ class Health(BaseModel):
)
+class EnergyToday(BaseModel):
+ wh: int | None
+ estimated: bool = Field(description="Integrated from AC power, not the inverter's own counter")
+
+
class InverterStatus(BaseModel):
inverter: Inverter
health: Health
+ energy_today: EnergyToday
latest: dict[str, Any] | None
class Totals(BaseModel):
ac_power_w: int
- daily_energy_wh: int
- total_energy_wh: int
+ daily_energy_wh: int | None
+ daily_energy_estimated: bool
+ total_energy_wh: int | None = Field(description="Null until the inverters report a lifetime counter")
inverter_count: int
online_count: int
+ feeding_count: int
problem_count: int
diff --git a/backend/app/store.py b/backend/app/store.py
index 57fe8eb..142a276 100644
--- a/backend/app/store.py
+++ b/backend/app/store.py
@@ -37,26 +37,76 @@ def today() -> date:
# ---------------------------------------------------------------- ingest
-def _ts_of(r: ReadingIn) -> int:
+def _ts_of(r: ReadingIn, received: int) -> tuple[int, bool]:
+ """Reading time in unix seconds, and whether it had to be clamped
+ because it lay in the future (bad clock / local time sent as UTC)."""
if r.timestamp is None:
- return now_ts()
+ return received, False
t = r.timestamp
if t.tzinfo is None:
t = t.replace(tzinfo=timezone.utc)
- return int(t.timestamp())
+ ts = int(t.timestamp())
+ if ts > received + get_settings().max_future_skew_seconds:
+ return received, True
+ return ts, False
-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
+def _integrate(conn: sqlite3.Connection, inverter_id: str, ts: int, power: int | None) -> float | None:
+ """Wh produced since the previous reading (trapezoid rule), or None when
+ there's nothing to add (no power, first reading, gap too long)."""
+ if power is None:
+ return None
+ prev = conn.execute(
+ "SELECT ts, ac_power_total_w AS w FROM readings "
+ "WHERE inverter_id = ? AND ts < ? ORDER BY ts DESC LIMIT 1",
+ (inverter_id, ts),
+ ).fetchone()
+ if not prev or prev["w"] is None:
+ return None
+ dt = ts - prev["ts"]
+ if dt > get_settings().energy_integration_max_gap_seconds:
+ return None
+ return (prev["w"] + power) / 2 * dt / 3600
+
+
+def _integrated_for_day(conn: sqlite3.Connection, inverter_id: str, day: str) -> float:
+ """Integrated Wh for one inverter and local day, from scratch."""
+ tz = site_tz()
+ start = int(datetime.combine(date.fromisoformat(day), datetime.min.time(), tz).timestamp())
+ end = start + 2 * 86400 # covers DST days; filtered by local_day below
+ max_gap = get_settings().energy_integration_max_gap_seconds
+ rows = conn.execute(
+ "SELECT ts, ac_power_total_w AS w FROM readings "
+ "WHERE inverter_id = ? AND ts >= ? AND ts < ? ORDER BY ts",
+ (inverter_id, start - max_gap, end),
+ ).fetchall()
+ total, prev = 0.0, None
+ for r in rows:
+ if (
+ prev
+ and prev["w"] is not None
+ and r["w"] is not None
+ and r["ts"] - prev["ts"] <= max_gap
+ and local_day(r["ts"]) == day
+ ):
+ total += (prev["w"] + r["w"]) / 2 * (r["ts"] - prev["ts"]) / 3600
+ prev = r
+ return total
+
+
+def ingest(conn: sqlite3.Connection, readings: list[ReadingIn]) -> tuple[int, int, int]:
+ """Store readings; returns (stored, duplicates, clamped). Re-sent readings
+ (same inverter + timestamp) are ignored, so the poller can safely retry."""
+ stored = clamped = 0
+ received = now_ts()
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)
+ ts, was_clamped = _ts_of(r, received)
+ clamped += was_clamped
values = r.model_dump(include=set(FIELD_KEYS))
extra = {**(r.model_extra or {}), **(r.extra or {})}
@@ -76,13 +126,21 @@ def ingest(conn: sqlite3.Connection, readings: list[ReadingIn]) -> tuple[int, in
if cur.rowcount == 0:
continue
stored += 1
+ # A reading arriving after a later one (re-sent from the poller's
+ # spool out of order) changes intervals already counted: recompute
+ # that day instead of adding to it.
+ out_of_order = conn.execute(
+ "SELECT 1 FROM readings WHERE inverter_id = ? AND ts > ? LIMIT 1", (r.inverter_id, ts)
+ ).fetchone() is not None
+ integrated_wh = None if out_of_order else _integrate(conn, r.inverter_id, ts, values["ac_power_total_w"])
# 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 (?, ?, ?, ?, ?, ?)
+ (inverter_id, day, daily_energy_wh, total_min_wh, total_max_wh, peak_power_w,
+ integrated_wh)
+ 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)),
@@ -91,7 +149,8 @@ def ingest(conn: sqlite3.Connection, readings: list[ReadingIn]) -> tuple[int, in
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))
+ coalesce(excluded.peak_power_w, peak_power_w)),
+ integrated_wh = coalesce(integrated_wh, 0) + coalesce(excluded.integrated_wh, 0)
""",
(
r.inverter_id,
@@ -100,9 +159,37 @@ def ingest(conn: sqlite3.Connection, readings: list[ReadingIn]) -> tuple[int, in
values["total_energy_wh"],
values["total_energy_wh"],
values["ac_power_total_w"],
+ integrated_wh,
),
)
- return stored, len(readings) - stored
+ if out_of_order:
+ day = local_day(ts)
+ conn.execute(
+ "UPDATE daily_energy SET integrated_wh = ? WHERE inverter_id = ? AND day = ?",
+ (_integrated_for_day(conn, r.inverter_id, day), r.inverter_id, day),
+ )
+ return stored, len(readings) - stored, clamped
+
+
+def rebuild_integrated_energy(conn: sqlite3.Connection) -> None:
+ """Recompute daily integrated energy from the stored readings."""
+ max_gap = get_settings().energy_integration_max_gap_seconds
+ totals: dict[tuple[str, str], float] = {}
+ prev: dict[str, tuple[int, int | None]] = {}
+ for r in conn.execute(
+ "SELECT inverter_id, ts, ac_power_total_w AS w FROM readings ORDER BY inverter_id, ts"
+ ):
+ p = prev.get(r["inverter_id"])
+ if p and p[1] is not None and r["w"] is not None and r["ts"] - p[0] <= max_gap:
+ key = (r["inverter_id"], local_day(r["ts"]))
+ totals[key] = totals.get(key, 0) + (p[1] + r["w"]) / 2 * (r["ts"] - p[0]) / 3600
+ prev[r["inverter_id"]] = (r["ts"], r["w"])
+ conn.execute("UPDATE daily_energy SET integrated_wh = NULL")
+ for (inv, day), wh in totals.items():
+ conn.execute(
+ "UPDATE daily_energy SET integrated_wh = ? WHERE inverter_id = ? AND day = ?",
+ (wh, inv, day),
+ )
def purge(conn: sqlite3.Connection, retention_days: int) -> int:
@@ -238,15 +325,21 @@ def fleet_power(conn: sqlite3.Connection, start: int, end: int, bucket: int) ->
return list(points.values())
+# Best available energy for a day: the inverter's daily counter, else the
+# lifetime counter's growth, else AC power integrated over time (estimate).
+ENERGY_SQL = """
+ coalesce(daily_energy_wh, total_max_wh - total_min_wh, cast(round(integrated_wh) AS INTEGER)) AS wh,
+ (daily_energy_wh IS NULL AND total_max_wh IS NULL AND integrated_wh IS NOT NULL) AS estimated
+"""
+
+
def daily_energy(
conn: sqlite3.Connection, first: date, last: date, inverter_id: str | None = None
) -> list[dict]:
- """[{day, total_wh,
Daily energy · last 30 days
- {data &&
Not available yet
}- MPPT1 and MPPT2 should track each other when both carry similar strings — one dropping - away from the other points at that string. + {hasDc + ? 'MPPT1 and MPPT2 should track each other when both carry similar strings — one dropping away from the other points at that string.' + : 'DC input (MPPT) values are not available yet.'}
@@ -155,7 +167,9 @@ function HistoryCharts({ id, fields }) { ))}