Compare commits

..
4 Commits
Author SHA1 Message Date
bonaminandClaude Opus 5.5 9ac86e2588 docs: settings API, per-inverter offline window, language
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 18:15:38 +03:00
bonaminandClaude Opus 5.5 0b74842560 feat(frontend): settings page, Greek translation, comparison and chart options
The end user is Greek and the owner wants to confirm at a glance that
every inverter is working without one cloud-shaded reading raising doubt.

- Settings page (gear in the header), stored on the server and shared
  by every viewer; saving asks for the API key once per device.
- Output comparison: latest reading or average of the last 3/5 (evens out
  a passing cloud); bar scale auto (round ceiling above the best) /
  highest = 100% / custom kW; percentage vs fleet median, best inverter
  or the custom kW.
- Power chart: 30 min to last month plus "last production run", a
  per-visit range picker on the card, optional light/strong smoothing.
  Series reporting slower than the chart bucket (INV5, every 5 min) are
  now interpolated across short gaps — on 1-min buckets their line used
  to vanish entirely; night gaps still break the line.
- Greek/English: per-device switch in the header, shared default in
  settings, Greek number/date formats; issue texts translated from
  code + params.
- AC voltage shown as phase (L-N) or line (L-L, x√3, matching the
  inverter screens); lifetime total says how many inverters it covers;
  the inverter's own status text appears on its card.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 18:15:38 +03:00
bonaminandClaude Opus 5.5 c24770af1c feat(poller): simulate the five-inverter contract
The fake poller now matches the 2026-10-22 data contract: INV1/INV3 send
no currents/DC/energy, INV2/INV4 add currents and MPPT1 voltage, INV5
reports via the cloud every 5 min with real daily/lifetime counters and
keeps sending 0 W / Standby at night while the others go silent. Status
codes are the normalized 8/1. Lets the dashboard be tried against the
real mix of missing fields and cadences.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 18:15:38 +03:00
bonaminandClaude Opus 5.5 8029468fb1 feat(api): shared view settings, recent readings, last production run
Groundwork for the dashboard settings page and the five-inverter contract:

- GET/PUT /api/settings stores display options (comparison averaging,
  scale and reference, power chart range and smoothing, voltage display,
  default language) in the meta table. Shared by every viewer since there
  are no accounts; PUT needs the API key so a public visitor can't change
  everyone's view. Unknown keys are ignored, missing ones take defaults.
- /api/summary returns each inverter's last few readings (recent_power) so
  the comparison can average out one reading taken under a passing cloud.
- Offline is now judged per inverter: a couple of missed cycles at the
  unit's own cadence (INV5 is cloud-polled every ~5 min), never below
  ONLINE_WINDOW_SECONDS. Before, INV5 flapped offline between reports.
- /api/power?last_run=true covers the latest production run, split at
  night silences; units reporting 0 W overnight don't join runs.
