Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
42c7d18207 | ||
|
|
d01cef991f |
@@ -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=["*"]
|
||||
|
||||
@@ -88,13 +88,29 @@ the chart picker without further changes.
|
||||
datalogger is still posting and the sun is up. At night that's **Sleeping**;
|
||||
if the datalogger itself is silent the state is **No data** (and a banner
|
||||
says so).
|
||||
- **Fault** — the reading carries a non-zero `error_code`.
|
||||
- **Fault** — the reading carries a non-zero `error_code`. No `error_code`
|
||||
(the poller doesn't send one yet) means no fault.
|
||||
- **Feeding / Standby** — online and `status_code` is in
|
||||
`FEEDING_STATUS_CODES` (7, 8) → Feeding; any other code → Standby. An
|
||||
inverter in standby while its peers produce is caught by the
|
||||
underperformance check below.
|
||||
- **Check needed** — output below `UNDERPERFORM_RATIO` (75%) of the fleet
|
||||
median over the last 10 min (per kWp once every inverter has its array size
|
||||
set), or one MPPT input below half of the other.
|
||||
|
||||
Thresholds are in `.env`.
|
||||
|
||||
### Energy
|
||||
|
||||
Daily energy uses, in order: the inverter's daily counter
|
||||
(`daily_energy_wh`), the growth of its lifetime counter, or — while neither
|
||||
is decoded, which is the case today — AC power integrated over time
|
||||
(trapezoid between consecutive readings, gaps over 5 min not bridged). The
|
||||
estimate is flagged (`estimated: true` in the API, "≈" on the dashboard).
|
||||
Lifetime energy shows "not available yet" until `total_energy_wh` is sent.
|
||||
|
||||
The current state of the register map is in `poller/README.md`.
|
||||
|
||||
## Data retention
|
||||
|
||||
Raw readings older than `RETENTION_DAYS` (730) are purged every 6 h. The
|
||||
|
||||
+14
-4
@@ -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
|
||||
],
|
||||
}
|
||||
|
||||
@@ -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")
|
||||
|
||||
+11
-1
@@ -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:
|
||||
|
||||
+14
-2
@@ -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")),
|
||||
}
|
||||
|
||||
|
||||
+3
-1
@@ -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()
|
||||
|
||||
+18
-3
@@ -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
|
||||
|
||||
|
||||
|
||||
+119
-25
@@ -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, <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
|
||||
"""[{day, total_wh, estimated, <inverter_id>: Wh, ...}] for every day in
|
||||
range, oldest first. Days with no data have total_wh null."""
|
||||
sql = f"""
|
||||
SELECT day, inverter_id, peak_power_w, {ENERGY_SQL}
|
||||
FROM daily_energy WHERE day >= ? AND day <= ?
|
||||
"""
|
||||
params: list = [first.isoformat(), last.isoformat()]
|
||||
@@ -256,22 +349,23 @@ def daily_energy(
|
||||
by_day: dict[str, dict] = {}
|
||||
d = first
|
||||
while d <= last:
|
||||
by_day[d.isoformat()] = {"day": d.isoformat(), "total_wh": 0}
|
||||
by_day[d.isoformat()] = {"day": d.isoformat(), "total_wh": None, "estimated": False}
|
||||
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 r["wh"] is not None:
|
||||
row["total_wh"] = (row["total_wh"] or 0) + r["wh"]
|
||||
row["estimated"] = row["estimated"] or bool(r["estimated"])
|
||||
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]:
|
||||
def today_energy(conn: sqlite3.Connection) -> dict[str, dict]:
|
||||
"""{inverter_id: {"wh": int | None, "estimated": bool}} for today."""
|
||||
rows = conn.execute(
|
||||
"SELECT inverter_id, coalesce(daily_energy_wh, total_max_wh - total_min_wh) AS wh "
|
||||
"FROM daily_energy WHERE day = ?",
|
||||
f"SELECT inverter_id, {ENERGY_SQL} FROM daily_energy WHERE day = ?",
|
||||
(today().isoformat(),),
|
||||
)
|
||||
return {r["inverter_id"]: r["wh"] or 0 for r in rows}
|
||||
|
||||
return {r["inverter_id"]: {"wh": r["wh"], "estimated": bool(r["estimated"])} for r in rows}
|
||||
|
||||
@@ -26,7 +26,9 @@ def test_rejects_missing_key(client):
|
||||
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() == {
|
||||
"received": 1, "stored": 1, "duplicates": 0, "clamped_future": 0
|
||||
}
|
||||
assert client.post("/api/readings", json=batch).json()["duplicates"] == 1
|
||||
|
||||
latest = client.get("/api/inverters/inv1/latest").json()
|
||||
@@ -100,3 +102,90 @@ def test_empty_batch_marks_datalogger_alive(client):
|
||||
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
|
||||
|
||||
|
||||
def onsite_payload(inv, ts, power=6882, status=8):
|
||||
"""Exactly what the real on-site poller sends (2026-10-21)."""
|
||||
return {
|
||||
"timestamp": datetime.fromtimestamp(ts, timezone.utc).isoformat(),
|
||||
"inverter_id": inv,
|
||||
"ac_voltage_l1_v": 232.6, "ac_voltage_l2_v": 233.35, "ac_voltage_l3_v": 232.62,
|
||||
"ac_current_l1_a": 11.75, "ac_current_l2_a": 9.16, "ac_current_l3_a": 8.95,
|
||||
"ac_power_total_w": power, "grid_frequency_hz": 50.0, "temperature_c": 36,
|
||||
"status_code": status, "status_text": "feeding" if status in (7, 8) else "standby/not feeding",
|
||||
"p06d_raw_latched": 21450, "p052_static_v": 312.5, "p05a_static_a": 45.0,
|
||||
"p063_ind0_raw": 1872,
|
||||
}
|
||||
|
||||
|
||||
def test_onsite_payload_accepted_and_ok(client):
|
||||
now = int(time.time())
|
||||
batch = [onsite_payload("INV1", now, 6900, status=7), onsite_payload("INV2", now), onsite_payload("INV4", now, 6800)]
|
||||
r = client.post("/api/readings", json=batch)
|
||||
assert r.status_code == 200
|
||||
assert r.json() == {"received": 3, "stored": 3, "duplicates": 0, "clamped_future": 0}
|
||||
|
||||
s = client.get("/api/summary").json()
|
||||
for st in s["inverters"]:
|
||||
assert st["health"]["state"] == "ok", st
|
||||
assert st["health"]["feeding"] is True
|
||||
latest = s["inverters"][1]["latest"]
|
||||
assert latest["extra"]["p06d_raw_latched"] == 21450
|
||||
assert latest["dc_power_total_w"] is None and latest["efficiency_pct"] is None
|
||||
# No energy counters sent: lifetime unknown, today not yet integrated
|
||||
assert s["totals"]["total_energy_wh"] is None
|
||||
assert s["totals"]["feeding_count"] == 3
|
||||
|
||||
|
||||
def test_not_feeding_is_standby_and_flagged_when_peers_produce(client):
|
||||
now = int(time.time())
|
||||
client.post("/api/readings", json=[
|
||||
onsite_payload("INV1", now, 6900), onsite_payload("INV2", now, 7000),
|
||||
onsite_payload("INV4", now, 0, status=3),
|
||||
])
|
||||
by_id = {x["inverter"]["id"]: x["health"] for x in client.get("/api/summary").json()["inverters"]}
|
||||
assert by_id["INV4"]["feeding"] is False
|
||||
assert by_id["INV4"]["state"] == "warning" # 0 W while the others make ~7 kW
|
||||
|
||||
|
||||
def test_all_idle_is_plain_standby(client):
|
||||
# Everyone awake but not feeding (e.g. dusk): standby, no alarm
|
||||
now = int(time.time())
|
||||
client.post("/api/readings", json=[onsite_payload(i, now, 0, status=3) for i in ("INV1", "INV2", "INV4")])
|
||||
states = {x["health"]["state"] for x in client.get("/api/summary").json()["inverters"]}
|
||||
assert states == {"standby"}
|
||||
|
||||
|
||||
def test_heartbeat(client):
|
||||
r = client.post("/api/readings", json=[])
|
||||
assert r.status_code == 200 and r.json()["received"] == 0
|
||||
|
||||
|
||||
def test_future_timestamp_is_clamped(client):
|
||||
now = int(time.time())
|
||||
r = client.post("/api/readings", json=[onsite_payload("INV2", now + 3 * 3600)]).json()
|
||||
assert r["clamped_future"] == 1
|
||||
latest = client.get("/api/inverters/INV2/latest").json()
|
||||
assert abs(latest["age_seconds"]) < 5
|
||||
|
||||
|
||||
def test_energy_integrated_from_power_when_no_counters(client):
|
||||
now = int(time.time())
|
||||
# 6 kW for 30 minutes at 60 s steps -> 3 kWh
|
||||
client.post("/api/readings", json=[onsite_payload("INV1", now - 1800 + i * 60, 6000) for i in range(31)])
|
||||
s = client.get("/api/summary").json()
|
||||
e = s["inverters"][0]["energy_today"]
|
||||
if e["wh"] is not None: # skip when the window straddles local midnight
|
||||
assert e["estimated"] is True
|
||||
assert 2900 <= e["wh"] <= 3000
|
||||
assert s["totals"]["daily_energy_estimated"] is True
|
||||
|
||||
|
||||
def test_energy_survives_out_of_order_readings(client):
|
||||
now = int(time.time())
|
||||
# Latest reading arrives first, then the earlier ones (spool re-send)
|
||||
client.post("/api/readings", json=[onsite_payload("INV1", now, 6000)])
|
||||
client.post("/api/readings", json=[onsite_payload("INV1", now - 1800 + i * 60, 6000) for i in range(30)])
|
||||
e = client.get("/api/summary").json()["inverters"][0]["energy_today"]
|
||||
if e["wh"] is not None:
|
||||
assert 2900 <= e["wh"] <= 3000
|
||||
|
||||
@@ -189,3 +189,12 @@ export function DayBars({ days, series, format, axisFormat, height = 220 }) {
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export function EnergyFootnote({ estimated }) {
|
||||
return (
|
||||
<div className="mt-1 flex justify-between gap-3 text-[11px] text-muted">
|
||||
<span>{estimated && '≈ Estimated from AC power readings until the energy counters are decoded'}</span>
|
||||
<span className="shrink-0">axis in kWh</span>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ import Icon from './Icon'
|
||||
|
||||
export const STATES = {
|
||||
ok: { label: 'Operating', icon: 'check', tone: 'good' },
|
||||
standby: { label: 'Standby', icon: 'pause', tone: 'neutral' },
|
||||
warning: { label: 'Check needed', icon: 'alert', tone: 'warning' },
|
||||
fault: { label: 'Fault', icon: 'fault', tone: 'critical' },
|
||||
offline: { label: 'Offline', icon: 'offline', tone: 'critical' },
|
||||
@@ -20,8 +21,9 @@ const SEVERITY_TONE = { critical: 'critical', warning: 'warning', info: 'neutral
|
||||
const SEVERITY_ICON = { critical: 'fault', warning: 'alert', info: 'unknown' }
|
||||
|
||||
/** Health state pill: always icon + label, never color alone. */
|
||||
export function StatePill({ state, size = 'md' }) {
|
||||
const s = STATES[state] ?? STATES.unknown
|
||||
export function StatePill({ state, feeding, size = 'md' }) {
|
||||
let s = STATES[state] ?? STATES.unknown
|
||||
if (state === 'ok' && feeding) s = { ...s, label: 'Feeding' }
|
||||
const sz = size === 'lg' ? 'text-sm px-3 py-1.5 gap-1.5' : 'text-xs px-2 py-1 gap-1'
|
||||
return (
|
||||
<span className={`inline-flex items-center rounded-full font-semibold ${sz} ${TONE[s.tone]}`}>
|
||||
|
||||
@@ -18,6 +18,12 @@ const PATHS = {
|
||||
<path d="m2 2 20 20" />
|
||||
</>
|
||||
),
|
||||
pause: (
|
||||
<>
|
||||
<circle cx="12" cy="12" r="10" />
|
||||
<path d="M10 15V9M14 15V9" />
|
||||
</>
|
||||
),
|
||||
moon: <path d="M12 3a6 6 0 0 0 9 9 9 9 0 1 1-9-9Z" />,
|
||||
unknown: (
|
||||
<>
|
||||
|
||||
@@ -4,26 +4,28 @@ import { ago, energyParts, num, powerParts } from '../lib/format'
|
||||
import { IssueList, OnlineDot, StatePill } from './Health'
|
||||
import Icon from './Icon'
|
||||
|
||||
function Stat({ label, value, unit }) {
|
||||
function Stat({ label, value, unit, unavailable }) {
|
||||
return (
|
||||
<div className="min-w-0">
|
||||
<div className="text-[11px] uppercase tracking-wide text-muted">{label}</div>
|
||||
<div className="truncate tnum">
|
||||
<span className="font-semibold">{value}</span>
|
||||
{unit && <span className="ml-0.5 text-xs text-ink-2">{unit}</span>}
|
||||
</div>
|
||||
{unavailable ? (
|
||||
<div className="text-xs leading-5 text-muted">not available yet</div>
|
||||
) : (
|
||||
<div className="truncate tnum">
|
||||
<span className="font-semibold">{value}</span>
|
||||
{unit && <span className="ml-0.5 text-xs text-ink-2">{unit}</span>}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default function InverterCard({ status, ids }) {
|
||||
const { inverter, health, latest } = status
|
||||
const { inverter, health, latest, energy_today: energyToday } = status
|
||||
const r = latest ?? {}
|
||||
const live = health.online
|
||||
const [pw, pu] = powerParts(live ? r.ac_power_total_w : null)
|
||||
// The daily counter only counts if the last reading is from today
|
||||
const fromToday = r.timestamp && new Date(r.timestamp).toDateString() === new Date().toDateString()
|
||||
const [today, todayU] = energyParts(fromToday ? r.daily_energy_wh : null)
|
||||
const [today, todayU] = energyParts(energyToday.wh)
|
||||
const [life, lifeU] = energyParts(r.total_energy_wh)
|
||||
const volts = [r.ac_voltage_l1_v, r.ac_voltage_l2_v, r.ac_voltage_l3_v]
|
||||
|
||||
@@ -47,7 +49,7 @@ export default function InverterCard({ status, ids }) {
|
||||
<span className="text-xs text-muted">· {ago(r.timestamp)}</span>
|
||||
</div>
|
||||
</div>
|
||||
<StatePill state={health.state} />
|
||||
<StatePill state={health.state} feeding={health.feeding} />
|
||||
</div>
|
||||
|
||||
<div className="flex items-baseline gap-1 tnum">
|
||||
@@ -61,8 +63,13 @@ export default function InverterCard({ status, ids }) {
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-3 gap-3 text-sm">
|
||||
<Stat label="Today" value={today} unit={todayU} />
|
||||
<Stat label="Lifetime" value={life} unit={lifeU} />
|
||||
<Stat
|
||||
label={energyToday.estimated ? 'Today ≈' : 'Today'}
|
||||
value={today}
|
||||
unit={todayU}
|
||||
unavailable={energyToday.wh == null && live}
|
||||
/>
|
||||
<Stat label="Lifetime" value={life} unit={lifeU} unavailable={r.total_energy_wh == null} />
|
||||
<Stat label="Temp" value={live ? num(r.temperature_c) : '—'} unit="°C" />
|
||||
</div>
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useMemo, useState } from 'react'
|
||||
import { Link } from 'react-router-dom'
|
||||
import { DayBars, Legend, TimeLines } from '../components/Charts'
|
||||
import { DayBars, EnergyFootnote, Legend, TimeLines } from '../components/Charts'
|
||||
import Comparison from '../components/Comparison'
|
||||
import { IssueList } from '../components/Health'
|
||||
import Icon from '../components/Icon'
|
||||
@@ -25,21 +25,25 @@ function Hero({ summary }) {
|
||||
</div>
|
||||
<dl className="mt-4 grid grid-cols-3 gap-3 border-t border-line pt-4 text-sm">
|
||||
<div>
|
||||
<dt className="text-xs text-muted">Today</dt>
|
||||
<dt className="text-xs text-muted">{t.daily_energy_estimated ? 'Today ≈' : 'Today'}</dt>
|
||||
<dd className="tnum">
|
||||
<span className="text-lg font-semibold">{today}</span> <span className="text-ink-2">{todayU}</span>
|
||||
</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt className="text-xs text-muted">Lifetime</dt>
|
||||
<dd className="tnum">
|
||||
<span className="text-lg font-semibold">{life}</span> <span className="text-ink-2">{lifeU}</span>
|
||||
</dd>
|
||||
{t.total_energy_wh == null ? (
|
||||
<dd className="text-xs leading-7 text-muted">not available yet</dd>
|
||||
) : (
|
||||
<dd className="tnum">
|
||||
<span className="text-lg font-semibold">{life}</span> <span className="text-ink-2">{lifeU}</span>
|
||||
</dd>
|
||||
)}
|
||||
</div>
|
||||
<div>
|
||||
<dt className="text-xs text-muted">Online</dt>
|
||||
<dt className="text-xs text-muted">Feeding</dt>
|
||||
<dd className="tnum">
|
||||
<span className="text-lg font-semibold">{t.online_count}</span>
|
||||
<span className="text-lg font-semibold">{t.feeding_count}</span>
|
||||
<span className="text-ink-2"> / {t.inverter_count}</span>
|
||||
</dd>
|
||||
</div>
|
||||
@@ -114,13 +118,20 @@ function EnergyCard({ ids, names }) {
|
||||
mode === 'combined'
|
||||
? [{ key: 'total_wh', name: 'All inverters', color: c.accent }]
|
||||
: ids.map((id) => ({ key: id, name: names[id] ?? id, color: seriesColor(c, ids, id) }))
|
||||
const total = data?.days.reduce((s, d) => s + d.total_wh, 0)
|
||||
const total = data?.days.reduce((s, d) => s + (d.total_wh ?? 0), 0)
|
||||
const estimated = data?.days.some((d) => d.estimated)
|
||||
const empty = data && data.days.every((d) => d.total_wh == null)
|
||||
return (
|
||||
<section className="card p-4">
|
||||
<div className="mb-3 flex flex-wrap items-center justify-between gap-2">
|
||||
<div>
|
||||
<h2 className="text-sm font-semibold">Daily energy · last 30 days</h2>
|
||||
{data && <div className="text-xs text-muted tnum">{energy(total)} total</div>}
|
||||
{data && !empty && (
|
||||
<div className="text-xs text-muted tnum">
|
||||
{estimated && '≈ '}
|
||||
{energy(total)} total
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<Segmented
|
||||
label="Energy chart mode"
|
||||
@@ -137,12 +148,14 @@ function EnergyCard({ ids, names }) {
|
||||
<Legend series={series} />
|
||||
</div>
|
||||
)}
|
||||
{data ? (
|
||||
{empty ? (
|
||||
<div className="flex h-56 items-center justify-center text-sm text-muted">No energy data yet</div>
|
||||
) : data ? (
|
||||
<DayBars days={data.days} series={series} format={energy} axisFormat={(wh) => num(wh / 1000, 0)} />
|
||||
) : (
|
||||
<div className="h-56" />
|
||||
)}
|
||||
<div className="mt-1 text-right text-[11px] text-muted">axis in kWh</div>
|
||||
<EnergyFootnote estimated={estimated} />
|
||||
</section>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useMemo, useState } from 'react'
|
||||
import { Link, useParams } from 'react-router-dom'
|
||||
import { DayBars, Legend, TimeLines } from '../components/Charts'
|
||||
import { DayBars, EnergyFootnote, Legend, TimeLines } from '../components/Charts'
|
||||
import EditInverterDialog from '../components/EditInverterDialog'
|
||||
import { IssueList, OnlineDot, StatePill } from '../components/Health'
|
||||
import Icon from '../components/Icon'
|
||||
@@ -31,14 +31,18 @@ function formatField(field, value) {
|
||||
return `${num(value, field.decimals)}${field.unit ? ` ${field.unit}` : ''}`
|
||||
}
|
||||
|
||||
function KeyFigure({ label, parts }) {
|
||||
function KeyFigure({ label, parts, unavailable }) {
|
||||
return (
|
||||
<div className="card px-4 py-3">
|
||||
<div className="text-xs text-muted">{label}</div>
|
||||
<div className="tnum">
|
||||
<span className="text-2xl font-semibold tracking-tight">{parts[0]}</span>
|
||||
<span className="ml-1 text-sm text-ink-2">{parts[1]}</span>
|
||||
</div>
|
||||
{unavailable ? (
|
||||
<div className="text-sm leading-8 text-muted">not available yet</div>
|
||||
) : (
|
||||
<div className="tnum">
|
||||
<span className="text-2xl font-semibold tracking-tight">{parts[0]}</span>
|
||||
<span className="ml-1 text-sm text-ink-2">{parts[1]}</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -54,10 +58,12 @@ function Parameters({ fields, latest, live }) {
|
||||
</p>
|
||||
<div className="grid gap-x-8 gap-y-4 sm:grid-cols-2">
|
||||
{GROUPS.map((g) => {
|
||||
const items = fields.filter((f) => f.group === g.key)
|
||||
// Parameters the poller doesn't send (yet) are left out entirely
|
||||
const items = fields.filter((f) => f.group === g.key && latest?.[f.key] != null)
|
||||
return (
|
||||
<div key={g.key}>
|
||||
<h3 className="mb-1 text-xs font-semibold uppercase tracking-wide text-muted">{g.label}</h3>
|
||||
{items.length === 0 && <p className="py-1.5 text-sm text-muted">Not available yet</p>}
|
||||
<dl className="divide-y divide-[var(--border)] text-sm">
|
||||
{items.map((f) => (
|
||||
<div key={f.key} className="flex justify-between gap-4 py-1.5">
|
||||
@@ -94,13 +100,18 @@ function HistoryCharts({ id, fields }) {
|
||||
const seconds = RANGES[range].seconds
|
||||
const { data } = usePoll(() => api.history(id, { from: isoAgo(seconds) }), 120_000, `${id}:${range}`)
|
||||
|
||||
const points = data?.points ?? []
|
||||
const hasData = (key) => points.some((p) => p[key] != null)
|
||||
const powerSeries = [
|
||||
{ key: 'ac_power_total_w', name: 'AC output', color: c.series[0] },
|
||||
{ key: 'dc_power_mppt1_w', name: 'DC MPPT1', color: c.series[1] },
|
||||
{ key: 'dc_power_mppt2_w', name: 'DC MPPT2', color: c.series[2] },
|
||||
]
|
||||
const chartable = fields.filter((f) => !f.derived && f.agg === 'avg' && f.key !== 'ac_power_total_w')
|
||||
const paramField = fields.find((f) => f.key === param) ?? chartable[0]
|
||||
].filter((s, i) => i === 0 || hasData(s.key))
|
||||
const hasDc = powerSeries.length > 1
|
||||
const chartable = fields.filter(
|
||||
(f) => !f.derived && f.agg === 'avg' && f.key !== 'ac_power_total_w' && (!data || hasData(f.key)),
|
||||
)
|
||||
const paramField = chartable.find((f) => f.key === param) ?? chartable[0]
|
||||
const from = data ? Date.parse(data.from) / 1000 : 0
|
||||
const to = data ? Date.parse(data.to) / 1000 : 1
|
||||
|
||||
@@ -133,8 +144,9 @@ function HistoryCharts({ id, fields }) {
|
||||
<div className="h-60" />
|
||||
)}
|
||||
<p className="mt-2 text-xs text-muted">
|
||||
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.'}
|
||||
</p>
|
||||
</section>
|
||||
|
||||
@@ -155,7 +167,9 @@ function HistoryCharts({ id, fields }) {
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
{data && paramField ? (
|
||||
{data && !paramField ? (
|
||||
<div className="flex h-52 items-center justify-center text-sm text-muted">No data in this range</div>
|
||||
) : data && paramField ? (
|
||||
<TimeLines
|
||||
points={data.points}
|
||||
series={[{ key: paramField.key, name: paramField.label, color: c.series[0] }]}
|
||||
@@ -178,11 +192,20 @@ function YearEnergy({ id }) {
|
||||
const c = useThemeColors()
|
||||
const { data } = usePoll(() => api.inverterDaily(id, { days: 365 }), 600_000, id)
|
||||
const total = data?.days.reduce((s, d) => s + (d.energy_wh ?? 0), 0)
|
||||
const estimated = data?.days.some((d) => d.estimated)
|
||||
const empty = data && data.days.every((d) => d.energy_wh == null)
|
||||
return (
|
||||
<section className="card p-4">
|
||||
<h2 className="text-sm font-semibold">Daily energy · last 365 days</h2>
|
||||
{data && <div className="mb-3 text-xs text-muted tnum">{energy(total)} total</div>}
|
||||
{data ? (
|
||||
{data && !empty && (
|
||||
<div className="mb-3 text-xs text-muted tnum">
|
||||
{estimated && '≈ '}
|
||||
{energy(total)} total
|
||||
</div>
|
||||
)}
|
||||
{empty ? (
|
||||
<div className="flex h-56 items-center justify-center text-sm text-muted">No energy data yet</div>
|
||||
) : data ? (
|
||||
<DayBars
|
||||
days={data.days}
|
||||
series={[{ key: 'energy_wh', name: 'Energy', color: c.accent }]}
|
||||
@@ -192,7 +215,7 @@ function YearEnergy({ id }) {
|
||||
) : (
|
||||
<div className="h-56" />
|
||||
)}
|
||||
<div className="mt-1 text-right text-[11px] text-muted">axis in kWh</div>
|
||||
<EnergyFootnote estimated={estimated} />
|
||||
</section>
|
||||
)
|
||||
}
|
||||
@@ -218,7 +241,6 @@ export default function InverterDetail({ summaryPoll }) {
|
||||
|
||||
const { inverter, health, latest } = status
|
||||
const live = health.online
|
||||
const fromToday = latest?.timestamp && new Date(latest.timestamp).toDateString() === new Date().toDateString()
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
@@ -237,7 +259,7 @@ export default function InverterDetail({ summaryPoll }) {
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<StatePill state={health.state} size="lg" />
|
||||
<StatePill state={health.state} feeding={health.feeding} size="lg" />
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setEditing(true)}
|
||||
@@ -254,8 +276,11 @@ export default function InverterDetail({ summaryPoll }) {
|
||||
|
||||
<div className="grid grid-cols-2 gap-3 md:grid-cols-4">
|
||||
<KeyFigure label="Power now" parts={powerParts(live ? latest?.ac_power_total_w : null)} />
|
||||
<KeyFigure label="Today" parts={energyParts(fromToday ? latest?.daily_energy_wh : null)} />
|
||||
<KeyFigure label="Lifetime" parts={energyParts(latest?.total_energy_wh)} />
|
||||
<KeyFigure
|
||||
label={status.energy_today.estimated ? 'Today ≈' : 'Today'}
|
||||
parts={energyParts(status.energy_today.wh)}
|
||||
/>
|
||||
<KeyFigure label="Lifetime" parts={energyParts(latest?.total_energy_wh)} unavailable={latest?.total_energy_wh == null} />
|
||||
<KeyFigure
|
||||
label="vs fleet median"
|
||||
parts={[health.relative_output == null ? '—' : num(health.relative_output * 100, 0), '%']}
|
||||
|
||||
@@ -11,7 +11,8 @@ the on-site side: read the inverters, POST the values.
|
||||
use it to send. It's standard library only. It timestamps readings, keeps
|
||||
them in `unsent_readings.jsonl` when the internet is down, re-sends them
|
||||
later, and never raises.
|
||||
- `README.md` (next to this brief): the field names, units and scalings.
|
||||
- `README.md` (next to this brief): the field names, units and the current
|
||||
state of the register map (what's verified, what isn't sent yet).
|
||||
|
||||
## What to do every 60 s
|
||||
|
||||
@@ -44,9 +45,9 @@ while True:
|
||||
e.g. `INV1`..`INV5` matching labels on the units. It's the database key.
|
||||
Pretty names are set later in the dashboard, not here. Allowed characters:
|
||||
letters, digits, `_ . -`.
|
||||
3. **Send converted values**, not raw ones, using the keys and scalings in
|
||||
`README.md` (e.g. `ac_voltage_l1_v` = P050 raw / 40). Leave out anything
|
||||
you couldn't read; every field is optional.
|
||||
3. **Send converted values**, not raw ones, using the keys in `README.md`.
|
||||
Leave out anything you couldn't read or haven't verified; every field is
|
||||
optional. Timestamps must be real UTC (see README).
|
||||
4. **New or unconfirmed parameters:** send them too, under a descriptive key
|
||||
(e.g. `p0xx_raw`). The backend stores unknown keys and shows them on the
|
||||
inverter page under "Other (unmapped)". Tell the owner when a mapping is
|
||||
|
||||
+32
-15
@@ -1,6 +1,6 @@
|
||||
# On-site poller
|
||||
|
||||
`refusol_poller.py` (not in this repo yet) reads the inverters over USS/TCP
|
||||
`refusol_poller.py` (lives on the site laptop, not in this repo) 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.
|
||||
|
||||
@@ -30,20 +30,37 @@ 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 |
|
||||
State of the map as verified on site (2026-10-21):
|
||||
|
||||
| key | unit | status | source |
|
||||
|---|---|---|---|
|
||||
| `ac_power_total_w` | W | ✅ sent | **Computed** by the poller: Σ (phase V × phase I), forced to 0 when the inverter isn't feeding. *Not* P06D — P06D sits latched at 21450 on any feeding unit (nameplate/limit, not live power). |
|
||||
| `ac_voltage_l1_v` / `_l2_v` / `_l3_v` | V | ✅ sent | P050 / P05B / P064 raw / 40 |
|
||||
| `ac_current_l1_a` / `_l2_a` / `_l3_a` | A | ✅ sent | P068 / P069 / P06A raw / 100 |
|
||||
| `grid_frequency_hz` | Hz | ✅ sent | P06C raw / 20 |
|
||||
| `temperature_c` | °C | ✅ sent | P070 raw >> 16 |
|
||||
| `status_code` | – | ✅ sent | PZD status word. **7 and 8 = feeding** (7 on INV1's OEM board, 8 on the standard units); anything else shows as Standby. Other values not decoded yet. |
|
||||
| `status_text` | – | ✅ sent | `"feeding"` / `"standby/not feeding"` |
|
||||
| `dc_voltage_mppt1_v` / `_mppt2_v` | V | ❌ not sent | P052 / P054 are static nameplate/limit values, not live. Real registers TBD. |
|
||||
| `dc_current_mppt1_a` / `_mppt2_a` | A | ❌ not sent | P05A / P05C likewise static. Real registers TBD. |
|
||||
| `daily_energy_wh` | Wh | ❌ not sent | P063 IND=0 is frozen, not accumulating. Real register TBD. Until then the backend **estimates** daily energy by integrating `ac_power_total_w` (shown with ≈). |
|
||||
| `total_energy_wh` | Wh | ❌ not sent | P063 IND=11 decode wrong. Real register TBD. Lifetime shows "not available yet". |
|
||||
| `error_code` | – | ❌ not sent | No fault register confirmed yet. Absent = no fault. Non-zero will show the inverter as **Fault**. |
|
||||
|
||||
Unmapped diagnostics currently sent (stored, shown under "Other (unmapped)",
|
||||
never treated as telemetry): `p06d_raw_latched`, `p052_static_v`,
|
||||
`p05a_static_a`, `p063_ind0_raw`.
|
||||
|
||||
Inverter IDs (permanent database keys): INV1 = 192.168.1.11, INV2 =
|
||||
192.168.1.12, INV3 = 192.168.1.13 (reserved, not connected yet), INV4 =
|
||||
192.168.1.221, INV5 = REFUsol 20K-3T (reserved, no read path yet). An
|
||||
inverter appears on the dashboard the first time it reports.
|
||||
|
||||
**Timestamps must be UTC.** Send them with the right offset (e.g.
|
||||
`datetime.now(timezone.utc).isoformat()`), or leave `timestamp` out and let
|
||||
`backend_client.py` add it. A reading stamped more than 5 min in the future
|
||||
(e.g. local Athens time labelled `+00:00`) is stored at the time it was
|
||||
received instead, and the response's `clamped_future` count says so.
|
||||
|
||||
`send()` stamps each reading with the current UTC time, buffers to
|
||||
`unsent_readings.jsonl` when the internet is down and re-sends later, and
|
||||
|
||||
+26
-35
@@ -2,9 +2,11 @@
|
||||
|
||||
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.
|
||||
Sends what the real poller sends today (AC side, temperature, status code,
|
||||
unmapped diagnostics; no DC or energy counters). --backfill-days first loads
|
||||
that many days of history (one reading per 5 minutes), then it posts live
|
||||
readings every --interval seconds. INV4 runs at half output (as if a string
|
||||
fuse had blown) so the warnings show up.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
@@ -15,7 +17,7 @@ from datetime import datetime, timedelta, timezone
|
||||
|
||||
from backend_client import BackendClient
|
||||
|
||||
INVERTERS = ["INV1", "INV2", "INV3", "INV4", "INV5"]
|
||||
INVERTERS = ["INV1", "INV2", "INV4"]
|
||||
PEAK_W = 18_000
|
||||
|
||||
|
||||
@@ -26,40 +28,32 @@ def sun_factor(t: datetime) -> float:
|
||||
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:
|
||||
def reading(inv: str, t: datetime) -> 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
|
||||
feeding = f > 0.03
|
||||
w = int(PEAK_W * f * (0.5 if inv == "INV4" else 1.0)) if feeding else 0
|
||||
volts = [round(random.uniform(229, 236), 2) for _ in range(3)]
|
||||
amps = [round(w / 3 / v, 2) for v in volts]
|
||||
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,
|
||||
"ac_voltage_l1_v": volts[0],
|
||||
"ac_voltage_l2_v": volts[1],
|
||||
"ac_voltage_l3_v": volts[2],
|
||||
"ac_current_l1_a": amps[0],
|
||||
"ac_current_l2_a": amps[1],
|
||||
"ac_current_l3_a": amps[2],
|
||||
"ac_power_total_w": w,
|
||||
"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")]),
|
||||
"status_code": (7 if inv == "INV1" else 8) if feeding else 3,
|
||||
"status_text": "feeding" if feeding else "standby/not feeding",
|
||||
"p06d_raw_latched": 21450,
|
||||
"p052_static_v": 312.5,
|
||||
"p05a_static_a": 45.0,
|
||||
"p063_ind0_raw": 1872,
|
||||
}
|
||||
|
||||
|
||||
@@ -72,13 +66,11 @@ def main() -> None:
|
||||
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))]
|
||||
batch += [r for inv in INVERTERS if (r := reading(inv, t))]
|
||||
if len(batch) >= 1000:
|
||||
client.send(batch)
|
||||
batch = []
|
||||
@@ -86,10 +78,9 @@ def main() -> None:
|
||||
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))]
|
||||
batch = [r for inv in INVERTERS if (r := reading(inv, now))]
|
||||
ok = client.send(batch)
|
||||
print(f"{now:%H:%M:%S} sent {len(batch)} readings, ok={ok}")
|
||||
time.sleep(args.interval)
|
||||
|
||||
Reference in New Issue
Block a user