Compare commits
8
Commits
0b0e4b7d6d
..
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
80f82c8c63 | ||
|
|
9ac86e2588 | ||
|
|
0b74842560 | ||
|
|
c24770af1c | ||
|
|
8029468fb1 | ||
|
|
c725b748c7 | ||
|
|
42c7d18207 | ||
|
|
d01cef991f |
@@ -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=["*"]
|
||||||
|
|||||||
@@ -70,9 +70,11 @@ generate a Flutter client later).
|
|||||||
| `GET` | `/api/inverters/{id}/latest` | Latest reading (plus derived DC power / efficiency) |
|
| `GET` | `/api/inverters/{id}/latest` | Latest reading (plus derived DC power / efficiency) |
|
||||||
| `GET` | `/api/inverters/{id}/history` | `from`, `to` (ISO), optional `bucket` seconds, `field` (repeatable). Downsampled to ≤600 points |
|
| `GET` | `/api/inverters/{id}/history` | `from`, `to` (ISO), optional `bucket` seconds, `field` (repeatable). Downsampled to ≤600 points |
|
||||||
| `GET` | `/api/inverters/{id}/daily` | Energy + peak power per local day (`days`, default 365, or `from`/`to` dates) |
|
| `GET` | `/api/inverters/{id}/daily` | Energy + peak power per local day (`days`, default 365, or `from`/`to` dates) |
|
||||||
| `GET` | `/api/power` | AC power of all inverters over time (default 24 h) |
|
| `GET` | `/api/power` | AC power of all inverters over time (default 24 h; `last_run=true` = since the inverters last woke up) |
|
||||||
| `GET` | `/api/energy/daily` | Energy per day per inverter + total (default 30 days) |
|
| `GET` | `/api/energy/daily` | Energy per day per inverter + total (default 30 days) |
|
||||||
| `GET` | `/api/meta/fields` | Label / unit / group of every parameter — render from this |
|
| `GET` | `/api/meta/fields` | Label / unit / group of every parameter — render from this |
|
||||||
|
| `GET` | `/api/settings` | Dashboard display options (comparison averaging / scale / reference, power chart range / smoothing, voltage display, default language) |
|
||||||
|
| `PUT` | `/api/settings` | Replace them — applies to every viewer (no accounts). Open, no key: display only |
|
||||||
|
|
||||||
### Adding parameters
|
### Adding parameters
|
||||||
|
|
||||||
@@ -84,17 +86,44 @@ the chart picker without further changes.
|
|||||||
|
|
||||||
### Health rules
|
### Health rules
|
||||||
|
|
||||||
- **Offline** — no reading for `ONLINE_WINDOW_SECONDS` (5 min) while the
|
- **Offline** — no reading for `ONLINE_WINDOW_SECONDS` (5 min) — or 2.5× the
|
||||||
datalogger is still posting and the sun is up. At night that's **Sleeping**;
|
inverter's own reporting interval if that is longer (INV5 comes from the
|
||||||
|
cloud every ~5 min → ~12 min) — while the 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
|
if the datalogger itself is silent the state is **No data** (and a banner
|
||||||
says so).
|
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
|
- **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
|
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.
|
set), or one MPPT input below half of the other.
|
||||||
|
|
||||||
Thresholds are in `.env`.
|
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 sent (INV1–INV4 today; only INV5 has real counters) — 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 only exists where `total_energy_wh` is sent;
|
||||||
|
the dashboard total says how many inverters it covers.
|
||||||
|
|
||||||
|
### Dashboard settings and language
|
||||||
|
|
||||||
|
The ⚙ page sets the display options above for everyone, without an API key
|
||||||
|
(they only change how data is shown; inverter edits still need the key). The language (Greek / English) can be
|
||||||
|
switched per device from the header; devices that haven't picked one use the
|
||||||
|
shared default. Issue texts are translated client-side from each issue's
|
||||||
|
`code` + `params`, so new clients (Flutter) can do the same.
|
||||||
|
|
||||||
|
The current state of the register map is in `poller/README.md`.
|
||||||
|
|
||||||
## Data retention
|
## Data retention
|
||||||
|
|
||||||
Raw readings older than `RETENTION_DAYS` (730) are purged every 6 h. The
|
Raw readings older than `RETENTION_DAYS` (730) are purged every 6 h. The
|
||||||
|
|||||||
+64
-7
@@ -1,15 +1,19 @@
|
|||||||
|
import json
|
||||||
|
import logging
|
||||||
import secrets
|
import secrets
|
||||||
import sqlite3
|
import sqlite3
|
||||||
from datetime import date, datetime, timedelta, timezone
|
from datetime import date, datetime, timedelta, timezone
|
||||||
from typing import Annotated
|
from typing import Annotated
|
||||||
|
|
||||||
from fastapi import APIRouter, Body, Depends, Header, HTTPException, Query
|
from fastapi import APIRouter, Body, Depends, Header, HTTPException, Query
|
||||||
|
from pydantic import ValidationError
|
||||||
|
|
||||||
from . import fields, health, store
|
from . import fields, health, store
|
||||||
from .config import get_settings
|
from .config import get_settings
|
||||||
from .db import get_db, set_meta
|
from .db import get_db, get_meta, set_meta
|
||||||
from .schemas import IngestResult, Inverter, InverterUpdate, ReadingIn, Summary
|
from .schemas import IngestResult, Inverter, InverterUpdate, ReadingIn, Summary, ViewSettings
|
||||||
|
|
||||||
|
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 +73,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
|
||||||
@@ -84,8 +90,24 @@ def get_summary(conn: Db):
|
|||||||
|
|
||||||
|
|
||||||
@router.get("/power", tags=["dashboard"])
|
@router.get("/power", tags=["dashboard"])
|
||||||
def get_fleet_power(conn: Db, start: FromQ = None, end: ToQ = None, bucket: BucketQ = None):
|
def get_fleet_power(
|
||||||
|
conn: Db,
|
||||||
|
start: FromQ = None,
|
||||||
|
end: ToQ = None,
|
||||||
|
bucket: BucketQ = None,
|
||||||
|
last_run: Annotated[
|
||||||
|
bool,
|
||||||
|
Query(description="Ignore from/to and cover the latest production run (since the inverters last woke up)"),
|
||||||
|
] = False,
|
||||||
|
):
|
||||||
"""AC power of every inverter over time (default: last 24 h)."""
|
"""AC power of every inverter over time (default: last 24 h)."""
|
||||||
|
run = store.last_production_run(conn) if last_run else None
|
||||||
|
if run:
|
||||||
|
# A little margin either side; up to now while still producing
|
||||||
|
now = store.now_ts()
|
||||||
|
s = run[0] - 900
|
||||||
|
e = now if now - run[1] <= 900 else run[1] + 900
|
||||||
|
else:
|
||||||
s, e = _range(start, end, timedelta(hours=24))
|
s, e = _range(start, end, timedelta(hours=24))
|
||||||
b = store.pick_bucket(s, e, bucket)
|
b = store.pick_bucket(s, e, bucket)
|
||||||
return {
|
return {
|
||||||
@@ -97,6 +119,35 @@ def get_fleet_power(conn: Db, start: FromQ = None, end: ToQ = None, bucket: Buck
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------- settings
|
||||||
|
|
||||||
|
SETTINGS_KEY = "view_settings"
|
||||||
|
|
||||||
|
|
||||||
|
def _load_view_settings(conn: sqlite3.Connection) -> ViewSettings:
|
||||||
|
raw = get_meta(conn, SETTINGS_KEY)
|
||||||
|
try:
|
||||||
|
return ViewSettings.model_validate(json.loads(raw) if raw else {})
|
||||||
|
except (ValueError, ValidationError):
|
||||||
|
log.warning("Stored view settings are invalid; using defaults")
|
||||||
|
return ViewSettings()
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/settings", response_model=ViewSettings, tags=["settings"])
|
||||||
|
def get_view_settings(conn: Db):
|
||||||
|
"""Dashboard display options, shared by every viewer."""
|
||||||
|
return _load_view_settings(conn)
|
||||||
|
|
||||||
|
|
||||||
|
@router.put("/settings", response_model=ViewSettings, tags=["settings"])
|
||||||
|
def put_view_settings(conn: Db, body: ViewSettings):
|
||||||
|
"""Replace the display options for every viewer. Omitted keys reset to their default.
|
||||||
|
Open to anyone on purpose: these only change how data is displayed, and
|
||||||
|
the owner wants them adjustable without a key."""
|
||||||
|
set_meta(conn, SETTINGS_KEY, body.model_dump_json())
|
||||||
|
return body
|
||||||
|
|
||||||
|
|
||||||
@router.get("/energy/daily", tags=["dashboard"])
|
@router.get("/energy/daily", tags=["dashboard"])
|
||||||
def get_fleet_daily_energy(
|
def get_fleet_daily_energy(
|
||||||
conn: Db,
|
conn: Db,
|
||||||
@@ -181,14 +232,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")
|
||||||
|
|||||||
+15
-2
@@ -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;
|
||||||
|
|
||||||
@@ -50,7 +53,10 @@ CREATE TABLE IF NOT EXISTS meta (
|
|||||||
def connect() -> sqlite3.Connection:
|
def connect() -> sqlite3.Connection:
|
||||||
path = get_settings().db_path
|
path = get_settings().db_path
|
||||||
os.makedirs(os.path.dirname(os.path.abspath(path)), exist_ok=True)
|
os.makedirs(os.path.dirname(os.path.abspath(path)), exist_ok=True)
|
||||||
conn = sqlite3.connect(path, timeout=30)
|
# FastAPI may open, use and close a request's connection on different
|
||||||
|
# worker threads. Each request has its own connection used by one thread
|
||||||
|
# at a time, so the same-thread check can safely be off.
|
||||||
|
conn = sqlite3.connect(path, timeout=30, check_same_thread=False)
|
||||||
conn.row_factory = sqlite3.Row
|
conn.row_factory = sqlite3.Row
|
||||||
conn.execute("PRAGMA journal_mode=WAL")
|
conn.execute("PRAGMA journal_mode=WAL")
|
||||||
conn.execute("PRAGMA synchronous=NORMAL")
|
conn.execute("PRAGMA synchronous=NORMAL")
|
||||||
@@ -72,13 +78,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:
|
||||||
|
|||||||
+46
-3
@@ -14,6 +14,15 @@ from .config import get_settings
|
|||||||
from .db import get_meta
|
from .db import get_meta
|
||||||
|
|
||||||
|
|
||||||
|
# Recent readings per inverter: their spacing tells each unit's reporting
|
||||||
|
# cadence; the newest few let clients average out a passing cloud.
|
||||||
|
RECENT_SAMPLES = 8
|
||||||
|
RECENT_LOOKBACK_SECONDS = 2 * 3600
|
||||||
|
RECENT_POWER_COUNT = 5
|
||||||
|
RECENT_POWER_SECONDS = 1800
|
||||||
|
MAX_ONLINE_WINDOW_SECONDS = 1800
|
||||||
|
|
||||||
|
|
||||||
def _minutes(seconds: int) -> str:
|
def _minutes(seconds: int) -> str:
|
||||||
if seconds < 3600:
|
if seconds < 3600:
|
||||||
return f"{seconds // 60} min"
|
return f"{seconds // 60} min"
|
||||||
@@ -39,10 +48,21 @@ def summary(conn: sqlite3.Connection) -> dict:
|
|||||||
latest = store.latest_all(conn)
|
latest = store.latest_all(conn)
|
||||||
averages = store.window_averages(conn, s.underperform_window_seconds)
|
averages = store.window_averages(conn, s.underperform_window_seconds)
|
||||||
energy_today = store.today_energy(conn)
|
energy_today = store.today_energy(conn)
|
||||||
|
recent = store.recent_readings(conn, RECENT_SAMPLES, RECENT_LOOKBACK_SECONDS)
|
||||||
|
|
||||||
|
def window(inv_id: str) -> int:
|
||||||
|
"""Silence allowed before offline: a couple of missed cycles at the
|
||||||
|
unit's own cadence (60 s local, ~5 min cloud), never below the
|
||||||
|
configured window."""
|
||||||
|
ts = [x["ts"] for x in recent.get(inv_id, [])]
|
||||||
|
gaps = [a - b for a, b in zip(ts, ts[1:]) if a > b]
|
||||||
|
if not gaps:
|
||||||
|
return s.online_window_seconds
|
||||||
|
return int(min(MAX_ONLINE_WINDOW_SECONDS, max(s.online_window_seconds, 2.5 * statistics.median(gaps))))
|
||||||
|
|
||||||
def is_online(inv_id: str) -> bool:
|
def is_online(inv_id: str) -> bool:
|
||||||
r = latest.get(inv_id)
|
r = latest.get(inv_id)
|
||||||
return r is not None and r["age_seconds"] <= s.online_window_seconds
|
return r is not None and r["age_seconds"] <= window(inv_id)
|
||||||
|
|
||||||
# Fleet comparison: per kWp when every producing inverter has a capacity
|
# Fleet comparison: per kWp when every producing inverter has a capacity
|
||||||
# set, raw watts otherwise (assumes similar arrays).
|
# set, raw watts otherwise (assumes similar arrays).
|
||||||
@@ -69,8 +89,12 @@ 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"
|
||||||
|
silent_s = r["age_seconds"] if r else None
|
||||||
if not datalogger_online:
|
if not datalogger_online:
|
||||||
state = "unknown"
|
state = "unknown"
|
||||||
issues.append({
|
issues.append({
|
||||||
@@ -86,6 +110,7 @@ def summary(conn: sqlite3.Connection) -> dict:
|
|||||||
"code": "not_responding",
|
"code": "not_responding",
|
||||||
"severity": "critical",
|
"severity": "critical",
|
||||||
"message": f"Not responding {since} while the datalogger is online",
|
"message": f"Not responding {since} while the datalogger is online",
|
||||||
|
"params": {"seconds": silent_s},
|
||||||
})
|
})
|
||||||
else:
|
else:
|
||||||
if r.get("error_code"):
|
if r.get("error_code"):
|
||||||
@@ -95,12 +120,14 @@ def summary(conn: sqlite3.Connection) -> dict:
|
|||||||
"code": "error_code",
|
"code": "error_code",
|
||||||
"severity": "critical",
|
"severity": "critical",
|
||||||
"message": f"Inverter reports error code {r['error_code']}{text}",
|
"message": f"Inverter reports error code {r['error_code']}{text}",
|
||||||
|
"params": {"error_code": r["error_code"], "status_text": r.get("status_text")},
|
||||||
})
|
})
|
||||||
if compare and relative is not None and relative < s.underperform_ratio:
|
if compare and relative is not None and relative < s.underperform_ratio:
|
||||||
issues.append({
|
issues.append({
|
||||||
"code": "underperforming",
|
"code": "underperforming",
|
||||||
"severity": "warning",
|
"severity": "warning",
|
||||||
"message": f"Producing {relative:.0%} of the fleet median — check strings, fuses and breakers",
|
"message": f"Producing {relative:.0%} of the fleet median — check strings, fuses and breakers",
|
||||||
|
"params": {"relative": relative},
|
||||||
})
|
})
|
||||||
avg = averages.get(inv["id"], {})
|
avg = averages.get(inv["id"], {})
|
||||||
m1, m2 = avg.get("mppt1_w"), avg.get("mppt2_w")
|
m1, m2 = avg.get("mppt1_w"), avg.get("mppt2_w")
|
||||||
@@ -112,28 +139,44 @@ def summary(conn: sqlite3.Connection) -> dict:
|
|||||||
"code": "mppt_imbalance",
|
"code": "mppt_imbalance",
|
||||||
"severity": "warning",
|
"severity": "warning",
|
||||||
"message": f"{weak} at {lo:.0f} W vs {hi:.0f} W on the other input — check that string",
|
"message": f"{weak} at {lo:.0f} W vs {hi:.0f} W on the other input — check that string",
|
||||||
|
"params": {"input": weak, "weak_w": round(lo), "strong_w": round(hi)},
|
||||||
})
|
})
|
||||||
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,
|
||||||
|
"online_window_seconds": window(inv["id"]),
|
||||||
},
|
},
|
||||||
|
"energy_today": energy_today.get(inv["id"], {"wh": None, "estimated": False}),
|
||||||
"latest": r,
|
"latest": r,
|
||||||
|
"recent_power": [
|
||||||
|
{"timestamp": store.to_dt(x["ts"]), "ac_power_total_w": x["w"]}
|
||||||
|
for x in recent.get(inv["id"], [])
|
||||||
|
if x["ts"] >= now - RECENT_POWER_SECONDS
|
||||||
|
][:RECENT_POWER_COUNT],
|
||||||
})
|
})
|
||||||
|
|
||||||
|
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()
|
||||||
|
|||||||
+71
-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,37 +75,65 @@ 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):
|
||||||
code: str
|
code: str
|
||||||
severity: Severity
|
severity: Severity
|
||||||
message: str
|
message: str
|
||||||
|
params: dict[str, Any] = Field(
|
||||||
|
default_factory=dict,
|
||||||
|
description="Values inside the message, so clients can render it in their own language",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
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")
|
||||||
relative_output: float | None = Field(
|
relative_output: float | None = Field(
|
||||||
description="Output vs fleet median (1.0 = median), per kWp when capacities are set"
|
description="Output vs fleet median (1.0 = median), per kWp when capacities are set"
|
||||||
)
|
)
|
||||||
|
online_window_seconds: int = Field(
|
||||||
|
description="Silence after which this inverter counts as offline: ONLINE_WINDOW_SECONDS, "
|
||||||
|
"stretched for units that report slowly (e.g. cloud-polled every 5 min)"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class EnergyToday(BaseModel):
|
||||||
|
wh: int | None
|
||||||
|
estimated: bool = Field(description="Integrated from AC power, not the inverter's own counter")
|
||||||
|
|
||||||
|
|
||||||
|
class RecentPower(BaseModel):
|
||||||
|
timestamp: datetime
|
||||||
|
ac_power_total_w: int | None
|
||||||
|
|
||||||
|
|
||||||
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
|
||||||
|
recent_power: list[RecentPower] = Field(
|
||||||
|
description="Up to the last 5 readings of the past 30 min, newest first — lets clients "
|
||||||
|
"average out a single reading taken while a cloud shaded one array"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
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
|
||||||
|
|
||||||
|
|
||||||
@@ -115,6 +147,42 @@ class Sun(BaseModel):
|
|||||||
daylight: bool | None
|
daylight: bool | None
|
||||||
|
|
||||||
|
|
||||||
|
PowerRange = Literal["30m", "1h", "3h", "6h", "24h", "run", "3d", "7d", "30d"]
|
||||||
|
|
||||||
|
|
||||||
|
class ViewSettings(BaseModel):
|
||||||
|
"""Dashboard display options. Shared by every viewer (there are no user
|
||||||
|
accounts); unknown keys are ignored and missing ones take the default,
|
||||||
|
so older and newer clients can coexist."""
|
||||||
|
|
||||||
|
model_config = ConfigDict(extra="ignore")
|
||||||
|
|
||||||
|
# Output comparison
|
||||||
|
comparison_readings: Literal[1, 3, 5] = Field(
|
||||||
|
default=1, description="Average the last N readings per inverter (1 = latest only)"
|
||||||
|
)
|
||||||
|
comparison_scale: Literal["auto", "max", "custom"] = Field(
|
||||||
|
default="auto",
|
||||||
|
description="Bar length: auto = rounded-up ceiling above the highest, "
|
||||||
|
"max = highest inverter is a full bar, custom = comparison_custom_kw is a full bar",
|
||||||
|
)
|
||||||
|
comparison_custom_kw: float | None = Field(default=None, gt=0, le=1000)
|
||||||
|
comparison_reference: Literal["median", "best", "custom"] = Field(
|
||||||
|
default="median", description="What the percentage is relative to"
|
||||||
|
)
|
||||||
|
|
||||||
|
# Fleet power chart
|
||||||
|
power_range: PowerRange = "24h"
|
||||||
|
power_smoothing: Literal["off", "light", "strong"] = "off"
|
||||||
|
|
||||||
|
# Display
|
||||||
|
voltage_display: Literal["phase", "line"] = Field(
|
||||||
|
default="phase",
|
||||||
|
description="phase = line-to-neutral as sent (~240 V); line = x√3, matches the inverter screen (~415 V)",
|
||||||
|
)
|
||||||
|
default_language: Literal["en", "el"] = "el"
|
||||||
|
|
||||||
|
|
||||||
class Summary(BaseModel):
|
class Summary(BaseModel):
|
||||||
generated_at: datetime
|
generated_at: datetime
|
||||||
datalogger: Datalogger
|
datalogger: Datalogger
|
||||||
|
|||||||
+156
-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:
|
||||||
@@ -172,6 +259,43 @@ def window_averages(conn: sqlite3.Connection, seconds: int) -> dict[str, dict]:
|
|||||||
return {r["inverter_id"]: dict(r) for r in rows}
|
return {r["inverter_id"]: dict(r) for r in rows}
|
||||||
|
|
||||||
|
|
||||||
|
def recent_readings(conn: sqlite3.Connection, n: int, seconds: int) -> dict[str, list[dict]]:
|
||||||
|
"""{inverter_id: [{ts, w}, ...]} — up to the last n readings of the past
|
||||||
|
`seconds`, newest first."""
|
||||||
|
rows = conn.execute(
|
||||||
|
"""
|
||||||
|
SELECT inverter_id, ts, w FROM (
|
||||||
|
SELECT inverter_id, ts, ac_power_total_w AS w,
|
||||||
|
row_number() OVER (PARTITION BY inverter_id ORDER BY ts DESC) AS rn
|
||||||
|
FROM readings WHERE ts >= ?
|
||||||
|
) WHERE rn <= ? ORDER BY inverter_id, ts DESC
|
||||||
|
""",
|
||||||
|
(now_ts() - seconds, n),
|
||||||
|
).fetchall()
|
||||||
|
out: dict[str, list[dict]] = {}
|
||||||
|
for r in rows:
|
||||||
|
out.setdefault(r["inverter_id"], []).append({"ts": r["ts"], "w": r["w"]})
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def last_production_run(conn: sqlite3.Connection, gap_seconds: int = 5400) -> tuple[int, int] | None:
|
||||||
|
"""(start, end) of the most recent stretch in which some inverter produced
|
||||||
|
power, split at silences longer than `gap_seconds` (the night). A unit
|
||||||
|
that keeps reporting 0 W overnight (cloud-polled) doesn't join the runs."""
|
||||||
|
rows = conn.execute(
|
||||||
|
"SELECT DISTINCT ts FROM readings WHERE ac_power_total_w > 0 AND ts >= ? ORDER BY ts DESC",
|
||||||
|
(now_ts() - 4 * 86400,),
|
||||||
|
).fetchall()
|
||||||
|
if not rows:
|
||||||
|
return None
|
||||||
|
end = start = rows[0]["ts"]
|
||||||
|
for r in rows[1:]:
|
||||||
|
if start - r["ts"] > gap_seconds:
|
||||||
|
break
|
||||||
|
start = r["ts"]
|
||||||
|
return start, end
|
||||||
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------- history
|
# ---------------------------------------------------------------- history
|
||||||
|
|
||||||
|
|
||||||
@@ -238,15 +362,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 +386,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}
|
||||||
|
|
||||||
|
|||||||
+144
-1
@@ -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,144 @@ 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
|
||||||
|
|
||||||
|
|
||||||
|
def test_view_settings_shared_defaults_and_auth(client):
|
||||||
|
s = client.get("/api/settings").json()
|
||||||
|
assert s["comparison_readings"] == 1 and s["power_range"] == "24h"
|
||||||
|
|
||||||
|
body = {**s, "comparison_readings": 3, "comparison_scale": "custom", "comparison_custom_kw": 25,
|
||||||
|
"power_range": "run", "power_smoothing": "light", "future_option": True}
|
||||||
|
# No API key needed: display options only
|
||||||
|
saved = client.put("/api/settings", json=body, headers={"X-API-Key": ""}).json()
|
||||||
|
assert saved["comparison_custom_kw"] == 25 and "future_option" not in saved
|
||||||
|
assert client.get("/api/settings").json()["power_range"] == "run"
|
||||||
|
|
||||||
|
assert client.put("/api/settings", json={"comparison_readings": 4}).status_code == 422
|
||||||
|
|
||||||
|
|
||||||
|
def test_recent_power_and_slow_unit_stays_online(client):
|
||||||
|
now = int(time.time())
|
||||||
|
batch = [onsite_payload("INV1", now - i * 60, 6000 + i) for i in range(7)]
|
||||||
|
# Cloud-polled unit: every 5 min, last one 8 min ago — beyond the 5 min
|
||||||
|
# default window but only ~1.5 of its own cycles
|
||||||
|
batch += [onsite_payload("INV5", now - 480 - i * 300, 5000) for i in range(6)]
|
||||||
|
client.post("/api/readings", json=batch)
|
||||||
|
|
||||||
|
by_id = {x["inverter"]["id"]: x for x in client.get("/api/summary").json()["inverters"]}
|
||||||
|
assert [p["ac_power_total_w"] for p in by_id["INV1"]["recent_power"]] == [6000, 6001, 6002, 6003, 6004]
|
||||||
|
assert by_id["INV1"]["health"]["online_window_seconds"] == 300
|
||||||
|
assert by_id["INV5"]["health"]["online"] is True
|
||||||
|
assert by_id["INV5"]["health"]["online_window_seconds"] == 750
|
||||||
|
assert len(by_id["INV5"]["recent_power"]) == 5
|
||||||
|
|
||||||
|
|
||||||
|
def test_issue_params_for_translation(client):
|
||||||
|
now = int(time.time())
|
||||||
|
client.post("/api/readings", json=[
|
||||||
|
onsite_payload("INV1", now, 7000), onsite_payload("INV2", now, 7000), onsite_payload("INV4", now, 2000),
|
||||||
|
])
|
||||||
|
inv4 = client.get("/api/summary").json()["inverters"][2]["health"]
|
||||||
|
assert inv4["issues"][0]["params"]["relative"] < 0.75
|
||||||
|
|
||||||
|
|
||||||
|
def test_power_last_production_run(client):
|
||||||
|
now = int(time.time())
|
||||||
|
# Yesterday's run, a night of silence, then this morning's run; INV5
|
||||||
|
# reports 0 W all night and must not glue the runs together
|
||||||
|
batch = [onsite_payload("INV1", now - 20 * 3600 + i * 600, 5000) for i in range(6)]
|
||||||
|
batch += [onsite_payload("INV5", now - 18 * 3600 + i * 1800, 0, status=1) for i in range(30)]
|
||||||
|
batch += [onsite_payload("INV1", now - 3 * 3600 + i * 600, 5000) for i in range(18)]
|
||||||
|
client.post("/api/readings", json=batch)
|
||||||
|
|
||||||
|
p = client.get("/api/power", params={"last_run": True}).json()
|
||||||
|
start = datetime.fromisoformat(p["from"]).timestamp()
|
||||||
|
assert abs(start - (now - 3 * 3600 - 900)) < 5
|
||||||
|
assert abs(datetime.fromisoformat(p["to"]).timestamp() - now) < 5
|
||||||
|
|||||||
+30
-10
@@ -5,8 +5,10 @@ import { useInstallPrompt } from './hooks/useInstallPrompt'
|
|||||||
import { usePoll } from './hooks/usePoll'
|
import { usePoll } from './hooks/usePoll'
|
||||||
import { api } from './lib/api'
|
import { api } from './lib/api'
|
||||||
import { ago } from './lib/format'
|
import { ago } from './lib/format'
|
||||||
|
import { useT } from './lib/i18n'
|
||||||
import Dashboard from './pages/Dashboard'
|
import Dashboard from './pages/Dashboard'
|
||||||
import InverterDetail from './pages/InverterDetail'
|
import InverterDetail from './pages/InverterDetail'
|
||||||
|
import Settings from './pages/Settings'
|
||||||
|
|
||||||
function useTick(ms) {
|
function useTick(ms) {
|
||||||
const [, setN] = useState(0)
|
const [, setN] = useState(0)
|
||||||
@@ -17,6 +19,7 @@ function useTick(ms) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function LiveChip({ summary, error }) {
|
function LiveChip({ summary, error }) {
|
||||||
|
const { t } = useT()
|
||||||
useTick(10_000)
|
useTick(10_000)
|
||||||
if (error && !summary) return null
|
if (error && !summary) return null
|
||||||
if (!summary) return null
|
if (!summary) return null
|
||||||
@@ -28,7 +31,11 @@ function LiveChip({ summary, error }) {
|
|||||||
style={{ background: ok ? 'var(--good)' : 'var(--critical)' }}
|
style={{ background: ok ? 'var(--good)' : 'var(--critical)' }}
|
||||||
aria-hidden="true"
|
aria-hidden="true"
|
||||||
/>
|
/>
|
||||||
{error ? 'Connection lost' : ok ? `Live · ${ago(summary.datalogger.last_ingest_at)}` : 'Datalogger offline'}
|
{error
|
||||||
|
? t('live.connectionLost')
|
||||||
|
: ok
|
||||||
|
? t('live.live', { ago: ago(summary.datalogger.last_ingest_at) })
|
||||||
|
: t('live.dataloggerOffline')}
|
||||||
</span>
|
</span>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -37,26 +44,38 @@ export default function App() {
|
|||||||
// One summary poll shared by both pages, so navigating is instant
|
// One summary poll shared by both pages, so navigating is instant
|
||||||
const summaryPoll = usePoll(() => api.summary(), 30_000)
|
const summaryPoll = usePoll(() => api.summary(), 30_000)
|
||||||
const install = useInstallPrompt()
|
const install = useInstallPrompt()
|
||||||
|
const { t, lang, setLang } = useT()
|
||||||
|
const iconButton =
|
||||||
|
'inline-flex min-h-9 min-w-9 items-center justify-center gap-1 rounded-lg border border-line px-2 text-xs font-medium text-ink-2 hover:text-ink'
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="min-h-dvh">
|
<div className="min-h-dvh">
|
||||||
<header className="sticky top-0 z-40 border-b border-line bg-page/85 pt-[env(safe-area-inset-top)] backdrop-blur">
|
<header className="sticky top-0 z-40 border-b border-line bg-page/85 pt-[env(safe-area-inset-top)] backdrop-blur">
|
||||||
<div className="mx-auto flex h-14 max-w-6xl items-center justify-between gap-3 px-4">
|
<div className="mx-auto flex h-14 max-w-6xl items-center justify-between gap-3 px-4">
|
||||||
<Link to="/" className="flex items-center gap-2 font-semibold">
|
<Link to="/" className="flex min-w-0 items-center gap-2 font-semibold">
|
||||||
<img src="/favicon.svg" alt="" className="h-7 w-7" />
|
<img src="/favicon.svg" alt="" className="h-7 w-7" />
|
||||||
<span>Solar Monitor</span>
|
<span className="hidden truncate min-[400px]:inline">{t('app.title')}</span>
|
||||||
</Link>
|
</Link>
|
||||||
<div className="flex items-center gap-3">
|
<div className="flex items-center gap-2">
|
||||||
<LiveChip summary={summaryPoll.data} error={summaryPoll.error} />
|
<LiveChip summary={summaryPoll.data} error={summaryPoll.error} />
|
||||||
{install && (
|
{install && (
|
||||||
<button
|
<button type="button" onClick={install} className={iconButton} aria-label={t('nav.install')}>
|
||||||
type="button"
|
<Icon name="download" size={14} />
|
||||||
onClick={install}
|
<span className="hidden sm:inline">{t('nav.install')}</span>
|
||||||
className="inline-flex min-h-8 items-center gap-1 rounded-lg border border-line px-2.5 text-xs font-medium"
|
|
||||||
>
|
|
||||||
<Icon name="download" size={14} /> Install
|
|
||||||
</button>
|
</button>
|
||||||
)}
|
)}
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => setLang(lang === 'el' ? 'en' : 'el')}
|
||||||
|
className={iconButton}
|
||||||
|
aria-label={t('nav.switchLanguage')}
|
||||||
|
title={t('nav.switchLanguage')}
|
||||||
|
>
|
||||||
|
{lang === 'el' ? 'EN' : 'ΕΛ'}
|
||||||
|
</button>
|
||||||
|
<Link to="/settings" className={iconButton} aria-label={t('nav.settings')} title={t('nav.settings')}>
|
||||||
|
<Icon name="settings" size={16} />
|
||||||
|
</Link>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</header>
|
</header>
|
||||||
@@ -64,6 +83,7 @@ export default function App() {
|
|||||||
<Routes>
|
<Routes>
|
||||||
<Route path="/" element={<Dashboard summaryPoll={summaryPoll} />} />
|
<Route path="/" element={<Dashboard summaryPoll={summaryPoll} />} />
|
||||||
<Route path="/inverters/:id" element={<InverterDetail summaryPoll={summaryPoll} />} />
|
<Route path="/inverters/:id" element={<InverterDetail summaryPoll={summaryPoll} />} />
|
||||||
|
<Route path="/settings" element={<Settings />} />
|
||||||
<Route path="*" element={<Dashboard summaryPoll={summaryPoll} />} />
|
<Route path="*" element={<Dashboard summaryPoll={summaryPoll} />} />
|
||||||
</Routes>
|
</Routes>
|
||||||
</main>
|
</main>
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ import {
|
|||||||
} from 'recharts'
|
} from 'recharts'
|
||||||
import { useThemeColors } from '../lib/colors'
|
import { useThemeColors } from '../lib/colors'
|
||||||
import { dateTimeLabel, dayLabel, timeLabel } from '../lib/format'
|
import { dateTimeLabel, dayLabel, timeLabel } from '../lib/format'
|
||||||
|
import { useT } from '../lib/i18n'
|
||||||
|
|
||||||
export function Legend({ series }) {
|
export function Legend({ series }) {
|
||||||
if (series.length < 2) return null
|
if (series.length < 2) return null
|
||||||
@@ -28,6 +29,7 @@ export function Legend({ series }) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function TooltipBox({ title, rows, total }) {
|
function TooltipBox({ title, rows, total }) {
|
||||||
|
const { t } = useT()
|
||||||
return (
|
return (
|
||||||
<div className="card min-w-40 px-3 py-2 text-xs shadow-lg">
|
<div className="card min-w-40 px-3 py-2 text-xs shadow-lg">
|
||||||
<div className="mb-1 font-medium text-ink-2">{title}</div>
|
<div className="mb-1 font-medium text-ink-2">{title}</div>
|
||||||
@@ -46,7 +48,7 @@ function TooltipBox({ title, rows, total }) {
|
|||||||
))}
|
))}
|
||||||
{total && (
|
{total && (
|
||||||
<tr className="border-t border-line">
|
<tr className="border-t border-line">
|
||||||
<td className="pt-1 pr-3 text-ink-2">Total</td>
|
<td className="pt-1 pr-3 text-ink-2">{t('chart.total')}</td>
|
||||||
<td className="tnum pt-1 text-right font-semibold text-ink">{total}</td>
|
<td className="tnum pt-1 text-right font-semibold text-ink">{total}</td>
|
||||||
</tr>
|
</tr>
|
||||||
)}
|
)}
|
||||||
@@ -58,26 +60,83 @@ function TooltipBox({ title, rows, total }) {
|
|||||||
|
|
||||||
const axisTick = (c) => ({ fill: c.muted, fontSize: 11 })
|
const axisTick = (c) => ({ fill: c.muted, fontSize: 11 })
|
||||||
|
|
||||||
/** Insert an empty point wherever readings stop for more than a couple of
|
// Silences up to this long are drawn through; longer ones (night, outage)
|
||||||
* buckets (night, outage), so the line breaks instead of bridging the gap. */
|
// break the line. Covers a unit reporting every ~5 min plus a missed cycle.
|
||||||
function withGaps(points, bucket) {
|
const BRIDGE_SECONDS = 900
|
||||||
if (!bucket || points.length < 2) return points
|
const SMOOTHING_RADIUS = { off: 0, light: 1, strong: 3 }
|
||||||
const out = [points[0]]
|
|
||||||
for (let i = 1; i < points.length; i++) {
|
/**
|
||||||
if (points[i].t - points[i - 1].t > bucket * 2.5) out.push({ t: points[i - 1].t + bucket })
|
* Chart rows from API points: a gap row where the whole fleet went silent,
|
||||||
out.push(points[i])
|
* values interpolated where one series reports less often than the bucket
|
||||||
|
* (INV5 every ~5 min on a 1-min chart would otherwise have no line at all),
|
||||||
|
* then an optional centred moving average. Interpolated values are flagged
|
||||||
|
* `<key>__est` so the tooltip can mark them.
|
||||||
|
*/
|
||||||
|
function prepare(points, keys, bucket, smoothing) {
|
||||||
|
const maxGap = Math.max(BRIDGE_SECONDS, (bucket || 0) * 2.5)
|
||||||
|
const rows = []
|
||||||
|
points.forEach((p, i) => {
|
||||||
|
if (i && p.t - points[i - 1].t > maxGap) rows.push({ t: points[i - 1].t + (bucket || 1) })
|
||||||
|
rows.push({ ...p })
|
||||||
|
})
|
||||||
|
for (const key of keys) {
|
||||||
|
let prev = -1
|
||||||
|
rows.forEach((r, i) => {
|
||||||
|
if (r[key] == null) return
|
||||||
|
if (prev >= 0 && i - prev > 1 && r.t - rows[prev].t <= maxGap) {
|
||||||
|
const a = rows[prev]
|
||||||
|
for (let j = prev + 1; j < i; j++) {
|
||||||
|
rows[j][key] = a[key] + ((r[key] - a[key]) * (rows[j].t - a.t)) / (r.t - a.t)
|
||||||
|
rows[j][`${key}__est`] = true
|
||||||
}
|
}
|
||||||
return out
|
}
|
||||||
|
prev = i
|
||||||
|
})
|
||||||
|
}
|
||||||
|
const radius = SMOOTHING_RADIUS[smoothing] ?? 0
|
||||||
|
if (radius) {
|
||||||
|
for (const key of keys) {
|
||||||
|
const raw = rows.map((r) => r[key])
|
||||||
|
rows.forEach((r, i) => {
|
||||||
|
if (raw[i] == null) return
|
||||||
|
// Only neighbours on the same unbroken stretch of line
|
||||||
|
let sum = raw[i]
|
||||||
|
let n = 1
|
||||||
|
for (let j = i - 1; j >= i - radius && j >= 0 && raw[j] != null; j--) {
|
||||||
|
sum += raw[j]
|
||||||
|
n++
|
||||||
|
}
|
||||||
|
for (let j = i + 1; j <= i + radius && j < raw.length && raw[j] != null; j++) {
|
||||||
|
sum += raw[j]
|
||||||
|
n++
|
||||||
|
}
|
||||||
|
r[key] = sum / n
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return rows
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Lines over time. points: [{t: unix seconds, [series.key]: number}]
|
* Lines over time. points: [{t: unix seconds, [series.key]: number}]
|
||||||
* series: [{key, name, color}]. Gaps (night, outages) stay gaps.
|
* series: [{key, name, color}]. Gaps (night, outages) stay gaps.
|
||||||
*/
|
*/
|
||||||
export function TimeLines({ points, series, from, to, bucket, format, axisFormat, height = 240, showTotal = false }) {
|
export function TimeLines({
|
||||||
|
points,
|
||||||
|
series,
|
||||||
|
from,
|
||||||
|
to,
|
||||||
|
bucket,
|
||||||
|
format,
|
||||||
|
axisFormat,
|
||||||
|
height = 240,
|
||||||
|
showTotal = false,
|
||||||
|
smoothing = 'off',
|
||||||
|
}) {
|
||||||
const c = useThemeColors()
|
const c = useThemeColors()
|
||||||
const span = to - from
|
const span = to - from
|
||||||
const data = useMemo(() => withGaps(points, bucket), [points, bucket])
|
const keys = series.map((s) => s.key).join(',')
|
||||||
|
const data = useMemo(() => prepare(points, keys.split(','), bucket, smoothing), [points, keys, bucket, smoothing])
|
||||||
return (
|
return (
|
||||||
<div style={{ height }}>
|
<div style={{ height }}>
|
||||||
<ResponsiveContainer width="100%" height="100%">
|
<ResponsiveContainer width="100%" height="100%">
|
||||||
@@ -105,9 +164,10 @@ export function TimeLines({ points, series, from, to, bucket, format, axisFormat
|
|||||||
cursor={{ stroke: c.axis, strokeWidth: 1 }}
|
cursor={{ stroke: c.axis, strokeWidth: 1 }}
|
||||||
content={({ active, payload, label }) => {
|
content={({ active, payload, label }) => {
|
||||||
if (!active || !payload?.length) return null
|
if (!active || !payload?.length) return null
|
||||||
|
const row = payload[0].payload
|
||||||
const rows = series
|
const rows = series
|
||||||
.filter((s) => payload[0].payload[s.key] != null)
|
.filter((s) => row[s.key] != null)
|
||||||
.map((s) => ({ ...s, value: format(payload[0].payload[s.key]) }))
|
.map((s) => ({ ...s, value: (row[`${s.key}__est`] ? '≈ ' : '') + format(row[s.key]) }))
|
||||||
const total = showTotal
|
const total = showTotal
|
||||||
? format(series.reduce((sum, s) => sum + (payload[0].payload[s.key] ?? 0), 0))
|
? format(series.reduce((sum, s) => sum + (payload[0].payload[s.key] ?? 0), 0))
|
||||||
: null
|
: null
|
||||||
@@ -121,6 +181,7 @@ export function TimeLines({ points, series, from, to, bucket, format, axisFormat
|
|||||||
name={s.name}
|
name={s.name}
|
||||||
stroke={s.color}
|
stroke={s.color}
|
||||||
strokeWidth={2}
|
strokeWidth={2}
|
||||||
|
type={smoothing === 'off' ? 'linear' : 'monotone'}
|
||||||
dot={false}
|
dot={false}
|
||||||
activeDot={{ r: 4, stroke: c.surface, strokeWidth: 2 }}
|
activeDot={{ r: 4, stroke: c.surface, strokeWidth: 2 }}
|
||||||
connectNulls={false}
|
connectNulls={false}
|
||||||
@@ -189,3 +250,13 @@ export function DayBars({ days, series, format, axisFormat, height = 220 }) {
|
|||||||
</div>
|
</div>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function EnergyFootnote({ estimated }) {
|
||||||
|
const { t } = useT()
|
||||||
|
return (
|
||||||
|
<div className="mt-1 flex justify-between gap-3 text-[11px] text-muted">
|
||||||
|
<span>{estimated && t('energy.footEstimated')}</span>
|
||||||
|
<span className="shrink-0">{t('energy.axis')}</span>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,35 +1,112 @@
|
|||||||
import { Link } from 'react-router-dom'
|
import { Link } from 'react-router-dom'
|
||||||
import { seriesCssVar } from '../lib/colors'
|
import { seriesCssVar } from '../lib/colors'
|
||||||
import { pct, power } from '../lib/format'
|
import { pct, power } from '../lib/format'
|
||||||
|
import { useT } from '../lib/i18n'
|
||||||
|
import { useSettings } from '../lib/settings'
|
||||||
import Icon from './Icon'
|
import Icon from './Icon'
|
||||||
import { STATES } from './Health'
|
import { STATES } from './Health'
|
||||||
|
|
||||||
|
/** Smallest "round" number ≥ x (1, 1.5, 2, 2.5, 3, 4, 5, 6, 8 × 10ⁿ), so the
|
||||||
|
* auto scale doesn't jump with every reading. */
|
||||||
|
function niceCeil(x) {
|
||||||
|
if (!(x > 0)) return 1
|
||||||
|
const mag = 10 ** Math.floor(Math.log10(x))
|
||||||
|
const step = [1, 1.5, 2, 2.5, 3, 4, 5, 6, 8, 10].find((s) => s * mag >= x * 0.9999)
|
||||||
|
return step * mag
|
||||||
|
}
|
||||||
|
|
||||||
|
function median(values) {
|
||||||
|
const v = [...values].sort((a, b) => a - b)
|
||||||
|
const m = Math.floor(v.length / 2)
|
||||||
|
return v.length % 2 ? v[m] : (v[m - 1] + v[m]) / 2
|
||||||
|
}
|
||||||
|
|
||||||
|
/** AC power to compare: the latest reading, or the mean of the last n, which
|
||||||
|
* evens out one reading taken while a cloud shaded that array. */
|
||||||
|
function watts(st, n) {
|
||||||
|
if (!st.health.online) return null
|
||||||
|
if (n > 1) {
|
||||||
|
const recent = (st.recent_power ?? [])
|
||||||
|
.slice(0, n)
|
||||||
|
.map((p) => p.ac_power_total_w)
|
||||||
|
.filter((w) => w != null)
|
||||||
|
if (recent.length) return recent.reduce((a, b) => a + b, 0) / recent.length
|
||||||
|
}
|
||||||
|
return st.latest?.ac_power_total_w ?? null
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Side-by-side output of every inverter — the quickest way to spot one
|
* Side-by-side output of every inverter — the quickest way to spot one
|
||||||
* that is producing far less than the others (blown string fuse, tripped
|
* that is producing far less than the others (blown string fuse, tripped
|
||||||
* breaker, disconnected string).
|
* breaker, disconnected string). Averaging, scale and percentage reference
|
||||||
|
* come from the shared settings.
|
||||||
*/
|
*/
|
||||||
export default function Comparison({ summary, ids }) {
|
export default function Comparison({ summary, ids }) {
|
||||||
const rows = summary.inverters
|
const { t } = useT()
|
||||||
|
const { settings } = useSettings()
|
||||||
|
const n = settings.comparison_readings
|
||||||
|
const customW = settings.comparison_custom_kw ? settings.comparison_custom_kw * 1000 : null
|
||||||
|
// "Custom" without a value falls back to the default rather than breaking
|
||||||
|
const scale = settings.comparison_scale === 'custom' && !customW ? 'auto' : settings.comparison_scale
|
||||||
|
const reference =
|
||||||
|
settings.comparison_reference === 'custom' && !customW ? 'median' : settings.comparison_reference
|
||||||
|
// Per kWp once every producing inverter has its array size (as the backend decides)
|
||||||
const perKwp = summary.fleet_median_w_per_kwp !== null
|
const perKwp = summary.fleet_median_w_per_kwp !== null
|
||||||
const value = (st) => {
|
|
||||||
const w = st.health.online ? st.latest?.ac_power_total_w ?? null : null
|
const rows = summary.inverters.map((st) => {
|
||||||
if (w === null) return null
|
const w = watts(st, n)
|
||||||
return perKwp && st.inverter.capacity_kwp ? w / st.inverter.capacity_kwp : w
|
const kwp = st.inverter.capacity_kwp
|
||||||
|
return { st, w, spec: w === null ? null : perKwp && kwp ? w / kwp : w }
|
||||||
|
})
|
||||||
|
const specs = rows.map((r) => r.spec).filter((v) => v !== null)
|
||||||
|
const best = specs.length ? Math.max(...specs) : null
|
||||||
|
const med = specs.length >= 2 ? median(specs) : null
|
||||||
|
|
||||||
|
const ratio = (r) => {
|
||||||
|
if (r.w === null) return null
|
||||||
|
if (reference === 'custom') return r.w / customW
|
||||||
|
if (reference === 'best') return best > 0 ? r.spec / best : null
|
||||||
|
return med > 0 ? r.spec / med : null
|
||||||
}
|
}
|
||||||
const max = Math.max(1, ...rows.map((st) => value(st) ?? 0))
|
const ceiling = scale === 'auto' ? niceCeil(best ?? 0) : best
|
||||||
|
const barPct = (r) => {
|
||||||
|
if (r.w === null) return 0
|
||||||
|
const f = scale === 'custom' ? r.w / customW : ceiling > 0 ? r.spec / ceiling : 0
|
||||||
|
return Math.min(100, Math.max(r.w > 0 ? 1 : 0, f * 100))
|
||||||
|
}
|
||||||
|
|
||||||
|
const caption = [
|
||||||
|
n > 1 ? t('cmp.avg', { n }) : t('cmp.latest'),
|
||||||
|
perKwp && scale !== 'custom' && reference !== 'custom' ? t('cmp.perKwp') : null,
|
||||||
|
reference === 'custom'
|
||||||
|
? t('cmp.vsCustom', { v: power(customW) })
|
||||||
|
: reference === 'best'
|
||||||
|
? t('cmp.vsBest')
|
||||||
|
: t('cmp.vsMedian'),
|
||||||
|
]
|
||||||
|
.filter(Boolean)
|
||||||
|
.join(' · ')
|
||||||
|
const fullBar =
|
||||||
|
scale === 'custom'
|
||||||
|
? power(customW)
|
||||||
|
: scale === 'auto' && best > 0
|
||||||
|
? perKwp
|
||||||
|
? `${Math.round(ceiling)} W/kWp`
|
||||||
|
: power(ceiling)
|
||||||
|
: null
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<section className="card p-4">
|
<section className="card p-4">
|
||||||
<div className="mb-3 flex items-baseline justify-between gap-2">
|
<div className="mb-3 flex flex-wrap items-baseline justify-between gap-x-3 gap-y-0.5">
|
||||||
<h2 className="text-sm font-semibold">Output comparison</h2>
|
<h2 className="text-sm font-semibold">{t('cmp.title')}</h2>
|
||||||
<span className="text-xs text-muted">{perKwp ? 'per kWp · vs median' : 'now · vs median'}</span>
|
<span className="text-xs text-muted">{caption}</span>
|
||||||
</div>
|
</div>
|
||||||
<ul className="space-y-3">
|
<ul className="space-y-3">
|
||||||
{rows.map((st) => {
|
{rows.map((r) => {
|
||||||
const v = value(st)
|
const { st } = r
|
||||||
const flagged = st.health.issues.some((i) => i.code === 'underperforming')
|
const flagged = st.health.issues.some((i) => i.code === 'underperforming')
|
||||||
const state = STATES[st.health.state]
|
const state = STATES[st.health.state] ?? STATES.unknown
|
||||||
|
const over = scale === 'custom' && r.w > customW
|
||||||
return (
|
return (
|
||||||
<li key={st.inverter.id}>
|
<li key={st.inverter.id}>
|
||||||
<Link
|
<Link
|
||||||
@@ -46,33 +123,33 @@ export default function Comparison({ summary, ids }) {
|
|||||||
<span className="truncate font-medium">{st.inverter.name}</span>
|
<span className="truncate font-medium">{st.inverter.name}</span>
|
||||||
</span>
|
</span>
|
||||||
<span className="flex shrink-0 items-center gap-2 tnum">
|
<span className="flex shrink-0 items-center gap-2 tnum">
|
||||||
{v === null ? (
|
{r.w === null ? (
|
||||||
<span className="inline-flex items-center gap-1 text-xs text-ink-2">
|
<span className="inline-flex items-center gap-1 text-xs text-ink-2">
|
||||||
<Icon name={state.icon} size={13} />
|
<Icon name={state.icon} size={13} />
|
||||||
{state.label}
|
{t(`state.${STATES[st.health.state] ? st.health.state : 'unknown'}`)}
|
||||||
</span>
|
</span>
|
||||||
) : (
|
) : (
|
||||||
<>
|
<>
|
||||||
<span className="font-semibold">{power(st.latest.ac_power_total_w)}</span>
|
<span className="font-semibold">{power(r.w)}</span>
|
||||||
<span
|
<span
|
||||||
className={`inline-flex w-14 items-center justify-end gap-0.5 text-xs ${
|
className={`inline-flex w-14 items-center justify-end gap-0.5 text-xs ${
|
||||||
flagged ? 'font-semibold text-warn' : 'text-muted'
|
flagged ? 'font-semibold text-warn' : 'text-muted'
|
||||||
}`}
|
}`}
|
||||||
>
|
>
|
||||||
{flagged && <Icon name="alert" size={12} strokeWidth={2.5} />}
|
{flagged && <Icon name="alert" size={12} strokeWidth={2.5} />}
|
||||||
{pct(st.health.relative_output)}
|
{pct(ratio(r))}
|
||||||
</span>
|
</span>
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
<div className="h-2.5 overflow-hidden rounded-full bg-surface-2">
|
<div
|
||||||
|
className="h-2.5 overflow-hidden rounded-full bg-surface-2"
|
||||||
|
title={over ? t('cmp.overScale') : undefined}
|
||||||
|
>
|
||||||
<div
|
<div
|
||||||
className="h-full rounded-full transition-[width] duration-500"
|
className="h-full rounded-full transition-[width] duration-500"
|
||||||
style={{
|
style={{ width: `${barPct(r)}%`, background: seriesCssVar(ids, st.inverter.id) }}
|
||||||
width: `${v === null ? 0 : Math.max(1, (v / max) * 100)}%`,
|
|
||||||
background: seriesCssVar(ids, st.inverter.id),
|
|
||||||
}}
|
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
</Link>
|
</Link>
|
||||||
@@ -80,6 +157,9 @@ export default function Comparison({ summary, ids }) {
|
|||||||
)
|
)
|
||||||
})}
|
})}
|
||||||
</ul>
|
</ul>
|
||||||
|
{fullBar && (
|
||||||
|
<div className="mt-3 text-right text-[11px] text-muted tnum">{t('cmp.fullBar', { v: fullBar })}</div>
|
||||||
|
)}
|
||||||
</section>
|
</section>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,17 +1,9 @@
|
|||||||
import { useState } from 'react'
|
import { useState } from 'react'
|
||||||
import { api } from '../lib/api'
|
import { api } from '../lib/api'
|
||||||
|
import { rememberApiKey, storedApiKey } from '../lib/apiKey'
|
||||||
|
import { useT } from '../lib/i18n'
|
||||||
import Icon from './Icon'
|
import Icon from './Icon'
|
||||||
|
|
||||||
const KEY_STORAGE = 'solar.apiKey'
|
|
||||||
|
|
||||||
function storedKey() {
|
|
||||||
try {
|
|
||||||
return localStorage.getItem(KEY_STORAGE) ?? ''
|
|
||||||
} catch {
|
|
||||||
return ''
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function Field({ label, hint, children }) {
|
function Field({ label, hint, children }) {
|
||||||
return (
|
return (
|
||||||
<label className="block">
|
<label className="block">
|
||||||
@@ -22,10 +14,11 @@ function Field({ label, hint, children }) {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
const input =
|
export const input =
|
||||||
'mt-1 block w-full min-h-10 rounded-lg border border-line bg-surface-2 px-3 text-base text-ink outline-none focus:border-[var(--accent)]'
|
'mt-1 block w-full min-h-10 rounded-lg border border-line bg-surface-2 px-3 text-base text-ink outline-none focus:border-[var(--accent)]'
|
||||||
|
|
||||||
export default function EditInverterDialog({ inverter, onClose, onSaved }) {
|
export default function EditInverterDialog({ inverter, onClose, onSaved }) {
|
||||||
|
const { t } = useT()
|
||||||
const [form, setForm] = useState({
|
const [form, setForm] = useState({
|
||||||
name: inverter.name ?? '',
|
name: inverter.name ?? '',
|
||||||
capacity_kwp: inverter.capacity_kwp ?? '',
|
capacity_kwp: inverter.capacity_kwp ?? '',
|
||||||
@@ -33,7 +26,7 @@ export default function EditInverterDialog({ inverter, onClose, onSaved }) {
|
|||||||
sort_order: inverter.sort_order ?? 0,
|
sort_order: inverter.sort_order ?? 0,
|
||||||
notes: inverter.notes ?? '',
|
notes: inverter.notes ?? '',
|
||||||
})
|
})
|
||||||
const [apiKey, setApiKey] = useState(storedKey)
|
const [apiKey, setApiKey] = useState(storedApiKey)
|
||||||
const [saving, setSaving] = useState(false)
|
const [saving, setSaving] = useState(false)
|
||||||
const [error, setError] = useState(null)
|
const [error, setError] = useState(null)
|
||||||
const set = (k) => (e) => setForm((f) => ({ ...f, [k]: e.target.value }))
|
const set = (k) => (e) => setForm((f) => ({ ...f, [k]: e.target.value }))
|
||||||
@@ -51,14 +44,10 @@ export default function EditInverterDialog({ inverter, onClose, onSaved }) {
|
|||||||
notes: form.notes.trim() || null,
|
notes: form.notes.trim() || null,
|
||||||
}
|
}
|
||||||
const saved = await api.updateInverter(inverter.id, body, apiKey)
|
const saved = await api.updateInverter(inverter.id, body, apiKey)
|
||||||
try {
|
rememberApiKey(apiKey)
|
||||||
localStorage.setItem(KEY_STORAGE, apiKey)
|
|
||||||
} catch {
|
|
||||||
/* storage unavailable — key just isn't remembered */
|
|
||||||
}
|
|
||||||
onSaved(saved)
|
onSaved(saved)
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
setError(err.status === 401 ? 'Wrong API key' : err.message)
|
setError(err.status === 401 ? t('common.wrongKey') : err.message)
|
||||||
} finally {
|
} finally {
|
||||||
setSaving(false)
|
setSaving(false)
|
||||||
}
|
}
|
||||||
@@ -75,17 +64,17 @@ export default function EditInverterDialog({ inverter, onClose, onSaved }) {
|
|||||||
className="card max-h-[92dvh] w-full max-w-md overflow-y-auto rounded-b-none p-5 pb-[max(1.25rem,env(safe-area-inset-bottom))] sm:rounded-b-[14px]"
|
className="card max-h-[92dvh] w-full max-w-md overflow-y-auto rounded-b-none p-5 pb-[max(1.25rem,env(safe-area-inset-bottom))] sm:rounded-b-[14px]"
|
||||||
>
|
>
|
||||||
<div className="mb-4 flex items-center justify-between">
|
<div className="mb-4 flex items-center justify-between">
|
||||||
<h2 className="font-semibold">Inverter settings</h2>
|
<h2 className="font-semibold">{t('edit.title')}</h2>
|
||||||
<button type="button" onClick={onClose} className="-m-2 p-2 text-ink-2" aria-label="Close">
|
<button type="button" onClick={onClose} className="-m-2 p-2 text-ink-2" aria-label={t('common.close')}>
|
||||||
<Icon name="close" size={20} />
|
<Icon name="close" size={20} />
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
<div className="space-y-4">
|
<div className="space-y-4">
|
||||||
<Field label="Display name" hint={`ID sent by the poller: ${inverter.id}`}>
|
<Field label={t('edit.name')} hint={t('edit.idHint', { id: inverter.id })}>
|
||||||
<input className={input} value={form.name} onChange={set('name')} maxLength={100} />
|
<input className={input} value={form.name} onChange={set('name')} maxLength={100} />
|
||||||
</Field>
|
</Field>
|
||||||
<div className="grid grid-cols-2 gap-3">
|
<div className="grid grid-cols-2 gap-3">
|
||||||
<Field label="Array size (kWp)">
|
<Field label={t('edit.kwp')}>
|
||||||
<input
|
<input
|
||||||
className={input}
|
className={input}
|
||||||
type="number"
|
type="number"
|
||||||
@@ -96,24 +85,21 @@ export default function EditInverterDialog({ inverter, onClose, onSaved }) {
|
|||||||
onChange={set('capacity_kwp')}
|
onChange={set('capacity_kwp')}
|
||||||
/>
|
/>
|
||||||
</Field>
|
</Field>
|
||||||
<Field label="MPPT inputs used">
|
<Field label={t('edit.mppt')}>
|
||||||
<select className={input} value={form.mppt_count} onChange={set('mppt_count')}>
|
<select className={input} value={form.mppt_count} onChange={set('mppt_count')}>
|
||||||
<option value={1}>1</option>
|
<option value={1}>1</option>
|
||||||
<option value={2}>2</option>
|
<option value={2}>2</option>
|
||||||
</select>
|
</select>
|
||||||
</Field>
|
</Field>
|
||||||
</div>
|
</div>
|
||||||
<p className="-mt-2 text-xs text-muted">
|
<p className="-mt-2 text-xs text-muted">{t('edit.kwpHint')}</p>
|
||||||
Set the array size on every inverter to compare output per kWp — needed when the arrays
|
<Field label={t('edit.sort')}>
|
||||||
differ. With one MPPT input in use, the string-imbalance check is skipped.
|
|
||||||
</p>
|
|
||||||
<Field label="Sort order">
|
|
||||||
<input className={input} type="number" inputMode="numeric" value={form.sort_order} onChange={set('sort_order')} />
|
<input className={input} type="number" inputMode="numeric" value={form.sort_order} onChange={set('sort_order')} />
|
||||||
</Field>
|
</Field>
|
||||||
<Field label="Notes">
|
<Field label={t('edit.notes')}>
|
||||||
<textarea className={`${input} min-h-20 py-2`} value={form.notes} onChange={set('notes')} />
|
<textarea className={`${input} min-h-20 py-2`} value={form.notes} onChange={set('notes')} />
|
||||||
</Field>
|
</Field>
|
||||||
<Field label="API key">
|
<Field label={t('common.apiKey')}>
|
||||||
<input
|
<input
|
||||||
className={input}
|
className={input}
|
||||||
type="password"
|
type="password"
|
||||||
@@ -129,7 +115,7 @@ export default function EditInverterDialog({ inverter, onClose, onSaved }) {
|
|||||||
disabled={saving}
|
disabled={saving}
|
||||||
className="min-h-11 w-full rounded-lg bg-ink font-semibold text-page disabled:opacity-60"
|
className="min-h-11 w-full rounded-lg bg-ink font-semibold text-page disabled:opacity-60"
|
||||||
>
|
>
|
||||||
{saving ? 'Saving…' : 'Save'}
|
{saving ? t('common.saving') : t('common.save')}
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</form>
|
</form>
|
||||||
|
|||||||
@@ -1,12 +1,15 @@
|
|||||||
|
import { issueText, useT } from '../lib/i18n'
|
||||||
import Icon from './Icon'
|
import Icon from './Icon'
|
||||||
|
|
||||||
|
// Labels: t(`state.${key}`)
|
||||||
export const STATES = {
|
export const STATES = {
|
||||||
ok: { label: 'Operating', icon: 'check', tone: 'good' },
|
ok: { icon: 'check', tone: 'good' },
|
||||||
warning: { label: 'Check needed', icon: 'alert', tone: 'warning' },
|
standby: { icon: 'pause', tone: 'neutral' },
|
||||||
fault: { label: 'Fault', icon: 'fault', tone: 'critical' },
|
warning: { icon: 'alert', tone: 'warning' },
|
||||||
offline: { label: 'Offline', icon: 'offline', tone: 'critical' },
|
fault: { icon: 'fault', tone: 'critical' },
|
||||||
sleeping: { label: 'Sleeping', icon: 'moon', tone: 'neutral' },
|
offline: { icon: 'offline', tone: 'critical' },
|
||||||
unknown: { label: 'No data', icon: 'unknown', tone: 'neutral' },
|
sleeping: { icon: 'moon', tone: 'neutral' },
|
||||||
|
unknown: { icon: 'unknown', tone: 'neutral' },
|
||||||
}
|
}
|
||||||
|
|
||||||
const TONE = {
|
const TONE = {
|
||||||
@@ -20,19 +23,23 @@ 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
|
const { t } = useT()
|
||||||
|
const key = STATES[state] ? state : 'unknown'
|
||||||
|
const s = STATES[key]
|
||||||
|
const label = t(key === 'ok' && feeding ? 'state.feeding' : `state.${key}`)
|
||||||
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]}`}>
|
||||||
<Icon name={s.icon} size={size === 'lg' ? 16 : 13} strokeWidth={2.5} />
|
<Icon name={s.icon} size={size === 'lg' ? 16 : 13} strokeWidth={2.5} />
|
||||||
{s.label}
|
{label}
|
||||||
</span>
|
</span>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Online = a reading within the last 5 minutes. */
|
/** Online = a reading within the last 5 minutes. */
|
||||||
export function OnlineDot({ online }) {
|
export function OnlineDot({ online }) {
|
||||||
|
const { t } = useT()
|
||||||
return (
|
return (
|
||||||
<span className="inline-flex items-center gap-1.5 text-xs text-ink-2">
|
<span className="inline-flex items-center gap-1.5 text-xs text-ink-2">
|
||||||
<span
|
<span
|
||||||
@@ -40,12 +47,14 @@ export function OnlineDot({ online }) {
|
|||||||
style={{ background: online ? 'var(--good)' : 'var(--muted)' }}
|
style={{ background: online ? 'var(--good)' : 'var(--muted)' }}
|
||||||
aria-hidden="true"
|
aria-hidden="true"
|
||||||
/>
|
/>
|
||||||
{online ? 'Online' : 'Offline'}
|
{online ? t('online.online') : t('online.offline')}
|
||||||
</span>
|
</span>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** issues: from /api/summary; an optional `who` (inverter name) is prefixed. */
|
||||||
export function IssueList({ issues, compact = false }) {
|
export function IssueList({ issues, compact = false }) {
|
||||||
|
const { t } = useT()
|
||||||
if (!issues?.length) return null
|
if (!issues?.length) return null
|
||||||
return (
|
return (
|
||||||
<ul className={compact ? 'space-y-1' : 'space-y-2'}>
|
<ul className={compact ? 'space-y-1' : 'space-y-2'}>
|
||||||
@@ -53,11 +62,14 @@ export function IssueList({ issues, compact = false }) {
|
|||||||
const tone = SEVERITY_TONE[issue.severity]
|
const tone = SEVERITY_TONE[issue.severity]
|
||||||
return (
|
return (
|
||||||
<li
|
<li
|
||||||
key={issue.code}
|
key={issue.key ?? issue.code}
|
||||||
className={`flex items-start gap-2 rounded-lg ${compact ? 'px-2 py-1.5 text-xs' : 'px-3 py-2 text-sm'} ${TONE[tone]}`}
|
className={`flex items-start gap-2 rounded-lg ${compact ? 'px-2 py-1.5 text-xs' : 'px-3 py-2 text-sm'} ${TONE[tone]}`}
|
||||||
>
|
>
|
||||||
<Icon name={SEVERITY_ICON[issue.severity]} size={compact ? 14 : 16} className="mt-px" />
|
<Icon name={SEVERITY_ICON[issue.severity]} size={compact ? 14 : 16} className="mt-px" />
|
||||||
<span className="text-ink">{issue.message}</span>
|
<span className="text-ink">
|
||||||
|
{issue.who && `${issue.who}: `}
|
||||||
|
{issueText(t, issue)}
|
||||||
|
</span>
|
||||||
</li>
|
</li>
|
||||||
)
|
)
|
||||||
})}
|
})}
|
||||||
|
|||||||
@@ -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: (
|
||||||
<>
|
<>
|
||||||
@@ -46,6 +52,18 @@ const PATHS = {
|
|||||||
</>
|
</>
|
||||||
),
|
),
|
||||||
close: <path d="M18 6 6 18M6 6l12 12" />,
|
close: <path d="M18 6 6 18M6 6l12 12" />,
|
||||||
|
settings: (
|
||||||
|
<>
|
||||||
|
<path d="M12.2 2h-.4a2 2 0 0 0-2 2v.2a2 2 0 0 1-1 1.7l-.4.3a2 2 0 0 1-2 0l-.2-.1a2 2 0 0 0-2.7.7l-.2.4a2 2 0 0 0 .7 2.7l.2.1a2 2 0 0 1 1 1.7v.6a2 2 0 0 1-1 1.7l-.2.1a2 2 0 0 0-.7 2.7l.2.4a2 2 0 0 0 2.7.7l.2-.1a2 2 0 0 1 2 0l.4.3a2 2 0 0 1 1 1.7v.2a2 2 0 0 0 2 2h.4a2 2 0 0 0 2-2v-.2a2 2 0 0 1 1-1.7l.4-.3a2 2 0 0 1 2 0l.2.1a2 2 0 0 0 2.7-.7l.2-.4a2 2 0 0 0-.7-2.7l-.2-.1a2 2 0 0 1-1-1.7v-.6a2 2 0 0 1 1-1.7l.2-.1a2 2 0 0 0 .7-2.7l-.2-.4a2 2 0 0 0-2.7-.7l-.2.1a2 2 0 0 1-2 0l-.4-.3a2 2 0 0 1-1-1.7V4a2 2 0 0 0-2-2Z" />
|
||||||
|
<circle cx="12" cy="12" r="3" />
|
||||||
|
</>
|
||||||
|
),
|
||||||
|
globe: (
|
||||||
|
<>
|
||||||
|
<circle cx="12" cy="12" r="10" />
|
||||||
|
<path d="M2 12h20M12 2a15 15 0 0 1 0 20 15 15 0 0 1 0-20Z" />
|
||||||
|
</>
|
||||||
|
),
|
||||||
link: (
|
link: (
|
||||||
<>
|
<>
|
||||||
<path d="M5 12.55a11 11 0 0 1 14.08 0M1.42 9a16 16 0 0 1 21.16 0M8.53 16.11a6 6 0 0 1 6.95 0M12 20h.01" />
|
<path d="M5 12.55a11 11 0 0 1 14.08 0M1.42 9a16 16 0 0 1 21.16 0M8.53 16.11a6 6 0 0 1 6.95 0M12 20h.01" />
|
||||||
|
|||||||
@@ -1,31 +1,38 @@
|
|||||||
import { Link } from 'react-router-dom'
|
import { Link } from 'react-router-dom'
|
||||||
import { seriesCssVar } from '../lib/colors'
|
import { seriesCssVar } from '../lib/colors'
|
||||||
import { ago, energyParts, num, powerParts } from '../lib/format'
|
import { ago, energyParts, num, powerParts } from '../lib/format'
|
||||||
|
import { useT } from '../lib/i18n'
|
||||||
|
import { displayVoltage, useSettings } from '../lib/settings'
|
||||||
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 }) {
|
||||||
|
const { t } = useT()
|
||||||
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>
|
||||||
|
{unavailable ? (
|
||||||
|
<div className="text-xs leading-5 text-muted">{unavailable === true ? t('common.notAvailable') : unavailable}</div>
|
||||||
|
) : (
|
||||||
<div className="truncate tnum">
|
<div className="truncate tnum">
|
||||||
<span className="font-semibold">{value}</span>
|
<span className="font-semibold">{value}</span>
|
||||||
{unit && <span className="ml-0.5 text-xs text-ink-2">{unit}</span>}
|
{unit && <span className="ml-0.5 text-xs text-ink-2">{unit}</span>}
|
||||||
</div>
|
</div>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
export default function InverterCard({ status, ids }) {
|
export default function InverterCard({ status, ids }) {
|
||||||
const { inverter, health, latest } = status
|
const { t } = useT()
|
||||||
|
const { settings } = useSettings()
|
||||||
|
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].map((v) => displayVoltage(v, settings))
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Link
|
<Link
|
||||||
@@ -46,8 +53,9 @@ export default function InverterCard({ status, ids }) {
|
|||||||
<OnlineDot online={live} />
|
<OnlineDot online={live} />
|
||||||
<span className="text-xs text-muted">· {ago(r.timestamp)}</span>
|
<span className="text-xs text-muted">· {ago(r.timestamp)}</span>
|
||||||
</div>
|
</div>
|
||||||
|
{live && r.status_text && <div className="mt-0.5 truncate text-xs text-muted">{r.status_text}</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,13 +69,18 @@ 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={t(energyToday.estimated ? 'hero.todayEst' : 'hero.today')}
|
||||||
<Stat label="Temp" value={live ? num(r.temperature_c) : '—'} unit="°C" />
|
value={today}
|
||||||
|
unit={todayU}
|
||||||
|
unavailable={energyToday.wh == null && live}
|
||||||
|
/>
|
||||||
|
<Stat label={t('hero.lifetime')} value={life} unit={lifeU} unavailable={r.total_energy_wh == null} />
|
||||||
|
<Stat label={t('card.temp')} value={live ? num(r.temperature_c) : '—'} unit="°C" />
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="flex items-center justify-between rounded-lg bg-surface-2 px-3 py-2 text-xs tnum">
|
<div className="flex items-center justify-between rounded-lg bg-surface-2 px-3 py-2 text-xs tnum">
|
||||||
<span className="text-muted">AC</span>
|
<span className="text-muted">{t(settings.voltage_display === 'line' ? 'card.acLine' : 'card.acPhase')}</span>
|
||||||
{volts.map((v, i) => (
|
{volts.map((v, i) => (
|
||||||
<span key={i}>
|
<span key={i}>
|
||||||
<span className="text-muted">L{i + 1} </span>
|
<span className="text-muted">L{i + 1} </span>
|
||||||
@@ -80,7 +93,7 @@ export default function InverterCard({ status, ids }) {
|
|||||||
{health.issues.length > 0 && <IssueList issues={health.issues} compact />}
|
{health.issues.length > 0 && <IssueList issues={health.issues} compact />}
|
||||||
|
|
||||||
<span className="mt-auto inline-flex items-center gap-1 self-end text-xs text-muted group-hover:text-ink-2">
|
<span className="mt-auto inline-flex items-center gap-1 self-end text-xs text-muted group-hover:text-ink-2">
|
||||||
Details <Icon name="chevron" size={12} />
|
{t('card.details')} <Icon name="chevron" size={12} />
|
||||||
</span>
|
</span>
|
||||||
</Link>
|
</Link>
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -43,6 +43,8 @@ export const api = {
|
|||||||
history: (id, params) => request(`${inv(id)}/history${qs(params)}`),
|
history: (id, params) => request(`${inv(id)}/history${qs(params)}`),
|
||||||
inverterDaily: (id, params) => request(`${inv(id)}/daily${qs(params)}`),
|
inverterDaily: (id, params) => request(`${inv(id)}/daily${qs(params)}`),
|
||||||
updateInverter: (id, body, apiKey) => request(inv(id), { method: 'PATCH', body, apiKey }),
|
updateInverter: (id, body, apiKey) => request(inv(id), { method: 'PATCH', body, apiKey }),
|
||||||
|
settings: () => request('/settings'),
|
||||||
|
saveSettings: (body) => request('/settings', { method: 'PUT', body }),
|
||||||
}
|
}
|
||||||
|
|
||||||
export function isoAgo(seconds) {
|
export function isoAgo(seconds) {
|
||||||
|
|||||||
@@ -0,0 +1,19 @@
|
|||||||
|
// The API key guards every change (inverter settings, view settings). It is
|
||||||
|
// remembered per device once it has worked.
|
||||||
|
const KEY_STORAGE = 'solar.apiKey'
|
||||||
|
|
||||||
|
export function storedApiKey() {
|
||||||
|
try {
|
||||||
|
return localStorage.getItem(KEY_STORAGE) ?? ''
|
||||||
|
} catch {
|
||||||
|
return ''
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function rememberApiKey(key) {
|
||||||
|
try {
|
||||||
|
localStorage.setItem(KEY_STORAGE, key)
|
||||||
|
} catch {
|
||||||
|
/* storage unavailable — key just isn't remembered */
|
||||||
|
}
|
||||||
|
}
|
||||||
+46
-12
@@ -1,5 +1,21 @@
|
|||||||
const nf = (digits) =>
|
// Set by the language provider so numbers and dates follow the chosen language
|
||||||
new Intl.NumberFormat(undefined, { minimumFractionDigits: digits, maximumFractionDigits: digits })
|
let lang = 'en'
|
||||||
|
const LOCALES = { en: 'en-GB', el: 'el-GR' }
|
||||||
|
|
||||||
|
export function setFormatLanguage(l) {
|
||||||
|
lang = LOCALES[l] ? l : 'en'
|
||||||
|
}
|
||||||
|
|
||||||
|
const locale = () => LOCALES[lang]
|
||||||
|
|
||||||
|
const nfCache = new Map()
|
||||||
|
const nf = (digits) => {
|
||||||
|
const key = `${lang}:${digits}`
|
||||||
|
if (!nfCache.has(key)) {
|
||||||
|
nfCache.set(key, new Intl.NumberFormat(locale(), { minimumFractionDigits: digits, maximumFractionDigits: digits }))
|
||||||
|
}
|
||||||
|
return nfCache.get(key)
|
||||||
|
}
|
||||||
|
|
||||||
export function num(v, digits = 0) {
|
export function num(v, digits = 0) {
|
||||||
return v === null || v === undefined || Number.isNaN(v) ? '—' : nf(digits).format(v)
|
return v === null || v === undefined || Number.isNaN(v) ? '—' : nf(digits).format(v)
|
||||||
@@ -33,13 +49,31 @@ export function energy(wh) {
|
|||||||
return `${v} ${u}`
|
return `${v} ${u}`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const UNITS = {
|
||||||
|
en: { s: 's', min: 'min', h: 'h', d: 'd', days: 'days', ago: (x) => `${x} ago`, never: 'never' },
|
||||||
|
el: { s: 'δευτ.', min: 'λεπ.', h: 'ώρ.', d: 'ημ.', days: 'ημ.', ago: (x) => `πριν ${x}`, never: 'ποτέ' },
|
||||||
|
}
|
||||||
|
|
||||||
export function ago(iso) {
|
export function ago(iso) {
|
||||||
if (!iso) return 'never'
|
const u = UNITS[lang]
|
||||||
|
if (!iso) return u.never
|
||||||
const s = Math.max(0, Math.round((Date.now() - new Date(iso).getTime()) / 1000))
|
const s = Math.max(0, Math.round((Date.now() - new Date(iso).getTime()) / 1000))
|
||||||
if (s < 60) return `${s} s ago`
|
if (s < 60) return u.ago(`${s} ${u.s}`)
|
||||||
if (s < 3600) return `${Math.floor(s / 60)} min ago`
|
if (s < 3600) return u.ago(`${Math.floor(s / 60)} ${u.min}`)
|
||||||
if (s < 86400) return `${Math.floor(s / 3600)} h ago`
|
if (s < 86400) return u.ago(`${Math.floor(s / 3600)} ${u.h}`)
|
||||||
return `${Math.floor(s / 86400)} d ago`
|
return u.ago(`${Math.floor(s / 86400)} ${u.d}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Length of a silence: 12 min, 3.5 h, 2.0 days. */
|
||||||
|
export function duration(seconds) {
|
||||||
|
const u = UNITS[lang]
|
||||||
|
if (seconds < 3600) return `${Math.floor(seconds / 60)} ${u.min}`
|
||||||
|
if (seconds < 86400) return `${num(seconds / 3600, 1)} ${u.h}`
|
||||||
|
return `${num(seconds / 86400, 1)} ${u.days}`
|
||||||
|
}
|
||||||
|
|
||||||
|
export function dateTime(iso) {
|
||||||
|
return new Date(iso).toLocaleString(locale())
|
||||||
}
|
}
|
||||||
|
|
||||||
export function pct(ratio) {
|
export function pct(ratio) {
|
||||||
@@ -48,12 +82,12 @@ export function pct(ratio) {
|
|||||||
|
|
||||||
export function timeLabel(unix, spanSeconds) {
|
export function timeLabel(unix, spanSeconds) {
|
||||||
const d = new Date(unix * 1000)
|
const d = new Date(unix * 1000)
|
||||||
if (spanSeconds <= 2 * 86400) return d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })
|
if (spanSeconds <= 2 * 86400) return d.toLocaleTimeString(locale(), { hour: '2-digit', minute: '2-digit' })
|
||||||
return d.toLocaleDateString([], { weekday: 'short', day: 'numeric' })
|
return d.toLocaleDateString(locale(), { weekday: 'short', day: 'numeric' })
|
||||||
}
|
}
|
||||||
|
|
||||||
export function dateTimeLabel(unix) {
|
export function dateTimeLabel(unix) {
|
||||||
return new Date(unix * 1000).toLocaleString([], {
|
return new Date(unix * 1000).toLocaleString(locale(), {
|
||||||
weekday: 'short',
|
weekday: 'short',
|
||||||
day: 'numeric',
|
day: 'numeric',
|
||||||
month: 'short',
|
month: 'short',
|
||||||
@@ -65,6 +99,6 @@ export function dateTimeLabel(unix) {
|
|||||||
export function dayLabel(isoDay, long = false) {
|
export function dayLabel(isoDay, long = false) {
|
||||||
const d = new Date(`${isoDay}T12:00:00`)
|
const d = new Date(`${isoDay}T12:00:00`)
|
||||||
return long
|
return long
|
||||||
? d.toLocaleDateString([], { weekday: 'short', day: 'numeric', month: 'short', year: 'numeric' })
|
? d.toLocaleDateString(locale(), { weekday: 'short', day: 'numeric', month: 'short', year: 'numeric' })
|
||||||
: d.toLocaleDateString([], { day: 'numeric', month: 'short' })
|
: d.toLocaleDateString(locale(), { day: 'numeric', month: 'short' })
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,479 @@
|
|||||||
|
import { createContext, useContext, useEffect, useMemo, useState } from 'react'
|
||||||
|
import { duration, pct, power, setFormatLanguage } from './format'
|
||||||
|
import { useSettings } from './settings'
|
||||||
|
|
||||||
|
export const LANGUAGES = [
|
||||||
|
{ code: 'el', label: 'Ελληνικά', short: 'ΕΛ' },
|
||||||
|
{ code: 'en', label: 'English', short: 'EN' },
|
||||||
|
]
|
||||||
|
|
||||||
|
const en = {
|
||||||
|
'app.title': 'Solar Monitor',
|
||||||
|
'live.connectionLost': 'Connection lost',
|
||||||
|
'live.live': 'Live · {ago}',
|
||||||
|
'live.dataloggerOffline': 'Datalogger offline',
|
||||||
|
'nav.settings': 'Settings',
|
||||||
|
'nav.install': 'Install',
|
||||||
|
'nav.switchLanguage': 'Ελληνικά',
|
||||||
|
|
||||||
|
'common.loading': 'Loading…',
|
||||||
|
'common.notAvailableYet': 'not available yet',
|
||||||
|
'common.notAvailable': 'not available',
|
||||||
|
'common.apiKey': 'API key',
|
||||||
|
'common.wrongKey': 'Wrong API key',
|
||||||
|
'common.save': 'Save',
|
||||||
|
'common.saving': 'Saving…',
|
||||||
|
'common.close': 'Close',
|
||||||
|
'common.never': 'never',
|
||||||
|
|
||||||
|
'hero.producingNow': 'Producing now',
|
||||||
|
'hero.today': 'Today',
|
||||||
|
'hero.todayEst': 'Today ≈',
|
||||||
|
'hero.lifetime': 'Lifetime',
|
||||||
|
'hero.lifetimePartial': 'Lifetime · {k} of {n}',
|
||||||
|
'hero.feeding': 'Feeding',
|
||||||
|
'alerts.label': 'Problems',
|
||||||
|
'banner.title': 'Site datalogger is not reporting',
|
||||||
|
'banner.body':
|
||||||
|
'Last data {when}. Check the on-site laptop and its internet connection — inverter states below are unknown.',
|
||||||
|
|
||||||
|
'power.range': 'Time range',
|
||||||
|
'power.smoothed': 'Smoothed',
|
||||||
|
'power.noData': 'No readings in this range',
|
||||||
|
'range.30m': 'last 30 min',
|
||||||
|
'range.1h': 'last hour',
|
||||||
|
'range.3h': 'last 3 hours',
|
||||||
|
'range.6h': 'last 6 hours',
|
||||||
|
'range.24h': 'last 24 h',
|
||||||
|
'range.run': 'last production run',
|
||||||
|
'range.3d': 'last 3 days',
|
||||||
|
'range.7d': 'last 7 days',
|
||||||
|
'range.30d': 'last month',
|
||||||
|
'chart.total': 'Total',
|
||||||
|
|
||||||
|
'energy.title': 'Daily energy · last 30 days',
|
||||||
|
'energy.total': '{v} total',
|
||||||
|
'energy.mode': 'Energy chart mode',
|
||||||
|
'energy.combined': 'Combined',
|
||||||
|
'energy.split': 'Per inverter',
|
||||||
|
'energy.allInverters': 'All inverters',
|
||||||
|
'energy.empty': 'No energy data yet',
|
||||||
|
'energy.footEstimated': '≈ Estimated from AC power for inverters without an energy counter',
|
||||||
|
'energy.axis': 'axis in kWh',
|
||||||
|
|
||||||
|
'dash.unreachable': "Can't reach the server: {msg}",
|
||||||
|
'dash.noInverters': 'No inverter has reported yet. Readings appear here as soon as the on-site poller posts to',
|
||||||
|
'dash.inverters': 'Inverters',
|
||||||
|
'dash.apiDocs': 'API documentation',
|
||||||
|
|
||||||
|
'cmp.title': 'Output comparison',
|
||||||
|
'cmp.latest': 'now',
|
||||||
|
'cmp.avg': 'avg of last {n}',
|
||||||
|
'cmp.perKwp': 'per kWp',
|
||||||
|
'cmp.vsMedian': 'vs median',
|
||||||
|
'cmp.vsBest': 'vs best',
|
||||||
|
'cmp.vsCustom': 'vs {v}',
|
||||||
|
'cmp.fullBar': 'Full bar = {v}',
|
||||||
|
'cmp.overScale': 'above the scale',
|
||||||
|
|
||||||
|
'state.ok': 'Operating',
|
||||||
|
'state.feeding': 'Feeding',
|
||||||
|
'state.standby': 'Standby',
|
||||||
|
'state.warning': 'Check needed',
|
||||||
|
'state.fault': 'Fault',
|
||||||
|
'state.offline': 'Offline',
|
||||||
|
'state.sleeping': 'Sleeping',
|
||||||
|
'state.unknown': 'No data',
|
||||||
|
'online.online': 'Online',
|
||||||
|
'online.offline': 'Offline',
|
||||||
|
|
||||||
|
'issue.not_responding': 'Not responding for {duration} while the datalogger is online',
|
||||||
|
'issue.not_responding_never': 'Has not reported yet while the datalogger is online',
|
||||||
|
'issue.error_code': 'Inverter reports error code {code}{text}',
|
||||||
|
'issue.underperforming': 'Producing {pct} of the fleet median — check strings, fuses and breakers',
|
||||||
|
'issue.mppt_imbalance': '{input} at {weak} vs {strong} on the other input — check that string',
|
||||||
|
'issue.datalogger_offline': 'No data from the site datalogger — inverter state unknown',
|
||||||
|
|
||||||
|
'card.temp': 'Temp',
|
||||||
|
'card.details': 'Details',
|
||||||
|
'card.acPhase': 'AC L-N',
|
||||||
|
'card.acLine': 'AC L-L ≈',
|
||||||
|
|
||||||
|
'detail.unknown': 'Unknown inverter “{id}”.',
|
||||||
|
'detail.back': 'Back to overview',
|
||||||
|
'detail.all': 'All inverters',
|
||||||
|
'detail.lastReading': 'last reading {ago}',
|
||||||
|
'detail.edit': 'Edit',
|
||||||
|
'detail.powerNow': 'Power now',
|
||||||
|
'detail.vsMedian': 'vs fleet median',
|
||||||
|
'detail.params': 'All parameters',
|
||||||
|
'detail.lastReadingAt': 'Last reading {when}',
|
||||||
|
'detail.noReadings': 'No readings yet',
|
||||||
|
'detail.stale': ' — values are from the last time it reported',
|
||||||
|
'detail.notSent': 'Not sent by this inverter',
|
||||||
|
'detail.power': 'Power',
|
||||||
|
'detail.historyRange': 'History range',
|
||||||
|
'detail.acOutput': 'AC output',
|
||||||
|
'detail.mpptNote':
|
||||||
|
'MPPT1 and MPPT2 should track each other when both carry similar strings — one dropping away from the other points at that string.',
|
||||||
|
'detail.noDc': 'DC input power (MPPT) is not available for this inverter.',
|
||||||
|
'detail.paramPicker': 'Parameter to chart',
|
||||||
|
'detail.noDataRange': 'No data in this range',
|
||||||
|
'detail.yearEnergy': 'Daily energy · last 365 days',
|
||||||
|
'detail.energy': 'Energy',
|
||||||
|
'detail.lineVoltage': '(L-L ≈)',
|
||||||
|
'rangeShort.24h': '24 h',
|
||||||
|
'rangeShort.7d': '7 days',
|
||||||
|
'rangeShort.30d': '30 days',
|
||||||
|
'group.ac': 'AC output',
|
||||||
|
'group.dc': 'DC input',
|
||||||
|
'group.energy': 'Energy',
|
||||||
|
'group.device': 'Device',
|
||||||
|
'group.extra': 'Other (unmapped)',
|
||||||
|
|
||||||
|
'edit.title': 'Inverter settings',
|
||||||
|
'edit.name': 'Display name',
|
||||||
|
'edit.idHint': 'ID sent by the poller: {id}',
|
||||||
|
'edit.kwp': 'Array size (kWp)',
|
||||||
|
'edit.mppt': 'MPPT inputs used',
|
||||||
|
'edit.kwpHint':
|
||||||
|
'Set the array size on every inverter to compare output per kWp — needed when the arrays differ. With one MPPT input in use, the string-imbalance check is skipped.',
|
||||||
|
'edit.sort': 'Sort order',
|
||||||
|
'edit.notes': 'Notes',
|
||||||
|
|
||||||
|
'settings.title': 'Settings',
|
||||||
|
'settings.shared': 'These settings apply to everyone who opens the dashboard.',
|
||||||
|
'settings.cmp': 'Output comparison',
|
||||||
|
'settings.readings': 'Value shown',
|
||||||
|
'settings.readingsHelp':
|
||||||
|
'A cloud passing over one array can make a single reading look far off. Averaging the last few readings evens that out. The local inverters report every minute and the cloud-connected one about every 5 minutes, so “last 5” covers ~5 min for the first and ~25 min for the second.',
|
||||||
|
'opt.readings.1': 'Latest reading',
|
||||||
|
'opt.readings.3': 'Average of last 3',
|
||||||
|
'opt.readings.5': 'Average of last 5',
|
||||||
|
'settings.scale': 'Bar scale',
|
||||||
|
'settings.scaleHelp':
|
||||||
|
'Auto: a full bar is a round number just above the strongest inverter. Highest = 100%: the strongest inverter fills the bar. Custom: the value below fills the bar — with 25 kW, an inverter at 12.5 kW shows half a bar.',
|
||||||
|
'opt.scale.auto': 'Auto',
|
||||||
|
'opt.scale.max': 'Highest = 100%',
|
||||||
|
'opt.scale.custom': 'Custom',
|
||||||
|
'settings.customKw': 'Custom value (kW)',
|
||||||
|
'settings.customKwHelp': 'Used by the Custom scale and the Custom percentage — e.g. the inverter rating, 20 kW.',
|
||||||
|
'settings.reference': 'Percentage compared to',
|
||||||
|
'settings.referenceHelp':
|
||||||
|
'Median: the middle inverter is 100%, so a weak one stands out. Best: the strongest inverter is 100%. Custom value: percentage of the kW above.',
|
||||||
|
'opt.reference.median': 'Fleet median',
|
||||||
|
'opt.reference.best': 'Best inverter',
|
||||||
|
'opt.reference.custom': 'Custom value',
|
||||||
|
'settings.customRequired': 'Enter a custom value in kW to use the Custom options.',
|
||||||
|
'settings.power': 'Power chart',
|
||||||
|
'settings.range': 'Default time range',
|
||||||
|
'settings.rangeHelp':
|
||||||
|
'“Last production run” is the latest stretch since the inverters woke up — today’s while the sun is up, yesterday’s at night. The range can also be changed on the chart for the current visit.',
|
||||||
|
'settings.smoothing': 'Smoothing',
|
||||||
|
'settings.smoothingHelp':
|
||||||
|
'Averages neighbouring points so passing clouds don’t draw sharp spikes. Light ≈ 3 points, strong ≈ 7 points.',
|
||||||
|
'opt.smoothing.off': 'Off',
|
||||||
|
'opt.smoothing.light': 'Light',
|
||||||
|
'opt.smoothing.strong': 'Strong',
|
||||||
|
'settings.display': 'Display',
|
||||||
|
'settings.voltage': 'AC voltage',
|
||||||
|
'settings.voltageHelp':
|
||||||
|
'The inverters report phase voltage (line-to-neutral, ~240 V). Their own screens show line-to-line voltage (~415 V, ×1.732).',
|
||||||
|
'opt.voltage.phase': 'Phase (L-N)',
|
||||||
|
'opt.voltage.line': 'Line (L-L), as on the inverter',
|
||||||
|
'settings.language': 'Language on this device',
|
||||||
|
'settings.languageHelp': 'Applies right away, only on this phone or browser.',
|
||||||
|
'settings.defaultLanguage': 'Default language for everyone',
|
||||||
|
'settings.defaultLanguageHelp': 'Used on devices where no language has been picked.',
|
||||||
|
'settings.saved': 'Saved — every viewer now sees these settings',
|
||||||
|
'settings.reset': 'Reset to defaults',
|
||||||
|
'settings.unsaved': 'Unsaved changes',
|
||||||
|
}
|
||||||
|
|
||||||
|
const el = {
|
||||||
|
'app.title': 'Παρακολούθηση Φ/Β',
|
||||||
|
'live.connectionLost': 'Χάθηκε η σύνδεση',
|
||||||
|
'live.live': 'Ζωντανά · {ago}',
|
||||||
|
'live.dataloggerOffline': 'Καταγραφικό εκτός σύνδεσης',
|
||||||
|
'nav.settings': 'Ρυθμίσεις',
|
||||||
|
'nav.install': 'Εγκατάσταση',
|
||||||
|
'nav.switchLanguage': 'English',
|
||||||
|
|
||||||
|
'common.loading': 'Φόρτωση…',
|
||||||
|
'common.notAvailableYet': 'δεν είναι διαθέσιμο ακόμα',
|
||||||
|
'common.notAvailable': 'μη διαθέσιμο',
|
||||||
|
'common.apiKey': 'Κλειδί API',
|
||||||
|
'common.wrongKey': 'Λάθος κλειδί API',
|
||||||
|
'common.save': 'Αποθήκευση',
|
||||||
|
'common.saving': 'Αποθήκευση…',
|
||||||
|
'common.close': 'Κλείσιμο',
|
||||||
|
'common.never': 'ποτέ',
|
||||||
|
|
||||||
|
'hero.producingNow': 'Παραγωγή τώρα',
|
||||||
|
'hero.today': 'Σήμερα',
|
||||||
|
'hero.todayEst': 'Σήμερα ≈',
|
||||||
|
'hero.lifetime': 'Συνολικά',
|
||||||
|
'hero.lifetimePartial': 'Συνολικά · {k} από {n}',
|
||||||
|
'hero.feeding': 'Σε παραγωγή',
|
||||||
|
'alerts.label': 'Προβλήματα',
|
||||||
|
'banner.title': 'Το καταγραφικό της εγκατάστασης δεν στέλνει δεδομένα',
|
||||||
|
'banner.body':
|
||||||
|
'Τελευταία δεδομένα: {when}. Ελέγξτε τον υπολογιστή στην εγκατάσταση και τη σύνδεσή του στο διαδίκτυο — η κατάσταση των μετατροπέων παρακάτω είναι άγνωστη.',
|
||||||
|
|
||||||
|
'power.range': 'Χρονικό διάστημα',
|
||||||
|
'power.smoothed': 'Εξομαλυμένο',
|
||||||
|
'power.noData': 'Δεν υπάρχουν μετρήσεις σε αυτό το διάστημα',
|
||||||
|
'range.30m': 'τελευταία 30 λεπτά',
|
||||||
|
'range.1h': 'τελευταία ώρα',
|
||||||
|
'range.3h': 'τελευταίες 3 ώρες',
|
||||||
|
'range.6h': 'τελευταίες 6 ώρες',
|
||||||
|
'range.24h': 'τελευταίες 24 ώρες',
|
||||||
|
'range.run': 'τελευταίος κύκλος παραγωγής',
|
||||||
|
'range.3d': 'τελευταίες 3 ημέρες',
|
||||||
|
'range.7d': 'τελευταίες 7 ημέρες',
|
||||||
|
'range.30d': 'τελευταίος μήνας',
|
||||||
|
'chart.total': 'Σύνολο',
|
||||||
|
|
||||||
|
'energy.title': 'Ημερήσια ενέργεια · τελευταίες 30 ημέρες',
|
||||||
|
'energy.total': '{v} συνολικά',
|
||||||
|
'energy.mode': 'Προβολή ενέργειας',
|
||||||
|
'energy.combined': 'Συνολικά',
|
||||||
|
'energy.split': 'Ανά μετατροπέα',
|
||||||
|
'energy.allInverters': 'Όλοι οι μετατροπείς',
|
||||||
|
'energy.empty': 'Δεν υπάρχουν ακόμα δεδομένα ενέργειας',
|
||||||
|
'energy.footEstimated': '≈ Εκτίμηση από την ισχύ AC για μετατροπείς χωρίς μετρητή ενέργειας',
|
||||||
|
'energy.axis': 'άξονας σε kWh',
|
||||||
|
|
||||||
|
'dash.unreachable': 'Δεν είναι δυνατή η σύνδεση με τον διακομιστή: {msg}',
|
||||||
|
'dash.noInverters':
|
||||||
|
'Κανένας μετατροπέας δεν έχει στείλει δεδομένα ακόμα. Οι μετρήσεις εμφανίζονται εδώ μόλις το καταγραφικό στείλει στο',
|
||||||
|
'dash.inverters': 'Μετατροπείς',
|
||||||
|
'dash.apiDocs': 'Τεκμηρίωση API',
|
||||||
|
|
||||||
|
'cmp.title': 'Σύγκριση παραγωγής',
|
||||||
|
'cmp.latest': 'τώρα',
|
||||||
|
'cmp.avg': 'μ.ό. τελευταίων {n}',
|
||||||
|
'cmp.perKwp': 'ανά kWp',
|
||||||
|
'cmp.vsMedian': 'έναντι διαμέσου',
|
||||||
|
'cmp.vsBest': 'έναντι καλύτερου',
|
||||||
|
'cmp.vsCustom': 'έναντι {v}',
|
||||||
|
'cmp.fullBar': 'Πλήρης μπάρα = {v}',
|
||||||
|
'cmp.overScale': 'πάνω από την κλίμακα',
|
||||||
|
|
||||||
|
'state.ok': 'Σε λειτουργία',
|
||||||
|
'state.feeding': 'Παράγει',
|
||||||
|
'state.standby': 'Αναμονή',
|
||||||
|
'state.warning': 'Χρειάζεται έλεγχο',
|
||||||
|
'state.fault': 'Βλάβη',
|
||||||
|
'state.offline': 'Εκτός σύνδεσης',
|
||||||
|
'state.sleeping': 'Αδράνεια (νύχτα)',
|
||||||
|
'state.unknown': 'Χωρίς δεδομένα',
|
||||||
|
'online.online': 'Σε σύνδεση',
|
||||||
|
'online.offline': 'Εκτός σύνδεσης',
|
||||||
|
|
||||||
|
'issue.not_responding': 'Δεν αποκρίνεται εδώ και {duration}, ενώ το καταγραφικό λειτουργεί',
|
||||||
|
'issue.not_responding_never': 'Δεν έχει στείλει δεδομένα ακόμα, ενώ το καταγραφικό λειτουργεί',
|
||||||
|
'issue.error_code': 'Ο μετατροπέας αναφέρει κωδικό σφάλματος {code}{text}',
|
||||||
|
'issue.underperforming': 'Παράγει το {pct} της διαμέσου — ελέγξτε strings, ασφάλειες και διακόπτες',
|
||||||
|
'issue.mppt_imbalance': '{input}: {weak} έναντι {strong} στην άλλη είσοδο — ελέγξτε αυτό το string',
|
||||||
|
'issue.datalogger_offline': 'Δεν υπάρχουν δεδομένα από το καταγραφικό — άγνωστη κατάσταση μετατροπέα',
|
||||||
|
|
||||||
|
'card.temp': 'Θερμ.',
|
||||||
|
'card.details': 'Λεπτομέρειες',
|
||||||
|
'card.acPhase': 'AC L-N',
|
||||||
|
'card.acLine': 'AC L-L ≈',
|
||||||
|
|
||||||
|
'detail.unknown': 'Άγνωστος μετατροπέας «{id}».',
|
||||||
|
'detail.back': 'Επιστροφή στην επισκόπηση',
|
||||||
|
'detail.all': 'Όλοι οι μετατροπείς',
|
||||||
|
'detail.lastReading': 'τελευταία μέτρηση {ago}',
|
||||||
|
'detail.edit': 'Επεξεργασία',
|
||||||
|
'detail.powerNow': 'Ισχύς τώρα',
|
||||||
|
'detail.vsMedian': 'έναντι διαμέσου',
|
||||||
|
'detail.params': 'Όλες οι παράμετροι',
|
||||||
|
'detail.lastReadingAt': 'Τελευταία μέτρηση {when}',
|
||||||
|
'detail.noReadings': 'Δεν υπάρχουν μετρήσεις ακόμα',
|
||||||
|
'detail.stale': ' — οι τιμές είναι από την τελευταία φορά που ανέφερε',
|
||||||
|
'detail.notSent': 'Δεν αποστέλλεται από αυτόν τον μετατροπέα',
|
||||||
|
'detail.power': 'Ισχύς',
|
||||||
|
'detail.historyRange': 'Εύρος ιστορικού',
|
||||||
|
'detail.acOutput': 'Έξοδος AC',
|
||||||
|
'detail.mpptNote':
|
||||||
|
'Τα MPPT1 και MPPT2 πρέπει να κινούνται μαζί όταν έχουν παρόμοια strings — αν το ένα πέσει σε σχέση με το άλλο, ελέγξτε εκείνο το string.',
|
||||||
|
'detail.noDc': 'Η ισχύς εισόδου DC (MPPT) δεν είναι διαθέσιμη για αυτόν τον μετατροπέα.',
|
||||||
|
'detail.paramPicker': 'Παράμετρος γραφήματος',
|
||||||
|
'detail.noDataRange': 'Δεν υπάρχουν δεδομένα σε αυτό το διάστημα',
|
||||||
|
'detail.yearEnergy': 'Ημερήσια ενέργεια · τελευταίες 365 ημέρες',
|
||||||
|
'detail.energy': 'Ενέργεια',
|
||||||
|
'detail.lineVoltage': '(L-L ≈)',
|
||||||
|
'rangeShort.24h': '24 ώρες',
|
||||||
|
'rangeShort.7d': '7 ημέρες',
|
||||||
|
'rangeShort.30d': '30 ημέρες',
|
||||||
|
'group.ac': 'Έξοδος AC',
|
||||||
|
'group.dc': 'Είσοδος DC',
|
||||||
|
'group.energy': 'Ενέργεια',
|
||||||
|
'group.device': 'Συσκευή',
|
||||||
|
'group.extra': 'Άλλα (μη αντιστοιχισμένα)',
|
||||||
|
|
||||||
|
'edit.title': 'Ρυθμίσεις μετατροπέα',
|
||||||
|
'edit.name': 'Όνομα εμφάνισης',
|
||||||
|
'edit.idHint': 'Αναγνωριστικό από το καταγραφικό: {id}',
|
||||||
|
'edit.kwp': 'Ισχύς πεδίου (kWp)',
|
||||||
|
'edit.mppt': 'Είσοδοι MPPT σε χρήση',
|
||||||
|
'edit.kwpHint':
|
||||||
|
'Ορίστε την ισχύ πεδίου σε κάθε μετατροπέα για σύγκριση ανά kWp — απαραίτητο όταν τα πεδία διαφέρουν. Με μία είσοδο MPPT ο έλεγχος ανισορροπίας string παραλείπεται.',
|
||||||
|
'edit.sort': 'Σειρά ταξινόμησης',
|
||||||
|
'edit.notes': 'Σημειώσεις',
|
||||||
|
|
||||||
|
'settings.title': 'Ρυθμίσεις',
|
||||||
|
'settings.shared': 'Οι ρυθμίσεις ισχύουν για όλους όσοι ανοίγουν την εφαρμογή.',
|
||||||
|
'settings.cmp': 'Σύγκριση παραγωγής',
|
||||||
|
'settings.readings': 'Τιμή που εμφανίζεται',
|
||||||
|
'settings.readingsHelp':
|
||||||
|
'Ένα σύννεφο πάνω από ένα πεδίο μπορεί να κάνει μία μεμονωμένη μέτρηση να φαίνεται πολύ χαμηλή. Ο μέσος όρος των τελευταίων μετρήσεων το εξομαλύνει. Οι τοπικοί μετατροπείς στέλνουν κάθε λεπτό και αυτός μέσω cloud περίπου κάθε 5 λεπτά, οπότε οι «τελευταίες 5» καλύπτουν ~5 λεπτά για τους πρώτους και ~25 λεπτά για τον δεύτερο.',
|
||||||
|
'opt.readings.1': 'Τελευταία μέτρηση',
|
||||||
|
'opt.readings.3': 'Μ.ό. τελευταίων 3',
|
||||||
|
'opt.readings.5': 'Μ.ό. τελευταίων 5',
|
||||||
|
'settings.scale': 'Κλίμακα μπάρας',
|
||||||
|
'settings.scaleHelp':
|
||||||
|
'Αυτόματη: γεμάτη μπάρα είναι ένας στρογγυλός αριθμός λίγο πάνω από τον ισχυρότερο μετατροπέα. Μέγιστο = 100%: ο ισχυρότερος γεμίζει τη μπάρα. Προσαρμοσμένη: η τιμή παρακάτω γεμίζει τη μπάρα — με 25 kW, ένας μετατροπέας στα 12,5 kW δείχνει μισή μπάρα.',
|
||||||
|
'opt.scale.auto': 'Αυτόματη',
|
||||||
|
'opt.scale.max': 'Μέγιστο = 100%',
|
||||||
|
'opt.scale.custom': 'Προσαρμοσμένη',
|
||||||
|
'settings.customKw': 'Προσαρμοσμένη τιμή (kW)',
|
||||||
|
'settings.customKwHelp':
|
||||||
|
'Χρησιμοποιείται από την προσαρμοσμένη κλίμακα και το προσαρμοσμένο ποσοστό — π.χ. η ονομαστική ισχύς του μετατροπέα, 20 kW.',
|
||||||
|
'settings.reference': 'Ποσοστό σε σχέση με',
|
||||||
|
'settings.referenceHelp':
|
||||||
|
'Διάμεσος: ο μεσαίος μετατροπέας είναι 100%, ώστε ένας αδύναμος να ξεχωρίζει. Καλύτερος: ο ισχυρότερος είναι 100%. Προσαρμοσμένη τιμή: ποσοστό επί των kW παραπάνω.',
|
||||||
|
'opt.reference.median': 'Διάμεσος',
|
||||||
|
'opt.reference.best': 'Καλύτερος μετατροπέας',
|
||||||
|
'opt.reference.custom': 'Προσαρμοσμένη τιμή',
|
||||||
|
'settings.customRequired': 'Συμπληρώστε προσαρμοσμένη τιμή σε kW για τις προσαρμοσμένες επιλογές.',
|
||||||
|
'settings.power': 'Γράφημα ισχύος',
|
||||||
|
'settings.range': 'Προεπιλεγμένο διάστημα',
|
||||||
|
'settings.rangeHelp':
|
||||||
|
'Ο «τελευταίος κύκλος παραγωγής» είναι το διάστημα από τότε που ξύπνησαν οι μετατροπείς — ο σημερινός όσο έχει ήλιο, ο χθεσινός τη νύχτα. Το διάστημα αλλάζει και πάνω στο γράφημα, μόνο για την τρέχουσα επίσκεψη.',
|
||||||
|
'settings.smoothing': 'Εξομάλυνση',
|
||||||
|
'settings.smoothingHelp':
|
||||||
|
'Υπολογίζει μέσο όρο γειτονικών σημείων ώστε τα σύννεφα να μη σχεδιάζουν απότομες αιχμές. Ελαφριά ≈ 3 σημεία, έντονη ≈ 7 σημεία.',
|
||||||
|
'opt.smoothing.off': 'Ανενεργή',
|
||||||
|
'opt.smoothing.light': 'Ελαφριά',
|
||||||
|
'opt.smoothing.strong': 'Έντονη',
|
||||||
|
'settings.display': 'Εμφάνιση',
|
||||||
|
'settings.voltage': 'Τάση AC',
|
||||||
|
'settings.voltageHelp':
|
||||||
|
'Οι μετατροπείς στέλνουν φασική τάση (φάση-ουδέτερος, ~240 V). Οι οθόνες τους δείχνουν πολική τάση (φάση-φάση, ~415 V, ×1,732).',
|
||||||
|
'opt.voltage.phase': 'Φασική (L-N)',
|
||||||
|
'opt.voltage.line': 'Πολική (L-L), όπως στην οθόνη',
|
||||||
|
'settings.language': 'Γλώσσα σε αυτή τη συσκευή',
|
||||||
|
'settings.languageHelp': 'Εφαρμόζεται αμέσως, μόνο σε αυτό το κινητό ή πρόγραμμα περιήγησης.',
|
||||||
|
'settings.defaultLanguage': 'Προεπιλεγμένη γλώσσα για όλους',
|
||||||
|
'settings.defaultLanguageHelp': 'Χρησιμοποιείται στις συσκευές όπου δεν έχει επιλεγεί γλώσσα.',
|
||||||
|
'settings.saved': 'Αποθηκεύτηκε — όλοι βλέπουν πλέον αυτές τις ρυθμίσεις',
|
||||||
|
'settings.reset': 'Επαναφορά προεπιλογών',
|
||||||
|
'settings.unsaved': 'Μη αποθηκευμένες αλλαγές',
|
||||||
|
|
||||||
|
// Parameter labels (English comes from /api/meta/fields)
|
||||||
|
'field.ac_power_total_w': 'Ισχύς AC',
|
||||||
|
'field.ac_voltage_l1_v': 'Τάση AC L1',
|
||||||
|
'field.ac_voltage_l2_v': 'Τάση AC L2',
|
||||||
|
'field.ac_voltage_l3_v': 'Τάση AC L3',
|
||||||
|
'field.ac_current_l1_a': 'Ρεύμα AC L1',
|
||||||
|
'field.ac_current_l2_a': 'Ρεύμα AC L2',
|
||||||
|
'field.ac_current_l3_a': 'Ρεύμα AC L3',
|
||||||
|
'field.grid_frequency_hz': 'Συχνότητα δικτύου',
|
||||||
|
'field.dc_voltage_mppt1_v': 'Τάση DC MPPT1',
|
||||||
|
'field.dc_voltage_mppt2_v': 'Τάση DC MPPT2',
|
||||||
|
'field.dc_current_mppt1_a': 'Ρεύμα DC MPPT1',
|
||||||
|
'field.dc_current_mppt2_a': 'Ρεύμα DC MPPT2',
|
||||||
|
'field.temperature_c': 'Θερμοκρασία',
|
||||||
|
'field.status_code': 'Κωδικός κατάστασης',
|
||||||
|
'field.error_code': 'Κωδικός σφάλματος',
|
||||||
|
'field.status_text': 'Κατάσταση',
|
||||||
|
'field.daily_energy_wh': 'Ενέργεια σήμερα',
|
||||||
|
'field.total_energy_wh': 'Συνολική ενέργεια',
|
||||||
|
'field.dc_power_mppt1_w': 'Ισχύς DC MPPT1',
|
||||||
|
'field.dc_power_mppt2_w': 'Ισχύς DC MPPT2',
|
||||||
|
'field.dc_power_total_w': 'Συνολική ισχύς DC',
|
||||||
|
'field.efficiency_pct': 'Απόδοση μετατροπής',
|
||||||
|
}
|
||||||
|
|
||||||
|
const DICT = { en, el }
|
||||||
|
const STORAGE = 'solar.lang'
|
||||||
|
|
||||||
|
function storedLang() {
|
||||||
|
try {
|
||||||
|
const v = localStorage.getItem(STORAGE)
|
||||||
|
return DICT[v] ? v : null
|
||||||
|
} catch {
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function interpolate(s, params) {
|
||||||
|
if (!params) return s
|
||||||
|
return s.replace(/\{(\w+)\}/g, (m, k) => (params[k] ?? m).toString())
|
||||||
|
}
|
||||||
|
|
||||||
|
const LangContext = createContext(null)
|
||||||
|
|
||||||
|
/** Language: the one picked on this device, else the shared default from
|
||||||
|
* the settings page. */
|
||||||
|
export function LanguageProvider({ children }) {
|
||||||
|
const { settings } = useSettings()
|
||||||
|
const [chosen, setChosen] = useState(storedLang)
|
||||||
|
const lang = chosen ?? (DICT[settings.default_language] ? settings.default_language : 'el')
|
||||||
|
// Before children render, so every number/date below uses this language
|
||||||
|
setFormatLanguage(lang)
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
document.documentElement.lang = lang
|
||||||
|
}, [lang])
|
||||||
|
|
||||||
|
const value = useMemo(() => {
|
||||||
|
const dict = DICT[lang]
|
||||||
|
const t = (key, params) => interpolate(dict[key] ?? en[key] ?? key, params)
|
||||||
|
return {
|
||||||
|
lang,
|
||||||
|
t,
|
||||||
|
/** Translation if there is one, else the given fallback (API labels). */
|
||||||
|
tOr: (key, fallback) => dict[key] ?? fallback,
|
||||||
|
setLang: (l) => {
|
||||||
|
try {
|
||||||
|
localStorage.setItem(STORAGE, l)
|
||||||
|
} catch {
|
||||||
|
/* not remembered */
|
||||||
|
}
|
||||||
|
setChosen(l)
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}, [lang])
|
||||||
|
return <LangContext.Provider value={value}>{children}</LangContext.Provider>
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useT() {
|
||||||
|
return useContext(LangContext)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** An issue from /api/summary in the current language, from its code and
|
||||||
|
* params; the server's English message when the code is unknown. */
|
||||||
|
export function issueText(t, issue) {
|
||||||
|
const p = issue.params ?? {}
|
||||||
|
switch (issue.code) {
|
||||||
|
case 'not_responding':
|
||||||
|
return p.seconds == null ? t('issue.not_responding_never') : t('issue.not_responding', { duration: duration(p.seconds) })
|
||||||
|
case 'error_code':
|
||||||
|
return t('issue.error_code', { code: p.error_code, text: p.status_text ? ` (${p.status_text})` : '' })
|
||||||
|
case 'underperforming':
|
||||||
|
return p.relative == null ? issue.message : t('issue.underperforming', { pct: pct(p.relative) })
|
||||||
|
case 'mppt_imbalance':
|
||||||
|
return p.weak_w == null
|
||||||
|
? issue.message
|
||||||
|
: t('issue.mppt_imbalance', { input: p.input, weak: power(p.weak_w), strong: power(p.strong_w) })
|
||||||
|
case 'datalogger_offline':
|
||||||
|
return t('issue.datalogger_offline')
|
||||||
|
default:
|
||||||
|
return issue.message
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,63 @@
|
|||||||
|
import { createContext, useContext, useMemo } from 'react'
|
||||||
|
import { usePoll } from '../hooks/usePoll'
|
||||||
|
import { api } from './api'
|
||||||
|
|
||||||
|
/** Same defaults as ViewSettings in backend/app/schemas.py — used until the
|
||||||
|
* server answers, and for keys an older backend doesn't know. */
|
||||||
|
export const DEFAULT_SETTINGS = {
|
||||||
|
comparison_readings: 1,
|
||||||
|
comparison_scale: 'auto',
|
||||||
|
comparison_custom_kw: null,
|
||||||
|
comparison_reference: 'median',
|
||||||
|
power_range: '24h',
|
||||||
|
power_smoothing: 'off',
|
||||||
|
voltage_display: 'phase',
|
||||||
|
default_language: 'el',
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fleet power chart ranges (keys = ViewSettings.power_range)
|
||||||
|
export const POWER_RANGES = {
|
||||||
|
'30m': { seconds: 1800 },
|
||||||
|
'1h': { seconds: 3600 },
|
||||||
|
'3h': { seconds: 3 * 3600 },
|
||||||
|
'6h': { seconds: 6 * 3600 },
|
||||||
|
'24h': { seconds: 86400 },
|
||||||
|
run: { lastRun: true },
|
||||||
|
'3d': { seconds: 3 * 86400 },
|
||||||
|
'7d': { seconds: 7 * 86400 },
|
||||||
|
'30d': { seconds: 30 * 86400 },
|
||||||
|
}
|
||||||
|
|
||||||
|
const SettingsContext = createContext({ settings: DEFAULT_SETTINGS, loaded: false, save: async () => {} })
|
||||||
|
|
||||||
|
/** Dashboard display options. Stored on the server and shared by every
|
||||||
|
* viewer; re-read every few minutes so a change shows up on other phones. */
|
||||||
|
export function SettingsProvider({ children }) {
|
||||||
|
const poll = usePoll(() => api.settings(), 300_000)
|
||||||
|
const { data, error, refresh } = poll
|
||||||
|
const value = useMemo(
|
||||||
|
() => ({
|
||||||
|
settings: { ...DEFAULT_SETTINGS, ...(data ?? {}) },
|
||||||
|
// An unreachable settings endpoint must not keep the charts from loading
|
||||||
|
loaded: data !== null || error !== null,
|
||||||
|
save: async (next) => {
|
||||||
|
const saved = await api.saveSettings(next)
|
||||||
|
await refresh()
|
||||||
|
return saved
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
[data, error, refresh],
|
||||||
|
)
|
||||||
|
return <SettingsContext.Provider value={value}>{children}</SettingsContext.Provider>
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useSettings() {
|
||||||
|
return useContext(SettingsContext)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** AC voltage as configured: phase (L-N) as sent, or line-to-line (×√3) to
|
||||||
|
* match what the inverter screens show. */
|
||||||
|
export function displayVoltage(v, settings) {
|
||||||
|
if (v === null || v === undefined) return v
|
||||||
|
return settings.voltage_display === 'line' ? v * Math.sqrt(3) : v
|
||||||
|
}
|
||||||
@@ -2,12 +2,18 @@ import { StrictMode } from 'react'
|
|||||||
import { createRoot } from 'react-dom/client'
|
import { createRoot } from 'react-dom/client'
|
||||||
import { BrowserRouter } from 'react-router-dom'
|
import { BrowserRouter } from 'react-router-dom'
|
||||||
import App from './App'
|
import App from './App'
|
||||||
|
import { LanguageProvider } from './lib/i18n'
|
||||||
|
import { SettingsProvider } from './lib/settings'
|
||||||
import './index.css'
|
import './index.css'
|
||||||
|
|
||||||
createRoot(document.getElementById('root')).render(
|
createRoot(document.getElementById('root')).render(
|
||||||
<StrictMode>
|
<StrictMode>
|
||||||
<BrowserRouter>
|
<BrowserRouter>
|
||||||
|
<SettingsProvider>
|
||||||
|
<LanguageProvider>
|
||||||
<App />
|
<App />
|
||||||
|
</LanguageProvider>
|
||||||
|
</SettingsProvider>
|
||||||
</BrowserRouter>
|
</BrowserRouter>
|
||||||
</StrictMode>,
|
</StrictMode>,
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -1,45 +1,58 @@
|
|||||||
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'
|
||||||
import InverterCard from '../components/InverterCard'
|
import InverterCard from '../components/InverterCard'
|
||||||
import Segmented from '../components/Segmented'
|
import Segmented from '../components/Segmented'
|
||||||
import { usePoll } from '../hooks/usePoll'
|
import { usePoll } from '../hooks/usePoll'
|
||||||
import { api } from '../lib/api'
|
import { api, isoAgo } from '../lib/api'
|
||||||
import { seriesColor, useThemeColors } from '../lib/colors'
|
import { seriesColor, useThemeColors } from '../lib/colors'
|
||||||
import { energy, energyParts, num, power, powerParts } from '../lib/format'
|
import { dateTime, energy, energyParts, num, power, powerParts } from '../lib/format'
|
||||||
|
import { useT } from '../lib/i18n'
|
||||||
|
import { POWER_RANGES, useSettings } from '../lib/settings'
|
||||||
|
|
||||||
function Hero({ summary }) {
|
function Hero({ summary }) {
|
||||||
|
const { t: tr } = useT()
|
||||||
const t = summary.totals
|
const t = summary.totals
|
||||||
|
// Only some units have a lifetime counter (today: INV5) — say so
|
||||||
|
const withLifetime = summary.inverters.filter((st) => st.latest?.total_energy_wh != null).length
|
||||||
const [pw, pu] = powerParts(t.ac_power_w)
|
const [pw, pu] = powerParts(t.ac_power_w)
|
||||||
const [today, todayU] = energyParts(t.daily_energy_wh)
|
const [today, todayU] = energyParts(t.daily_energy_wh)
|
||||||
const [life, lifeU] = energyParts(t.total_energy_wh)
|
const [life, lifeU] = energyParts(t.total_energy_wh)
|
||||||
return (
|
return (
|
||||||
<section className="card p-5">
|
<section className="card p-5">
|
||||||
<div className="text-xs font-medium uppercase tracking-wide text-muted">Producing now</div>
|
<div className="text-xs font-medium uppercase tracking-wide text-muted">{tr('hero.producingNow')}</div>
|
||||||
<div className="mt-1 flex items-baseline gap-2 tnum">
|
<div className="mt-1 flex items-baseline gap-2 tnum">
|
||||||
<span className="text-5xl font-semibold tracking-tight sm:text-6xl">{pw}</span>
|
<span className="text-5xl font-semibold tracking-tight sm:text-6xl">{pw}</span>
|
||||||
<span className="text-xl text-ink-2">{pu}</span>
|
<span className="text-xl text-ink-2">{pu}</span>
|
||||||
</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">{tr(t.daily_energy_estimated ? 'hero.todayEst' : 'hero.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">
|
||||||
|
{withLifetime && withLifetime < t.inverter_count
|
||||||
|
? tr('hero.lifetimePartial', { k: withLifetime, n: t.inverter_count })
|
||||||
|
: tr('hero.lifetime')}
|
||||||
|
</dt>
|
||||||
|
{t.total_energy_wh == null ? (
|
||||||
|
<dd className="text-xs leading-7 text-muted">{tr('common.notAvailableYet')}</dd>
|
||||||
|
) : (
|
||||||
<dd className="tnum">
|
<dd className="tnum">
|
||||||
<span className="text-lg font-semibold">{life}</span> <span className="text-ink-2">{lifeU}</span>
|
<span className="text-lg font-semibold">{life}</span> <span className="text-ink-2">{lifeU}</span>
|
||||||
</dd>
|
</dd>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
<div>
|
<div>
|
||||||
<dt className="text-xs text-muted">Online</dt>
|
<dt className="text-xs text-muted">{tr('hero.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>
|
||||||
@@ -49,46 +62,55 @@ function Hero({ summary }) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function Alerts({ summary }) {
|
function Alerts({ summary }) {
|
||||||
|
const { t } = useT()
|
||||||
const items = summary.inverters.flatMap((st) =>
|
const items = summary.inverters.flatMap((st) =>
|
||||||
st.health.issues
|
st.health.issues
|
||||||
.filter((i) => i.severity !== 'info')
|
.filter((i) => i.severity !== 'info')
|
||||||
.map((i) => ({ ...i, code: `${st.inverter.id}:${i.code}`, message: `${st.inverter.name}: ${i.message}` })),
|
.map((i) => ({ ...i, key: `${st.inverter.id}:${i.code}`, who: st.inverter.name })),
|
||||||
)
|
)
|
||||||
if (!items.length) return null
|
if (!items.length) return null
|
||||||
return (
|
return (
|
||||||
<section aria-label="Problems">
|
<section aria-label={t('alerts.label')}>
|
||||||
<IssueList issues={items} />
|
<IssueList issues={items} />
|
||||||
</section>
|
</section>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
function DataloggerBanner({ summary }) {
|
function DataloggerBanner({ summary }) {
|
||||||
|
const { t } = useT()
|
||||||
if (summary.datalogger.online) return null
|
if (summary.datalogger.online) return null
|
||||||
return (
|
return (
|
||||||
<div className="flex items-start gap-2 rounded-xl bg-[var(--critical-wash)] px-4 py-3 text-sm">
|
<div className="flex items-start gap-2 rounded-xl bg-[var(--critical-wash)] px-4 py-3 text-sm">
|
||||||
<Icon name="offline" size={18} className="mt-px text-crit" />
|
<Icon name="offline" size={18} className="mt-px text-crit" />
|
||||||
<div>
|
<div>
|
||||||
<div className="font-semibold">Site datalogger is not reporting</div>
|
<div className="font-semibold">{t('banner.title')}</div>
|
||||||
<div className="text-ink-2">
|
<div className="text-ink-2">
|
||||||
Last data {summary.datalogger.last_ingest_at ? new Date(summary.datalogger.last_ingest_at).toLocaleString() : 'never'}.
|
{t('banner.body', {
|
||||||
Check the on-site laptop and its internet connection — inverter states below are unknown.
|
when: summary.datalogger.last_ingest_at ? dateTime(summary.datalogger.last_ingest_at) : t('common.never'),
|
||||||
|
})}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
function PowerCard({ ids, names }) {
|
const capitalize = (s) => s.charAt(0).toUpperCase() + s.slice(1)
|
||||||
const c = useThemeColors()
|
|
||||||
const { data } = usePoll(() => api.power(), 60_000)
|
function PowerChart({ range, series, smoothing }) {
|
||||||
const series = ids.map((id) => ({ key: id, name: names[id] ?? id, color: seriesColor(c, ids, id) }))
|
const { t } = useT()
|
||||||
|
const r = POWER_RANGES[range] ?? POWER_RANGES['24h']
|
||||||
|
// Long ranges change slowly — no need to refetch them every minute
|
||||||
|
const every = r.seconds > 86400 ? 300_000 : 60_000
|
||||||
|
const { data } = usePoll(
|
||||||
|
() => api.power(r.lastRun ? { last_run: true } : { from: isoAgo(r.seconds) }),
|
||||||
|
every,
|
||||||
|
range,
|
||||||
|
)
|
||||||
|
if (!data) return <div className="h-60" />
|
||||||
|
if (!data.points.length) {
|
||||||
|
return <div className="flex h-60 items-center justify-center text-sm text-muted">{t('power.noData')}</div>
|
||||||
|
}
|
||||||
return (
|
return (
|
||||||
<section className="card p-4">
|
|
||||||
<div className="mb-3 flex flex-wrap items-baseline justify-between gap-2">
|
|
||||||
<h2 className="text-sm font-semibold">Power · last 24 h</h2>
|
|
||||||
<Legend series={series} />
|
|
||||||
</div>
|
|
||||||
{data ? (
|
|
||||||
<TimeLines
|
<TimeLines
|
||||||
points={data.points}
|
points={data.points}
|
||||||
series={series}
|
series={series}
|
||||||
@@ -98,37 +120,77 @@ function PowerCard({ ids, names }) {
|
|||||||
format={power}
|
format={power}
|
||||||
axisFormat={(w) => num(w / 1000, 0) + ' kW'}
|
axisFormat={(w) => num(w / 1000, 0) + ' kW'}
|
||||||
showTotal
|
showTotal
|
||||||
|
smoothing={smoothing}
|
||||||
/>
|
/>
|
||||||
) : (
|
)
|
||||||
<div className="h-60" />
|
}
|
||||||
)}
|
|
||||||
|
function PowerCard({ ids, names }) {
|
||||||
|
const c = useThemeColors()
|
||||||
|
const { t } = useT()
|
||||||
|
const { settings, loaded } = useSettings()
|
||||||
|
// The saved range is the default; switching here lasts for this visit only
|
||||||
|
const [picked, setPicked] = useState(null)
|
||||||
|
const range = picked ?? settings.power_range
|
||||||
|
const smoothing = settings.power_smoothing
|
||||||
|
const series = ids.map((id) => ({ key: id, name: names[id] ?? id, color: seriesColor(c, ids, id) }))
|
||||||
|
return (
|
||||||
|
<section className="card p-4">
|
||||||
|
<div className="mb-3 flex flex-wrap items-center justify-between gap-2">
|
||||||
|
<div className="flex flex-wrap items-center gap-x-2 gap-y-1">
|
||||||
|
<h2 className="text-sm font-semibold">{t('detail.power')}</h2>
|
||||||
|
<select
|
||||||
|
value={range}
|
||||||
|
onChange={(e) => setPicked(e.target.value)}
|
||||||
|
aria-label={t('power.range')}
|
||||||
|
className="min-h-8 rounded-lg border border-line bg-surface-2 px-1.5 text-sm"
|
||||||
|
>
|
||||||
|
{Object.keys(POWER_RANGES).map((k) => (
|
||||||
|
<option key={k} value={k}>
|
||||||
|
{capitalize(t(`range.${k}`))}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
{smoothing !== 'off' && <span className="text-xs text-muted">· {t('power.smoothed')}</span>}
|
||||||
|
</div>
|
||||||
|
<Legend series={series} />
|
||||||
|
</div>
|
||||||
|
{loaded ? <PowerChart range={range} series={series} smoothing={smoothing} /> : <div className="h-60" />}
|
||||||
</section>
|
</section>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
function EnergyCard({ ids, names }) {
|
function EnergyCard({ ids, names }) {
|
||||||
const c = useThemeColors()
|
const c = useThemeColors()
|
||||||
|
const { t } = useT()
|
||||||
const [mode, setMode] = useState('combined')
|
const [mode, setMode] = useState('combined')
|
||||||
const { data } = usePoll(() => api.dailyEnergy({ days: 30 }), 300_000)
|
const { data } = usePoll(() => api.dailyEnergy({ days: 30 }), 300_000)
|
||||||
const series =
|
const series =
|
||||||
mode === 'combined'
|
mode === 'combined'
|
||||||
? [{ key: 'total_wh', name: 'All inverters', color: c.accent }]
|
? [{ key: 'total_wh', name: t('energy.allInverters'), 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">{t('energy.title')}</h2>
|
||||||
{data && <div className="text-xs text-muted tnum">{energy(total)} total</div>}
|
{data && !empty && (
|
||||||
|
<div className="text-xs text-muted tnum">
|
||||||
|
{estimated && '≈ '}
|
||||||
|
{t('energy.total', { v: energy(total) })}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
<Segmented
|
<Segmented
|
||||||
label="Energy chart mode"
|
label={t('energy.mode')}
|
||||||
value={mode}
|
value={mode}
|
||||||
onChange={setMode}
|
onChange={setMode}
|
||||||
options={[
|
options={[
|
||||||
{ value: 'combined', label: 'Combined' },
|
{ value: 'combined', label: t('energy.combined') },
|
||||||
{ value: 'split', label: 'Per inverter' },
|
{ value: 'split', label: t('energy.split') },
|
||||||
]}
|
]}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
@@ -137,17 +199,20 @@ 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">{t('energy.empty')}</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>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
export default function Dashboard({ summaryPoll }) {
|
export default function Dashboard({ summaryPoll }) {
|
||||||
|
const { t } = useT()
|
||||||
const { data: summary, error } = summaryPoll
|
const { data: summary, error } = summaryPoll
|
||||||
const ids = useMemo(() => summary?.inverters.map((s) => s.inverter.id) ?? [], [summary])
|
const ids = useMemo(() => summary?.inverters.map((s) => s.inverter.id) ?? [], [summary])
|
||||||
const names = useMemo(
|
const names = useMemo(
|
||||||
@@ -158,7 +223,7 @@ export default function Dashboard({ summaryPoll }) {
|
|||||||
if (!summary) {
|
if (!summary) {
|
||||||
return (
|
return (
|
||||||
<div className="py-24 text-center text-sm text-ink-2">
|
<div className="py-24 text-center text-sm text-ink-2">
|
||||||
{error ? `Can't reach the server: ${error.message}` : 'Loading…'}
|
{error ? t('dash.unreachable', { msg: error.message }) : t('common.loading')}
|
||||||
</div>
|
</div>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -167,7 +232,7 @@ export default function Dashboard({ summaryPoll }) {
|
|||||||
return (
|
return (
|
||||||
<div className="card mx-auto max-w-md p-6 text-center text-sm text-ink-2">
|
<div className="card mx-auto max-w-md p-6 text-center text-sm text-ink-2">
|
||||||
<Icon name="sun" size={28} className="mx-auto mb-2 text-accent" />
|
<Icon name="sun" size={28} className="mx-auto mb-2 text-accent" />
|
||||||
No inverter has reported yet. Readings appear here as soon as the on-site poller posts to{' '}
|
{t('dash.noInverters')}{' '}
|
||||||
<code className="text-ink">/api/readings</code>.
|
<code className="text-ink">/api/readings</code>.
|
||||||
</div>
|
</div>
|
||||||
)
|
)
|
||||||
@@ -188,7 +253,7 @@ export default function Dashboard({ summaryPoll }) {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<section>
|
<section>
|
||||||
<h2 className="mb-2 px-1 text-sm font-semibold text-ink-2">Inverters</h2>
|
<h2 className="mb-2 px-1 text-sm font-semibold text-ink-2">{t('dash.inverters')}</h2>
|
||||||
<div className="grid gap-4 sm:grid-cols-2 xl:grid-cols-3">
|
<div className="grid gap-4 sm:grid-cols-2 xl:grid-cols-3">
|
||||||
{summary.inverters.map((st) => (
|
{summary.inverters.map((st) => (
|
||||||
<InverterCard key={st.inverter.id} status={st} ids={ids} />
|
<InverterCard key={st.inverter.id} status={st} ids={ids} />
|
||||||
@@ -197,7 +262,7 @@ export default function Dashboard({ summaryPoll }) {
|
|||||||
</section>
|
</section>
|
||||||
<p className="pb-4 text-center text-xs text-muted">
|
<p className="pb-4 text-center text-xs text-muted">
|
||||||
<Link to="/api/docs" reloadDocument className="underline-offset-2 hover:underline">
|
<Link to="/api/docs" reloadDocument className="underline-offset-2 hover:underline">
|
||||||
API documentation
|
{t('dash.apiDocs')}
|
||||||
</Link>
|
</Link>
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -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'
|
||||||
@@ -8,20 +8,28 @@ import Segmented from '../components/Segmented'
|
|||||||
import { usePoll } from '../hooks/usePoll'
|
import { usePoll } from '../hooks/usePoll'
|
||||||
import { api, isoAgo } from '../lib/api'
|
import { api, isoAgo } from '../lib/api'
|
||||||
import { useThemeColors } from '../lib/colors'
|
import { useThemeColors } from '../lib/colors'
|
||||||
import { ago, energy, energyParts, num, power, powerParts } from '../lib/format'
|
import { ago, dateTime, energy, energyParts, num, power, powerParts } from '../lib/format'
|
||||||
|
import { useT } from '../lib/i18n'
|
||||||
|
import { displayVoltage, useSettings } from '../lib/settings'
|
||||||
|
|
||||||
const RANGES = {
|
const RANGES = {
|
||||||
'24h': { label: '24 h', seconds: 86400 },
|
'24h': { seconds: 86400 },
|
||||||
'7d': { label: '7 days', seconds: 7 * 86400 },
|
'7d': { seconds: 7 * 86400 },
|
||||||
'30d': { label: '30 days', seconds: 30 * 86400 },
|
'30d': { seconds: 30 * 86400 },
|
||||||
}
|
}
|
||||||
|
|
||||||
const GROUPS = [
|
const GROUPS = ['ac', 'dc', 'energy', 'device']
|
||||||
{ key: 'ac', label: 'AC output' },
|
|
||||||
{ key: 'dc', label: 'DC input' },
|
const isVoltage = (key) => /^ac_voltage_l\d_v$/.test(key)
|
||||||
{ key: 'energy', label: 'Energy' },
|
|
||||||
{ key: 'device', label: 'Device' },
|
/** Field label in the current language, marking converted line voltages. */
|
||||||
]
|
function useFieldLabel() {
|
||||||
|
const { t, tOr } = useT()
|
||||||
|
const { settings } = useSettings()
|
||||||
|
return (f) =>
|
||||||
|
tOr(`field.${f.key}`, f.label) +
|
||||||
|
(isVoltage(f.key) && settings.voltage_display === 'line' ? ` ${t('detail.lineVoltage')}` : '')
|
||||||
|
}
|
||||||
|
|
||||||
function formatField(field, value) {
|
function formatField(field, value) {
|
||||||
if (value === null || value === undefined) return '—'
|
if (value === null || value === undefined) return '—'
|
||||||
@@ -31,38 +39,49 @@ 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 }) {
|
||||||
|
const { t } = useT()
|
||||||
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>
|
||||||
|
{unavailable ? (
|
||||||
|
<div className="text-sm leading-8 text-muted">{t('common.notAvailable')}</div>
|
||||||
|
) : (
|
||||||
<div className="tnum">
|
<div className="tnum">
|
||||||
<span className="text-2xl font-semibold tracking-tight">{parts[0]}</span>
|
<span className="text-2xl font-semibold tracking-tight">{parts[0]}</span>
|
||||||
<span className="ml-1 text-sm text-ink-2">{parts[1]}</span>
|
<span className="ml-1 text-sm text-ink-2">{parts[1]}</span>
|
||||||
</div>
|
</div>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
function Parameters({ fields, latest, live }) {
|
function Parameters({ fields, latest, live }) {
|
||||||
|
const { t } = useT()
|
||||||
|
const { settings } = useSettings()
|
||||||
|
const label = useFieldLabel()
|
||||||
const extra = Object.entries(latest?.extra ?? {})
|
const extra = Object.entries(latest?.extra ?? {})
|
||||||
|
const value = (f) => (isVoltage(f.key) ? displayVoltage(latest?.[f.key], settings) : latest?.[f.key])
|
||||||
return (
|
return (
|
||||||
<section className="card p-4">
|
<section className="card p-4">
|
||||||
<h2 className="mb-1 text-sm font-semibold">All parameters</h2>
|
<h2 className="mb-1 text-sm font-semibold">{t('detail.params')}</h2>
|
||||||
<p className="mb-3 text-xs text-muted">
|
<p className="mb-3 text-xs text-muted">
|
||||||
{latest ? `Last reading ${new Date(latest.timestamp).toLocaleString()}` : 'No readings yet'}
|
{latest ? t('detail.lastReadingAt', { when: dateTime(latest.timestamp) }) : t('detail.noReadings')}
|
||||||
{latest && !live && ' — values are from the last time it reported'}
|
{latest && !live && t('detail.stale')}
|
||||||
</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 this inverter doesn't send are left out entirely
|
||||||
|
const items = fields.filter((f) => f.group === g && latest?.[f.key] != null)
|
||||||
return (
|
return (
|
||||||
<div key={g.key}>
|
<div key={g}>
|
||||||
<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">{t(`group.${g}`)}</h3>
|
||||||
|
{items.length === 0 && <p className="py-1.5 text-sm text-muted">{t('detail.notSent')}</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">
|
||||||
<dt className="text-ink-2">{f.label}</dt>
|
<dt className="text-ink-2">{label(f)}</dt>
|
||||||
<dd className="tnum font-medium">{formatField(f, latest?.[f.key])}</dd>
|
<dd className="tnum font-medium">{formatField(f, value(f))}</dd>
|
||||||
</div>
|
</div>
|
||||||
))}
|
))}
|
||||||
</dl>
|
</dl>
|
||||||
@@ -71,7 +90,7 @@ function Parameters({ fields, latest, live }) {
|
|||||||
})}
|
})}
|
||||||
{extra.length > 0 && (
|
{extra.length > 0 && (
|
||||||
<div>
|
<div>
|
||||||
<h3 className="mb-1 text-xs font-semibold uppercase tracking-wide text-muted">Other (unmapped)</h3>
|
<h3 className="mb-1 text-xs font-semibold uppercase tracking-wide text-muted">{t('group.extra')}</h3>
|
||||||
<dl className="divide-y divide-[var(--border)] text-sm">
|
<dl className="divide-y divide-[var(--border)] text-sm">
|
||||||
{extra.map(([k, v]) => (
|
{extra.map(([k, v]) => (
|
||||||
<div key={k} className="flex justify-between gap-4 py-1.5">
|
<div key={k} className="flex justify-between gap-4 py-1.5">
|
||||||
@@ -89,18 +108,31 @@ function Parameters({ fields, latest, live }) {
|
|||||||
|
|
||||||
function HistoryCharts({ id, fields }) {
|
function HistoryCharts({ id, fields }) {
|
||||||
const c = useThemeColors()
|
const c = useThemeColors()
|
||||||
|
const { t } = useT()
|
||||||
|
const { settings } = useSettings()
|
||||||
|
const label = useFieldLabel()
|
||||||
const [range, setRange] = useState('7d')
|
const [range, setRange] = useState('7d')
|
||||||
const [param, setParam] = useState('temperature_c')
|
const [param, setParam] = useState('temperature_c')
|
||||||
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: t('detail.acOutput'), 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 lineVolts = paramField && isVoltage(paramField.key) && settings.voltage_display === 'line'
|
||||||
|
const paramPoints =
|
||||||
|
data && lineVolts
|
||||||
|
? data.points.map((p) => ({ ...p, [paramField.key]: displayVoltage(p[paramField.key], settings) }))
|
||||||
|
: data?.points
|
||||||
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
|
||||||
|
|
||||||
@@ -108,12 +140,12 @@ function HistoryCharts({ id, fields }) {
|
|||||||
<>
|
<>
|
||||||
<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">
|
||||||
<h2 className="text-sm font-semibold">Power</h2>
|
<h2 className="text-sm font-semibold">{t('detail.power')}</h2>
|
||||||
<Segmented
|
<Segmented
|
||||||
label="History range"
|
label={t('detail.historyRange')}
|
||||||
value={range}
|
value={range}
|
||||||
onChange={setRange}
|
onChange={setRange}
|
||||||
options={Object.entries(RANGES).map(([value, r]) => ({ value, label: r.label }))}
|
options={Object.keys(RANGES).map((value) => ({ value, label: t(`rangeShort.${value}`) }))}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
<div className="mb-2">
|
<div className="mb-2">
|
||||||
@@ -133,32 +165,33 @@ 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 ? t('detail.mpptNote') : t('detail.noDc')}
|
||||||
away from the other points at that string.
|
|
||||||
</p>
|
</p>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
<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">
|
||||||
<h2 className="text-sm font-semibold">{paramField?.label}</h2>
|
<h2 className="text-sm font-semibold">{paramField && label(paramField)}</h2>
|
||||||
<select
|
<select
|
||||||
value={paramField?.key}
|
value={paramField?.key}
|
||||||
onChange={(e) => setParam(e.target.value)}
|
onChange={(e) => setParam(e.target.value)}
|
||||||
className="min-h-9 rounded-lg border border-line bg-surface-2 px-2 text-sm"
|
className="min-h-9 rounded-lg border border-line bg-surface-2 px-2 text-sm"
|
||||||
aria-label="Parameter to chart"
|
aria-label={t('detail.paramPicker')}
|
||||||
>
|
>
|
||||||
{chartable.map((f) => (
|
{chartable.map((f) => (
|
||||||
<option key={f.key} value={f.key}>
|
<option key={f.key} value={f.key}>
|
||||||
{f.label}
|
{label(f)}
|
||||||
{f.unit ? ` (${f.unit})` : ''}
|
{f.unit ? ` (${f.unit})` : ''}
|
||||||
</option>
|
</option>
|
||||||
))}
|
))}
|
||||||
</select>
|
</select>
|
||||||
</div>
|
</div>
|
||||||
{data && paramField ? (
|
{data && !paramField ? (
|
||||||
|
<div className="flex h-52 items-center justify-center text-sm text-muted">{t('detail.noDataRange')}</div>
|
||||||
|
) : data && paramField ? (
|
||||||
<TimeLines
|
<TimeLines
|
||||||
points={data.points}
|
points={paramPoints}
|
||||||
series={[{ key: paramField.key, name: paramField.label, color: c.series[0] }]}
|
series={[{ key: paramField.key, name: label(paramField), color: c.series[0] }]}
|
||||||
from={from}
|
from={from}
|
||||||
to={to}
|
to={to}
|
||||||
bucket={data.bucket}
|
bucket={data.bucket}
|
||||||
@@ -176,41 +209,52 @@ function HistoryCharts({ id, fields }) {
|
|||||||
|
|
||||||
function YearEnergy({ id }) {
|
function YearEnergy({ id }) {
|
||||||
const c = useThemeColors()
|
const c = useThemeColors()
|
||||||
|
const { t } = useT()
|
||||||
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">{t('detail.yearEnergy')}</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 && '≈ '}
|
||||||
|
{t('energy.total', { v: energy(total) })}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{empty ? (
|
||||||
|
<div className="flex h-56 items-center justify-center text-sm text-muted">{t('energy.empty')}</div>
|
||||||
|
) : data ? (
|
||||||
<DayBars
|
<DayBars
|
||||||
days={data.days}
|
days={data.days}
|
||||||
series={[{ key: 'energy_wh', name: 'Energy', color: c.accent }]}
|
series={[{ key: 'energy_wh', name: t('detail.energy'), color: c.accent }]}
|
||||||
format={energy}
|
format={energy}
|
||||||
axisFormat={(wh) => num(wh / 1000, 0)}
|
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>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
export default function InverterDetail({ summaryPoll }) {
|
export default function InverterDetail({ summaryPoll }) {
|
||||||
|
const { t } = useT()
|
||||||
const { id } = useParams()
|
const { id } = useParams()
|
||||||
const { data: summary, refresh } = summaryPoll
|
const { data: summary, refresh } = summaryPoll
|
||||||
const { data: fields } = usePoll(() => api.fields(), 3_600_000)
|
const { data: fields } = usePoll(() => api.fields(), 3_600_000)
|
||||||
const [editing, setEditing] = useState(false)
|
const [editing, setEditing] = useState(false)
|
||||||
const status = useMemo(() => summary?.inverters.find((s) => s.inverter.id === id), [summary, id])
|
const status = useMemo(() => summary?.inverters.find((s) => s.inverter.id === id), [summary, id])
|
||||||
|
|
||||||
if (!summary) return <div className="py-24 text-center text-sm text-ink-2">Loading…</div>
|
if (!summary) return <div className="py-24 text-center text-sm text-ink-2">{t('common.loading')}</div>
|
||||||
if (!status) {
|
if (!status) {
|
||||||
return (
|
return (
|
||||||
<div className="py-24 text-center text-sm text-ink-2">
|
<div className="py-24 text-center text-sm text-ink-2">
|
||||||
Unknown inverter “{id}”.{' '}
|
{t('detail.unknown', { id })}{' '}
|
||||||
<Link to="/" className="underline">
|
<Link to="/" className="underline">
|
||||||
Back to overview
|
{t('detail.back')}
|
||||||
</Link>
|
</Link>
|
||||||
</div>
|
</div>
|
||||||
)
|
)
|
||||||
@@ -218,32 +262,31 @@ 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">
|
||||||
<div>
|
<div>
|
||||||
<Link to="/" className="-ml-1 inline-flex min-h-9 items-center gap-1 text-sm text-ink-2 hover:text-ink">
|
<Link to="/" className="-ml-1 inline-flex min-h-9 items-center gap-1 text-sm text-ink-2 hover:text-ink">
|
||||||
<Icon name="back" size={16} /> All inverters
|
<Icon name="back" size={16} /> {t('detail.all')}
|
||||||
</Link>
|
</Link>
|
||||||
<div className="mt-1 flex flex-wrap items-center justify-between gap-3">
|
<div className="mt-1 flex flex-wrap items-center justify-between gap-3">
|
||||||
<div className="min-w-0">
|
<div className="min-w-0">
|
||||||
<h1 className="truncate text-2xl font-semibold tracking-tight">{inverter.name}</h1>
|
<h1 className="truncate text-2xl font-semibold tracking-tight">{inverter.name}</h1>
|
||||||
<div className="mt-1 flex flex-wrap items-center gap-x-2 gap-y-1 text-xs text-muted">
|
<div className="mt-1 flex flex-wrap items-center gap-x-2 gap-y-1 text-xs text-muted">
|
||||||
<OnlineDot online={live} />
|
<OnlineDot online={live} />
|
||||||
<span>· last reading {ago(latest?.timestamp)}</span>
|
<span>· {t('detail.lastReading', { ago: ago(latest?.timestamp) })}</span>
|
||||||
{inverter.capacity_kwp && <span>· {num(inverter.capacity_kwp, 2)} kWp</span>}
|
{inverter.capacity_kwp && <span>· {num(inverter.capacity_kwp, 2)} kWp</span>}
|
||||||
{inverter.name !== inverter.id && <span>· {inverter.id}</span>}
|
{inverter.name !== inverter.id && <span>· {inverter.id}</span>}
|
||||||
</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)}
|
||||||
className="inline-flex min-h-9 items-center gap-1 rounded-lg border border-line px-3 text-sm text-ink-2 hover:text-ink"
|
className="inline-flex min-h-9 items-center gap-1 rounded-lg border border-line px-3 text-sm text-ink-2 hover:text-ink"
|
||||||
>
|
>
|
||||||
<Icon name="edit" size={14} /> Edit
|
<Icon name="edit" size={14} /> {t('detail.edit')}
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -253,11 +296,18 @@ export default function InverterDetail({ summaryPoll }) {
|
|||||||
<IssueList issues={health.issues} />
|
<IssueList issues={health.issues} />
|
||||||
|
|
||||||
<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={t('detail.powerNow')} 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
|
<KeyFigure
|
||||||
label="vs fleet median"
|
label={t(status.energy_today.estimated ? 'hero.todayEst' : 'hero.today')}
|
||||||
|
parts={energyParts(status.energy_today.wh)}
|
||||||
|
/>
|
||||||
|
<KeyFigure
|
||||||
|
label={t('hero.lifetime')}
|
||||||
|
parts={energyParts(latest?.total_energy_wh)}
|
||||||
|
unavailable={latest?.total_energy_wh == null}
|
||||||
|
/>
|
||||||
|
<KeyFigure
|
||||||
|
label={t('detail.vsMedian')}
|
||||||
parts={[health.relative_output == null ? '—' : num(health.relative_output * 100, 0), '%']}
|
parts={[health.relative_output == null ? '—' : num(health.relative_output * 100, 0), '%']}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -0,0 +1,226 @@
|
|||||||
|
import { useEffect, useState } from 'react'
|
||||||
|
import { Link } from 'react-router-dom'
|
||||||
|
import { input } from '../components/EditInverterDialog'
|
||||||
|
import Icon from '../components/Icon'
|
||||||
|
import { LANGUAGES, useT } from '../lib/i18n'
|
||||||
|
import { DEFAULT_SETTINGS, POWER_RANGES, useSettings } from '../lib/settings'
|
||||||
|
|
||||||
|
const capitalize = (s) => s.charAt(0).toUpperCase() + s.slice(1)
|
||||||
|
|
||||||
|
/** Wrapping row of choice buttons — fits long Greek labels on a phone. */
|
||||||
|
function Choices({ label, value, onChange, options }) {
|
||||||
|
return (
|
||||||
|
<div role="radiogroup" aria-label={label} className="mt-2 flex flex-wrap gap-1.5">
|
||||||
|
{options.map((o) => {
|
||||||
|
const active = o.value === value
|
||||||
|
return (
|
||||||
|
<button
|
||||||
|
key={String(o.value)}
|
||||||
|
type="button"
|
||||||
|
role="radio"
|
||||||
|
aria-checked={active}
|
||||||
|
onClick={() => onChange(o.value)}
|
||||||
|
className={`min-h-9 rounded-lg border px-3 text-sm font-medium transition-colors ${
|
||||||
|
active
|
||||||
|
? 'border-[var(--accent)] bg-[var(--accent)] text-page'
|
||||||
|
: 'border-line bg-surface-2 text-ink-2 hover:text-ink'
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
{o.label}
|
||||||
|
</button>
|
||||||
|
)
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function Option({ title, help, children }) {
|
||||||
|
return (
|
||||||
|
<div className="py-4 first:pt-1 last:pb-1">
|
||||||
|
{title && <div className="text-sm font-medium">{title}</div>}
|
||||||
|
{help && <p className="mt-0.5 text-xs leading-relaxed text-muted">{help}</p>}
|
||||||
|
{children}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function Section({ title, children }) {
|
||||||
|
return (
|
||||||
|
<section className="card px-4 py-3">
|
||||||
|
<h2 className="text-xs font-semibold uppercase tracking-wide text-muted">{title}</h2>
|
||||||
|
<div className="divide-y divide-[var(--border)]">{children}</div>
|
||||||
|
</section>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function Settings() {
|
||||||
|
const { t, lang, setLang } = useT()
|
||||||
|
const { settings, loaded, save } = useSettings()
|
||||||
|
const [form, setForm] = useState(settings)
|
||||||
|
const [dirty, setDirty] = useState(false)
|
||||||
|
const [status, setStatus] = useState(null) // null | 'saving' | 'saved' | Error
|
||||||
|
// Pick up the server's values until the user starts editing
|
||||||
|
useEffect(() => {
|
||||||
|
if (!dirty) setForm(settings)
|
||||||
|
}, [settings, dirty])
|
||||||
|
|
||||||
|
const set = (key) => (value) => {
|
||||||
|
setForm((f) => ({ ...f, [key]: value }))
|
||||||
|
setDirty(true)
|
||||||
|
setStatus(null)
|
||||||
|
}
|
||||||
|
const opts = (key, values) => values.map((v) => ({ value: v, label: t(`opt.${key}.${v}`) }))
|
||||||
|
|
||||||
|
const needsCustom = form.comparison_scale === 'custom' || form.comparison_reference === 'custom'
|
||||||
|
const missingCustom = needsCustom && !(form.comparison_custom_kw > 0)
|
||||||
|
|
||||||
|
async function submit(e) {
|
||||||
|
e.preventDefault()
|
||||||
|
if (missingCustom) return
|
||||||
|
setStatus('saving')
|
||||||
|
try {
|
||||||
|
const kw = form.comparison_custom_kw
|
||||||
|
await save({ ...form, comparison_custom_kw: kw > 0 ? kw : null })
|
||||||
|
setDirty(false)
|
||||||
|
setStatus('saved')
|
||||||
|
} catch (err) {
|
||||||
|
setStatus(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<form onSubmit={submit} className="mx-auto max-w-2xl space-y-4 pb-24">
|
||||||
|
<div>
|
||||||
|
<Link to="/" className="-ml-1 inline-flex min-h-9 items-center gap-1 text-sm text-ink-2 hover:text-ink">
|
||||||
|
<Icon name="back" size={16} /> {t('detail.back')}
|
||||||
|
</Link>
|
||||||
|
<h1 className="mt-1 text-2xl font-semibold tracking-tight">{t('settings.title')}</h1>
|
||||||
|
<p className="mt-1 text-sm text-ink-2">{t('settings.shared')}</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<Section title={t('settings.cmp')}>
|
||||||
|
<Option title={t('settings.readings')} help={t('settings.readingsHelp')}>
|
||||||
|
<Choices
|
||||||
|
label={t('settings.readings')}
|
||||||
|
value={form.comparison_readings}
|
||||||
|
onChange={set('comparison_readings')}
|
||||||
|
options={opts('readings', [1, 3, 5])}
|
||||||
|
/>
|
||||||
|
</Option>
|
||||||
|
<Option title={t('settings.scale')} help={t('settings.scaleHelp')}>
|
||||||
|
<Choices
|
||||||
|
label={t('settings.scale')}
|
||||||
|
value={form.comparison_scale}
|
||||||
|
onChange={set('comparison_scale')}
|
||||||
|
options={opts('scale', ['auto', 'max', 'custom'])}
|
||||||
|
/>
|
||||||
|
</Option>
|
||||||
|
<Option title={t('settings.reference')} help={t('settings.referenceHelp')}>
|
||||||
|
<Choices
|
||||||
|
label={t('settings.reference')}
|
||||||
|
value={form.comparison_reference}
|
||||||
|
onChange={set('comparison_reference')}
|
||||||
|
options={opts('reference', ['median', 'best', 'custom'])}
|
||||||
|
/>
|
||||||
|
</Option>
|
||||||
|
<Option title={t('settings.customKw')} help={t('settings.customKwHelp')}>
|
||||||
|
<input
|
||||||
|
className={`${input} max-w-40`}
|
||||||
|
type="number"
|
||||||
|
inputMode="decimal"
|
||||||
|
step="0.1"
|
||||||
|
min="0.1"
|
||||||
|
max="1000"
|
||||||
|
placeholder="20"
|
||||||
|
value={form.comparison_custom_kw ?? ''}
|
||||||
|
onChange={(e) => set('comparison_custom_kw')(e.target.value === '' ? null : Number(e.target.value))}
|
||||||
|
aria-invalid={missingCustom}
|
||||||
|
/>
|
||||||
|
{missingCustom && <p className="mt-1 text-xs text-crit">{t('settings.customRequired')}</p>}
|
||||||
|
</Option>
|
||||||
|
</Section>
|
||||||
|
|
||||||
|
<Section title={t('settings.power')}>
|
||||||
|
<Option title={t('settings.range')} help={t('settings.rangeHelp')}>
|
||||||
|
<Choices
|
||||||
|
label={t('settings.range')}
|
||||||
|
value={form.power_range}
|
||||||
|
onChange={set('power_range')}
|
||||||
|
options={Object.keys(POWER_RANGES).map((k) => ({ value: k, label: capitalize(t(`range.${k}`)) }))}
|
||||||
|
/>
|
||||||
|
</Option>
|
||||||
|
<Option title={t('settings.smoothing')} help={t('settings.smoothingHelp')}>
|
||||||
|
<Choices
|
||||||
|
label={t('settings.smoothing')}
|
||||||
|
value={form.power_smoothing}
|
||||||
|
onChange={set('power_smoothing')}
|
||||||
|
options={opts('smoothing', ['off', 'light', 'strong'])}
|
||||||
|
/>
|
||||||
|
</Option>
|
||||||
|
</Section>
|
||||||
|
|
||||||
|
<Section title={t('settings.display')}>
|
||||||
|
<Option title={t('settings.voltage')} help={t('settings.voltageHelp')}>
|
||||||
|
<Choices
|
||||||
|
label={t('settings.voltage')}
|
||||||
|
value={form.voltage_display}
|
||||||
|
onChange={set('voltage_display')}
|
||||||
|
options={opts('voltage', ['phase', 'line'])}
|
||||||
|
/>
|
||||||
|
</Option>
|
||||||
|
<Option title={t('settings.language')} help={t('settings.languageHelp')}>
|
||||||
|
<Choices
|
||||||
|
label={t('settings.language')}
|
||||||
|
value={lang}
|
||||||
|
onChange={setLang}
|
||||||
|
options={LANGUAGES.map((l) => ({ value: l.code, label: l.label }))}
|
||||||
|
/>
|
||||||
|
</Option>
|
||||||
|
<Option title={t('settings.defaultLanguage')} help={t('settings.defaultLanguageHelp')}>
|
||||||
|
<Choices
|
||||||
|
label={t('settings.defaultLanguage')}
|
||||||
|
value={form.default_language}
|
||||||
|
onChange={set('default_language')}
|
||||||
|
options={LANGUAGES.map((l) => ({ value: l.code, label: l.label }))}
|
||||||
|
/>
|
||||||
|
</Option>
|
||||||
|
</Section>
|
||||||
|
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => {
|
||||||
|
setForm(DEFAULT_SETTINGS)
|
||||||
|
setDirty(true)
|
||||||
|
setStatus(null)
|
||||||
|
}}
|
||||||
|
className="text-sm text-ink-2 underline-offset-2 hover:text-ink hover:underline"
|
||||||
|
>
|
||||||
|
{t('settings.reset')}
|
||||||
|
</button>
|
||||||
|
|
||||||
|
{/* Save bar stays reachable at the bottom of a long page on a phone */}
|
||||||
|
<div className="fixed inset-x-0 bottom-0 z-30 border-t border-line bg-page/90 pb-[env(safe-area-inset-bottom)] backdrop-blur">
|
||||||
|
<div className="mx-auto flex max-w-2xl items-center justify-between gap-3 px-4 py-3">
|
||||||
|
<span className="min-w-0 text-sm" role="status">
|
||||||
|
{status instanceof Error ? (
|
||||||
|
<span className="text-crit">{status.message}</span>
|
||||||
|
) : status === 'saved' ? (
|
||||||
|
<span className="inline-flex items-center gap-1 text-good">
|
||||||
|
<Icon name="check" size={16} strokeWidth={2.5} /> {t('settings.saved')}
|
||||||
|
</span>
|
||||||
|
) : dirty ? (
|
||||||
|
<span className="text-ink-2">{t('settings.unsaved')}</span>
|
||||||
|
) : null}
|
||||||
|
</span>
|
||||||
|
<button
|
||||||
|
type="submit"
|
||||||
|
disabled={!loaded || !dirty || status === 'saving' || missingCustom}
|
||||||
|
className="min-h-11 shrink-0 rounded-lg bg-ink px-6 font-semibold text-page disabled:opacity-50"
|
||||||
|
>
|
||||||
|
{status === 'saving' ? t('common.saving') : t('common.save')}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -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
|
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
|
them in `unsent_readings.jsonl` when the internet is down, re-sends them
|
||||||
later, and never raises.
|
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
|
## 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.
|
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:
|
Pretty names are set later in the dashboard, not here. Allowed characters:
|
||||||
letters, digits, `_ . -`.
|
letters, digits, `_ . -`.
|
||||||
3. **Send converted values**, not raw ones, using the keys and scalings in
|
3. **Send converted values**, not raw ones, using the keys in `README.md`.
|
||||||
`README.md` (e.g. `ac_voltage_l1_v` = P050 raw / 40). Leave out anything
|
Leave out anything you couldn't read or haven't verified; every field is
|
||||||
you couldn't read; every field is optional.
|
optional. Timestamps must be real UTC (see README).
|
||||||
4. **New or unconfirmed parameters:** send them too, under a descriptive key
|
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
|
(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
|
inverter page under "Other (unmapped)". Tell the owner when a mapping is
|
||||||
|
|||||||
+32
-15
@@ -1,6 +1,6 @@
|
|||||||
# On-site poller
|
# 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
|
(port 21062, USS address 0). It sends each cycle to the backend through
|
||||||
`backend_client.py` — copy that file next to the poller.
|
`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
|
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.
|
stored too and shows under "Other (unmapped)" on the inverter page.
|
||||||
|
|
||||||
| key | unit | source |
|
State of the map as verified on site (2026-10-21):
|
||||||
|---|---|---|
|
|
||||||
| `ac_voltage_l1_v` / `_l2_v` / `_l3_v` | V | P050 / P05B / P064 raw / 40 |
|
| key | unit | status | source |
|
||||||
| `dc_voltage_mppt1_v` / `_mppt2_v` | V | P052 / P054 raw / 40 |
|
|---|---|---|---|
|
||||||
| `dc_current_mppt1_a` / `_mppt2_a` | A | P05A / P05C raw / 10 |
|
| `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_current_l1_a` / `_l2_a` / `_l3_a` | A | P068 / P069 / P06A raw / 100 |
|
| `ac_voltage_l1_v` / `_l2_v` / `_l3_v` | V | ✅ sent | P050 / P05B / P064 raw / 40 |
|
||||||
| `ac_power_total_w` | W | P06D raw |
|
| `ac_current_l1_a` / `_l2_a` / `_l3_a` | A | ✅ sent | P068 / P069 / P06A raw / 100 |
|
||||||
| `grid_frequency_hz` | Hz | P06C raw / 20 |
|
| `grid_frequency_hz` | Hz | ✅ sent | P06C raw / 20 |
|
||||||
| `temperature_c` | °C | P070 raw >> 16 |
|
| `temperature_c` | °C | ✅ sent | P070 raw >> 16 |
|
||||||
| `daily_energy_wh` | Wh | P063 IND=0 raw × 10 |
|
| `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. |
|
||||||
| `total_energy_wh` | Wh | P063 IND=11 raw |
|
| `status_text` | – | ✅ sent | `"feeding"` / `"standby/not feeding"` |
|
||||||
| `status_code` | – | inverter state, once identified |
|
| `dc_voltage_mppt1_v` / `_mppt2_v` | V | ❌ not sent | P052 / P054 are static nameplate/limit values, not live. Real registers TBD. |
|
||||||
| `error_code` | – | non-zero = fault (shows the inverter as **Fault**) |
|
| `dc_current_mppt1_a` / `_mppt2_a` | A | ❌ not sent | P05A / P05C likewise static. Real registers TBD. |
|
||||||
| `status_text` | – | optional human text for the code |
|
| `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
|
`send()` stamps each reading with the current UTC time, buffers to
|
||||||
`unsent_readings.jsonl` when the internet is down and re-sends later, and
|
`unsent_readings.jsonl` when the internet is down and re-sends later, and
|
||||||
|
|||||||
+53
-38
@@ -2,9 +2,15 @@
|
|||||||
|
|
||||||
python fake_poller.py --url http://localhost:8090 --key change-me --backfill-days 30
|
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
|
Follows the poller data contract of 2026-10-22: five units, three sources.
|
||||||
5 minutes), then it posts live readings every --interval seconds. Inverter
|
INV1/INV3 (OEM board) send AC voltages, power, frequency, temperature and
|
||||||
INV3 runs with a dead MPPT2 string so the warnings show up.
|
status; INV2/INV4 (SunSpec) add phase currents and MPPT1 voltage; INV5
|
||||||
|
(SolarmanPV cloud) adds the real daily/lifetime energy counters, reports
|
||||||
|
only every 5 min and keeps reporting 0 W / Standby at night while the
|
||||||
|
others go silent. --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
|
import argparse
|
||||||
@@ -17,6 +23,11 @@ from backend_client import BackendClient
|
|||||||
|
|
||||||
INVERTERS = ["INV1", "INV2", "INV3", "INV4", "INV5"]
|
INVERTERS = ["INV1", "INV2", "INV3", "INV4", "INV5"]
|
||||||
PEAK_W = 18_000
|
PEAK_W = 18_000
|
||||||
|
CLOUD_EVERY_S = 300 # INV5's cadence
|
||||||
|
INV5_LIFETIME_START_WH = 41_250_000
|
||||||
|
|
||||||
|
# INV5's daily counter, accumulated by the simulator
|
||||||
|
_inv5 = {"day": None, "daily_wh": 0.0, "total_wh": float(INV5_LIFETIME_START_WH), "last": None}
|
||||||
|
|
||||||
|
|
||||||
def sun_factor(t: datetime) -> float:
|
def sun_factor(t: datetime) -> float:
|
||||||
@@ -26,41 +37,46 @@ def sun_factor(t: datetime) -> float:
|
|||||||
return max(0.0, math.sin(math.pi * x)) if 0 < x < 1 else 0.0
|
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)
|
f = sun_factor(t) * random.uniform(0.93, 1.0)
|
||||||
if f <= 0.01:
|
if inv == "INV5":
|
||||||
return None # inverter asleep at night, doesn't answer
|
if int(t.timestamp()) % CLOUD_EVERY_S >= 60:
|
||||||
dead_mppt2 = inv == "INV3"
|
return None # cloud value only refreshes every 5 min
|
||||||
p_dc1 = PEAK_W / 2 * f
|
elif f <= 0.01:
|
||||||
p_dc2 = 0 if dead_mppt2 else PEAK_W / 2 * f
|
return None # local units power down at night and don't answer
|
||||||
v1, v2 = 560 + 60 * f, 560 + 60 * f
|
feeding = f > 0.03
|
||||||
ac = int((p_dc1 + p_dc2) * 0.97)
|
w = int(PEAK_W * f * (0.5 if inv == "INV4" else 1.0)) if feeding else 0
|
||||||
day = t.date()
|
volts = [round(random.uniform(236, 244), 1) for _ in range(3)]
|
||||||
if state.get((inv, "day")) != day:
|
r = {
|
||||||
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
|
|
||||||
return {
|
|
||||||
"inverter_id": inv,
|
"inverter_id": inv,
|
||||||
"timestamp": t.isoformat(timespec="seconds"),
|
"timestamp": t.isoformat(timespec="seconds"),
|
||||||
"ac_voltage_l1_v": round(random.uniform(228, 236), 1),
|
"ac_voltage_l1_v": volts[0],
|
||||||
"ac_voltage_l2_v": round(random.uniform(228, 236), 1),
|
"ac_voltage_l2_v": volts[1],
|
||||||
"ac_voltage_l3_v": round(random.uniform(228, 236), 1),
|
"ac_voltage_l3_v": volts[2],
|
||||||
"dc_voltage_mppt1_v": round(v1, 1),
|
"ac_power_total_w": w,
|
||||||
"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,
|
|
||||||
"grid_frequency_hz": round(random.uniform(49.95, 50.05), 2),
|
"grid_frequency_hz": round(random.uniform(49.95, 50.05), 2),
|
||||||
"temperature_c": int(30 + 25 * f),
|
"temperature_c": int(30 + 25 * f),
|
||||||
"daily_energy_wh": int(state[(inv, "daily")] // 10 * 10),
|
"status_code": 8 if feeding else 1,
|
||||||
"total_energy_wh": int(state[(inv, "total")]),
|
"status_text": ("MPP" if feeding else "Standby") if inv != "INV5" else ("Generating" if feeding else "Standby"),
|
||||||
}
|
}
|
||||||
|
if inv in ("INV1", "INV3"):
|
||||||
|
r["raw_status_oem"] = 7 if feeding else 3
|
||||||
|
return r
|
||||||
|
r.update({f"ac_current_l{i + 1}_a": round(w / 3 / v, 2) for i, v in enumerate(volts)})
|
||||||
|
r["dc_voltage_mppt1_v"] = round(random.uniform(560, 640), 1) if feeding else 0.0
|
||||||
|
if inv in ("INV2", "INV4"):
|
||||||
|
r["raw_status_sunspec"] = 4 if feeding else 2
|
||||||
|
return r
|
||||||
|
day = (t + timedelta(hours=3)).date()
|
||||||
|
if _inv5["day"] != day:
|
||||||
|
_inv5.update(day=day, daily_wh=0.0)
|
||||||
|
if _inv5["last"] is not None:
|
||||||
|
wh = w * (t - _inv5["last"]).total_seconds() / 3600
|
||||||
|
_inv5["daily_wh"] += wh
|
||||||
|
_inv5["total_wh"] += wh
|
||||||
|
_inv5["last"] = t
|
||||||
|
r.update(daily_energy_wh=int(_inv5["daily_wh"]), total_energy_wh=int(_inv5["total_wh"]), raw_status_cloud=1 if feeding else 0)
|
||||||
|
return r
|
||||||
|
|
||||||
|
|
||||||
def main() -> None:
|
def main() -> None:
|
||||||
@@ -72,13 +88,13 @@ def main() -> None:
|
|||||||
args = ap.parse_args()
|
args = ap.parse_args()
|
||||||
client = BackendClient(args.url, args.key, spool_path="fake_unsent.jsonl")
|
client = BackendClient(args.url, args.key, spool_path="fake_unsent.jsonl")
|
||||||
|
|
||||||
state: dict = {}
|
|
||||||
if args.backfill_days:
|
if args.backfill_days:
|
||||||
state["step"] = 300
|
now = int(time.time())
|
||||||
t = datetime.now(timezone.utc) - timedelta(days=args.backfill_days)
|
# On the 5-min grid, so INV5's cloud readings land in the backfill too
|
||||||
|
t = datetime.fromtimestamp(now - now % CLOUD_EVERY_S - args.backfill_days * 86400, timezone.utc)
|
||||||
batch: list[dict] = []
|
batch: list[dict] = []
|
||||||
while t < datetime.now(timezone.utc):
|
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:
|
if len(batch) >= 1000:
|
||||||
client.send(batch)
|
client.send(batch)
|
||||||
batch = []
|
batch = []
|
||||||
@@ -86,10 +102,9 @@ def main() -> None:
|
|||||||
client.send(batch)
|
client.send(batch)
|
||||||
print(f"Backfilled {args.backfill_days} days")
|
print(f"Backfilled {args.backfill_days} days")
|
||||||
|
|
||||||
state["step"] = args.interval
|
|
||||||
while True:
|
while True:
|
||||||
now = datetime.now(timezone.utc)
|
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)
|
ok = client.send(batch)
|
||||||
print(f"{now:%H:%M:%S} sent {len(batch)} readings, ok={ok}")
|
print(f"{now:%H:%M:%S} sent {len(batch)} readings, ok={ok}")
|
||||||
time.sleep(args.interval)
|
time.sleep(args.interval)
|
||||||
|
|||||||
Reference in New Issue
Block a user