- Issues carry params so clients can render them in Greek.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 17:59:33 +03:00
23 changed files with 1597 additions and 234 deletions
+20 -7
View File
@@ -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}/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/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/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). `X-API-Key` required |
### Adding parameters
@@ -84,8 +86,10 @@ the chart picker without further changes.
### Health rules
- **Offline** — no reading for `ONLINE_WINDOW_SECONDS` (5 min) while the
datalogger is still posting and the sun is up. At night that's **Sleeping**;
- **Offline** — no reading for `ONLINE_WINDOW_SECONDS` (5 min) — or 2.5× the
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
says so).
- **Fault** — the reading carries a non-zero `error_code`. No `error_code`
@@ -104,10 +108,19 @@ Thresholds are in `.env`.
Daily energy uses, in order: the inverter's daily counter
(`daily_energy_wh`), the growth of its lifetime counter, or — while neither
is decoded, which is the case today — AC power integrated over time
(trapezoid between consecutive readings, gaps over 5 min not bridged). The
estimate is flagged (`estimated: true` in the API, "≈" on the dashboard).
Lifetime energy shows "not available yet" until `total_energy_wh` is sent.
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; the API key is asked
once and remembered on the device. 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`.
+54 -4
View File
@@ -1,3 +1,4 @@
import json
import logging
import secrets
import sqlite3
@@ -5,11 +6,12 @@ from datetime import date, datetime, timedelta, timezone
from typing import Annotated
from fastapi import APIRouter, Body, Depends, Header, HTTPException, Query
from pydantic import ValidationError
from . import fields, health, store
from .config import get_settings
from .db import get_db, set_meta
from .schemas import IngestResult, Inverter, InverterUpdate, ReadingIn, Summary
from .db import get_db, get_meta, set_meta
from .schemas import IngestResult, Inverter, InverterUpdate, ReadingIn, Summary, ViewSettings
log = logging.getLogger("solar")
router = APIRouter(prefix="/api")
@@ -88,9 +90,25 @@ def get_summary(conn: Db):
@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)."""
s, e = _range(start, end, timedelta(hours=24))
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))
b = store.pick_bucket(s, e, bucket)
return {
"from": store.to_dt(s),
@@ -101,6 +119,38 @@ 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,
dependencies=[Depends(require_api_key)],
tags=["settings"],
)
def put_view_settings(conn: Db, body: ViewSettings):
"""Replace the display options for every viewer. Omitted keys reset to their default."""
set_meta(conn, SETTINGS_KEY, body.model_dump_json())
return body
@router.get("/energy/daily", tags=["dashboard"])
def get_fleet_daily_energy(
conn: Db,
+32 -1
View File
@@ -14,6 +14,15 @@ from .config import get_settings
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:
if seconds < 3600:
return f"{seconds // 60} min"
@@ -39,10 +48,21 @@ def summary(conn: sqlite3.Connection) -> dict:
latest = store.latest_all(conn)
averages = store.window_averages(conn, s.underperform_window_seconds)
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:
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
# set, raw watts otherwise (assumes similar arrays).
@@ -74,6 +94,7 @@ def summary(conn: sqlite3.Connection) -> dict:
if not online:
since = f"for {_minutes(r['age_seconds'])}" if r else "yet"
silent_s = r["age_seconds"] if r else None
if not datalogger_online:
state = "unknown"
issues.append({
@@ -89,6 +110,7 @@ def summary(conn: sqlite3.Connection) -> dict:
"code": "not_responding",
"severity": "critical",
"message": f"Not responding {since} while the datalogger is online",
"params": {"seconds": silent_s},
})
else:
if r.get("error_code"):
@@ -98,12 +120,14 @@ def summary(conn: sqlite3.Connection) -> dict:
"code": "error_code",
"severity": "critical",
"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:
issues.append({
"code": "underperforming",
"severity": "warning",
"message": f"Producing {relative:.0%} of the fleet median — check strings, fuses and breakers",
"params": {"relative": relative},
})
avg = averages.get(inv["id"], {})
m1, m2 = avg.get("mppt1_w"), avg.get("mppt2_w")
@@ -115,6 +139,7 @@ def summary(conn: sqlite3.Connection) -> dict:
"code": "mppt_imbalance",
"severity": "warning",
"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:
state = "warning"
@@ -131,9 +156,15 @@ def summary(conn: sqlite3.Connection) -> dict:
"issues": issues,
"avg_power_w": round(averages[inv["id"]]["ac_power_w"]) if online and averages.get(inv["id"], {}).get("ac_power_w") is not None else None,
"relative_output": relative,
"online_window_seconds": window(inv["id"]),
},
"energy_today": energy_today.get(inv["id"], {"wh": None, "estimated": False}),
"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]
+53
View File
@@ -82,6 +82,10 @@ class Issue(BaseModel):
code: str
severity: Severity
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):
@@ -95,6 +99,10 @@ class Health(BaseModel):
relative_output: float | None = Field(
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):
@@ -102,11 +110,20 @@ class EnergyToday(BaseModel):
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):
inverter: Inverter
health: Health
energy_today: EnergyToday
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):
@@ -130,6 +147,42 @@ class Sun(BaseModel):
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):
generated_at: datetime
datalogger: Datalogger
+37
View File
@@ -259,6 +259,43 @@ def window_averages(conn: sqlite3.Connection, seconds: int) -> dict[str, dict]:
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
+54
View File
@@ -189,3 +189,57 @@ def test_energy_survives_out_of_order_readings(client):
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}
assert client.put("/api/settings", json=body, headers={"X-API-Key": "nope"}).status_code == 401
saved = client.put("/api/settings", json=body).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
View File
@@ -5,8 +5,10 @@ import { useInstallPrompt } from './hooks/useInstallPrompt'
import { usePoll } from './hooks/usePoll'
import { api } from './lib/api'
import { ago } from './lib/format'
import { useT } from './lib/i18n'
import Dashboard from './pages/Dashboard'
import InverterDetail from './pages/InverterDetail'
import Settings from './pages/Settings'
function useTick(ms) {
const [, setN] = useState(0)
@@ -17,6 +19,7 @@ function useTick(ms) {
}
function LiveChip({ summary, error }) {
const { t } = useT()
useTick(10_000)
if (error && !summary) return null
if (!summary) return null
@@ -28,7 +31,11 @@ function LiveChip({ summary, error }) {
style={{ background: ok ? 'var(--good)' : 'var(--critical)' }}
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>
)
}
@@ -37,26 +44,38 @@ export default function App() {
// One summary poll shared by both pages, so navigating is instant
const summaryPoll = usePoll(() => api.summary(), 30_000)
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 (
<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">
<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" />
<span>Solar Monitor</span>
<span className="hidden truncate min-[400px]:inline">{t('app.title')}</span>
</Link>
<div className="flex items-center gap-3">
<div className="flex items-center gap-2">
<LiveChip summary={summaryPoll.data} error={summaryPoll.error} />
{install && (
<button
type="button"
onClick={install}
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 type="button" onClick={install} className={iconButton} aria-label={t('nav.install')}>
<Icon name="download" size={14} />
<span className="hidden sm:inline">{t('nav.install')}</span>
</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>
</header>
@@ -64,6 +83,7 @@ export default function App() {
<Routes>
<Route path="/" element={<Dashboard summaryPoll={summaryPoll} />} />
<Route path="/inverters/:id" element={<InverterDetail summaryPoll={summaryPoll} />} />
<Route path="/settings" element={<Settings />} />
<Route path="*" element={<Dashboard summaryPoll={summaryPoll} />} />
</Routes>
</main>
+78 -16
View File
@@ -12,6 +12,7 @@ import {
} from 'recharts'
import { useThemeColors } from '../lib/colors'
import { dateTimeLabel, dayLabel, timeLabel } from '../lib/format'
import { useT } from '../lib/i18n'
export function Legend({ series }) {
if (series.length < 2) return null
@@ -28,6 +29,7 @@ export function Legend({ series }) {
}
function TooltipBox({ title, rows, total }) {
const { t } = useT()
return (
<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>
@@ -46,7 +48,7 @@ function TooltipBox({ title, rows, total }) {
))}
{total && (
<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>
</tr>
)}
@@ -58,26 +60,83 @@ function TooltipBox({ title, rows, total }) {
const axisTick = (c) => ({ fill: c.muted, fontSize: 11 })
/** Insert an empty point wherever readings stop for more than a couple of
* buckets (night, outage), so the line breaks instead of bridging the gap. */
function withGaps(points, bucket) {
if (!bucket || points.length < 2) return points
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 })
out.push(points[i])
// Silences up to this long are drawn through; longer ones (night, outage)
// break the line. Covers a unit reporting every ~5 min plus a missed cycle.
const BRIDGE_SECONDS = 900
const SMOOTHING_RADIUS = { off: 0, light: 1, strong: 3 }
/**
* Chart rows from API points: a gap row where the whole fleet went silent,
* 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
}
}
prev = i
})
}
return out
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}]
* 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 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 (
<div style={{ height }}>
<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 }}
content={({ active, payload, label }) => {
if (!active || !payload?.length) return null
const row = payload[0].payload
const rows = series
.filter((s) => payload[0].payload[s.key] != null)
.map((s) => ({ ...s, value: format(payload[0].payload[s.key]) }))
.filter((s) => row[s.key] != null)
.map((s) => ({ ...s, value: (row[`${s.key}__est`] ? '≈ ' : '') + format(row[s.key]) }))
const total = showTotal
? format(series.reduce((sum, s) => sum + (payload[0].payload[s.key] ?? 0), 0))
: null
@@ -121,6 +181,7 @@ export function TimeLines({ points, series, from, to, bucket, format, axisFormat
name={s.name}
stroke={s.color}
strokeWidth={2}
type={smoothing === 'off' ? 'linear' : 'monotone'}
dot={false}
activeDot={{ r: 4, stroke: c.surface, strokeWidth: 2 }}
connectNulls={false}
@@ -191,10 +252,11 @@ export function DayBars({ days, series, format, axisFormat, height = 220 }) {
}
export function EnergyFootnote({ estimated }) {
const { t } = useT()
return (
<div className="mt-1 flex justify-between gap-3 text-[11px] text-muted">
<span>{estimated && '≈ Estimated from AC power readings until the energy counters are decoded'}</span>
<span className="shrink-0">axis in kWh</span>
<span>{estimated && t('energy.footEstimated')}</span>
<span className="shrink-0">{t('energy.axis')}</span>
</div>
)
}
+102 -22
View File
@@ -1,35 +1,112 @@
import { Link } from 'react-router-dom'
import { seriesCssVar } from '../lib/colors'
import { pct, power } from '../lib/format'
import { useT } from '../lib/i18n'
import { useSettings } from '../lib/settings'
import Icon from './Icon'
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
* 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 }) {
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 value = (st) => {
const w = st.health.online ? st.latest?.ac_power_total_w ?? null : null
if (w === null) return null
return perKwp && st.inverter.capacity_kwp ? w / st.inverter.capacity_kwp : w
const rows = summary.inverters.map((st) => {
const w = watts(st, n)
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 (
<section className="card p-4">
<div className="mb-3 flex items-baseline justify-between gap-2">
<h2 className="text-sm font-semibold">Output comparison</h2>
<span className="text-xs text-muted">{perKwp ? 'per kWp · vs median' : 'now · vs median'}</span>
<div className="mb-3 flex flex-wrap items-baseline justify-between gap-x-3 gap-y-0.5">
<h2 className="text-sm font-semibold">{t('cmp.title')}</h2>
<span className="text-xs text-muted">{caption}</span>
</div>
<ul className="space-y-3">
{rows.map((st) => {
const v = value(st)
{rows.map((r) => {
const { st } = r
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 (
<li key={st.inverter.id}>
<Link
@@ -46,33 +123,33 @@ export default function Comparison({ summary, ids }) {
<span className="truncate font-medium">{st.inverter.name}</span>
</span>
<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">
<Icon name={state.icon} size={13} />
{state.label}
{t(`state.${STATES[st.health.state] ? st.health.state : 'unknown'}`)}
</span>
) : (
<>
<span className="font-semibold">{power(st.latest.ac_power_total_w)}</span>
<span className="font-semibold">{power(r.w)}</span>
<span
className={`inline-flex w-14 items-center justify-end gap-0.5 text-xs ${
flagged ? 'font-semibold text-warn' : 'text-muted'
}`}
>
{flagged && <Icon name="alert" size={12} strokeWidth={2.5} />}
{pct(st.health.relative_output)}
{pct(ratio(r))}
</span>
</>
)}
</span>
</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
className="h-full rounded-full transition-[width] duration-500"
style={{
width: `${v === null ? 0 : Math.max(1, (v / max) * 100)}%`,
background: seriesCssVar(ids, st.inverter.id),
}}
style={{ width: `${barPct(r)}%`, background: seriesCssVar(ids, st.inverter.id) }}
/>
</div>
</Link>
@@ -80,6 +157,9 @@ export default function Comparison({ summary, ids }) {
)
})}
</ul>
{fullBar && (
<div className="mt-3 text-right text-[11px] text-muted tnum">{t('cmp.fullBar', { v: fullBar })}</div>
)}
</section>
)
}
+17 -31
View File
@@ -1,17 +1,9 @@
import { useState } from 'react'
import { api } from '../lib/api'
import { rememberApiKey, storedApiKey } from '../lib/apiKey'
import { useT } from '../lib/i18n'
import Icon from './Icon'
const KEY_STORAGE = 'solar.apiKey'
function storedKey() {
try {
return localStorage.getItem(KEY_STORAGE) ?? ''
} catch {
return ''
}
}
function Field({ label, hint, children }) {
return (
<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)]'
export default function EditInverterDialog({ inverter, onClose, onSaved }) {
const { t } = useT()
const [form, setForm] = useState({
name: inverter.name ?? '',
capacity_kwp: inverter.capacity_kwp ?? '',
@@ -33,7 +26,7 @@ export default function EditInverterDialog({ inverter, onClose, onSaved }) {
sort_order: inverter.sort_order ?? 0,
notes: inverter.notes ?? '',
})
const [apiKey, setApiKey] = useState(storedKey)
const [apiKey, setApiKey] = useState(storedApiKey)
const [saving, setSaving] = useState(false)
const [error, setError] = useState(null)
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,
}
const saved = await api.updateInverter(inverter.id, body, apiKey)
try {
localStorage.setItem(KEY_STORAGE, apiKey)
} catch {
/* storage unavailable — key just isn't remembered */
}
rememberApiKey(apiKey)
onSaved(saved)
} catch (err) {
setError(err.status === 401 ? 'Wrong API key' : err.message)
setError(err.status === 401 ? t('common.wrongKey') : err.message)
} finally {
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]"
>
<div className="mb-4 flex items-center justify-between">
<h2 className="font-semibold">Inverter settings</h2>
<button type="button" onClick={onClose} className="-m-2 p-2 text-ink-2" aria-label="Close">
<h2 className="font-semibold">{t('edit.title')}</h2>
<button type="button" onClick={onClose} className="-m-2 p-2 text-ink-2" aria-label={t('common.close')}>
<Icon name="close" size={20} />
</button>
</div>
<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} />
</Field>
<div className="grid grid-cols-2 gap-3">
<Field label="Array size (kWp)">
<Field label={t('edit.kwp')}>
<input
className={input}
type="number"
@@ -96,24 +85,21 @@ export default function EditInverterDialog({ inverter, onClose, onSaved }) {
onChange={set('capacity_kwp')}
/>
</Field>
<Field label="MPPT inputs used">
<Field label={t('edit.mppt')}>
<select className={input} value={form.mppt_count} onChange={set('mppt_count')}>
<option value={1}>1</option>
<option value={2}>2</option>
</select>
</Field>
</div>
<p className="-mt-2 text-xs text-muted">
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.
</p>
<Field label="Sort order">
<p className="-mt-2 text-xs text-muted">{t('edit.kwpHint')}</p>
<Field label={t('edit.sort')}>
<input className={input} type="number" inputMode="numeric" value={form.sort_order} onChange={set('sort_order')} />
</Field>
<Field label="Notes">
<Field label={t('edit.notes')}>
<textarea className={`${input} min-h-20 py-2`} value={form.notes} onChange={set('notes')} />
</Field>
<Field label="API key">
<Field label={t('common.apiKey')}>
<input
className={input}
type="password"
@@ -129,7 +115,7 @@ export default function EditInverterDialog({ inverter, onClose, onSaved }) {
disabled={saving}
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>
</div>
</form>
+23 -13
View File
@@ -1,13 +1,15 @@
import { issueText, useT } from '../lib/i18n'
import Icon from './Icon'
// Labels: t(`state.${key}`)
export const STATES = {
ok: { label: 'Operating', icon: 'check', tone: 'good' },
standby: { label: 'Standby', icon: 'pause', tone: 'neutral' },
warning: { label: 'Check needed', icon: 'alert', tone: 'warning' },
fault: { label: 'Fault', icon: 'fault', tone: 'critical' },
offline: { label: 'Offline', icon: 'offline', tone: 'critical' },
sleeping: { label: 'Sleeping', icon: 'moon', tone: 'neutral' },
unknown: { label: 'No data', icon: 'unknown', tone: 'neutral' },
ok: { icon: 'check', tone: 'good' },
standby: { icon: 'pause', tone: 'neutral' },
warning: { icon: 'alert', tone: 'warning' },
fault: { icon: 'fault', tone: 'critical' },
offline: { icon: 'offline', tone: 'critical' },
sleeping: { icon: 'moon', tone: 'neutral' },
unknown: { icon: 'unknown', tone: 'neutral' },
}
const TONE = {
@@ -22,19 +24,22 @@ const SEVERITY_ICON = { critical: 'fault', warning: 'alert', info: 'unknown' }
/** Health state pill: always icon + label, never color alone. */
export function StatePill({ state, feeding, size = 'md' }) {
let s = STATES[state] ?? STATES.unknown
if (state === 'ok' && feeding) s = { ...s, label: 'Feeding' }
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'
return (
<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} />
{s.label}
{label}
</span>
)
}
/** Online = a reading within the last 5 minutes. */
export function OnlineDot({ online }) {
const { t } = useT()
return (
<span className="inline-flex items-center gap-1.5 text-xs text-ink-2">
<span
@@ -42,12 +47,14 @@ export function OnlineDot({ online }) {
style={{ background: online ? 'var(--good)' : 'var(--muted)' }}
aria-hidden="true"
/>
{online ? 'Online' : 'Offline'}
{online ? t('online.online') : t('online.offline')}
</span>
)
}
/** issues: from /api/summary; an optional `who` (inverter name) is prefixed. */
export function IssueList({ issues, compact = false }) {
const { t } = useT()
if (!issues?.length) return null
return (
<ul className={compact ? 'space-y-1' : 'space-y-2'}>
@@ -55,11 +62,14 @@ export function IssueList({ issues, compact = false }) {
const tone = SEVERITY_TONE[issue.severity]
return (
<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]}`}
>
<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>
)
})}
+12
View File
@@ -52,6 +52,18 @@ const PATHS = {
</>
),
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: (
<>
<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" />
+13 -7
View File
@@ -1,15 +1,18 @@
import { Link } from 'react-router-dom'
import { seriesCssVar } from '../lib/colors'
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 Icon from './Icon'
function Stat({ label, value, unit, unavailable }) {
const { t } = useT()
return (
<div className="min-w-0">
<div className="text-[11px] uppercase tracking-wide text-muted">{label}</div>
{unavailable ? (
<div className="text-xs leading-5 text-muted">not available yet</div>
<div className="text-xs leading-5 text-muted">{unavailable === true ? t('common.notAvailable') : unavailable}</div>
) : (
<div className="truncate tnum">
<span className="font-semibold">{value}</span>
@@ -21,13 +24,15 @@ function Stat({ label, value, unit, unavailable }) {
}
export default function InverterCard({ status, ids }) {
const { t } = useT()
const { settings } = useSettings()
const { inverter, health, latest, energy_today: energyToday } = status
const r = latest ?? {}
const live = health.online
const [pw, pu] = powerParts(live ? r.ac_power_total_w : null)
const [today, todayU] = energyParts(energyToday.wh)
const [life, lifeU] = energyParts(r.total_energy_wh)
const volts = [r.ac_voltage_l1_v, r.ac_voltage_l2_v, r.ac_voltage_l3_v]
const volts = [r.ac_voltage_l1_v, r.ac_voltage_l2_v, r.ac_voltage_l3_v].map((v) => displayVoltage(v, settings))
return (
<Link
@@ -48,6 +53,7 @@ export default function InverterCard({ status, ids }) {
<OnlineDot online={live} />
<span className="text-xs text-muted">· {ago(r.timestamp)}</span>
</div>
{live && r.status_text && <div className="mt-0.5 truncate text-xs text-muted">{r.status_text}</div>}
</div>
<StatePill state={health.state} feeding={health.feeding} />
</div>
@@ -64,17 +70,17 @@ export default function InverterCard({ status, ids }) {
<div className="grid grid-cols-3 gap-3 text-sm">
<Stat
label={energyToday.estimated ? 'Today ≈' : 'Today'}
label={t(energyToday.estimated ? 'hero.todayEst' : 'hero.today')}
value={today}
unit={todayU}
unavailable={energyToday.wh == null && live}
/>
<Stat label="Lifetime" value={life} unit={lifeU} unavailable={r.total_energy_wh == null} />
<Stat label="Temp" value={live ? num(r.temperature_c) : '—'} unit="°C" />
<Stat label={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 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) => (
<span key={i}>
<span className="text-muted">L{i + 1} </span>
@@ -87,7 +93,7 @@ export default function InverterCard({ status, ids }) {
{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">
Details <Icon name="chevron" size={12} />
{t('card.details')} <Icon name="chevron" size={12} />
</span>
</Link>
)
+2
View File
@@ -43,6 +43,8 @@ export const api = {
history: (id, params) => request(`${inv(id)}/history${qs(params)}`),
inverterDaily: (id, params) => request(`${inv(id)}/daily${qs(params)}`),
updateInverter: (id, body, apiKey) => request(inv(id), { method: 'PATCH', body, apiKey }),
settings: () => request('/settings'),
saveSettings: (body, apiKey) => request('/settings', { method: 'PUT', body, apiKey }),
}
export function isoAgo(seconds) {
+19
View File
@@ -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
View File
@@ -1,5 +1,21 @@
const nf = (digits) =>
new Intl.NumberFormat(undefined, { minimumFractionDigits: digits, maximumFractionDigits: digits })
// Set by the language provider so numbers and dates follow the chosen language
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) {
return v === null || v === undefined || Number.isNaN(v) ? '—' : nf(digits).format(v)
@@ -33,13 +49,31 @@ export function energy(wh) {
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) {
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))
if (s < 60) return `${s} s ago`
if (s < 3600) return `${Math.floor(s / 60)} min ago`
if (s < 86400) return `${Math.floor(s / 3600)} h ago`
return `${Math.floor(s / 86400)} d ago`
if (s < 60) return u.ago(`${s} ${u.s}`)
if (s < 3600) return u.ago(`${Math.floor(s / 60)} ${u.min}`)
if (s < 86400) return u.ago(`${Math.floor(s / 3600)} ${u.h}`)
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) {
@@ -48,12 +82,12 @@ export function pct(ratio) {
export function timeLabel(unix, spanSeconds) {
const d = new Date(unix * 1000)
if (spanSeconds <= 2 * 86400) return d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })
return d.toLocaleDateString([], { weekday: 'short', day: 'numeric' })
if (spanSeconds <= 2 * 86400) return d.toLocaleTimeString(locale(), { hour: '2-digit', minute: '2-digit' })
return d.toLocaleDateString(locale(), { weekday: 'short', day: 'numeric' })
}
export function dateTimeLabel(unix) {
return new Date(unix * 1000).toLocaleString([], {
return new Date(unix * 1000).toLocaleString(locale(), {
weekday: 'short',
day: 'numeric',
month: 'short',
@@ -65,6 +99,6 @@ export function dateTimeLabel(unix) {
export function dayLabel(isoDay, long = false) {
const d = new Date(`${isoDay}T12:00:00`)
return long
? d.toLocaleDateString([], { weekday: 'short', day: 'numeric', month: 'short', year: 'numeric' })
: d.toLocaleDateString([], { day: 'numeric', month: 'short' })
? d.toLocaleDateString(locale(), { weekday: 'short', day: 'numeric', month: 'short', year: 'numeric' })
: d.toLocaleDateString(locale(), { day: 'numeric', month: 'short' })
}
+481
View File
@@ -0,0 +1,481 @@
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.apiKeyHelp': 'Needed to save. Remembered on this device.',
'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.apiKeyHelp': 'Απαιτείται για αποθήκευση. Απομνημονεύεται σε αυτή τη συσκευή.',
'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
}
}
+63
View File
@@ -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, apiKey) => {
const saved = await api.saveSettings(next, apiKey)
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
}
+7 -1
View File
@@ -2,12 +2,18 @@ import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import { BrowserRouter } from 'react-router-dom'
import App from './App'
import { LanguageProvider } from './lib/i18n'
import { SettingsProvider } from './lib/settings'
import './index.css'
createRoot(document.getElementById('root')).render(
<StrictMode>
<BrowserRouter>
<App />
<SettingsProvider>
<LanguageProvider>
<App />
</LanguageProvider>
</SettingsProvider>
</BrowserRouter>
</StrictMode>,
)
+92 -40
View File
@@ -7,33 +7,42 @@ import Icon from '../components/Icon'
import InverterCard from '../components/InverterCard'
import Segmented from '../components/Segmented'
import { usePoll } from '../hooks/usePoll'
import { api } from '../lib/api'
import { api, isoAgo } from '../lib/api'
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 }) {
const { t: tr } = useT()
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 [today, todayU] = energyParts(t.daily_energy_wh)
const [life, lifeU] = energyParts(t.total_energy_wh)
return (
<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">
<span className="text-5xl font-semibold tracking-tight sm:text-6xl">{pw}</span>
<span className="text-xl text-ink-2">{pu}</span>
</div>
<dl className="mt-4 grid grid-cols-3 gap-3 border-t border-line pt-4 text-sm">
<div>
<dt className="text-xs text-muted">{t.daily_energy_estimated ? 'Today ≈' : 'Today'}</dt>
<dt className="text-xs text-muted">{tr(t.daily_energy_estimated ? 'hero.todayEst' : 'hero.today')}</dt>
<dd className="tnum">
<span className="text-lg font-semibold">{today}</span> <span className="text-ink-2">{todayU}</span>
</dd>
</div>
<div>
<dt className="text-xs text-muted">Lifetime</dt>
<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">not available yet</dd>
<dd className="text-xs leading-7 text-muted">{tr('common.notAvailableYet')}</dd>
) : (
<dd className="tnum">
<span className="text-lg font-semibold">{life}</span> <span className="text-ink-2">{lifeU}</span>
@@ -41,7 +50,7 @@ function Hero({ summary }) {
)}
</div>
<div>
<dt className="text-xs text-muted">Feeding</dt>
<dt className="text-xs text-muted">{tr('hero.feeding')}</dt>
<dd className="tnum">
<span className="text-lg font-semibold">{t.feeding_count}</span>
<span className="text-ink-2"> / {t.inverter_count}</span>
@@ -53,70 +62,112 @@ function Hero({ summary }) {
}
function Alerts({ summary }) {
const { t } = useT()
const items = summary.inverters.flatMap((st) =>
st.health.issues
.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
return (
<section aria-label="Problems">
<section aria-label={t('alerts.label')}>
<IssueList issues={items} />
</section>
)
}
function DataloggerBanner({ summary }) {
const { t } = useT()
if (summary.datalogger.online) return null
return (
<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" />
<div>
<div className="font-semibold">Site datalogger is not reporting</div>
<div className="font-semibold">{t('banner.title')}</div>
<div className="text-ink-2">
Last data {summary.datalogger.last_ingest_at ? new Date(summary.datalogger.last_ingest_at).toLocaleString() : 'never'}.
Check the on-site laptop and its internet connection — inverter states below are unknown.
{t('banner.body', {
when: summary.datalogger.last_ingest_at ? dateTime(summary.datalogger.last_ingest_at) : t('common.never'),
})}
</div>
</div>
</div>
)
}
const capitalize = (s) => s.charAt(0).toUpperCase() + s.slice(1)
function PowerChart({ range, series, smoothing }) {
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 (
<TimeLines
points={data.points}
series={series}
from={Date.parse(data.from) / 1000}
to={Date.parse(data.to) / 1000}
bucket={data.bucket}
format={power}
axisFormat={(w) => num(w / 1000, 0) + ' kW'}
showTotal
smoothing={smoothing}
/>
)
}
function PowerCard({ ids, names }) {
const c = useThemeColors()
const { data } = usePoll(() => api.power(), 60_000)
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-baseline justify-between gap-2">
<h2 className="text-sm font-semibold">Power · last 24 h</h2>
<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>
{data ? (
<TimeLines
points={data.points}
series={series}
from={Date.parse(data.from) / 1000}
to={Date.parse(data.to) / 1000}
bucket={data.bucket}
format={power}
axisFormat={(w) => num(w / 1000, 0) + ' kW'}
showTotal
/>
) : (
<div className="h-60" />
)}
{loaded ? <PowerChart range={range} series={series} smoothing={smoothing} /> : <div className="h-60" />}
</section>
)
}
function EnergyCard({ ids, names }) {
const c = useThemeColors()
const { t } = useT()
const [mode, setMode] = useState('combined')
const { data } = usePoll(() => api.dailyEnergy({ days: 30 }), 300_000)
const series =
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) }))
const total = data?.days.reduce((s, d) => s + (d.total_wh ?? 0), 0)
const estimated = data?.days.some((d) => d.estimated)
@@ -125,21 +176,21 @@ function EnergyCard({ ids, names }) {
<section className="card p-4">
<div className="mb-3 flex flex-wrap items-center justify-between gap-2">
<div>
<h2 className="text-sm font-semibold">Daily energy · last 30 days</h2>
<h2 className="text-sm font-semibold">{t('energy.title')}</h2>
{data && !empty && (
<div className="text-xs text-muted tnum">
{estimated && '≈ '}
{energy(total)} total
{t('energy.total', { v: energy(total) })}
</div>
)}
</div>
<Segmented
label="Energy chart mode"
label={t('energy.mode')}
value={mode}
onChange={setMode}
options={[
{ value: 'combined', label: 'Combined' },
{ value: 'split', label: 'Per inverter' },
{ value: 'combined', label: t('energy.combined') },
{ value: 'split', label: t('energy.split') },
]}
/>
</div>
@@ -149,7 +200,7 @@ function EnergyCard({ ids, names }) {
</div>
)}
{empty ? (
<div className="flex h-56 items-center justify-center text-sm text-muted">No energy data yet</div>
<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)} />
) : (
@@ -161,6 +212,7 @@ function EnergyCard({ ids, names }) {
}
export default function Dashboard({ summaryPoll }) {
const { t } = useT()
const { data: summary, error } = summaryPoll
const ids = useMemo(() => summary?.inverters.map((s) => s.inverter.id) ?? [], [summary])
const names = useMemo(
@@ -171,7 +223,7 @@ export default function Dashboard({ summaryPoll }) {
if (!summary) {
return (
<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>
)
}
@@ -180,7 +232,7 @@ export default function Dashboard({ summaryPoll }) {
return (
<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" />
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>.
</div>
)
@@ -201,7 +253,7 @@ export default function Dashboard({ summaryPoll }) {
</div>
</div>
<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">
{summary.inverters.map((st) => (
<InverterCard key={st.inverter.id} status={st} ids={ids} />
@@ -210,7 +262,7 @@ export default function Dashboard({ summaryPoll }) {
</section>
<p className="pb-4 text-center text-xs text-muted">
<Link to="/api/docs" reloadDocument className="underline-offset-2 hover:underline">
API documentation
{t('dash.apiDocs')}
</Link>
</p>
</div>
+74 -49
View File
@@ -8,20 +8,28 @@ import Segmented from '../components/Segmented'
import { usePoll } from '../hooks/usePoll'
import { api, isoAgo } from '../lib/api'
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 = {
'24h': { label: '24 h', seconds: 86400 },
'7d': { label: '7 days', seconds: 7 * 86400 },
'30d': { label: '30 days', seconds: 30 * 86400 },
'24h': { seconds: 86400 },
'7d': { seconds: 7 * 86400 },
'30d': { seconds: 30 * 86400 },
}
const GROUPS = [
{ key: 'ac', label: 'AC output' },
{ key: 'dc', label: 'DC input' },
{ key: 'energy', label: 'Energy' },
{ key: 'device', label: 'Device' },
]
const GROUPS = ['ac', 'dc', 'energy', 'device']
const isVoltage = (key) => /^ac_voltage_l\d_v$/.test(key)
/** 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) {
if (value === null || value === undefined) return '—'
@@ -32,11 +40,12 @@ function formatField(field, value) {
}
function KeyFigure({ label, parts, unavailable }) {
const { t } = useT()
return (
<div className="card px-4 py-3">
<div className="text-xs text-muted">{label}</div>
{unavailable ? (
<div className="text-sm leading-8 text-muted">not available yet</div>
<div className="text-sm leading-8 text-muted">{t('common.notAvailable')}</div>
) : (
<div className="tnum">
<span className="text-2xl font-semibold tracking-tight">{parts[0]}</span>
@@ -48,27 +57,31 @@ function KeyFigure({ label, parts, unavailable }) {
}
function Parameters({ fields, latest, live }) {
const { t } = useT()
const { settings } = useSettings()
const label = useFieldLabel()
const extra = Object.entries(latest?.extra ?? {})
const value = (f) => (isVoltage(f.key) ? displayVoltage(latest?.[f.key], settings) : latest?.[f.key])
return (
<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">
{latest ? `Last reading ${new Date(latest.timestamp).toLocaleString()}` : 'No readings yet'}
{latest && !live && ' — values are from the last time it reported'}
{latest ? t('detail.lastReadingAt', { when: dateTime(latest.timestamp) }) : t('detail.noReadings')}
{latest && !live && t('detail.stale')}
</p>
<div className="grid gap-x-8 gap-y-4 sm:grid-cols-2">
{GROUPS.map((g) => {
// Parameters the poller doesn't send (yet) are left out entirely
const items = fields.filter((f) => f.group === g.key && latest?.[f.key] != null)
// Parameters this inverter doesn't send are left out entirely
const items = fields.filter((f) => f.group === g && latest?.[f.key] != null)
return (
<div key={g.key}>
<h3 className="mb-1 text-xs font-semibold uppercase tracking-wide text-muted">{g.label}</h3>
{items.length === 0 && <p className="py-1.5 text-sm text-muted">Not available yet</p>}
<div key={g}>
<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">
{items.map((f) => (
<div key={f.key} className="flex justify-between gap-4 py-1.5">
<dt className="text-ink-2">{f.label}</dt>
<dd className="tnum font-medium">{formatField(f, latest?.[f.key])}</dd>
<dt className="text-ink-2">{label(f)}</dt>
<dd className="tnum font-medium">{formatField(f, value(f))}</dd>
</div>
))}
</dl>
@@ -77,7 +90,7 @@ function Parameters({ fields, latest, live }) {
})}
{extra.length > 0 && (
<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">
{extra.map(([k, v]) => (
<div key={k} className="flex justify-between gap-4 py-1.5">
@@ -95,6 +108,9 @@ function Parameters({ fields, latest, live }) {
function HistoryCharts({ id, fields }) {
const c = useThemeColors()
const { t } = useT()
const { settings } = useSettings()
const label = useFieldLabel()
const [range, setRange] = useState('7d')
const [param, setParam] = useState('temperature_c')
const seconds = RANGES[range].seconds
@@ -103,7 +119,7 @@ function HistoryCharts({ id, fields }) {
const points = data?.points ?? []
const hasData = (key) => points.some((p) => p[key] != null)
const powerSeries = [
{ key: 'ac_power_total_w', name: 'AC output', color: c.series[0] },
{ key: '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_mppt2_w', name: 'DC MPPT2', color: c.series[2] },
].filter((s, i) => i === 0 || hasData(s.key))
@@ -112,6 +128,11 @@ function HistoryCharts({ id, fields }) {
(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 to = data ? Date.parse(data.to) / 1000 : 1
@@ -119,12 +140,12 @@ function HistoryCharts({ id, fields }) {
<>
<section className="card p-4">
<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
label="History range"
label={t('detail.historyRange')}
value={range}
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 className="mb-2">
@@ -144,35 +165,33 @@ function HistoryCharts({ id, fields }) {
<div className="h-60" />
)}
<p className="mt-2 text-xs text-muted">
{hasDc
? 'MPPT1 and MPPT2 should track each other when both carry similar strings — one dropping away from the other points at that string.'
: 'DC input (MPPT) values are not available yet.'}
{hasDc ? t('detail.mpptNote') : t('detail.noDc')}
</p>
</section>
<section className="card p-4">
<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
value={paramField?.key}
onChange={(e) => setParam(e.target.value)}
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) => (
<option key={f.key} value={f.key}>
{f.label}
{label(f)}
{f.unit ? ` (${f.unit})` : ''}
</option>
))}
</select>
</div>
{data && !paramField ? (
<div className="flex h-52 items-center justify-center text-sm text-muted">No data in this range</div>
<div className="flex h-52 items-center justify-center text-sm text-muted">{t('detail.noDataRange')}</div>
) : data && paramField ? (
<TimeLines
points={data.points}
series={[{ key: paramField.key, name: paramField.label, color: c.series[0] }]}
points={paramPoints}
series={[{ key: paramField.key, name: label(paramField), color: c.series[0] }]}
from={from}
to={to}
bucket={data.bucket}
@@ -190,25 +209,26 @@ function HistoryCharts({ id, fields }) {
function YearEnergy({ id }) {
const c = useThemeColors()
const { t } = useT()
const { data } = usePoll(() => api.inverterDaily(id, { days: 365 }), 600_000, id)
const total = data?.days.reduce((s, d) => s + (d.energy_wh ?? 0), 0)
const estimated = data?.days.some((d) => d.estimated)
const empty = data && data.days.every((d) => d.energy_wh == null)
return (
<section className="card p-4">
<h2 className="text-sm font-semibold">Daily energy · last 365 days</h2>
<h2 className="text-sm font-semibold">{t('detail.yearEnergy')}</h2>
{data && !empty && (
<div className="mb-3 text-xs text-muted tnum">
{estimated && '≈ '}
{energy(total)} total
{t('energy.total', { v: energy(total) })}
</div>
)}
{empty ? (
<div className="flex h-56 items-center justify-center text-sm text-muted">No energy data yet</div>
<div className="flex h-56 items-center justify-center text-sm text-muted">{t('energy.empty')}</div>
) : data ? (
<DayBars
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}
axisFormat={(wh) => num(wh / 1000, 0)}
/>
@@ -221,19 +241,20 @@ function YearEnergy({ id }) {
}
export default function InverterDetail({ summaryPoll }) {
const { t } = useT()
const { id } = useParams()
const { data: summary, refresh } = summaryPoll
const { data: fields } = usePoll(() => api.fields(), 3_600_000)
const [editing, setEditing] = useState(false)
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) {
return (
<div className="py-24 text-center text-sm text-ink-2">
Unknown inverter “{id}”.{' '}
{t('detail.unknown', { id })}{' '}
<Link to="/" className="underline">
Back to overview
{t('detail.back')}
</Link>
</div>
)
@@ -246,14 +267,14 @@ export default function InverterDetail({ summaryPoll }) {
<div className="space-y-4">
<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} /> All inverters
<Icon name="back" size={16} /> {t('detail.all')}
</Link>
<div className="mt-1 flex flex-wrap items-center justify-between gap-3">
<div className="min-w-0">
<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">
<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.name !== inverter.id && <span>· {inverter.id}</span>}
</div>
@@ -265,7 +286,7 @@ export default function InverterDetail({ summaryPoll }) {
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"
>
<Icon name="edit" size={14} /> Edit
<Icon name="edit" size={14} /> {t('detail.edit')}
</button>
</div>
</div>
@@ -275,14 +296,18 @@ export default function InverterDetail({ summaryPoll }) {
<IssueList issues={health.issues} />
<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={status.energy_today.estimated ? 'Today ≈' : 'Today'}
label={t(status.energy_today.estimated ? 'hero.todayEst' : 'hero.today')}
parts={energyParts(status.energy_today.wh)}
/>
<KeyFigure label="Lifetime" parts={energyParts(latest?.total_energy_wh)} unavailable={latest?.total_energy_wh == null} />
<KeyFigure
label="vs fleet median"
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), '%']}
/>
</div>
+243
View File
@@ -0,0 +1,243 @@
import { useEffect, useState } from 'react'
import { Link } from 'react-router-dom'
import { input } from '../components/EditInverterDialog'
import Icon from '../components/Icon'
import { rememberApiKey, storedApiKey } from '../lib/apiKey'
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 [apiKey, setApiKey] = useState(storedApiKey)
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 }, apiKey)
rememberApiKey(apiKey)
setDirty(false)
setStatus('saved')
} catch (err) {
setStatus(new Error(err.status === 401 ? t('common.wrongKey') : err.message))
}
}
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>
<Section title={t('common.apiKey')}>
<Option help={t('settings.apiKeyHelp')}>
<input
className={input}
type="password"
autoComplete="current-password"
value={apiKey}
onChange={(e) => setApiKey(e.target.value)}
aria-label={t('common.apiKey')}
required
/>
</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>
)
}
+45 -21
View File
@@ -2,11 +2,15 @@
python fake_poller.py --url http://localhost:8090 --key change-me --backfill-days 30
Sends what the real poller sends today (AC side, temperature, status code,
unmapped diagnostics; no DC or energy counters). --backfill-days first loads
that many days of history (one reading per 5 minutes), then it posts live
readings every --interval seconds. INV4 runs at half output (as if a string
fuse had blown) so the warnings show up.
Follows the poller data contract of 2026-10-22: five units, three sources.
INV1/INV3 (OEM board) send AC voltages, power, frequency, temperature and
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
@@ -17,8 +21,13 @@ from datetime import datetime, timedelta, timezone
from backend_client import BackendClient
INVERTERS = ["INV1", "INV2", "INV4"]
INVERTERS = ["INV1", "INV2", "INV3", "INV4", "INV5"]
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:
@@ -30,31 +39,44 @@ def sun_factor(t: datetime) -> float:
def reading(inv: str, t: datetime) -> dict | None:
f = sun_factor(t) * random.uniform(0.93, 1.0)
if f <= 0.01:
return None # inverter asleep at night, doesn't answer
if inv == "INV5":
if int(t.timestamp()) % CLOUD_EVERY_S >= 60:
return None # cloud value only refreshes every 5 min
elif f <= 0.01:
return None # local units power down at night and don't answer
feeding = f > 0.03
w = int(PEAK_W * f * (0.5 if inv == "INV4" else 1.0)) if feeding else 0
volts = [round(random.uniform(229, 236), 2) for _ in range(3)]
amps = [round(w / 3 / v, 2) for v in volts]
return {
volts = [round(random.uniform(236, 244), 1) for _ in range(3)]
r = {
"inverter_id": inv,
"timestamp": t.isoformat(timespec="seconds"),
"ac_voltage_l1_v": volts[0],
"ac_voltage_l2_v": volts[1],
"ac_voltage_l3_v": volts[2],
"ac_current_l1_a": amps[0],
"ac_current_l2_a": amps[1],
"ac_current_l3_a": amps[2],
"ac_power_total_w": w,
"grid_frequency_hz": round(random.uniform(49.95, 50.05), 2),
"temperature_c": int(30 + 25 * f),
"status_code": (7 if inv == "INV1" else 8) if feeding else 3,
"status_text": "feeding" if feeding else "standby/not feeding",
"p06d_raw_latched": 21450,
"p052_static_v": 312.5,
"p05a_static_a": 45.0,
"p063_ind0_raw": 1872,
"status_code": 8 if feeding else 1,
"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:
@@ -67,7 +89,9 @@ def main() -> None:
client = BackendClient(args.url, args.key, spool_path="fake_unsent.jsonl")
if args.backfill_days:
t = datetime.now(timezone.utc) - timedelta(days=args.backfill_days)
now = int(time.time())
# 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] = []
while t < datetime.now(timezone.utc):
batch += [r for inv in INVERTERS if (r := reading(inv, t))]