feat: match the verified on-site poller payload
The on-site agent found that the DC (P052/P054/P05A/P05C) and energy (P063) registers are static/frozen and ac_power_total_w is now computed V*I, so the backend and dashboard have to cope with those fields being absent. - Feeding/Standby from status_code (FEEDING_STATUS_CODES, default 7 and 8: INV1's OEM board uses 7). Online but not feeding = Standby; a standby inverter while peers produce is still caught by the underperformance check. Missing error_code stays "no fault". - Daily energy falls back to AC power integrated between readings, flagged estimated (≈ in the UI); out-of-order (spooled) readings recompute the day. Existing databases get the column and a rebuild on startup. - Totals are null instead of 0 when there's no energy data; lifetime shows "not available yet". Parameters the poller doesn't send are hidden on the detail page, DC lines only drawn when DC data exists. - Timestamps more than 5 min in the future are stored at receive time and counted in clamped_future — the example payload carried local Athens time labelled +00:00. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -34,6 +34,18 @@ UNDERPERFORM_MIN_FLEET_W=1000
|
|||||||
MPPT_IMBALANCE_RATIO=0.5
|
MPPT_IMBALANCE_RATIO=0.5
|
||||||
MPPT_MIN_POWER_W=1000
|
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
|
# Browser origins allowed to call the API directly (JSON list). The dashboard
|
||||||
# itself is same-origin and doesn't need this.
|
# itself is same-origin and doesn't need this.
|
||||||
CORS_ORIGINS=["*"]
|
CORS_ORIGINS=["*"]
|
||||||
|
|||||||
+14
-4
@@ -1,3 +1,4 @@
|
|||||||
|
import logging
|
||||||
import secrets
|
import secrets
|
||||||
import sqlite3
|
import sqlite3
|
||||||
from datetime import date, datetime, timedelta, timezone
|
from datetime import date, datetime, timedelta, timezone
|
||||||
@@ -10,6 +11,7 @@ from .config import get_settings
|
|||||||
from .db import get_db, set_meta
|
from .db import get_db, set_meta
|
||||||
from .schemas import IngestResult, Inverter, InverterUpdate, ReadingIn, Summary
|
from .schemas import IngestResult, Inverter, InverterUpdate, ReadingIn, Summary
|
||||||
|
|
||||||
|
log = logging.getLogger("solar")
|
||||||
router = APIRouter(prefix="/api")
|
router = APIRouter(prefix="/api")
|
||||||
Db = Annotated[sqlite3.Connection, Depends(get_db)]
|
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
|
"""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
|
backend the datalogger is alive, which is how a dead inverter is told
|
||||||
apart from a dead internet link."""
|
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()))
|
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
|
# ---------------------------------------------------------------- dashboard
|
||||||
@@ -181,14 +185,20 @@ def get_inverter_daily(
|
|||||||
end: Annotated[date | None, Query(alias="to")] = None,
|
end: Annotated[date | None, Query(alias="to")] = None,
|
||||||
days: Annotated[int, Query(ge=1, le=3660)] = 365,
|
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)
|
_inverter_or_404(conn, inverter_id)
|
||||||
first, last = _day_range(start, end, days)
|
first, last = _day_range(start, end, days)
|
||||||
rows = store.daily_energy(conn, first, last, inverter_id)
|
rows = store.daily_energy(conn, first, last, inverter_id)
|
||||||
return {
|
return {
|
||||||
"inverter_id": inverter_id,
|
"inverter_id": inverter_id,
|
||||||
"days": [
|
"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
|
for r in rows
|
||||||
],
|
],
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -44,6 +44,19 @@ class Settings(BaseSettings):
|
|||||||
mppt_imbalance_ratio: float = 0.5
|
mppt_imbalance_ratio: float = 0.5
|
||||||
mppt_min_power_w: float = 1000.0
|
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] = ["*"]
|
cors_origins: list[str] = ["*"]
|
||||||
|
|
||||||
@field_validator("site_latitude", "site_longitude", mode="before")
|
@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_min_wh INTEGER,
|
||||||
total_max_wh INTEGER,
|
total_max_wh INTEGER,
|
||||||
peak_power_w 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)
|
PRIMARY KEY (inverter_id, day)
|
||||||
) WITHOUT ROWID;
|
) WITHOUT ROWID;
|
||||||
|
|
||||||
@@ -72,13 +75,20 @@ def get_db() -> Iterator[sqlite3.Connection]:
|
|||||||
yield conn
|
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:
|
with session() as conn:
|
||||||
conn.executescript(SCHEMA)
|
conn.executescript(SCHEMA)
|
||||||
existing = {r["name"] for r in conn.execute("PRAGMA table_info(readings)")}
|
existing = {r["name"] for r in conn.execute("PRAGMA table_info(readings)")}
|
||||||
for f in FIELDS:
|
for f in FIELDS:
|
||||||
if f.key not in existing:
|
if f.key not in existing:
|
||||||
conn.execute(f"ALTER TABLE readings ADD COLUMN {f.key} {f.sql_type}")
|
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:
|
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
|
spec = specific(inv) if online else None
|
||||||
relative = round(spec / median, 3) if spec is not None and median 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:
|
if not online:
|
||||||
since = f"for {_minutes(r['age_seconds'])}" if r else "yet"
|
since = f"for {_minutes(r['age_seconds'])}" if r else "yet"
|
||||||
if not datalogger_online:
|
if not datalogger_online:
|
||||||
@@ -115,25 +118,34 @@ def summary(conn: sqlite3.Connection) -> dict:
|
|||||||
})
|
})
|
||||||
if state == "ok" and issues:
|
if state == "ok" and issues:
|
||||||
state = "warning"
|
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({
|
statuses.append({
|
||||||
"inverter": inv,
|
"inverter": inv,
|
||||||
"health": {
|
"health": {
|
||||||
"online": online,
|
"online": online,
|
||||||
|
"feeding": feeding if online else None,
|
||||||
"state": state,
|
"state": state,
|
||||||
"issues": issues,
|
"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,
|
"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,
|
"relative_output": relative,
|
||||||
},
|
},
|
||||||
|
"energy_today": energy_today.get(inv["id"], {"wh": None, "estimated": False}),
|
||||||
"latest": r,
|
"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 = {
|
totals = {
|
||||||
"ac_power_w": sum((latest[i["id"]].get("ac_power_total_w") or 0) for i in inverters if is_online(i["id"])),
|
"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()),
|
"daily_energy_wh": sum(today_values) if today_values else None,
|
||||||
"total_energy_wh": sum((r.get("total_energy_wh") or 0) for r in latest.values()),
|
"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),
|
"inverter_count": len(inverters),
|
||||||
"online_count": sum(1 for i in inverters if is_online(i["id"])),
|
"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")),
|
"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
|
@asynccontextmanager
|
||||||
async def lifespan(app: FastAPI):
|
async def lifespan(app: FastAPI):
|
||||||
migrate()
|
if migrate():
|
||||||
|
with session() as conn:
|
||||||
|
store.rebuild_integrated_energy(conn)
|
||||||
task = asyncio.create_task(purge_loop())
|
task = asyncio.create_task(purge_loop())
|
||||||
yield
|
yield
|
||||||
task.cancel()
|
task.cancel()
|
||||||
|
|||||||
+18
-3
@@ -49,6 +49,10 @@ class IngestResult(BaseModel):
|
|||||||
received: int
|
received: int
|
||||||
stored: int
|
stored: int
|
||||||
duplicates: 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):
|
class InverterUpdate(BaseModel):
|
||||||
@@ -71,7 +75,7 @@ class Inverter(BaseModel):
|
|||||||
|
|
||||||
|
|
||||||
Severity = Literal["info", "warning", "critical"]
|
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):
|
class Issue(BaseModel):
|
||||||
@@ -82,6 +86,9 @@ class Issue(BaseModel):
|
|||||||
|
|
||||||
class Health(BaseModel):
|
class Health(BaseModel):
|
||||||
online: bool = Field(description="A reading arrived within ONLINE_WINDOW_SECONDS")
|
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
|
state: State
|
||||||
issues: list[Issue]
|
issues: list[Issue]
|
||||||
avg_power_w: float | None = Field(description="Mean AC power over the comparison window")
|
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):
|
class InverterStatus(BaseModel):
|
||||||
inverter: Inverter
|
inverter: Inverter
|
||||||
health: Health
|
health: Health
|
||||||
|
energy_today: EnergyToday
|
||||||
latest: dict[str, Any] | None
|
latest: dict[str, Any] | None
|
||||||
|
|
||||||
|
|
||||||
class Totals(BaseModel):
|
class Totals(BaseModel):
|
||||||
ac_power_w: int
|
ac_power_w: int
|
||||||
daily_energy_wh: int
|
daily_energy_wh: int | None
|
||||||
total_energy_wh: int
|
daily_energy_estimated: bool
|
||||||
|
total_energy_wh: int | None = Field(description="Null until the inverters report a lifetime counter")
|
||||||
inverter_count: int
|
inverter_count: int
|
||||||
online_count: int
|
online_count: int
|
||||||
|
feeding_count: int
|
||||||
problem_count: int
|
problem_count: int
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
+119
-25
@@ -37,26 +37,76 @@ def today() -> date:
|
|||||||
# ---------------------------------------------------------------- ingest
|
# ---------------------------------------------------------------- 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:
|
if r.timestamp is None:
|
||||||
return now_ts()
|
return received, False
|
||||||
t = r.timestamp
|
t = r.timestamp
|
||||||
if t.tzinfo is None:
|
if t.tzinfo is None:
|
||||||
t = t.replace(tzinfo=timezone.utc)
|
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]:
|
def _integrate(conn: sqlite3.Connection, inverter_id: str, ts: int, power: int | None) -> float | None:
|
||||||
"""Store readings; returns (stored, duplicates). Re-sent readings (same
|
"""Wh produced since the previous reading (trapezoid rule), or None when
|
||||||
inverter + timestamp) are ignored, so the poller can safely retry."""
|
there's nothing to add (no power, first reading, gap too long)."""
|
||||||
stored = 0
|
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]
|
cols = ["inverter_id", "ts", "extra", *FIELD_KEYS]
|
||||||
insert_sql = (
|
insert_sql = (
|
||||||
f"INSERT OR IGNORE INTO readings ({', '.join(cols)}) "
|
f"INSERT OR IGNORE INTO readings ({', '.join(cols)}) "
|
||||||
f"VALUES ({', '.join('?' for _ in cols)})"
|
f"VALUES ({', '.join('?' for _ in cols)})"
|
||||||
)
|
)
|
||||||
for r in readings:
|
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))
|
values = r.model_dump(include=set(FIELD_KEYS))
|
||||||
extra = {**(r.model_extra or {}), **(r.extra or {})}
|
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:
|
if cur.rowcount == 0:
|
||||||
continue
|
continue
|
||||||
stored += 1
|
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
|
# max()/min() of two values where either may be NULL
|
||||||
conn.execute(
|
conn.execute(
|
||||||
"""
|
"""
|
||||||
INSERT INTO daily_energy
|
INSERT INTO daily_energy
|
||||||
(inverter_id, day, daily_energy_wh, total_min_wh, total_max_wh, peak_power_w)
|
(inverter_id, day, daily_energy_wh, total_min_wh, total_max_wh, peak_power_w,
|
||||||
VALUES (?, ?, ?, ?, ?, ?)
|
integrated_wh)
|
||||||
|
VALUES (?, ?, ?, ?, ?, ?, ?)
|
||||||
ON CONFLICT (inverter_id, day) DO UPDATE SET
|
ON CONFLICT (inverter_id, day) DO UPDATE SET
|
||||||
daily_energy_wh = max(coalesce(daily_energy_wh, excluded.daily_energy_wh),
|
daily_energy_wh = max(coalesce(daily_energy_wh, excluded.daily_energy_wh),
|
||||||
coalesce(excluded.daily_energy_wh, 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),
|
total_max_wh = max(coalesce(total_max_wh, excluded.total_max_wh),
|
||||||
coalesce(excluded.total_max_wh, total_max_wh)),
|
coalesce(excluded.total_max_wh, total_max_wh)),
|
||||||
peak_power_w = max(coalesce(peak_power_w, excluded.peak_power_w),
|
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,
|
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["total_energy_wh"],
|
values["total_energy_wh"],
|
||||||
values["ac_power_total_w"],
|
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:
|
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())
|
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(
|
def daily_energy(
|
||||||
conn: sqlite3.Connection, first: date, last: date, inverter_id: str | None = None
|
conn: sqlite3.Connection, first: date, last: date, inverter_id: str | None = None
|
||||||
) -> list[dict]:
|
) -> list[dict]:
|
||||||
"""[{day, total_wh, <inverter_id>: Wh, ...}] for every day in range, oldest first.
|
"""[{day, total_wh, estimated, <inverter_id>: Wh, ...}] for every day in
|
||||||
Uses the inverter's own daily counter, falling back to the lifetime
|
range, oldest first. Days with no data have total_wh null."""
|
||||||
counter's growth over the day when the daily counter wasn't reported."""
|
sql = f"""
|
||||||
sql = """
|
SELECT day, inverter_id, peak_power_w, {ENERGY_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 <= ?
|
FROM daily_energy WHERE day >= ? AND day <= ?
|
||||||
"""
|
"""
|
||||||
params: list = [first.isoformat(), last.isoformat()]
|
params: list = [first.isoformat(), last.isoformat()]
|
||||||
@@ -256,22 +349,23 @@ def daily_energy(
|
|||||||
by_day: dict[str, dict] = {}
|
by_day: dict[str, dict] = {}
|
||||||
d = first
|
d = first
|
||||||
while d <= last:
|
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)
|
d += timedelta(days=1)
|
||||||
for r in conn.execute(sql, params):
|
for r in conn.execute(sql, params):
|
||||||
row = by_day[r["day"]]
|
row = by_day[r["day"]]
|
||||||
row[r["inverter_id"]] = r["wh"]
|
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:
|
if inverter_id:
|
||||||
row["peak_power_w"] = r["peak_power_w"]
|
row["peak_power_w"] = r["peak_power_w"]
|
||||||
return list(by_day.values())
|
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(
|
rows = conn.execute(
|
||||||
"SELECT inverter_id, coalesce(daily_energy_wh, total_max_wh - total_min_wh) AS wh "
|
f"SELECT inverter_id, {ENERGY_SQL} FROM daily_energy WHERE day = ?",
|
||||||
"FROM daily_energy WHERE day = ?",
|
|
||||||
(today().isoformat(),),
|
(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):
|
def test_ingest_is_idempotent_and_keeps_unknown_fields(client):
|
||||||
now = int(time.time())
|
now = int(time.time())
|
||||||
batch = [reading("inv1", now, 10000, p_new_param=42)]
|
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
|
assert client.post("/api/readings", json=batch).json()["duplicates"] == 1
|
||||||
|
|
||||||
latest = client.get("/api/inverters/inv1/latest").json()
|
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):
|
def test_fields_meta(client):
|
||||||
keys = [f["key"] for f in client.get("/api/meta/fields").json()]
|
keys = [f["key"] for f in client.get("/api/meta/fields").json()]
|
||||||
assert "ac_power_total_w" in keys and "efficiency_pct" in keys
|
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>
|
</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 = {
|
export const STATES = {
|
||||||
ok: { label: 'Operating', icon: 'check', tone: 'good' },
|
ok: { label: 'Operating', icon: 'check', tone: 'good' },
|
||||||
|
standby: { label: 'Standby', icon: 'pause', tone: 'neutral' },
|
||||||
warning: { label: 'Check needed', icon: 'alert', tone: 'warning' },
|
warning: { label: 'Check needed', icon: 'alert', tone: 'warning' },
|
||||||
fault: { label: 'Fault', icon: 'fault', tone: 'critical' },
|
fault: { label: 'Fault', icon: 'fault', tone: 'critical' },
|
||||||
offline: { label: 'Offline', icon: 'offline', 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' }
|
const SEVERITY_ICON = { critical: 'fault', warning: 'alert', info: 'unknown' }
|
||||||
|
|
||||||
/** Health state pill: always icon + label, never color alone. */
|
/** Health state pill: always icon + label, never color alone. */
|
||||||
export function StatePill({ state, size = 'md' }) {
|
export function StatePill({ state, feeding, size = 'md' }) {
|
||||||
const s = STATES[state] ?? STATES.unknown
|
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'
|
const sz = size === 'lg' ? 'text-sm px-3 py-1.5 gap-1.5' : 'text-xs px-2 py-1 gap-1'
|
||||||
return (
|
return (
|
||||||
<span className={`inline-flex items-center rounded-full font-semibold ${sz} ${TONE[s.tone]}`}>
|
<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" />
|
<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" />,
|
moon: <path d="M12 3a6 6 0 0 0 9 9 9 9 0 1 1-9-9Z" />,
|
||||||
unknown: (
|
unknown: (
|
||||||
<>
|
<>
|
||||||
|
|||||||
@@ -4,26 +4,28 @@ import { ago, energyParts, num, powerParts } from '../lib/format'
|
|||||||
import { IssueList, OnlineDot, StatePill } from './Health'
|
import { IssueList, OnlineDot, StatePill } from './Health'
|
||||||
import Icon from './Icon'
|
import Icon from './Icon'
|
||||||
|
|
||||||
function Stat({ label, value, unit }) {
|
function Stat({ label, value, unit, unavailable }) {
|
||||||
return (
|
return (
|
||||||
<div className="min-w-0">
|
<div className="min-w-0">
|
||||||
<div className="text-[11px] uppercase tracking-wide text-muted">{label}</div>
|
<div className="text-[11px] uppercase tracking-wide text-muted">{label}</div>
|
||||||
<div className="truncate tnum">
|
{unavailable ? (
|
||||||
<span className="font-semibold">{value}</span>
|
<div className="text-xs leading-5 text-muted">not available yet</div>
|
||||||
{unit && <span className="ml-0.5 text-xs text-ink-2">{unit}</span>}
|
) : (
|
||||||
</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>
|
</div>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
export default function InverterCard({ status, ids }) {
|
export default function InverterCard({ status, ids }) {
|
||||||
const { inverter, health, latest } = status
|
const { inverter, health, latest, energy_today: energyToday } = status
|
||||||
const r = latest ?? {}
|
const r = latest ?? {}
|
||||||
const live = health.online
|
const live = health.online
|
||||||
const [pw, pu] = powerParts(live ? r.ac_power_total_w : null)
|
const [pw, pu] = powerParts(live ? r.ac_power_total_w : null)
|
||||||
// The daily counter only counts if the last reading is from today
|
const [today, todayU] = energyParts(energyToday.wh)
|
||||||
const fromToday = r.timestamp && new Date(r.timestamp).toDateString() === new Date().toDateString()
|
|
||||||
const [today, todayU] = energyParts(fromToday ? r.daily_energy_wh : null)
|
|
||||||
const [life, lifeU] = energyParts(r.total_energy_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]
|
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>
|
<span className="text-xs text-muted">· {ago(r.timestamp)}</span>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<StatePill state={health.state} />
|
<StatePill state={health.state} feeding={health.feeding} />
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="flex items-baseline gap-1 tnum">
|
<div className="flex items-baseline gap-1 tnum">
|
||||||
@@ -61,8 +63,13 @@ export default function InverterCard({ status, ids }) {
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="grid grid-cols-3 gap-3 text-sm">
|
<div className="grid grid-cols-3 gap-3 text-sm">
|
||||||
<Stat label="Today" value={today} unit={todayU} />
|
<Stat
|
||||||
<Stat label="Lifetime" value={life} unit={lifeU} />
|
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" />
|
<Stat label="Temp" value={live ? num(r.temperature_c) : '—'} unit="°C" />
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import { useMemo, useState } from 'react'
|
import { useMemo, useState } from 'react'
|
||||||
import { Link } from 'react-router-dom'
|
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 Comparison from '../components/Comparison'
|
||||||
import { IssueList } from '../components/Health'
|
import { IssueList } from '../components/Health'
|
||||||
import Icon from '../components/Icon'
|
import Icon from '../components/Icon'
|
||||||
@@ -25,21 +25,25 @@ function Hero({ summary }) {
|
|||||||
</div>
|
</div>
|
||||||
<dl className="mt-4 grid grid-cols-3 gap-3 border-t border-line pt-4 text-sm">
|
<dl className="mt-4 grid grid-cols-3 gap-3 border-t border-line pt-4 text-sm">
|
||||||
<div>
|
<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">
|
<dd className="tnum">
|
||||||
<span className="text-lg font-semibold">{today}</span> <span className="text-ink-2">{todayU}</span>
|
<span className="text-lg font-semibold">{today}</span> <span className="text-ink-2">{todayU}</span>
|
||||||
</dd>
|
</dd>
|
||||||
</div>
|
</div>
|
||||||
<div>
|
<div>
|
||||||
<dt className="text-xs text-muted">Lifetime</dt>
|
<dt className="text-xs text-muted">Lifetime</dt>
|
||||||
<dd className="tnum">
|
{t.total_energy_wh == null ? (
|
||||||
<span className="text-lg font-semibold">{life}</span> <span className="text-ink-2">{lifeU}</span>
|
<dd className="text-xs leading-7 text-muted">not available yet</dd>
|
||||||
</dd>
|
) : (
|
||||||
|
<dd className="tnum">
|
||||||
|
<span className="text-lg font-semibold">{life}</span> <span className="text-ink-2">{lifeU}</span>
|
||||||
|
</dd>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
<div>
|
<div>
|
||||||
<dt className="text-xs text-muted">Online</dt>
|
<dt className="text-xs text-muted">Feeding</dt>
|
||||||
<dd className="tnum">
|
<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>
|
<span className="text-ink-2"> / {t.inverter_count}</span>
|
||||||
</dd>
|
</dd>
|
||||||
</div>
|
</div>
|
||||||
@@ -114,13 +118,20 @@ function EnergyCard({ ids, names }) {
|
|||||||
mode === 'combined'
|
mode === 'combined'
|
||||||
? [{ key: 'total_wh', name: 'All inverters', color: c.accent }]
|
? [{ key: 'total_wh', name: 'All inverters', color: c.accent }]
|
||||||
: ids.map((id) => ({ key: id, name: names[id] ?? id, color: seriesColor(c, ids, id) }))
|
: 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 (
|
return (
|
||||||
<section className="card p-4">
|
<section className="card p-4">
|
||||||
<div className="mb-3 flex flex-wrap items-center justify-between gap-2">
|
<div className="mb-3 flex flex-wrap items-center justify-between gap-2">
|
||||||
<div>
|
<div>
|
||||||
<h2 className="text-sm font-semibold">Daily energy · last 30 days</h2>
|
<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>
|
</div>
|
||||||
<Segmented
|
<Segmented
|
||||||
label="Energy chart mode"
|
label="Energy chart mode"
|
||||||
@@ -137,12 +148,14 @@ function EnergyCard({ ids, names }) {
|
|||||||
<Legend series={series} />
|
<Legend series={series} />
|
||||||
</div>
|
</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)} />
|
<DayBars days={data.days} series={series} format={energy} axisFormat={(wh) => num(wh / 1000, 0)} />
|
||||||
) : (
|
) : (
|
||||||
<div className="h-56" />
|
<div className="h-56" />
|
||||||
)}
|
)}
|
||||||
<div className="mt-1 text-right text-[11px] text-muted">axis in kWh</div>
|
<EnergyFootnote estimated={estimated} />
|
||||||
</section>
|
</section>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import { useMemo, useState } from 'react'
|
import { useMemo, useState } from 'react'
|
||||||
import { Link, useParams } from 'react-router-dom'
|
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 EditInverterDialog from '../components/EditInverterDialog'
|
||||||
import { IssueList, OnlineDot, StatePill } from '../components/Health'
|
import { IssueList, OnlineDot, StatePill } from '../components/Health'
|
||||||
import Icon from '../components/Icon'
|
import Icon from '../components/Icon'
|
||||||
@@ -31,14 +31,18 @@ function formatField(field, value) {
|
|||||||
return `${num(value, field.decimals)}${field.unit ? ` ${field.unit}` : ''}`
|
return `${num(value, field.decimals)}${field.unit ? ` ${field.unit}` : ''}`
|
||||||
}
|
}
|
||||||
|
|
||||||
function KeyFigure({ label, parts }) {
|
function KeyFigure({ label, parts, unavailable }) {
|
||||||
return (
|
return (
|
||||||
<div className="card px-4 py-3">
|
<div className="card px-4 py-3">
|
||||||
<div className="text-xs text-muted">{label}</div>
|
<div className="text-xs text-muted">{label}</div>
|
||||||
<div className="tnum">
|
{unavailable ? (
|
||||||
<span className="text-2xl font-semibold tracking-tight">{parts[0]}</span>
|
<div className="text-sm leading-8 text-muted">not available yet</div>
|
||||||
<span className="ml-1 text-sm text-ink-2">{parts[1]}</span>
|
) : (
|
||||||
</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>
|
</div>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -54,10 +58,12 @@ function Parameters({ fields, latest, live }) {
|
|||||||
</p>
|
</p>
|
||||||
<div className="grid gap-x-8 gap-y-4 sm:grid-cols-2">
|
<div className="grid gap-x-8 gap-y-4 sm:grid-cols-2">
|
||||||
{GROUPS.map((g) => {
|
{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 (
|
return (
|
||||||
<div key={g.key}>
|
<div key={g.key}>
|
||||||
<h3 className="mb-1 text-xs font-semibold uppercase tracking-wide text-muted">{g.label}</h3>
|
<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">
|
<dl className="divide-y divide-[var(--border)] text-sm">
|
||||||
{items.map((f) => (
|
{items.map((f) => (
|
||||||
<div key={f.key} className="flex justify-between gap-4 py-1.5">
|
<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 seconds = RANGES[range].seconds
|
||||||
const { data } = usePoll(() => api.history(id, { from: isoAgo(seconds) }), 120_000, `${id}:${range}`)
|
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 = [
|
const powerSeries = [
|
||||||
{ key: 'ac_power_total_w', name: 'AC output', color: c.series[0] },
|
{ 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_mppt1_w', name: 'DC MPPT1', color: c.series[1] },
|
||||||
{ key: 'dc_power_mppt2_w', name: 'DC MPPT2', color: c.series[2] },
|
{ key: 'dc_power_mppt2_w', name: 'DC MPPT2', color: c.series[2] },
|
||||||
]
|
].filter((s, i) => i === 0 || hasData(s.key))
|
||||||
const chartable = fields.filter((f) => !f.derived && f.agg === 'avg' && f.key !== 'ac_power_total_w')
|
const hasDc = powerSeries.length > 1
|
||||||
const paramField = fields.find((f) => f.key === param) ?? chartable[0]
|
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 from = data ? Date.parse(data.from) / 1000 : 0
|
||||||
const to = data ? Date.parse(data.to) / 1000 : 1
|
const to = data ? Date.parse(data.to) / 1000 : 1
|
||||||
|
|
||||||
@@ -133,8 +144,9 @@ function HistoryCharts({ id, fields }) {
|
|||||||
<div className="h-60" />
|
<div className="h-60" />
|
||||||
)}
|
)}
|
||||||
<p className="mt-2 text-xs text-muted">
|
<p className="mt-2 text-xs text-muted">
|
||||||
MPPT1 and MPPT2 should track each other when both carry similar strings — one dropping
|
{hasDc
|
||||||
away from the other points at that string.
|
? '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>
|
</p>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
@@ -155,7 +167,9 @@ function HistoryCharts({ id, fields }) {
|
|||||||
))}
|
))}
|
||||||
</select>
|
</select>
|
||||||
</div>
|
</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
|
<TimeLines
|
||||||
points={data.points}
|
points={data.points}
|
||||||
series={[{ key: paramField.key, name: paramField.label, color: c.series[0] }]}
|
series={[{ key: paramField.key, name: paramField.label, color: c.series[0] }]}
|
||||||
@@ -178,11 +192,20 @@ function YearEnergy({ id }) {
|
|||||||
const c = useThemeColors()
|
const c = useThemeColors()
|
||||||
const { data } = usePoll(() => api.inverterDaily(id, { days: 365 }), 600_000, id)
|
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 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 (
|
return (
|
||||||
<section className="card p-4">
|
<section className="card p-4">
|
||||||
<h2 className="text-sm font-semibold">Daily energy · last 365 days</h2>
|
<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 && !empty && (
|
||||||
{data ? (
|
<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
|
<DayBars
|
||||||
days={data.days}
|
days={data.days}
|
||||||
series={[{ key: 'energy_wh', name: 'Energy', color: c.accent }]}
|
series={[{ key: 'energy_wh', name: 'Energy', color: c.accent }]}
|
||||||
@@ -192,7 +215,7 @@ function YearEnergy({ id }) {
|
|||||||
) : (
|
) : (
|
||||||
<div className="h-56" />
|
<div className="h-56" />
|
||||||
)}
|
)}
|
||||||
<div className="mt-1 text-right text-[11px] text-muted">axis in kWh</div>
|
<EnergyFootnote estimated={estimated} />
|
||||||
</section>
|
</section>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -218,7 +241,6 @@ export default function InverterDetail({ summaryPoll }) {
|
|||||||
|
|
||||||
const { inverter, health, latest } = status
|
const { inverter, health, latest } = status
|
||||||
const live = health.online
|
const live = health.online
|
||||||
const fromToday = latest?.timestamp && new Date(latest.timestamp).toDateString() === new Date().toDateString()
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="space-y-4">
|
<div className="space-y-4">
|
||||||
@@ -237,7 +259,7 @@ export default function InverterDetail({ summaryPoll }) {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div className="flex items-center gap-2">
|
<div className="flex items-center gap-2">
|
||||||
<StatePill state={health.state} size="lg" />
|
<StatePill state={health.state} feeding={health.feeding} size="lg" />
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
onClick={() => setEditing(true)}
|
onClick={() => setEditing(true)}
|
||||||
@@ -254,8 +276,11 @@ export default function InverterDetail({ summaryPoll }) {
|
|||||||
|
|
||||||
<div className="grid grid-cols-2 gap-3 md:grid-cols-4">
|
<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="Power now" parts={powerParts(live ? latest?.ac_power_total_w : null)} />
|
||||||
<KeyFigure label="Today" parts={energyParts(fromToday ? latest?.daily_energy_wh : null)} />
|
<KeyFigure
|
||||||
<KeyFigure label="Lifetime" parts={energyParts(latest?.total_energy_wh)} />
|
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
|
<KeyFigure
|
||||||
label="vs fleet median"
|
label="vs fleet median"
|
||||||
parts={[health.relative_output == null ? '—' : num(health.relative_output * 100, 0), '%']}
|
parts={[health.relative_output == null ? '—' : num(health.relative_output * 100, 0), '%']}
|
||||||
|
|||||||
Reference in New Issue
Block a user