feat: solar inverter monitor — FastAPI + SQLite backend, React PWA dashboard
Monitoring for the Refusol 020K inverters. The on-site poller POSTs each 60 s cycle to /api/readings; the dashboard answers first whether every inverter is operating and whether one is producing far less than its peers (string fuse / breaker problems). - Backend: FastAPI + SQLite. Parameters defined once in fields.py (columns auto-added on start); unknown poller keys are kept in `extra` since the parameter map is still being researched. Idempotent ingest, daily energy rollup in site-local days, history downsampling, 2-year retention. - Health: Offline vs Sleeping (sun elevation) vs No data (datalogger silent, detected via empty-batch heartbeats), Fault from error_code, underperformance vs fleet median (per kWp when sizes set), MPPT imbalance. - Frontend: mobile-first React + Tailwind, installable PWA, comparison bars, 24 h power / 30 day energy charts, detail page with all parameters. - Docker: backend + frontend + nginx on one port for NPM, as in bellsystems-cp; deploy-host.sh pulls main and rebuilds. - poller/backend_client.py: stdlib client with offline spool for refusol_poller.py; fake_poller.py simulates the site. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,39 @@
|
|||||||
|
# Host port the nginx container binds; point NPM (solar.bonamin.net) at it
|
||||||
|
HTTP_PORT=8090
|
||||||
|
|
||||||
|
# Shared secret: the on-site poller sends it as X-API-Key on POST /api/readings,
|
||||||
|
# and the dashboard asks for it when editing inverter settings.
|
||||||
|
# Generate one with: python -c "import secrets; print(secrets.token_urlsafe(32))"
|
||||||
|
API_KEY=change-me
|
||||||
|
|
||||||
|
# Site location — local day boundaries for daily energy, and the sun's
|
||||||
|
# elevation so inverters that switch off at night show "Sleeping", not "Offline".
|
||||||
|
# Leave LATITUDE/LONGITUDE empty to treat every silent inverter as offline.
|
||||||
|
SITE_TIMEZONE=Europe/Athens
|
||||||
|
SITE_LATITUDE=
|
||||||
|
SITE_LONGITUDE=
|
||||||
|
# Sun elevation (degrees) below which inverters are expected to be off
|
||||||
|
DAYLIGHT_MIN_ELEVATION=5
|
||||||
|
|
||||||
|
# Inverter counts as Online if its last reading is newer than this
|
||||||
|
ONLINE_WINDOW_SECONDS=300
|
||||||
|
# Raw readings older than this are purged (daily energy totals are kept)
|
||||||
|
RETENTION_DAYS=730
|
||||||
|
|
||||||
|
# Underperformance alarm: flag an inverter producing less than this fraction
|
||||||
|
# of the fleet median, averaged over the window. Skipped while the fleet makes
|
||||||
|
# less than the minimum (dawn/dusk/heavy cloud). The per-kWp minimum is used
|
||||||
|
# once every inverter has its array size (kWp) set, the W minimum otherwise.
|
||||||
|
UNDERPERFORM_RATIO=0.75
|
||||||
|
UNDERPERFORM_WINDOW_SECONDS=600
|
||||||
|
UNDERPERFORM_MIN_FLEET_W_PER_KWP=50
|
||||||
|
UNDERPERFORM_MIN_FLEET_W=1000
|
||||||
|
|
||||||
|
# String alarm: one MPPT input below this fraction of the other, once the
|
||||||
|
# stronger input exceeds MPPT_MIN_POWER_W (inverters set to 2 MPPTs only)
|
||||||
|
MPPT_IMBALANCE_RATIO=0.5
|
||||||
|
MPPT_MIN_POWER_W=1000
|
||||||
|
|
||||||
|
# Browser origins allowed to call the API directly (JSON list). The dashboard
|
||||||
|
# itself is same-origin and doesn't need this.
|
||||||
|
CORS_ORIGINS=["*"]
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
* text=auto eol=lf
|
||||||
|
*.png binary
|
||||||
+42
@@ -0,0 +1,42 @@
|
|||||||
|
# Auto-deploy generated files
|
||||||
|
deploy.sh
|
||||||
|
deploy.log
|
||||||
|
.deploy-trigger
|
||||||
|
|
||||||
|
# Secrets
|
||||||
|
.env
|
||||||
|
|
||||||
|
# Persistent runtime data (lives outside docker, not in git)
|
||||||
|
/data/*
|
||||||
|
!/data/.gitkeep
|
||||||
|
|
||||||
|
# SQLite databases
|
||||||
|
*.db
|
||||||
|
*.db-shm
|
||||||
|
*.db-wal
|
||||||
|
|
||||||
|
# Python
|
||||||
|
__pycache__/
|
||||||
|
*.pyc
|
||||||
|
.venv/
|
||||||
|
.pytest_cache/
|
||||||
|
*.egg-info/
|
||||||
|
|
||||||
|
# Poller local state
|
||||||
|
poller/*.jsonl
|
||||||
|
|
||||||
|
# Node
|
||||||
|
node_modules/
|
||||||
|
dist/
|
||||||
|
dev-dist/
|
||||||
|
|
||||||
|
# IDE
|
||||||
|
.vscode/
|
||||||
|
.idea/
|
||||||
|
|
||||||
|
# OS
|
||||||
|
.DS_Store
|
||||||
|
Thumbs.db
|
||||||
|
|
||||||
|
# claude
|
||||||
|
.claude/
|
||||||
+144
@@ -0,0 +1,144 @@
|
|||||||
|
# Refusol Solar Inverter Dashboard — Build Brief
|
||||||
|
|
||||||
|
## Context
|
||||||
|
|
||||||
|
Before writing any code, read the existing project at `C:\development\bellsystems-cp`.
|
||||||
|
Use it as the reference for all conventions: Docker setup, image naming, registry config,
|
||||||
|
Nginx Proxy Manager integration, compose structure, environment variable patterns, etc.
|
||||||
|
Mirror those conventions exactly throughout this project.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## What to Build
|
||||||
|
|
||||||
|
A full-stack solar inverter monitoring system.
|
||||||
|
|
||||||
|
An on-site Python poller script runs on a laptop at the solar installation, reads live
|
||||||
|
data from up to 5 Refusol 020K inverters over the local network, and POSTs readings to
|
||||||
|
this backend every 60 seconds. The frontend displays the data as a live dashboard.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Backend API
|
||||||
|
|
||||||
|
**Stack:** match whatever `bellsystems-cp` uses. If it uses FastAPI + SQLite, use that.
|
||||||
|
If it uses Express + PostgreSQL, use that.
|
||||||
|
|
||||||
|
### Endpoints
|
||||||
|
|
||||||
|
| Method | Path | Description |
|
||||||
|
|--------|------|-------------|
|
||||||
|
| `POST` | `/api/readings` | Ingest a batch of readings (one per inverter). Auth: `X-API-Key` header. |
|
||||||
|
| `GET` | `/api/inverters` | List all known inverters |
|
||||||
|
| `GET` | `/api/inverters/{id}/latest` | Latest reading for one inverter |
|
||||||
|
| `GET` | `/api/inverters/{id}/history` | Historical readings. Query params: `from`, `to` (ISO timestamps) |
|
||||||
|
| `GET` | `/api/summary` | Latest reading from every inverter + combined totals |
|
||||||
|
|
||||||
|
### Reading Schema
|
||||||
|
|
||||||
|
Each reading stored per inverter per poll cycle:
|
||||||
|
|
||||||
|
```
|
||||||
|
inverter_id string
|
||||||
|
timestamp datetime (UTC)
|
||||||
|
|
||||||
|
ac_voltage_l1_v float (Volts)
|
||||||
|
ac_voltage_l2_v float
|
||||||
|
ac_voltage_l3_v float
|
||||||
|
|
||||||
|
dc_voltage_mppt1_v float (Volts)
|
||||||
|
dc_voltage_mppt2_v float
|
||||||
|
dc_current_mppt1_a float (Amps)
|
||||||
|
dc_current_mppt2_a float
|
||||||
|
|
||||||
|
ac_current_l1_a float (Amps)
|
||||||
|
ac_current_l2_a float
|
||||||
|
ac_current_l3_a float
|
||||||
|
|
||||||
|
ac_power_total_w integer (Watts)
|
||||||
|
grid_frequency_hz float (Hz)
|
||||||
|
temperature_c integer (°C)
|
||||||
|
daily_energy_wh integer (Wh)
|
||||||
|
total_energy_wh integer (Wh)
|
||||||
|
```
|
||||||
|
|
||||||
|
### Data Retention
|
||||||
|
|
||||||
|
Auto-purge readings older than 2 years.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Frontend Dashboard
|
||||||
|
|
||||||
|
No login required — public read-only dashboard.
|
||||||
|
|
||||||
|
### Main page — all inverters
|
||||||
|
|
||||||
|
- One card per inverter showing:
|
||||||
|
- Current power output (W)
|
||||||
|
- Today's yield (kWh)
|
||||||
|
- Total lifetime yield (kWh)
|
||||||
|
- AC voltages (L1/L2/L3)
|
||||||
|
- Inverter temperature (°C)
|
||||||
|
- Status badge: **Online** (reading within last 5 min) / **Offline**
|
||||||
|
- Combined total power across all inverters (hero number at top)
|
||||||
|
- **Power chart:** last 24 h, one line per inverter
|
||||||
|
- **Daily energy chart:** last 30 days, bar chart, combined or per-inverter toggle
|
||||||
|
|
||||||
|
### Inverter detail page
|
||||||
|
|
||||||
|
- All parameters (voltages, currents, power, frequency, temperature, energy)
|
||||||
|
- Longer history charts (7 day power, 365 day daily energy)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Docker
|
||||||
|
|
||||||
|
- `docker-compose.yml` with separate containers for backend, frontend (and DB if needed)
|
||||||
|
- Follow `bellsystems-cp` for image naming and private registry push workflow
|
||||||
|
- Expose on a single port that NPM (Nginx Proxy Manager) can proxy to
|
||||||
|
- Target domain: **`solar.bonamin.net`**
|
||||||
|
- Include `.env.example` with all required variables documented
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Poller Integration
|
||||||
|
|
||||||
|
Update `refusol_poller.py` to POST to the backend after each poll cycle.
|
||||||
|
Add `BACKEND_URL` and `API_KEY` as config variables at the top of the file.
|
||||||
|
|
||||||
|
The POST payload for `/api/readings` should be a JSON array — one object per inverter
|
||||||
|
polled in that cycle, each matching the reading schema above plus `inverter_id`.
|
||||||
|
|
||||||
|
### Confirmed parameter map (do not change these)
|
||||||
|
|
||||||
|
```python
|
||||||
|
# USS protocol over TCP, port 21062, USS address 0
|
||||||
|
# Scaling factors are reverse-engineered and verified against live inverter data
|
||||||
|
|
||||||
|
# P050 AC Voltage L1 raw / 40 → V
|
||||||
|
# P05B AC Voltage L2 raw / 40 → V
|
||||||
|
# P064 AC Voltage L3 raw / 40 → V
|
||||||
|
# P052 DC Voltage MPPT1 raw / 40 → V
|
||||||
|
# P054 DC Voltage MPPT2 raw / 40 → V
|
||||||
|
# P05A DC Current MPPT1 raw / 10 → A
|
||||||
|
# P05C DC Current MPPT2 raw / 10 → A
|
||||||
|
# P068 AC Current L1 raw / 100 → A
|
||||||
|
# P069 AC Current L2 raw / 100 → A
|
||||||
|
# P06A AC Current L3 raw / 100 → A
|
||||||
|
# P06D AC Power Total raw → W
|
||||||
|
# P06C Grid Frequency raw / 20 → Hz
|
||||||
|
# P070 Temperature raw >> 16 → °C
|
||||||
|
# P063 IND=0 Daily Energy raw * 10 → Wh
|
||||||
|
# P063 IND=11 Total Energy raw → Wh
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Questions?
|
||||||
|
|
||||||
|
Ask me for:
|
||||||
|
- The full `refusol_poller.py` source
|
||||||
|
- Gitea server URL / Docker registry credentials
|
||||||
|
- Specific port to expose
|
||||||
|
- Any other VPS / infrastructure detail
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
# Refusol Solar Monitor — notes for Claude
|
||||||
|
|
||||||
|
See README.md for stack, API and health rules.
|
||||||
|
|
||||||
|
## Priorities
|
||||||
|
|
||||||
|
What matters most to the owner, in order:
|
||||||
|
1. Is each inverter operational or has it failed?
|
||||||
|
2. Current power per inverter, side by side — a big gap means a blown string
|
||||||
|
fuse / breaker on one array.
|
||||||
|
More data is welcome, but never at the expense of those two.
|
||||||
|
|
||||||
|
## Conventions
|
||||||
|
|
||||||
|
- Mirrors `C:\development\bellsystems-cp` infra: compose with backend +
|
||||||
|
frontend + nginx containers, one host port proxied by Nginx Proxy Manager,
|
||||||
|
`.env` from `.env.example`, deploy by `git pull` + `docker compose up -d --build`
|
||||||
|
on the VPS (`deploy-host.sh`). Repo lives on gitea.bonamin.net.
|
||||||
|
- Frontend must work well on phones (it's mostly used there) and stays an
|
||||||
|
installable PWA. A Flutter app may come later — keep everything the UI
|
||||||
|
needs available through the REST API.
|
||||||
|
- Parameters are defined once in `backend/app/fields.py`. The parameter map
|
||||||
|
and scaling factors are still being researched; keep the schema tolerant
|
||||||
|
(all fields optional, unknown keys land in `extra`).
|
||||||
|
- Chart colors: one categorical slot per inverter by its position in the
|
||||||
|
sorted inverter list (`--series-N` tokens in `frontend/src/index.css`).
|
||||||
|
Status colors are only for health and always come with an icon + label.
|
||||||
|
|
||||||
|
## Commits
|
||||||
|
|
||||||
|
Commit every change with a descriptive conventional message
|
||||||
|
(`feat(scope): ...`, `fix(scope): ...`, `docs: ...`), explaining why.
|
||||||
|
|
||||||
|
## Checks
|
||||||
|
|
||||||
|
- `cd backend && .venv/Scripts/python -m pytest`
|
||||||
|
- `cd frontend && npm run build`
|
||||||
@@ -0,0 +1,111 @@
|
|||||||
|
# Refusol Solar Monitor
|
||||||
|
|
||||||
|
Live dashboard for the Refusol 020K inverters. A poller on the site laptop
|
||||||
|
reads the inverters every 60 s and POSTs the values here; the dashboard
|
||||||
|
answers two questions first:
|
||||||
|
|
||||||
|
1. **Is every inverter operating, or has one failed?** (Operating / Check
|
||||||
|
needed / Fault / Offline / Sleeping at night / No data)
|
||||||
|
2. **Is any inverter producing much less than the others?** (output
|
||||||
|
comparison vs the fleet median, plus an MPPT1-vs-MPPT2 string check)
|
||||||
|
|
||||||
|
Public read-only, installable on phones as an app (PWA), served at
|
||||||
|
`solar.bonamin.net`.
|
||||||
|
|
||||||
|
## Tech Stack
|
||||||
|
|
||||||
|
- **Backend:** Python / FastAPI, SQLite (`./data/solar.db`)
|
||||||
|
- **Frontend:** React + Tailwind CSS (Vite), Recharts, vite-plugin-pwa
|
||||||
|
- **Deployment:** Docker Compose + Nginx (single port for NPM)
|
||||||
|
- **Poller:** `poller/backend_client.py` (stdlib only) used by `refusol_poller.py`
|
||||||
|
|
||||||
|
## Getting Started
|
||||||
|
|
||||||
|
```bash
|
||||||
|
git clone https://gitea.bonamin.net/bonamin/refusol-datalogger.git
|
||||||
|
cd refusol-datalogger
|
||||||
|
|
||||||
|
cp .env.example .env # set API_KEY, SITE_LATITUDE/LONGITUDE, HTTP_PORT
|
||||||
|
docker compose up -d --build
|
||||||
|
```
|
||||||
|
|
||||||
|
The stack listens on `HTTP_PORT` (default 8090). In Nginx Proxy Manager add a
|
||||||
|
proxy host `solar.bonamin.net` → `<vps>:8090` with SSL (Let's Encrypt, force
|
||||||
|
HTTPS) — the PWA install needs HTTPS.
|
||||||
|
|
||||||
|
Server deploys: `deploy-host.sh` (fetch `main`, reset, `docker compose up -d --build`).
|
||||||
|
Set `PROJECT` in it to the checkout path on the VPS.
|
||||||
|
|
||||||
|
To see it with fake data locally:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
python poller/fake_poller.py --url http://localhost:8090 --key change-me --backfill-days 30
|
||||||
|
```
|
||||||
|
|
||||||
|
## Project Structure
|
||||||
|
|
||||||
|
```
|
||||||
|
refusol-datalogger/
|
||||||
|
├── backend/ # FastAPI API (app/), tests/
|
||||||
|
├── frontend/ # React PWA
|
||||||
|
├── nginx/ # Single-port reverse proxy (/api → backend, / → frontend)
|
||||||
|
├── poller/ # backend_client.py for the site laptop + fake_poller.py
|
||||||
|
├── data/ # SQLite database (gitignored, bind-mounted)
|
||||||
|
├── docker-compose.yml
|
||||||
|
└── .env # from .env.example
|
||||||
|
```
|
||||||
|
|
||||||
|
## API
|
||||||
|
|
||||||
|
Interactive docs: `/api/docs` (OpenAPI at `/api/openapi.json` — usable to
|
||||||
|
generate a Flutter client later).
|
||||||
|
|
||||||
|
| Method | Path | |
|
||||||
|
|---|---|---|
|
||||||
|
| `POST` | `/api/readings` | Ingest one poll cycle (JSON array, one object per inverter). `X-API-Key` required. Empty array = heartbeat. Duplicates (same inverter + timestamp) are ignored. |
|
||||||
|
| `GET` | `/api/summary` | Every inverter's latest reading + health + issues, fleet totals, datalogger status |
|
||||||
|
| `GET` | `/api/inverters` | All known inverters (auto-registered on first reading) |
|
||||||
|
| `GET` | `/api/inverters/{id}` | One inverter |
|
||||||
|
| `PATCH` | `/api/inverters/{id}` | Name, `capacity_kwp`, `mppt_count`, `sort_order`, `notes`. `X-API-Key` required |
|
||||||
|
| `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/energy/daily` | Energy per day per inverter + total (default 30 days) |
|
||||||
|
| `GET` | `/api/meta/fields` | Label / unit / group of every parameter — render from this |
|
||||||
|
|
||||||
|
### Adding parameters
|
||||||
|
|
||||||
|
The reading parameters are defined once in `backend/app/fields.py`. Unknown
|
||||||
|
keys the poller sends are stored as-is (`extra`) and shown on the inverter
|
||||||
|
page as "Other (unmapped)". To promote one, add it to `FIELDS` — the column is
|
||||||
|
created on the next start and it appears in the API, the parameter table and
|
||||||
|
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**;
|
||||||
|
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`.
|
||||||
|
- **Check needed** — output below `UNDERPERFORM_RATIO` (75%) of the fleet
|
||||||
|
median over the last 10 min (per kWp once every inverter has its array size
|
||||||
|
set), or one MPPT input below half of the other.
|
||||||
|
|
||||||
|
Thresholds are in `.env`.
|
||||||
|
|
||||||
|
## Data retention
|
||||||
|
|
||||||
|
Raw readings older than `RETENTION_DAYS` (730) are purged every 6 h. The
|
||||||
|
per-day energy table is kept indefinitely.
|
||||||
|
|
||||||
|
## Development
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd backend && python -m venv .venv && .venv/Scripts/pip install -r requirements-dev.txt
|
||||||
|
.venv/Scripts/python -m pytest
|
||||||
|
.venv/Scripts/python -m uvicorn app.main:app --reload # :8000
|
||||||
|
|
||||||
|
cd frontend && npm install && npm run dev # :5173, proxies /api to :8000
|
||||||
|
```
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
__pycache__/
|
||||||
|
*.pyc
|
||||||
|
.venv/
|
||||||
|
.pytest_cache/
|
||||||
|
tests/
|
||||||
|
data/
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
FROM python:3.11-slim
|
||||||
|
|
||||||
|
WORKDIR /app
|
||||||
|
|
||||||
|
COPY requirements.txt .
|
||||||
|
RUN pip install --no-cache-dir -r requirements.txt
|
||||||
|
|
||||||
|
COPY app ./app
|
||||||
|
|
||||||
|
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000", "--proxy-headers", "--forwarded-allow-ips", "*"]
|
||||||
@@ -0,0 +1,219 @@
|
|||||||
|
import secrets
|
||||||
|
import sqlite3
|
||||||
|
from datetime import date, datetime, timedelta, timezone
|
||||||
|
from typing import Annotated
|
||||||
|
|
||||||
|
from fastapi import APIRouter, Body, Depends, Header, HTTPException, Query
|
||||||
|
|
||||||
|
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
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/api")
|
||||||
|
Db = Annotated[sqlite3.Connection, Depends(get_db)]
|
||||||
|
|
||||||
|
|
||||||
|
def require_api_key(x_api_key: Annotated[str | None, Header()] = None) -> None:
|
||||||
|
if not x_api_key or not secrets.compare_digest(x_api_key, get_settings().api_key):
|
||||||
|
raise HTTPException(401, "Invalid or missing X-API-Key")
|
||||||
|
|
||||||
|
|
||||||
|
def _range(start: datetime | None, end: datetime | None, default: timedelta) -> tuple[int, int]:
|
||||||
|
def ts(d: datetime) -> int:
|
||||||
|
return int((d if d.tzinfo else d.replace(tzinfo=timezone.utc)).timestamp())
|
||||||
|
|
||||||
|
e = ts(end) if end else store.now_ts()
|
||||||
|
s = ts(start) if start else e - int(default.total_seconds())
|
||||||
|
if s >= e:
|
||||||
|
raise HTTPException(422, "'from' must be before 'to'")
|
||||||
|
return s, e
|
||||||
|
|
||||||
|
|
||||||
|
def _day_range(start: date | None, end: date | None, days: int) -> tuple[date, date]:
|
||||||
|
last = end or store.today()
|
||||||
|
first = start or last - timedelta(days=days - 1)
|
||||||
|
if first > last:
|
||||||
|
raise HTTPException(422, "'from' must not be after 'to'")
|
||||||
|
if (last - first).days > 3660:
|
||||||
|
raise HTTPException(422, "Range too long (max 10 years)")
|
||||||
|
return first, last
|
||||||
|
|
||||||
|
|
||||||
|
def _inverter_or_404(conn: sqlite3.Connection, inverter_id: str) -> dict:
|
||||||
|
inv = store.get_inverter(conn, inverter_id)
|
||||||
|
if not inv:
|
||||||
|
raise HTTPException(404, f"Unknown inverter '{inverter_id}'")
|
||||||
|
return inv
|
||||||
|
|
||||||
|
|
||||||
|
FromQ = Annotated[datetime | None, Query(alias="from", description="ISO timestamp, UTC if no offset")]
|
||||||
|
ToQ = Annotated[datetime | None, Query(alias="to", description="ISO timestamp, UTC if no offset")]
|
||||||
|
BucketQ = Annotated[
|
||||||
|
int | None,
|
||||||
|
Query(ge=60, le=86400, description="Seconds per point. Omit to pick one giving ≤600 points."),
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------- ingest
|
||||||
|
|
||||||
|
|
||||||
|
@router.post(
|
||||||
|
"/readings",
|
||||||
|
response_model=IngestResult,
|
||||||
|
dependencies=[Depends(require_api_key)],
|
||||||
|
tags=["ingest"],
|
||||||
|
summary="Ingest one poll cycle (one object per inverter)",
|
||||||
|
)
|
||||||
|
def post_readings(conn: Db, readings: Annotated[list[ReadingIn], Body(max_length=200)]):
|
||||||
|
"""Send an empty array when no inverter answered — it still tells the
|
||||||
|
backend the datalogger is alive, which is how a dead inverter is told
|
||||||
|
apart from a dead internet link."""
|
||||||
|
stored, duplicates = store.ingest(conn, readings)
|
||||||
|
set_meta(conn, "last_ingest_at", str(store.now_ts()))
|
||||||
|
return {"received": len(readings), "stored": stored, "duplicates": duplicates}
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------- dashboard
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/summary", response_model=Summary, tags=["dashboard"])
|
||||||
|
def get_summary(conn: Db):
|
||||||
|
"""Latest reading + health of every inverter, fleet totals."""
|
||||||
|
return health.summary(conn)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/power", tags=["dashboard"])
|
||||||
|
def get_fleet_power(conn: Db, start: FromQ = None, end: ToQ = None, bucket: BucketQ = None):
|
||||||
|
"""AC power of every inverter over time (default: last 24 h)."""
|
||||||
|
s, e = _range(start, end, timedelta(hours=24))
|
||||||
|
b = store.pick_bucket(s, e, bucket)
|
||||||
|
return {
|
||||||
|
"from": store.to_dt(s),
|
||||||
|
"to": store.to_dt(e),
|
||||||
|
"bucket": b,
|
||||||
|
"inverters": [i["id"] for i in store.list_inverters(conn)],
|
||||||
|
"points": store.fleet_power(conn, s, e, b),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/energy/daily", tags=["dashboard"])
|
||||||
|
def get_fleet_daily_energy(
|
||||||
|
conn: Db,
|
||||||
|
start: Annotated[date | None, Query(alias="from")] = None,
|
||||||
|
end: Annotated[date | None, Query(alias="to")] = None,
|
||||||
|
days: Annotated[int, Query(ge=1, le=3660)] = 30,
|
||||||
|
):
|
||||||
|
"""Energy per local day for every inverter plus the total (default: last 30 days)."""
|
||||||
|
first, last = _day_range(start, end, days)
|
||||||
|
return {
|
||||||
|
"inverters": [i["id"] for i in store.list_inverters(conn)],
|
||||||
|
"days": store.daily_energy(conn, first, last),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------- inverters
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/inverters", response_model=list[Inverter], tags=["inverters"])
|
||||||
|
def get_inverters(conn: Db):
|
||||||
|
return store.list_inverters(conn)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/inverters/{inverter_id}", response_model=Inverter, tags=["inverters"])
|
||||||
|
def get_inverter(conn: Db, inverter_id: str):
|
||||||
|
return _inverter_or_404(conn, inverter_id)
|
||||||
|
|
||||||
|
|
||||||
|
@router.patch(
|
||||||
|
"/inverters/{inverter_id}",
|
||||||
|
response_model=Inverter,
|
||||||
|
dependencies=[Depends(require_api_key)],
|
||||||
|
tags=["inverters"],
|
||||||
|
)
|
||||||
|
def update_inverter(conn: Db, inverter_id: str, body: InverterUpdate):
|
||||||
|
"""Set display name, array size (kWp, enables per-kWp comparison), MPPT count, order, notes."""
|
||||||
|
_inverter_or_404(conn, inverter_id)
|
||||||
|
changes = body.model_dump(exclude_unset=True)
|
||||||
|
if changes:
|
||||||
|
sets = ", ".join(f"{k} = ?" for k in changes)
|
||||||
|
conn.execute(f"UPDATE inverters SET {sets} WHERE id = ?", [*changes.values(), inverter_id])
|
||||||
|
return store.get_inverter(conn, inverter_id)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/inverters/{inverter_id}/latest", tags=["inverters"])
|
||||||
|
def get_latest(conn: Db, inverter_id: str):
|
||||||
|
_inverter_or_404(conn, inverter_id)
|
||||||
|
r = store.latest(conn, inverter_id)
|
||||||
|
if not r:
|
||||||
|
raise HTTPException(404, "No readings yet")
|
||||||
|
return r
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/inverters/{inverter_id}/history", tags=["inverters"])
|
||||||
|
def get_history(
|
||||||
|
conn: Db,
|
||||||
|
inverter_id: str,
|
||||||
|
start: FromQ = None,
|
||||||
|
end: ToQ = None,
|
||||||
|
bucket: BucketQ = None,
|
||||||
|
field: Annotated[list[str] | None, Query(description="Limit to these fields (repeatable)")] = None,
|
||||||
|
):
|
||||||
|
"""Readings over time, averaged per bucket (energy counters and codes use the max).
|
||||||
|
Default: last 24 h."""
|
||||||
|
_inverter_or_404(conn, inverter_id)
|
||||||
|
s, e = _range(start, end, timedelta(hours=24))
|
||||||
|
b = store.pick_bucket(s, e, bucket)
|
||||||
|
return {
|
||||||
|
"inverter_id": inverter_id,
|
||||||
|
"from": store.to_dt(s),
|
||||||
|
"to": store.to_dt(e),
|
||||||
|
"bucket": b,
|
||||||
|
"points": store.history(conn, inverter_id, s, e, b, field),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/inverters/{inverter_id}/daily", tags=["inverters"])
|
||||||
|
def get_inverter_daily(
|
||||||
|
conn: Db,
|
||||||
|
inverter_id: str,
|
||||||
|
start: Annotated[date | None, Query(alias="from")] = None,
|
||||||
|
end: Annotated[date | None, Query(alias="to")] = None,
|
||||||
|
days: Annotated[int, Query(ge=1, le=3660)] = 365,
|
||||||
|
):
|
||||||
|
"""Energy and peak power per local day (default: last 365 days)."""
|
||||||
|
_inverter_or_404(conn, inverter_id)
|
||||||
|
first, last = _day_range(start, end, days)
|
||||||
|
rows = store.daily_energy(conn, first, last, inverter_id)
|
||||||
|
return {
|
||||||
|
"inverter_id": inverter_id,
|
||||||
|
"days": [
|
||||||
|
{"day": r["day"], "energy_wh": r.get(inverter_id), "peak_power_w": r.get("peak_power_w")}
|
||||||
|
for r in rows
|
||||||
|
],
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------- meta
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/meta/fields", tags=["meta"])
|
||||||
|
def get_fields():
|
||||||
|
"""Labels, units and groups of every reading parameter — render from this
|
||||||
|
instead of hard-coding, so new parameters show up automatically."""
|
||||||
|
return fields.describe()
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/meta/config", tags=["meta"])
|
||||||
|
def get_public_config():
|
||||||
|
s = get_settings()
|
||||||
|
return {
|
||||||
|
"site_timezone": s.site_timezone,
|
||||||
|
"online_window_seconds": s.online_window_seconds,
|
||||||
|
"underperform_ratio": s.underperform_ratio,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/health", tags=["meta"])
|
||||||
|
def get_health():
|
||||||
|
return {"status": "ok"}
|
||||||
@@ -0,0 +1,57 @@
|
|||||||
|
from functools import lru_cache
|
||||||
|
|
||||||
|
from pydantic import field_validator
|
||||||
|
from pydantic_settings import BaseSettings, SettingsConfigDict
|
||||||
|
|
||||||
|
|
||||||
|
class Settings(BaseSettings):
|
||||||
|
model_config = SettingsConfigDict(env_file=".env", extra="ignore")
|
||||||
|
|
||||||
|
# Shared secret the on-site poller sends in X-API-Key. Also guards the
|
||||||
|
# inverter metadata edits (name, kWp, ...).
|
||||||
|
api_key: str = "change-me"
|
||||||
|
|
||||||
|
db_path: str = "/app/data/solar.db"
|
||||||
|
|
||||||
|
# Local calendar of the installation — decides where "today" starts for
|
||||||
|
# the daily-energy rollup and the charts.
|
||||||
|
site_timezone: str = "Europe/Athens"
|
||||||
|
# Used to compute the sun's elevation so an inverter that went quiet at
|
||||||
|
# night shows as "sleeping" instead of raising an alarm. Leave empty to
|
||||||
|
# treat every silent inverter as offline.
|
||||||
|
site_latitude: float | None = None
|
||||||
|
site_longitude: float | None = None
|
||||||
|
# Below this sun elevation (degrees) inverters are expected to be off.
|
||||||
|
daylight_min_elevation: float = 5.0
|
||||||
|
|
||||||
|
# A reading newer than this marks an inverter as Online.
|
||||||
|
online_window_seconds: int = 300
|
||||||
|
retention_days: int = 730
|
||||||
|
|
||||||
|
# Underperformance check: an inverter is flagged when its output (per kWp
|
||||||
|
# if capacities are set, otherwise raw W) is below this fraction of the
|
||||||
|
# fleet median over the last few minutes.
|
||||||
|
underperform_ratio: float = 0.75
|
||||||
|
underperform_window_seconds: int = 600
|
||||||
|
# Skip the check while the fleet is barely producing (dawn, dusk, heavy
|
||||||
|
# overcast) — differences there are noise.
|
||||||
|
underperform_min_fleet_w_per_kwp: float = 50.0
|
||||||
|
underperform_min_fleet_w: float = 1000.0
|
||||||
|
|
||||||
|
# One MPPT producing under this fraction of the other is flagged (only
|
||||||
|
# for inverters with mppt_count = 2), once the stronger one exceeds
|
||||||
|
# mppt_min_power_w.
|
||||||
|
mppt_imbalance_ratio: float = 0.5
|
||||||
|
mppt_min_power_w: float = 1000.0
|
||||||
|
|
||||||
|
cors_origins: list[str] = ["*"]
|
||||||
|
|
||||||
|
@field_validator("site_latitude", "site_longitude", mode="before")
|
||||||
|
@classmethod
|
||||||
|
def blank_is_none(cls, v):
|
||||||
|
return None if isinstance(v, str) and not v.strip() else v
|
||||||
|
|
||||||
|
|
||||||
|
@lru_cache
|
||||||
|
def get_settings() -> Settings:
|
||||||
|
return Settings()
|
||||||
@@ -0,0 +1,94 @@
|
|||||||
|
import os
|
||||||
|
import sqlite3
|
||||||
|
from collections.abc import Iterator
|
||||||
|
from contextlib import contextmanager
|
||||||
|
|
||||||
|
from .config import get_settings
|
||||||
|
from .fields import FIELDS
|
||||||
|
|
||||||
|
SCHEMA = """
|
||||||
|
CREATE TABLE IF NOT EXISTS inverters (
|
||||||
|
id TEXT PRIMARY KEY,
|
||||||
|
name TEXT,
|
||||||
|
capacity_kwp REAL,
|
||||||
|
mppt_count INTEGER NOT NULL DEFAULT 2,
|
||||||
|
sort_order INTEGER NOT NULL DEFAULT 0,
|
||||||
|
notes TEXT,
|
||||||
|
first_seen INTEGER,
|
||||||
|
last_seen INTEGER
|
||||||
|
);
|
||||||
|
|
||||||
|
-- One row per inverter per poll cycle. ts = unix seconds, UTC.
|
||||||
|
-- The per-parameter columns are added from fields.py by migrate().
|
||||||
|
CREATE TABLE IF NOT EXISTS readings (
|
||||||
|
inverter_id TEXT NOT NULL,
|
||||||
|
ts INTEGER NOT NULL,
|
||||||
|
extra TEXT,
|
||||||
|
PRIMARY KEY (inverter_id, ts)
|
||||||
|
) WITHOUT ROWID;
|
||||||
|
CREATE INDEX IF NOT EXISTS readings_ts ON readings (ts);
|
||||||
|
|
||||||
|
-- Daily rollup, kept forever (readings are purged after the retention
|
||||||
|
-- period). day is the local date at the site (SITE_TIMEZONE).
|
||||||
|
CREATE TABLE IF NOT EXISTS daily_energy (
|
||||||
|
inverter_id TEXT NOT NULL,
|
||||||
|
day TEXT NOT NULL,
|
||||||
|
daily_energy_wh INTEGER,
|
||||||
|
total_min_wh INTEGER,
|
||||||
|
total_max_wh INTEGER,
|
||||||
|
peak_power_w INTEGER,
|
||||||
|
PRIMARY KEY (inverter_id, day)
|
||||||
|
) WITHOUT ROWID;
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS meta (
|
||||||
|
key TEXT PRIMARY KEY,
|
||||||
|
value TEXT
|
||||||
|
);
|
||||||
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
def connect() -> sqlite3.Connection:
|
||||||
|
path = get_settings().db_path
|
||||||
|
os.makedirs(os.path.dirname(os.path.abspath(path)), exist_ok=True)
|
||||||
|
conn = sqlite3.connect(path, timeout=30)
|
||||||
|
conn.row_factory = sqlite3.Row
|
||||||
|
conn.execute("PRAGMA journal_mode=WAL")
|
||||||
|
conn.execute("PRAGMA synchronous=NORMAL")
|
||||||
|
return conn
|
||||||
|
|
||||||
|
|
||||||
|
@contextmanager
|
||||||
|
def session() -> Iterator[sqlite3.Connection]:
|
||||||
|
conn = connect()
|
||||||
|
try:
|
||||||
|
with conn:
|
||||||
|
yield conn
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
def get_db() -> Iterator[sqlite3.Connection]:
|
||||||
|
with session() as conn:
|
||||||
|
yield conn
|
||||||
|
|
||||||
|
|
||||||
|
def migrate() -> None:
|
||||||
|
with session() as conn:
|
||||||
|
conn.executescript(SCHEMA)
|
||||||
|
existing = {r["name"] for r in conn.execute("PRAGMA table_info(readings)")}
|
||||||
|
for f in FIELDS:
|
||||||
|
if f.key not in existing:
|
||||||
|
conn.execute(f"ALTER TABLE readings ADD COLUMN {f.key} {f.sql_type}")
|
||||||
|
|
||||||
|
|
||||||
|
def get_meta(conn: sqlite3.Connection, key: str) -> str | None:
|
||||||
|
row = conn.execute("SELECT value FROM meta WHERE key = ?", (key,)).fetchone()
|
||||||
|
return row["value"] if row else None
|
||||||
|
|
||||||
|
|
||||||
|
def set_meta(conn: sqlite3.Connection, key: str, value: str) -> None:
|
||||||
|
conn.execute(
|
||||||
|
"INSERT INTO meta (key, value) VALUES (?, ?) "
|
||||||
|
"ON CONFLICT(key) DO UPDATE SET value = excluded.value",
|
||||||
|
(key, value),
|
||||||
|
)
|
||||||
@@ -0,0 +1,82 @@
|
|||||||
|
"""Single source of truth for the per-reading parameters.
|
||||||
|
|
||||||
|
Every field listed here gets its own column in `readings` (missing columns are
|
||||||
|
added on startup), is accepted by POST /api/readings, and is described by
|
||||||
|
GET /api/meta/fields so the dashboard and future apps can render it without a
|
||||||
|
code change. Anything the poller sends that is NOT listed here is still kept,
|
||||||
|
in the reading's `extra` JSON — promote it to this list once its meaning and
|
||||||
|
scaling are confirmed.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from dataclasses import asdict, dataclass
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class Field:
|
||||||
|
key: str
|
||||||
|
sql_type: str # REAL | INTEGER | TEXT
|
||||||
|
label: str
|
||||||
|
unit: str | None
|
||||||
|
group: str # ac | dc | energy | device
|
||||||
|
# How values combine when history is downsampled into buckets.
|
||||||
|
agg: str = "avg" # avg | max | last
|
||||||
|
decimals: int = 1
|
||||||
|
|
||||||
|
|
||||||
|
FIELDS: list[Field] = [
|
||||||
|
Field("ac_power_total_w", "INTEGER", "AC power", "W", "ac", decimals=0),
|
||||||
|
Field("ac_voltage_l1_v", "REAL", "AC voltage L1", "V", "ac"),
|
||||||
|
Field("ac_voltage_l2_v", "REAL", "AC voltage L2", "V", "ac"),
|
||||||
|
Field("ac_voltage_l3_v", "REAL", "AC voltage L3", "V", "ac"),
|
||||||
|
Field("ac_current_l1_a", "REAL", "AC current L1", "A", "ac", decimals=2),
|
||||||
|
Field("ac_current_l2_a", "REAL", "AC current L2", "A", "ac", decimals=2),
|
||||||
|
Field("ac_current_l3_a", "REAL", "AC current L3", "A", "ac", decimals=2),
|
||||||
|
Field("grid_frequency_hz", "REAL", "Grid frequency", "Hz", "ac", decimals=2),
|
||||||
|
Field("dc_voltage_mppt1_v", "REAL", "DC voltage MPPT1", "V", "dc"),
|
||||||
|
Field("dc_voltage_mppt2_v", "REAL", "DC voltage MPPT2", "V", "dc"),
|
||||||
|
Field("dc_current_mppt1_a", "REAL", "DC current MPPT1", "A", "dc"),
|
||||||
|
Field("dc_current_mppt2_a", "REAL", "DC current MPPT2", "A", "dc"),
|
||||||
|
Field("temperature_c", "INTEGER", "Temperature", "°C", "device", decimals=0),
|
||||||
|
Field("status_code", "INTEGER", "Status code", None, "device", agg="last", decimals=0),
|
||||||
|
Field("error_code", "INTEGER", "Error code", None, "device", agg="last", decimals=0),
|
||||||
|
Field("status_text", "TEXT", "Status", None, "device", agg="last"),
|
||||||
|
Field("daily_energy_wh", "INTEGER", "Energy today", "Wh", "energy", agg="max", decimals=0),
|
||||||
|
Field("total_energy_wh", "INTEGER", "Lifetime energy", "Wh", "energy", agg="max", decimals=0),
|
||||||
|
]
|
||||||
|
|
||||||
|
FIELD_KEYS = [f.key for f in FIELDS]
|
||||||
|
FIELDS_BY_KEY = {f.key: f for f in FIELDS}
|
||||||
|
NUMERIC_KEYS = [f.key for f in FIELDS if f.sql_type != "TEXT"]
|
||||||
|
|
||||||
|
# Values derived from the stored ones, shown alongside them.
|
||||||
|
DERIVED: list[Field] = [
|
||||||
|
Field("dc_power_mppt1_w", "REAL", "DC power MPPT1", "W", "dc", decimals=0),
|
||||||
|
Field("dc_power_mppt2_w", "REAL", "DC power MPPT2", "W", "dc", decimals=0),
|
||||||
|
Field("dc_power_total_w", "REAL", "DC power total", "W", "dc", decimals=0),
|
||||||
|
Field("efficiency_pct", "REAL", "Conversion efficiency", "%", "dc", decimals=1),
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def describe() -> list[dict]:
|
||||||
|
return [asdict(f) | {"derived": False} for f in FIELDS] + [
|
||||||
|
asdict(f) | {"derived": True} for f in DERIVED
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def derive(r: dict) -> dict:
|
||||||
|
"""Add DC power and efficiency to a reading dict (in place) and return it."""
|
||||||
|
|
||||||
|
def mul(v, a):
|
||||||
|
return None if v is None or a is None else v * a
|
||||||
|
|
||||||
|
p1 = mul(r.get("dc_voltage_mppt1_v"), r.get("dc_current_mppt1_a"))
|
||||||
|
p2 = mul(r.get("dc_voltage_mppt2_v"), r.get("dc_current_mppt2_a"))
|
||||||
|
r["dc_power_mppt1_w"] = round(p1) if p1 is not None else None
|
||||||
|
r["dc_power_mppt2_w"] = round(p2) if p2 is not None else None
|
||||||
|
dc = None if p1 is None and p2 is None else (p1 or 0) + (p2 or 0)
|
||||||
|
r["dc_power_total_w"] = round(dc) if dc is not None else None
|
||||||
|
ac = r.get("ac_power_total_w")
|
||||||
|
r["efficiency_pct"] = (
|
||||||
|
round(ac / dc * 100, 1) if ac is not None and dc and dc > 200 else None
|
||||||
|
)
|
||||||
|
return r
|
||||||
@@ -0,0 +1,147 @@
|
|||||||
|
"""Answers the two questions that matter most:
|
||||||
|
|
||||||
|
1. Is inverter X operational, or has it failed?
|
||||||
|
2. Is inverter X producing as much as its peers? A big gap usually means a
|
||||||
|
string fuse, breaker or connector problem on that array.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import sqlite3
|
||||||
|
import statistics
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
|
||||||
|
from . import store, sun
|
||||||
|
from .config import get_settings
|
||||||
|
from .db import get_meta
|
||||||
|
|
||||||
|
|
||||||
|
def _minutes(seconds: int) -> str:
|
||||||
|
if seconds < 3600:
|
||||||
|
return f"{seconds // 60} min"
|
||||||
|
if seconds < 86400:
|
||||||
|
return f"{seconds / 3600:.1f} h"
|
||||||
|
return f"{seconds / 86400:.1f} days"
|
||||||
|
|
||||||
|
|
||||||
|
def summary(conn: sqlite3.Connection) -> dict:
|
||||||
|
s = get_settings()
|
||||||
|
now = store.now_ts()
|
||||||
|
|
||||||
|
last_ingest = get_meta(conn, "last_ingest_at")
|
||||||
|
last_ingest = int(last_ingest) if last_ingest else None
|
||||||
|
datalogger_online = last_ingest is not None and now - last_ingest <= s.online_window_seconds
|
||||||
|
|
||||||
|
elevation = daylight = None
|
||||||
|
if s.site_latitude is not None and s.site_longitude is not None:
|
||||||
|
elevation = round(sun.elevation(datetime.now(timezone.utc), s.site_latitude, s.site_longitude), 1)
|
||||||
|
daylight = elevation >= s.daylight_min_elevation
|
||||||
|
|
||||||
|
inverters = store.list_inverters(conn)
|
||||||
|
latest = store.latest_all(conn)
|
||||||
|
averages = store.window_averages(conn, s.underperform_window_seconds)
|
||||||
|
energy_today = store.today_energy(conn)
|
||||||
|
|
||||||
|
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
|
||||||
|
|
||||||
|
# Fleet comparison: per kWp when every producing inverter has a capacity
|
||||||
|
# set, raw watts otherwise (assumes similar arrays).
|
||||||
|
producing = [i for i in inverters if is_online(i["id"]) and averages.get(i["id"], {}).get("ac_power_w") is not None]
|
||||||
|
per_kwp = bool(producing) and all(i["capacity_kwp"] for i in producing)
|
||||||
|
|
||||||
|
def specific(inv: dict) -> float | None:
|
||||||
|
w = averages.get(inv["id"], {}).get("ac_power_w")
|
||||||
|
if w is None:
|
||||||
|
return None
|
||||||
|
return w / inv["capacity_kwp"] if per_kwp else w
|
||||||
|
|
||||||
|
specs = [v for v in (specific(i) for i in producing) if v is not None]
|
||||||
|
median = statistics.median(specs) if len(specs) >= 2 else None
|
||||||
|
min_fleet = s.underperform_min_fleet_w_per_kwp if per_kwp else s.underperform_min_fleet_w
|
||||||
|
compare = median is not None and median >= min_fleet
|
||||||
|
|
||||||
|
statuses = []
|
||||||
|
for inv in inverters:
|
||||||
|
r = latest.get(inv["id"])
|
||||||
|
online = is_online(inv["id"])
|
||||||
|
issues: list[dict] = []
|
||||||
|
state = "ok"
|
||||||
|
spec = specific(inv) if online else None
|
||||||
|
relative = round(spec / median, 3) if spec is not None and median else None
|
||||||
|
|
||||||
|
if not online:
|
||||||
|
since = f"for {_minutes(r['age_seconds'])}" if r else "yet"
|
||||||
|
if not datalogger_online:
|
||||||
|
state = "unknown"
|
||||||
|
issues.append({
|
||||||
|
"code": "datalogger_offline",
|
||||||
|
"severity": "info",
|
||||||
|
"message": "No data from the site datalogger — inverter state unknown",
|
||||||
|
})
|
||||||
|
elif daylight is False:
|
||||||
|
state = "sleeping"
|
||||||
|
else:
|
||||||
|
state = "offline"
|
||||||
|
issues.append({
|
||||||
|
"code": "not_responding",
|
||||||
|
"severity": "critical",
|
||||||
|
"message": f"Not responding {since} while the datalogger is online",
|
||||||
|
})
|
||||||
|
else:
|
||||||
|
if r.get("error_code"):
|
||||||
|
state = "fault"
|
||||||
|
text = f" ({r['status_text']})" if r.get("status_text") else ""
|
||||||
|
issues.append({
|
||||||
|
"code": "error_code",
|
||||||
|
"severity": "critical",
|
||||||
|
"message": f"Inverter reports error code {r['error_code']}{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",
|
||||||
|
})
|
||||||
|
avg = averages.get(inv["id"], {})
|
||||||
|
m1, m2 = avg.get("mppt1_w"), avg.get("mppt2_w")
|
||||||
|
if inv["mppt_count"] >= 2 and m1 is not None and m2 is not None:
|
||||||
|
hi, lo = max(m1, m2), min(m1, m2)
|
||||||
|
if hi >= s.mppt_min_power_w and lo < hi * s.mppt_imbalance_ratio:
|
||||||
|
weak = "MPPT1" if m1 < m2 else "MPPT2"
|
||||||
|
issues.append({
|
||||||
|
"code": "mppt_imbalance",
|
||||||
|
"severity": "warning",
|
||||||
|
"message": f"{weak} at {lo:.0f} W vs {hi:.0f} W on the other input — check that string",
|
||||||
|
})
|
||||||
|
if state == "ok" and issues:
|
||||||
|
state = "warning"
|
||||||
|
|
||||||
|
statuses.append({
|
||||||
|
"inverter": inv,
|
||||||
|
"health": {
|
||||||
|
"online": online,
|
||||||
|
"state": state,
|
||||||
|
"issues": issues,
|
||||||
|
"avg_power_w": round(averages[inv["id"]]["ac_power_w"]) if online and averages.get(inv["id"], {}).get("ac_power_w") is not None else None,
|
||||||
|
"relative_output": relative,
|
||||||
|
},
|
||||||
|
"latest": r,
|
||||||
|
})
|
||||||
|
|
||||||
|
totals = {
|
||||||
|
"ac_power_w": sum((latest[i["id"]].get("ac_power_total_w") or 0) for i in inverters if is_online(i["id"])),
|
||||||
|
"daily_energy_wh": sum(energy_today.values()),
|
||||||
|
"total_energy_wh": sum((r.get("total_energy_wh") or 0) for r in latest.values()),
|
||||||
|
"inverter_count": len(inverters),
|
||||||
|
"online_count": sum(1 for i in inverters if is_online(i["id"])),
|
||||||
|
"problem_count": sum(1 for st in statuses if st["health"]["state"] in ("fault", "warning", "offline")),
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
"generated_at": datetime.now(timezone.utc),
|
||||||
|
"datalogger": {"online": datalogger_online, "last_ingest_at": store.to_dt(last_ingest)},
|
||||||
|
"sun": {"elevation": elevation, "daylight": daylight},
|
||||||
|
"totals": totals,
|
||||||
|
"fleet_median_w_per_kwp": round(median, 1) if median is not None and per_kwp else None,
|
||||||
|
"inverters": statuses,
|
||||||
|
}
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
import asyncio
|
||||||
|
import logging
|
||||||
|
from contextlib import asynccontextmanager
|
||||||
|
|
||||||
|
from fastapi import FastAPI
|
||||||
|
from fastapi.middleware.cors import CORSMiddleware
|
||||||
|
|
||||||
|
from . import store
|
||||||
|
from .api import router
|
||||||
|
from .config import get_settings
|
||||||
|
from .db import migrate, session
|
||||||
|
|
||||||
|
log = logging.getLogger("solar")
|
||||||
|
PURGE_INTERVAL_SECONDS = 6 * 3600
|
||||||
|
|
||||||
|
|
||||||
|
def purge_once() -> None:
|
||||||
|
with session() as conn:
|
||||||
|
deleted = store.purge(conn, get_settings().retention_days)
|
||||||
|
if deleted:
|
||||||
|
log.info("Retention: purged %d readings", deleted)
|
||||||
|
|
||||||
|
|
||||||
|
async def purge_loop() -> None:
|
||||||
|
while True:
|
||||||
|
try:
|
||||||
|
await asyncio.to_thread(purge_once)
|
||||||
|
except Exception:
|
||||||
|
log.exception("Retention purge failed")
|
||||||
|
await asyncio.sleep(PURGE_INTERVAL_SECONDS)
|
||||||
|
|
||||||
|
|
||||||
|
@asynccontextmanager
|
||||||
|
async def lifespan(app: FastAPI):
|
||||||
|
migrate()
|
||||||
|
task = asyncio.create_task(purge_loop())
|
||||||
|
yield
|
||||||
|
task.cancel()
|
||||||
|
|
||||||
|
|
||||||
|
app = FastAPI(
|
||||||
|
title="Refusol Solar Monitor",
|
||||||
|
lifespan=lifespan,
|
||||||
|
docs_url="/api/docs",
|
||||||
|
redoc_url=None,
|
||||||
|
openapi_url="/api/openapi.json",
|
||||||
|
)
|
||||||
|
app.add_middleware(
|
||||||
|
CORSMiddleware,
|
||||||
|
allow_origins=get_settings().cors_origins,
|
||||||
|
allow_methods=["*"],
|
||||||
|
allow_headers=["*"],
|
||||||
|
)
|
||||||
|
app.include_router(router)
|
||||||
@@ -0,0 +1,124 @@
|
|||||||
|
from datetime import datetime
|
||||||
|
from typing import Any, Literal
|
||||||
|
|
||||||
|
from pydantic import BaseModel, ConfigDict, Field
|
||||||
|
|
||||||
|
InverterId = Field(min_length=1, max_length=64, pattern=r"^[A-Za-z0-9_.\-]+$")
|
||||||
|
|
||||||
|
|
||||||
|
class ReadingIn(BaseModel):
|
||||||
|
"""One inverter's values from one poll cycle.
|
||||||
|
|
||||||
|
Every parameter is optional — send what the poller could read. Unknown
|
||||||
|
keys are accepted and stored in `extra` (as are keys of an explicit
|
||||||
|
`extra` object), so new parameters can be logged before the backend
|
||||||
|
knows about them.
|
||||||
|
"""
|
||||||
|
|
||||||
|
model_config = ConfigDict(extra="allow")
|
||||||
|
|
||||||
|
inverter_id: str = InverterId
|
||||||
|
timestamp: datetime | None = Field(
|
||||||
|
default=None, description="UTC. Defaults to the time the backend receives it."
|
||||||
|
)
|
||||||
|
|
||||||
|
ac_voltage_l1_v: float | None = None
|
||||||
|
ac_voltage_l2_v: float | None = None
|
||||||
|
ac_voltage_l3_v: float | None = None
|
||||||
|
dc_voltage_mppt1_v: float | None = None
|
||||||
|
dc_voltage_mppt2_v: float | None = None
|
||||||
|
dc_current_mppt1_a: float | None = None
|
||||||
|
dc_current_mppt2_a: float | None = None
|
||||||
|
ac_current_l1_a: float | None = None
|
||||||
|
ac_current_l2_a: float | None = None
|
||||||
|
ac_current_l3_a: float | None = None
|
||||||
|
ac_power_total_w: int | None = None
|
||||||
|
grid_frequency_hz: float | None = None
|
||||||
|
temperature_c: int | None = None
|
||||||
|
daily_energy_wh: int | None = None
|
||||||
|
total_energy_wh: int | None = None
|
||||||
|
|
||||||
|
status_code: int | None = Field(default=None, description="Raw inverter state, if known")
|
||||||
|
error_code: int | None = Field(default=None, description="Non-zero = inverter reports a fault")
|
||||||
|
status_text: str | None = Field(default=None, max_length=200)
|
||||||
|
|
||||||
|
extra: dict[str, Any] | None = None
|
||||||
|
|
||||||
|
|
||||||
|
class IngestResult(BaseModel):
|
||||||
|
received: int
|
||||||
|
stored: int
|
||||||
|
duplicates: int
|
||||||
|
|
||||||
|
|
||||||
|
class InverterUpdate(BaseModel):
|
||||||
|
name: str | None = Field(default=None, max_length=100)
|
||||||
|
capacity_kwp: float | None = Field(default=None, ge=0, le=1000)
|
||||||
|
mppt_count: int | None = Field(default=None, ge=1, le=4)
|
||||||
|
sort_order: int | None = None
|
||||||
|
notes: str | None = Field(default=None, max_length=2000)
|
||||||
|
|
||||||
|
|
||||||
|
class Inverter(BaseModel):
|
||||||
|
id: str
|
||||||
|
name: str
|
||||||
|
capacity_kwp: float | None
|
||||||
|
mppt_count: int
|
||||||
|
sort_order: int
|
||||||
|
notes: str | None
|
||||||
|
first_seen: datetime | None
|
||||||
|
last_seen: datetime | None
|
||||||
|
|
||||||
|
|
||||||
|
Severity = Literal["info", "warning", "critical"]
|
||||||
|
State = Literal["ok", "warning", "fault", "offline", "sleeping", "unknown"]
|
||||||
|
|
||||||
|
|
||||||
|
class Issue(BaseModel):
|
||||||
|
code: str
|
||||||
|
severity: Severity
|
||||||
|
message: str
|
||||||
|
|
||||||
|
|
||||||
|
class Health(BaseModel):
|
||||||
|
online: bool = Field(description="A reading arrived within ONLINE_WINDOW_SECONDS")
|
||||||
|
state: State
|
||||||
|
issues: list[Issue]
|
||||||
|
avg_power_w: float | None = Field(description="Mean AC power over the comparison window")
|
||||||
|
relative_output: float | None = Field(
|
||||||
|
description="Output vs fleet median (1.0 = median), per kWp when capacities are set"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class InverterStatus(BaseModel):
|
||||||
|
inverter: Inverter
|
||||||
|
health: Health
|
||||||
|
latest: dict[str, Any] | None
|
||||||
|
|
||||||
|
|
||||||
|
class Totals(BaseModel):
|
||||||
|
ac_power_w: int
|
||||||
|
daily_energy_wh: int
|
||||||
|
total_energy_wh: int
|
||||||
|
inverter_count: int
|
||||||
|
online_count: int
|
||||||
|
problem_count: int
|
||||||
|
|
||||||
|
|
||||||
|
class Datalogger(BaseModel):
|
||||||
|
online: bool
|
||||||
|
last_ingest_at: datetime | None
|
||||||
|
|
||||||
|
|
||||||
|
class Sun(BaseModel):
|
||||||
|
elevation: float | None
|
||||||
|
daylight: bool | None
|
||||||
|
|
||||||
|
|
||||||
|
class Summary(BaseModel):
|
||||||
|
generated_at: datetime
|
||||||
|
datalogger: Datalogger
|
||||||
|
sun: Sun
|
||||||
|
totals: Totals
|
||||||
|
fleet_median_w_per_kwp: float | None
|
||||||
|
inverters: list[InverterStatus]
|
||||||
@@ -0,0 +1,277 @@
|
|||||||
|
"""Database reads and writes. All timestamps in the DB are unix seconds (UTC)."""
|
||||||
|
|
||||||
|
import json
|
||||||
|
import sqlite3
|
||||||
|
import time
|
||||||
|
from datetime import date, datetime, timedelta, timezone
|
||||||
|
from zoneinfo import ZoneInfo
|
||||||
|
|
||||||
|
from .config import get_settings
|
||||||
|
from .fields import FIELD_KEYS, FIELDS_BY_KEY, NUMERIC_KEYS, derive
|
||||||
|
from .schemas import ReadingIn
|
||||||
|
|
||||||
|
BUCKETS = [60, 300, 900, 1800, 3600, 3 * 3600, 6 * 3600, 86400]
|
||||||
|
MAX_POINTS = 600
|
||||||
|
|
||||||
|
|
||||||
|
def now_ts() -> int:
|
||||||
|
return int(time.time())
|
||||||
|
|
||||||
|
|
||||||
|
def to_dt(ts: int | None) -> datetime | None:
|
||||||
|
return datetime.fromtimestamp(ts, timezone.utc) if ts is not None else None
|
||||||
|
|
||||||
|
|
||||||
|
def site_tz() -> ZoneInfo:
|
||||||
|
return ZoneInfo(get_settings().site_timezone)
|
||||||
|
|
||||||
|
|
||||||
|
def local_day(ts: int) -> str:
|
||||||
|
return datetime.fromtimestamp(ts, site_tz()).date().isoformat()
|
||||||
|
|
||||||
|
|
||||||
|
def today() -> date:
|
||||||
|
return datetime.now(site_tz()).date()
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------- ingest
|
||||||
|
|
||||||
|
|
||||||
|
def _ts_of(r: ReadingIn) -> int:
|
||||||
|
if r.timestamp is None:
|
||||||
|
return now_ts()
|
||||||
|
t = r.timestamp
|
||||||
|
if t.tzinfo is None:
|
||||||
|
t = t.replace(tzinfo=timezone.utc)
|
||||||
|
return int(t.timestamp())
|
||||||
|
|
||||||
|
|
||||||
|
def ingest(conn: sqlite3.Connection, readings: list[ReadingIn]) -> tuple[int, int]:
|
||||||
|
"""Store readings; returns (stored, duplicates). Re-sent readings (same
|
||||||
|
inverter + timestamp) are ignored, so the poller can safely retry."""
|
||||||
|
stored = 0
|
||||||
|
cols = ["inverter_id", "ts", "extra", *FIELD_KEYS]
|
||||||
|
insert_sql = (
|
||||||
|
f"INSERT OR IGNORE INTO readings ({', '.join(cols)}) "
|
||||||
|
f"VALUES ({', '.join('?' for _ in cols)})"
|
||||||
|
)
|
||||||
|
for r in readings:
|
||||||
|
ts = _ts_of(r)
|
||||||
|
values = r.model_dump(include=set(FIELD_KEYS))
|
||||||
|
extra = {**(r.model_extra or {}), **(r.extra or {})}
|
||||||
|
|
||||||
|
conn.execute(
|
||||||
|
"INSERT OR IGNORE INTO inverters (id, name, first_seen, last_seen) VALUES (?, ?, ?, ?)",
|
||||||
|
(r.inverter_id, r.inverter_id, ts, ts),
|
||||||
|
)
|
||||||
|
conn.execute(
|
||||||
|
"UPDATE inverters SET last_seen = max(coalesce(last_seen, 0), ?) WHERE id = ?",
|
||||||
|
(ts, r.inverter_id),
|
||||||
|
)
|
||||||
|
cur = conn.execute(
|
||||||
|
insert_sql,
|
||||||
|
[r.inverter_id, ts, json.dumps(extra) if extra else None]
|
||||||
|
+ [values[k] for k in FIELD_KEYS],
|
||||||
|
)
|
||||||
|
if cur.rowcount == 0:
|
||||||
|
continue
|
||||||
|
stored += 1
|
||||||
|
|
||||||
|
# max()/min() of two values where either may be NULL
|
||||||
|
conn.execute(
|
||||||
|
"""
|
||||||
|
INSERT INTO daily_energy
|
||||||
|
(inverter_id, day, daily_energy_wh, total_min_wh, total_max_wh, peak_power_w)
|
||||||
|
VALUES (?, ?, ?, ?, ?, ?)
|
||||||
|
ON CONFLICT (inverter_id, day) DO UPDATE SET
|
||||||
|
daily_energy_wh = max(coalesce(daily_energy_wh, excluded.daily_energy_wh),
|
||||||
|
coalesce(excluded.daily_energy_wh, daily_energy_wh)),
|
||||||
|
total_min_wh = min(coalesce(total_min_wh, excluded.total_min_wh),
|
||||||
|
coalesce(excluded.total_min_wh, total_min_wh)),
|
||||||
|
total_max_wh = max(coalesce(total_max_wh, excluded.total_max_wh),
|
||||||
|
coalesce(excluded.total_max_wh, total_max_wh)),
|
||||||
|
peak_power_w = max(coalesce(peak_power_w, excluded.peak_power_w),
|
||||||
|
coalesce(excluded.peak_power_w, peak_power_w))
|
||||||
|
""",
|
||||||
|
(
|
||||||
|
r.inverter_id,
|
||||||
|
local_day(ts),
|
||||||
|
values["daily_energy_wh"],
|
||||||
|
values["total_energy_wh"],
|
||||||
|
values["total_energy_wh"],
|
||||||
|
values["ac_power_total_w"],
|
||||||
|
),
|
||||||
|
)
|
||||||
|
return stored, len(readings) - stored
|
||||||
|
|
||||||
|
|
||||||
|
def purge(conn: sqlite3.Connection, retention_days: int) -> int:
|
||||||
|
cutoff = now_ts() - retention_days * 86400
|
||||||
|
return conn.execute("DELETE FROM readings WHERE ts < ?", (cutoff,)).rowcount
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------- inverters
|
||||||
|
|
||||||
|
|
||||||
|
def inverter_dict(row: sqlite3.Row) -> dict:
|
||||||
|
d = dict(row)
|
||||||
|
d["name"] = d["name"] or d["id"]
|
||||||
|
d["first_seen"] = to_dt(d["first_seen"])
|
||||||
|
d["last_seen"] = to_dt(d["last_seen"])
|
||||||
|
return d
|
||||||
|
|
||||||
|
|
||||||
|
def list_inverters(conn: sqlite3.Connection) -> list[dict]:
|
||||||
|
rows = conn.execute("SELECT * FROM inverters ORDER BY sort_order, id").fetchall()
|
||||||
|
return [inverter_dict(r) for r in rows]
|
||||||
|
|
||||||
|
|
||||||
|
def get_inverter(conn: sqlite3.Connection, inverter_id: str) -> dict | None:
|
||||||
|
row = conn.execute("SELECT * FROM inverters WHERE id = ?", (inverter_id,)).fetchone()
|
||||||
|
return inverter_dict(row) if row else None
|
||||||
|
|
||||||
|
|
||||||
|
def reading_dict(row: sqlite3.Row) -> dict:
|
||||||
|
d = dict(row)
|
||||||
|
ts = d.pop("ts")
|
||||||
|
d["timestamp"] = to_dt(ts)
|
||||||
|
d["age_seconds"] = now_ts() - ts
|
||||||
|
d["extra"] = json.loads(d["extra"]) if d.get("extra") else {}
|
||||||
|
return derive(d)
|
||||||
|
|
||||||
|
|
||||||
|
def latest(conn: sqlite3.Connection, inverter_id: str) -> dict | None:
|
||||||
|
row = conn.execute(
|
||||||
|
"SELECT * FROM readings WHERE inverter_id = ? ORDER BY ts DESC LIMIT 1", (inverter_id,)
|
||||||
|
).fetchone()
|
||||||
|
return reading_dict(row) if row else None
|
||||||
|
|
||||||
|
|
||||||
|
def latest_all(conn: sqlite3.Connection) -> dict[str, dict]:
|
||||||
|
rows = conn.execute(
|
||||||
|
"""
|
||||||
|
SELECT r.* FROM readings r
|
||||||
|
JOIN (SELECT inverter_id, max(ts) AS ts FROM readings GROUP BY inverter_id) m
|
||||||
|
ON m.inverter_id = r.inverter_id AND m.ts = r.ts
|
||||||
|
"""
|
||||||
|
).fetchall()
|
||||||
|
return {r["inverter_id"]: reading_dict(r) for r in rows}
|
||||||
|
|
||||||
|
|
||||||
|
def window_averages(conn: sqlite3.Connection, seconds: int) -> dict[str, dict]:
|
||||||
|
rows = conn.execute(
|
||||||
|
"""
|
||||||
|
SELECT inverter_id,
|
||||||
|
avg(ac_power_total_w) AS ac_power_w,
|
||||||
|
avg(dc_voltage_mppt1_v * dc_current_mppt1_a) AS mppt1_w,
|
||||||
|
avg(dc_voltage_mppt2_v * dc_current_mppt2_a) AS mppt2_w
|
||||||
|
FROM readings WHERE ts >= ? GROUP BY inverter_id
|
||||||
|
""",
|
||||||
|
(now_ts() - seconds,),
|
||||||
|
).fetchall()
|
||||||
|
return {r["inverter_id"]: dict(r) for r in rows}
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------- history
|
||||||
|
|
||||||
|
|
||||||
|
def pick_bucket(start: int, end: int, requested: int | None) -> int:
|
||||||
|
if requested:
|
||||||
|
return max(60, requested)
|
||||||
|
span = max(1, end - start)
|
||||||
|
return next((b for b in BUCKETS if span / b <= MAX_POINTS), BUCKETS[-1])
|
||||||
|
|
||||||
|
|
||||||
|
def _agg(key: str) -> str:
|
||||||
|
fn = "max" if FIELDS_BY_KEY[key].agg in ("max", "last") else "avg"
|
||||||
|
return f"{fn}({key}) AS {key}"
|
||||||
|
|
||||||
|
|
||||||
|
def history(
|
||||||
|
conn: sqlite3.Connection,
|
||||||
|
inverter_id: str,
|
||||||
|
start: int,
|
||||||
|
end: int,
|
||||||
|
bucket: int,
|
||||||
|
fields: list[str] | None,
|
||||||
|
) -> list[dict]:
|
||||||
|
keys = [k for k in (fields or NUMERIC_KEYS) if k in NUMERIC_KEYS]
|
||||||
|
# DC power is averaged per row (V*I), not as avg(V)*avg(I)
|
||||||
|
sql = f"""
|
||||||
|
SELECT (ts / :b) * :b AS t,
|
||||||
|
{', '.join(_agg(k) for k in keys)},
|
||||||
|
avg(dc_voltage_mppt1_v * dc_current_mppt1_a) AS dc_power_mppt1_w,
|
||||||
|
avg(dc_voltage_mppt2_v * dc_current_mppt2_a) AS dc_power_mppt2_w
|
||||||
|
FROM readings
|
||||||
|
WHERE inverter_id = :id AND ts >= :start AND ts <= :end
|
||||||
|
GROUP BY t ORDER BY t
|
||||||
|
"""
|
||||||
|
rows = conn.execute(sql, {"b": bucket, "id": inverter_id, "start": start, "end": end})
|
||||||
|
out = []
|
||||||
|
for r in rows:
|
||||||
|
d = {"t": r["t"]}
|
||||||
|
for k in r.keys()[1:]:
|
||||||
|
v = r[k]
|
||||||
|
if v is not None and k in FIELDS_BY_KEY:
|
||||||
|
v = round(v, FIELDS_BY_KEY[k].decimals + 1)
|
||||||
|
elif v is not None:
|
||||||
|
v = round(v)
|
||||||
|
d[k] = v
|
||||||
|
out.append(d)
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def fleet_power(conn: sqlite3.Connection, start: int, end: int, bucket: int) -> list[dict]:
|
||||||
|
"""AC power per inverter per bucket, pivoted: [{t, <inverter_id>: W, ...}]."""
|
||||||
|
rows = conn.execute(
|
||||||
|
"""
|
||||||
|
SELECT (ts / :b) * :b AS t, inverter_id, avg(ac_power_total_w) AS w
|
||||||
|
FROM readings WHERE ts >= :start AND ts <= :end
|
||||||
|
GROUP BY t, inverter_id ORDER BY t
|
||||||
|
""",
|
||||||
|
{"b": bucket, "start": start, "end": end},
|
||||||
|
)
|
||||||
|
points: dict[int, dict] = {}
|
||||||
|
for r in rows:
|
||||||
|
p = points.setdefault(r["t"], {"t": r["t"]})
|
||||||
|
p[r["inverter_id"]] = round(r["w"]) if r["w"] is not None else None
|
||||||
|
return list(points.values())
|
||||||
|
|
||||||
|
|
||||||
|
def daily_energy(
|
||||||
|
conn: sqlite3.Connection, first: date, last: date, inverter_id: str | None = None
|
||||||
|
) -> list[dict]:
|
||||||
|
"""[{day, total_wh, <inverter_id>: Wh, ...}] for every day in range, oldest first.
|
||||||
|
Uses the inverter's own daily counter, falling back to the lifetime
|
||||||
|
counter's growth over the day when the daily counter wasn't reported."""
|
||||||
|
sql = """
|
||||||
|
SELECT day, inverter_id, peak_power_w,
|
||||||
|
coalesce(daily_energy_wh, total_max_wh - total_min_wh) AS wh
|
||||||
|
FROM daily_energy WHERE day >= ? AND day <= ?
|
||||||
|
"""
|
||||||
|
params: list = [first.isoformat(), last.isoformat()]
|
||||||
|
if inverter_id:
|
||||||
|
sql += " AND inverter_id = ?"
|
||||||
|
params.append(inverter_id)
|
||||||
|
by_day: dict[str, dict] = {}
|
||||||
|
d = first
|
||||||
|
while d <= last:
|
||||||
|
by_day[d.isoformat()] = {"day": d.isoformat(), "total_wh": 0}
|
||||||
|
d += timedelta(days=1)
|
||||||
|
for r in conn.execute(sql, params):
|
||||||
|
row = by_day[r["day"]]
|
||||||
|
row[r["inverter_id"]] = r["wh"]
|
||||||
|
row["total_wh"] += r["wh"] or 0
|
||||||
|
if inverter_id:
|
||||||
|
row["peak_power_w"] = r["peak_power_w"]
|
||||||
|
return list(by_day.values())
|
||||||
|
|
||||||
|
|
||||||
|
def today_energy(conn: sqlite3.Connection) -> dict[str, int]:
|
||||||
|
rows = conn.execute(
|
||||||
|
"SELECT inverter_id, coalesce(daily_energy_wh, total_max_wh - total_min_wh) AS wh "
|
||||||
|
"FROM daily_energy WHERE day = ?",
|
||||||
|
(today().isoformat(),),
|
||||||
|
)
|
||||||
|
return {r["inverter_id"]: r["wh"] or 0 for r in rows}
|
||||||
|
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
"""Sun elevation from date/time and position (NOAA approximation, ±0.5°)."""
|
||||||
|
|
||||||
|
import math
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
|
||||||
|
|
||||||
|
def elevation(when: datetime, lat: float, lon: float) -> float:
|
||||||
|
when = when.astimezone(timezone.utc)
|
||||||
|
day_of_year = when.timetuple().tm_yday
|
||||||
|
hours = when.hour + when.minute / 60 + when.second / 3600
|
||||||
|
|
||||||
|
g = 2 * math.pi / 365 * (day_of_year - 1 + (hours - 12) / 24)
|
||||||
|
eq_time = 229.18 * (
|
||||||
|
0.000075
|
||||||
|
+ 0.001868 * math.cos(g)
|
||||||
|
- 0.032077 * math.sin(g)
|
||||||
|
- 0.014615 * math.cos(2 * g)
|
||||||
|
- 0.040849 * math.sin(2 * g)
|
||||||
|
)
|
||||||
|
decl = (
|
||||||
|
0.006918
|
||||||
|
- 0.399912 * math.cos(g)
|
||||||
|
+ 0.070257 * math.sin(g)
|
||||||
|
- 0.006758 * math.cos(2 * g)
|
||||||
|
+ 0.000907 * math.sin(2 * g)
|
||||||
|
- 0.002697 * math.cos(3 * g)
|
||||||
|
+ 0.00148 * math.sin(3 * g)
|
||||||
|
)
|
||||||
|
true_solar_minutes = hours * 60 + eq_time + 4 * lon
|
||||||
|
hour_angle = math.radians(true_solar_minutes / 4 - 180)
|
||||||
|
lat_r = math.radians(lat)
|
||||||
|
cos_zenith = math.sin(lat_r) * math.sin(decl) + math.cos(lat_r) * math.cos(decl) * math.cos(
|
||||||
|
hour_angle
|
||||||
|
)
|
||||||
|
return 90 - math.degrees(math.acos(max(-1.0, min(1.0, cos_zenith))))
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
-r requirements.txt
|
||||||
|
pytest==8.3.4
|
||||||
|
httpx>=0.27.0
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
fastapi==0.115.6
|
||||||
|
uvicorn[standard]==0.34.0
|
||||||
|
pydantic-settings==2.7.1
|
||||||
|
python-dotenv==1.0.1
|
||||||
|
tzdata
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
import pytest
|
||||||
|
from fastapi.testclient import TestClient
|
||||||
|
|
||||||
|
KEY = "test-key"
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def client(tmp_path, monkeypatch):
|
||||||
|
monkeypatch.setenv("DB_PATH", str(tmp_path / "test.db"))
|
||||||
|
monkeypatch.setenv("API_KEY", KEY)
|
||||||
|
# Midday sun at this position so silent inverters count as offline
|
||||||
|
monkeypatch.setenv("SITE_LATITUDE", "0")
|
||||||
|
monkeypatch.setenv("SITE_LONGITUDE", "0")
|
||||||
|
monkeypatch.setenv("DAYLIGHT_MIN_ELEVATION", "-90")
|
||||||
|
from app.config import get_settings
|
||||||
|
|
||||||
|
get_settings.cache_clear()
|
||||||
|
from app.main import app
|
||||||
|
|
||||||
|
with TestClient(app) as c:
|
||||||
|
c.headers["X-API-Key"] = KEY
|
||||||
|
yield c
|
||||||
|
get_settings.cache_clear()
|
||||||
@@ -0,0 +1,102 @@
|
|||||||
|
import time
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
|
||||||
|
|
||||||
|
def reading(inv, ts, power, **kw):
|
||||||
|
return {
|
||||||
|
"inverter_id": inv,
|
||||||
|
"timestamp": datetime.fromtimestamp(ts, timezone.utc).isoformat(),
|
||||||
|
"ac_power_total_w": power,
|
||||||
|
"ac_voltage_l1_v": 230.5,
|
||||||
|
"dc_voltage_mppt1_v": 600.0,
|
||||||
|
"dc_current_mppt1_a": power / 1200,
|
||||||
|
"dc_voltage_mppt2_v": 600.0,
|
||||||
|
"dc_current_mppt2_a": power / 1200,
|
||||||
|
"daily_energy_wh": 1000 + power,
|
||||||
|
"total_energy_wh": 5_000_000,
|
||||||
|
**kw,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def test_rejects_missing_key(client):
|
||||||
|
r = client.post("/api/readings", json=[], headers={"X-API-Key": "nope"})
|
||||||
|
assert r.status_code == 401
|
||||||
|
|
||||||
|
|
||||||
|
def test_ingest_is_idempotent_and_keeps_unknown_fields(client):
|
||||||
|
now = int(time.time())
|
||||||
|
batch = [reading("inv1", now, 10000, p_new_param=42)]
|
||||||
|
assert client.post("/api/readings", json=batch).json() == {"received": 1, "stored": 1, "duplicates": 0}
|
||||||
|
assert client.post("/api/readings", json=batch).json()["duplicates"] == 1
|
||||||
|
|
||||||
|
latest = client.get("/api/inverters/inv1/latest").json()
|
||||||
|
assert latest["ac_power_total_w"] == 10000
|
||||||
|
assert latest["extra"] == {"p_new_param": 42}
|
||||||
|
assert latest["dc_power_total_w"] == 10000
|
||||||
|
|
||||||
|
|
||||||
|
def test_summary_flags_weak_and_silent_inverters(client):
|
||||||
|
now = int(time.time())
|
||||||
|
batch = []
|
||||||
|
for t in (now - 120, now - 60, now):
|
||||||
|
batch += [reading("inv1", t, 15000), reading("inv2", t, 14500), reading("inv3", t, 6000)]
|
||||||
|
# MPPT2 dead on inv4
|
||||||
|
batch.append(reading("inv4", t, 7500, dc_current_mppt1_a=12.5, dc_current_mppt2_a=0))
|
||||||
|
batch.append(reading("inv5", now - 3600, 15000))
|
||||||
|
batch.append(reading("inv6", now, 15000, error_code=301, status_text="Isolation fault"))
|
||||||
|
client.post("/api/readings", json=batch)
|
||||||
|
|
||||||
|
s = client.get("/api/summary").json()
|
||||||
|
by_id = {x["inverter"]["id"]: x["health"] for x in s["inverters"]}
|
||||||
|
assert s["datalogger"]["online"] is True
|
||||||
|
assert by_id["inv1"]["state"] == "ok"
|
||||||
|
assert by_id["inv3"]["state"] == "warning"
|
||||||
|
assert by_id["inv3"]["issues"][0]["code"] == "underperforming"
|
||||||
|
assert "mppt_imbalance" in [i["code"] for i in by_id["inv4"]["issues"]]
|
||||||
|
assert by_id["inv5"]["state"] == "offline" and not by_id["inv5"]["online"]
|
||||||
|
assert by_id["inv6"]["state"] == "fault"
|
||||||
|
assert s["totals"]["online_count"] == 5
|
||||||
|
assert s["totals"]["ac_power_w"] == 15000 + 14500 + 6000 + 7500 + 15000
|
||||||
|
|
||||||
|
|
||||||
|
def test_per_kwp_comparison_uses_capacity(client):
|
||||||
|
now = int(time.time())
|
||||||
|
client.post("/api/readings", json=[reading("big", now, 16000), reading("small", now, 8000)])
|
||||||
|
client.patch("/api/inverters/big", json={"capacity_kwp": 20, "name": "Roof A"})
|
||||||
|
client.patch("/api/inverters/small", json={"capacity_kwp": 10})
|
||||||
|
s = client.get("/api/summary").json()
|
||||||
|
assert s["fleet_median_w_per_kwp"] == 800
|
||||||
|
assert all(x["health"]["state"] == "ok" for x in s["inverters"])
|
||||||
|
assert s["inverters"][0]["inverter"]["name"] == "Roof A"
|
||||||
|
|
||||||
|
|
||||||
|
def test_history_power_and_daily(client):
|
||||||
|
now = int(time.time())
|
||||||
|
batch = [reading("inv1", now - i * 60, 1000 + i) for i in range(30)]
|
||||||
|
client.post("/api/readings", json=batch)
|
||||||
|
|
||||||
|
h = client.get("/api/inverters/inv1/history", params={"bucket": 600}).json()
|
||||||
|
assert h["bucket"] == 600 and 3 <= len(h["points"]) <= 4
|
||||||
|
assert "dc_power_mppt1_w" in h["points"][0]
|
||||||
|
|
||||||
|
p = client.get("/api/power").json()
|
||||||
|
assert p["inverters"] == ["inv1"] and p["points"][-1]["inv1"] > 0
|
||||||
|
|
||||||
|
d = client.get("/api/energy/daily", params={"days": 7}).json()
|
||||||
|
assert len(d["days"]) == 7
|
||||||
|
assert d["days"][-1]["total_wh"] >= 1000
|
||||||
|
|
||||||
|
d1 = client.get("/api/inverters/inv1/daily", params={"days": 3}).json()
|
||||||
|
assert d1["days"][-1]["peak_power_w"] == 1029
|
||||||
|
|
||||||
|
|
||||||
|
def test_empty_batch_marks_datalogger_alive(client):
|
||||||
|
s = client.get("/api/summary").json()
|
||||||
|
assert s["datalogger"]["online"] is False
|
||||||
|
client.post("/api/readings", json=[])
|
||||||
|
assert client.get("/api/summary").json()["datalogger"]["online"] is True
|
||||||
|
|
||||||
|
|
||||||
|
def test_fields_meta(client):
|
||||||
|
keys = [f["key"] for f in client.get("/api/meta/fields").json()]
|
||||||
|
assert "ac_power_total_w" in keys and "efficiency_pct" in keys
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
set -e
|
||||||
|
|
||||||
|
PROJECT=/home/bonamin/refusol-datalogger
|
||||||
|
|
||||||
|
echo "Deploy started at $(date)"
|
||||||
|
cd "$PROJECT"
|
||||||
|
git fetch origin main
|
||||||
|
git reset --hard origin/main
|
||||||
|
docker compose up -d --build 2>&1
|
||||||
|
echo "Deploy finished at $(date)"
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
services:
|
||||||
|
backend:
|
||||||
|
build: ./backend
|
||||||
|
container_name: solar-backend
|
||||||
|
restart: unless-stopped
|
||||||
|
env_file: .env
|
||||||
|
environment:
|
||||||
|
DB_PATH: /app/data/solar.db
|
||||||
|
volumes:
|
||||||
|
- ./data:/app/data
|
||||||
|
networks:
|
||||||
|
- internal
|
||||||
|
|
||||||
|
frontend:
|
||||||
|
build: ./frontend
|
||||||
|
container_name: solar-frontend
|
||||||
|
restart: unless-stopped
|
||||||
|
networks:
|
||||||
|
- internal
|
||||||
|
|
||||||
|
nginx:
|
||||||
|
image: nginx:alpine
|
||||||
|
container_name: solar-nginx
|
||||||
|
restart: unless-stopped
|
||||||
|
ports:
|
||||||
|
- "${HTTP_PORT:-8090}:80" # NPM proxies solar.bonamin.net to this port
|
||||||
|
volumes:
|
||||||
|
- ./nginx/nginx.conf:/etc/nginx/nginx.conf:ro
|
||||||
|
depends_on:
|
||||||
|
- backend
|
||||||
|
- frontend
|
||||||
|
networks:
|
||||||
|
- internal
|
||||||
|
|
||||||
|
networks:
|
||||||
|
internal:
|
||||||
|
driver: bridge
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
node_modules/
|
||||||
|
dist/
|
||||||
|
dev-dist/
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
node_modules/
|
||||||
|
dist/
|
||||||
|
dev-dist/
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
# Stage 1: build
|
||||||
|
FROM node:20-alpine AS builder
|
||||||
|
|
||||||
|
WORKDIR /app
|
||||||
|
|
||||||
|
COPY package.json package-lock.json ./
|
||||||
|
RUN npm ci
|
||||||
|
|
||||||
|
COPY . .
|
||||||
|
RUN npm run build
|
||||||
|
|
||||||
|
# Stage 2: serve with nginx
|
||||||
|
FROM nginx:alpine
|
||||||
|
|
||||||
|
COPY --from=builder /app/dist /usr/share/nginx/html
|
||||||
|
COPY nginx.prod.conf /etc/nginx/conf.d/default.conf
|
||||||
|
|
||||||
|
EXPOSE 80
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
<!doctype html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8" />
|
||||||
|
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
|
||||||
|
<link rel="apple-touch-icon" href="/icons/apple-touch-icon.png" />
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />
|
||||||
|
<meta name="theme-color" content="#f9f9f7" media="(prefers-color-scheme: light)" />
|
||||||
|
<meta name="theme-color" content="#0d0d0d" media="(prefers-color-scheme: dark)" />
|
||||||
|
<meta name="apple-mobile-web-app-capable" content="yes" />
|
||||||
|
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />
|
||||||
|
<meta name="apple-mobile-web-app-title" content="Solar" />
|
||||||
|
<title>Solar Monitor</title>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div id="root"></div>
|
||||||
|
<script type="module" src="/src/main.jsx"></script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
server {
|
||||||
|
listen 80;
|
||||||
|
|
||||||
|
root /usr/share/nginx/html;
|
||||||
|
index index.html;
|
||||||
|
|
||||||
|
# SPA fallback — all unknown routes serve index.html
|
||||||
|
location / {
|
||||||
|
try_files $uri $uri/ /index.html;
|
||||||
|
}
|
||||||
|
|
||||||
|
# The service worker and manifest must be re-checked on every load,
|
||||||
|
# otherwise phones keep running an old build.
|
||||||
|
location ~* ^/(sw\.js|workbox-.*\.js|manifest\.webmanifest|index\.html)$ {
|
||||||
|
add_header Cache-Control "no-cache";
|
||||||
|
}
|
||||||
|
|
||||||
|
# Hashed build assets
|
||||||
|
location /assets/ {
|
||||||
|
expires 1y;
|
||||||
|
add_header Cache-Control "public, immutable";
|
||||||
|
}
|
||||||
|
}
|
||||||
Generated
+7169
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,24 @@
|
|||||||
|
{
|
||||||
|
"name": "frontend",
|
||||||
|
"private": true,
|
||||||
|
"version": "0.1.0",
|
||||||
|
"type": "module",
|
||||||
|
"scripts": {
|
||||||
|
"dev": "vite",
|
||||||
|
"build": "vite build",
|
||||||
|
"preview": "vite preview"
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"react": "^19.2.5",
|
||||||
|
"react-dom": "^19.2.5",
|
||||||
|
"react-router-dom": "^7.14.1",
|
||||||
|
"recharts": "^3.2.1"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@tailwindcss/vite": "^4.1.18",
|
||||||
|
"@vitejs/plugin-react": "^6.0.1",
|
||||||
|
"tailwindcss": "^4.1.18",
|
||||||
|
"vite": "^8.0.9",
|
||||||
|
"vite-plugin-pwa": "^1.2.0"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64"><rect width="64" height="64" rx="14" fill="#1a1a19"/><g stroke="#f5b324" stroke-width="4" stroke-linecap="round"><path d="M32 8v6M32 50v6M8 32h6M50 32h6M15 15l4.2 4.2M44.8 44.8 49 49M15 49l4.2-4.2M44.8 19.2 49 15"/></g><circle cx="32" cy="32" r="11" fill="#f5b324"/></svg>
|
||||||
|
After Width: | Height: | Size: 333 B |
Binary file not shown.
|
After Width: | Height: | Size: 6.4 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 10 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 26 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 16 KiB |
@@ -0,0 +1,72 @@
|
|||||||
|
import { useEffect, useState } from 'react'
|
||||||
|
import { Link, Route, Routes } from 'react-router-dom'
|
||||||
|
import Icon from './components/Icon'
|
||||||
|
import { useInstallPrompt } from './hooks/useInstallPrompt'
|
||||||
|
import { usePoll } from './hooks/usePoll'
|
||||||
|
import { api } from './lib/api'
|
||||||
|
import { ago } from './lib/format'
|
||||||
|
import Dashboard from './pages/Dashboard'
|
||||||
|
import InverterDetail from './pages/InverterDetail'
|
||||||
|
|
||||||
|
function useTick(ms) {
|
||||||
|
const [, setN] = useState(0)
|
||||||
|
useEffect(() => {
|
||||||
|
const id = setInterval(() => setN((n) => n + 1), ms)
|
||||||
|
return () => clearInterval(id)
|
||||||
|
}, [ms])
|
||||||
|
}
|
||||||
|
|
||||||
|
function LiveChip({ summary, error }) {
|
||||||
|
useTick(10_000)
|
||||||
|
if (error && !summary) return null
|
||||||
|
if (!summary) return null
|
||||||
|
const ok = summary.datalogger.online && !error
|
||||||
|
return (
|
||||||
|
<span className="inline-flex items-center gap-1.5 text-xs text-ink-2">
|
||||||
|
<span
|
||||||
|
className={`h-2 w-2 rounded-full ${ok ? 'animate-pulse' : ''}`}
|
||||||
|
style={{ background: ok ? 'var(--good)' : 'var(--critical)' }}
|
||||||
|
aria-hidden="true"
|
||||||
|
/>
|
||||||
|
{error ? 'Connection lost' : ok ? `Live · ${ago(summary.datalogger.last_ingest_at)}` : 'Datalogger offline'}
|
||||||
|
</span>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
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()
|
||||||
|
|
||||||
|
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">
|
||||||
|
<img src="/favicon.svg" alt="" className="h-7 w-7" />
|
||||||
|
<span>Solar Monitor</span>
|
||||||
|
</Link>
|
||||||
|
<div className="flex items-center gap-3">
|
||||||
|
<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>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</header>
|
||||||
|
<main className="mx-auto max-w-6xl px-4 py-4">
|
||||||
|
<Routes>
|
||||||
|
<Route path="/" element={<Dashboard summaryPoll={summaryPoll} />} />
|
||||||
|
<Route path="/inverters/:id" element={<InverterDetail summaryPoll={summaryPoll} />} />
|
||||||
|
<Route path="*" element={<Dashboard summaryPoll={summaryPoll} />} />
|
||||||
|
</Routes>
|
||||||
|
</main>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,191 @@
|
|||||||
|
import { useMemo } from 'react'
|
||||||
|
import {
|
||||||
|
Bar,
|
||||||
|
BarChart,
|
||||||
|
CartesianGrid,
|
||||||
|
Line,
|
||||||
|
LineChart,
|
||||||
|
ResponsiveContainer,
|
||||||
|
Tooltip,
|
||||||
|
XAxis,
|
||||||
|
YAxis,
|
||||||
|
} from 'recharts'
|
||||||
|
import { useThemeColors } from '../lib/colors'
|
||||||
|
import { dateTimeLabel, dayLabel, timeLabel } from '../lib/format'
|
||||||
|
|
||||||
|
export function Legend({ series }) {
|
||||||
|
if (series.length < 2) return null
|
||||||
|
return (
|
||||||
|
<ul className="flex flex-wrap gap-x-4 gap-y-1 text-xs text-ink-2">
|
||||||
|
{series.map((s) => (
|
||||||
|
<li key={s.key} className="inline-flex items-center gap-1.5">
|
||||||
|
<span className="h-0.5 w-3 rounded-full" style={{ background: s.color, height: 3 }} />
|
||||||
|
{s.name}
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function TooltipBox({ title, rows, total }) {
|
||||||
|
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>
|
||||||
|
<table className="w-full">
|
||||||
|
<tbody>
|
||||||
|
{rows.map((r) => (
|
||||||
|
<tr key={r.key}>
|
||||||
|
<td className="py-0.5 pr-3">
|
||||||
|
<span className="inline-flex items-center gap-1.5 text-ink-2">
|
||||||
|
<span className="inline-block h-2 w-2 rounded-full" style={{ background: r.color }} />
|
||||||
|
{r.name}
|
||||||
|
</span>
|
||||||
|
</td>
|
||||||
|
<td className="tnum py-0.5 text-right font-medium text-ink">{r.value}</td>
|
||||||
|
</tr>
|
||||||
|
))}
|
||||||
|
{total && (
|
||||||
|
<tr className="border-t border-line">
|
||||||
|
<td className="pt-1 pr-3 text-ink-2">Total</td>
|
||||||
|
<td className="tnum pt-1 text-right font-semibold text-ink">{total}</td>
|
||||||
|
</tr>
|
||||||
|
)}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
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])
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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 }) {
|
||||||
|
const c = useThemeColors()
|
||||||
|
const span = to - from
|
||||||
|
const data = useMemo(() => withGaps(points, bucket), [points, bucket])
|
||||||
|
return (
|
||||||
|
<div style={{ height }}>
|
||||||
|
<ResponsiveContainer width="100%" height="100%">
|
||||||
|
<LineChart data={data} margin={{ top: 8, right: 8, bottom: 0, left: 0 }}>
|
||||||
|
<CartesianGrid stroke={c.grid} vertical={false} />
|
||||||
|
<XAxis
|
||||||
|
dataKey="t"
|
||||||
|
type="number"
|
||||||
|
domain={[from, to]}
|
||||||
|
scale="time"
|
||||||
|
tickFormatter={(t) => timeLabel(t, span)}
|
||||||
|
tick={axisTick(c)}
|
||||||
|
stroke={c.axis}
|
||||||
|
tickLine={false}
|
||||||
|
minTickGap={28}
|
||||||
|
/>
|
||||||
|
<YAxis
|
||||||
|
tickFormatter={axisFormat ?? format}
|
||||||
|
tick={axisTick(c)}
|
||||||
|
axisLine={false}
|
||||||
|
tickLine={false}
|
||||||
|
width={48}
|
||||||
|
/>
|
||||||
|
<Tooltip
|
||||||
|
cursor={{ stroke: c.axis, strokeWidth: 1 }}
|
||||||
|
content={({ active, payload, label }) => {
|
||||||
|
if (!active || !payload?.length) return null
|
||||||
|
const rows = series
|
||||||
|
.filter((s) => payload[0].payload[s.key] != null)
|
||||||
|
.map((s) => ({ ...s, value: format(payload[0].payload[s.key]) }))
|
||||||
|
const total = showTotal
|
||||||
|
? format(series.reduce((sum, s) => sum + (payload[0].payload[s.key] ?? 0), 0))
|
||||||
|
: null
|
||||||
|
return <TooltipBox title={dateTimeLabel(label)} rows={rows} total={total} />
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
{series.map((s) => (
|
||||||
|
<Line
|
||||||
|
key={s.key}
|
||||||
|
dataKey={s.key}
|
||||||
|
name={s.name}
|
||||||
|
stroke={s.color}
|
||||||
|
strokeWidth={2}
|
||||||
|
dot={false}
|
||||||
|
activeDot={{ r: 4, stroke: c.surface, strokeWidth: 2 }}
|
||||||
|
connectNulls={false}
|
||||||
|
isAnimationActive={false}
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
</LineChart>
|
||||||
|
</ResponsiveContainer>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Bars per day. days: [{day: 'YYYY-MM-DD', [series.key]: number}].
|
||||||
|
* Several series are stacked (the stack height is the day's total).
|
||||||
|
*/
|
||||||
|
export function DayBars({ days, series, format, axisFormat, height = 220 }) {
|
||||||
|
const c = useThemeColors()
|
||||||
|
const last = series.length - 1
|
||||||
|
return (
|
||||||
|
<div style={{ height }}>
|
||||||
|
<ResponsiveContainer width="100%" height="100%">
|
||||||
|
<BarChart data={days} margin={{ top: 8, right: 8, bottom: 0, left: 0 }} barCategoryGap="18%">
|
||||||
|
<CartesianGrid stroke={c.grid} vertical={false} />
|
||||||
|
<XAxis
|
||||||
|
dataKey="day"
|
||||||
|
tickFormatter={(d) => dayLabel(d)}
|
||||||
|
tick={axisTick(c)}
|
||||||
|
stroke={c.axis}
|
||||||
|
tickLine={false}
|
||||||
|
minTickGap={24}
|
||||||
|
/>
|
||||||
|
<YAxis
|
||||||
|
tickFormatter={axisFormat ?? format}
|
||||||
|
tick={axisTick(c)}
|
||||||
|
axisLine={false}
|
||||||
|
tickLine={false}
|
||||||
|
width={48}
|
||||||
|
/>
|
||||||
|
<Tooltip
|
||||||
|
cursor={{ fill: c.grid, opacity: 0.5 }}
|
||||||
|
content={({ active, payload, label }) => {
|
||||||
|
if (!active || !payload?.length) return null
|
||||||
|
const row = payload[0].payload
|
||||||
|
const rows = series.map((s) => ({ ...s, value: format(row[s.key]) }))
|
||||||
|
const total =
|
||||||
|
series.length > 1 ? format(series.reduce((sum, s) => sum + (row[s.key] ?? 0), 0)) : null
|
||||||
|
return <TooltipBox title={dayLabel(label, true)} rows={rows} total={total} />
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
{series.map((s, i) => (
|
||||||
|
<Bar
|
||||||
|
key={s.key}
|
||||||
|
dataKey={s.key}
|
||||||
|
name={s.name}
|
||||||
|
stackId="day"
|
||||||
|
fill={s.color}
|
||||||
|
stroke={series.length > 1 ? c.surface : undefined}
|
||||||
|
strokeWidth={series.length > 1 ? 1 : 0}
|
||||||
|
radius={i === last ? [3, 3, 0, 0] : 0}
|
||||||
|
isAnimationActive={false}
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
</BarChart>
|
||||||
|
</ResponsiveContainer>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,85 @@
|
|||||||
|
import { Link } from 'react-router-dom'
|
||||||
|
import { seriesCssVar } from '../lib/colors'
|
||||||
|
import { pct, power } from '../lib/format'
|
||||||
|
import Icon from './Icon'
|
||||||
|
import { STATES } from './Health'
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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).
|
||||||
|
*/
|
||||||
|
export default function Comparison({ summary, ids }) {
|
||||||
|
const rows = summary.inverters
|
||||||
|
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 max = Math.max(1, ...rows.map((st) => value(st) ?? 0))
|
||||||
|
|
||||||
|
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>
|
||||||
|
<ul className="space-y-3">
|
||||||
|
{rows.map((st) => {
|
||||||
|
const v = value(st)
|
||||||
|
const flagged = st.health.issues.some((i) => i.code === 'underperforming')
|
||||||
|
const state = STATES[st.health.state]
|
||||||
|
return (
|
||||||
|
<li key={st.inverter.id}>
|
||||||
|
<Link
|
||||||
|
to={`/inverters/${encodeURIComponent(st.inverter.id)}`}
|
||||||
|
className="group block rounded-lg -mx-1 px-1 py-0.5 hover:bg-surface-2"
|
||||||
|
>
|
||||||
|
<div className="mb-1 flex items-center justify-between gap-2 text-sm">
|
||||||
|
<span className="flex min-w-0 items-center gap-2">
|
||||||
|
<span
|
||||||
|
className="h-2.5 w-2.5 shrink-0 rounded-sm"
|
||||||
|
style={{ background: seriesCssVar(ids, st.inverter.id) }}
|
||||||
|
aria-hidden="true"
|
||||||
|
/>
|
||||||
|
<span className="truncate font-medium">{st.inverter.name}</span>
|
||||||
|
</span>
|
||||||
|
<span className="flex shrink-0 items-center gap-2 tnum">
|
||||||
|
{v === null ? (
|
||||||
|
<span className="inline-flex items-center gap-1 text-xs text-ink-2">
|
||||||
|
<Icon name={state.icon} size={13} />
|
||||||
|
{state.label}
|
||||||
|
</span>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<span className="font-semibold">{power(st.latest.ac_power_total_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)}
|
||||||
|
</span>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<div className="h-2.5 overflow-hidden rounded-full bg-surface-2">
|
||||||
|
<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),
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</Link>
|
||||||
|
</li>
|
||||||
|
)
|
||||||
|
})}
|
||||||
|
</ul>
|
||||||
|
</section>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,138 @@
|
|||||||
|
import { useState } from 'react'
|
||||||
|
import { api } from '../lib/api'
|
||||||
|
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">
|
||||||
|
<span className="text-xs font-medium text-ink-2">{label}</span>
|
||||||
|
{children}
|
||||||
|
{hint && <span className="mt-1 block text-xs text-muted">{hint}</span>}
|
||||||
|
</label>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
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 [form, setForm] = useState({
|
||||||
|
name: inverter.name ?? '',
|
||||||
|
capacity_kwp: inverter.capacity_kwp ?? '',
|
||||||
|
mppt_count: inverter.mppt_count ?? 2,
|
||||||
|
sort_order: inverter.sort_order ?? 0,
|
||||||
|
notes: inverter.notes ?? '',
|
||||||
|
})
|
||||||
|
const [apiKey, setApiKey] = useState(storedKey)
|
||||||
|
const [saving, setSaving] = useState(false)
|
||||||
|
const [error, setError] = useState(null)
|
||||||
|
const set = (k) => (e) => setForm((f) => ({ ...f, [k]: e.target.value }))
|
||||||
|
|
||||||
|
async function save(e) {
|
||||||
|
e.preventDefault()
|
||||||
|
setSaving(true)
|
||||||
|
setError(null)
|
||||||
|
try {
|
||||||
|
const body = {
|
||||||
|
name: form.name.trim() || inverter.id,
|
||||||
|
capacity_kwp: form.capacity_kwp === '' ? null : Number(form.capacity_kwp),
|
||||||
|
mppt_count: Number(form.mppt_count),
|
||||||
|
sort_order: Number(form.sort_order) || 0,
|
||||||
|
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 */
|
||||||
|
}
|
||||||
|
onSaved(saved)
|
||||||
|
} catch (err) {
|
||||||
|
setError(err.status === 401 ? 'Wrong API key' : err.message)
|
||||||
|
} finally {
|
||||||
|
setSaving(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
className="fixed inset-0 z-50 flex items-end justify-center bg-black/50 sm:items-center sm:p-4"
|
||||||
|
onClick={onClose}
|
||||||
|
>
|
||||||
|
<form
|
||||||
|
onSubmit={save}
|
||||||
|
onClick={(e) => e.stopPropagation()}
|
||||||
|
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">
|
||||||
|
<Icon name="close" size={20} />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<div className="space-y-4">
|
||||||
|
<Field label="Display name" hint={`ID sent by the poller: ${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)">
|
||||||
|
<input
|
||||||
|
className={input}
|
||||||
|
type="number"
|
||||||
|
inputMode="decimal"
|
||||||
|
step="0.01"
|
||||||
|
min="0"
|
||||||
|
value={form.capacity_kwp}
|
||||||
|
onChange={set('capacity_kwp')}
|
||||||
|
/>
|
||||||
|
</Field>
|
||||||
|
<Field label="MPPT inputs used">
|
||||||
|
<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">
|
||||||
|
<input className={input} type="number" inputMode="numeric" value={form.sort_order} onChange={set('sort_order')} />
|
||||||
|
</Field>
|
||||||
|
<Field label="Notes">
|
||||||
|
<textarea className={`${input} min-h-20 py-2`} value={form.notes} onChange={set('notes')} />
|
||||||
|
</Field>
|
||||||
|
<Field label="API key">
|
||||||
|
<input
|
||||||
|
className={input}
|
||||||
|
type="password"
|
||||||
|
autoComplete="current-password"
|
||||||
|
value={apiKey}
|
||||||
|
onChange={(e) => setApiKey(e.target.value)}
|
||||||
|
required
|
||||||
|
/>
|
||||||
|
</Field>
|
||||||
|
{error && <p className="text-sm text-crit">{error}</p>}
|
||||||
|
<button
|
||||||
|
type="submit"
|
||||||
|
disabled={saving}
|
||||||
|
className="min-h-11 w-full rounded-lg bg-ink font-semibold text-page disabled:opacity-60"
|
||||||
|
>
|
||||||
|
{saving ? 'Saving…' : 'Save'}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,66 @@
|
|||||||
|
import Icon from './Icon'
|
||||||
|
|
||||||
|
export const STATES = {
|
||||||
|
ok: { label: 'Operating', icon: 'check', tone: 'good' },
|
||||||
|
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' },
|
||||||
|
}
|
||||||
|
|
||||||
|
const TONE = {
|
||||||
|
good: 'bg-[var(--good-wash)] text-good',
|
||||||
|
warning: 'bg-[var(--warning-wash)] text-warn',
|
||||||
|
critical: 'bg-[var(--critical-wash)] text-crit',
|
||||||
|
neutral: 'bg-surface-2 text-ink-2',
|
||||||
|
}
|
||||||
|
|
||||||
|
const SEVERITY_TONE = { critical: 'critical', warning: 'warning', info: 'neutral' }
|
||||||
|
const SEVERITY_ICON = { critical: 'fault', warning: 'alert', info: 'unknown' }
|
||||||
|
|
||||||
|
/** Health state pill: always icon + label, never color alone. */
|
||||||
|
export function StatePill({ state, size = 'md' }) {
|
||||||
|
const s = STATES[state] ?? STATES.unknown
|
||||||
|
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}
|
||||||
|
</span>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Online = a reading within the last 5 minutes. */
|
||||||
|
export function OnlineDot({ online }) {
|
||||||
|
return (
|
||||||
|
<span className="inline-flex items-center gap-1.5 text-xs text-ink-2">
|
||||||
|
<span
|
||||||
|
className="h-2 w-2 rounded-full"
|
||||||
|
style={{ background: online ? 'var(--good)' : 'var(--muted)' }}
|
||||||
|
aria-hidden="true"
|
||||||
|
/>
|
||||||
|
{online ? 'Online' : 'Offline'}
|
||||||
|
</span>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function IssueList({ issues, compact = false }) {
|
||||||
|
if (!issues?.length) return null
|
||||||
|
return (
|
||||||
|
<ul className={compact ? 'space-y-1' : 'space-y-2'}>
|
||||||
|
{issues.map((issue) => {
|
||||||
|
const tone = SEVERITY_TONE[issue.severity]
|
||||||
|
return (
|
||||||
|
<li
|
||||||
|
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>
|
||||||
|
</li>
|
||||||
|
)
|
||||||
|
})}
|
||||||
|
</ul>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,73 @@
|
|||||||
|
const PATHS = {
|
||||||
|
check: <path d="M20 6 9 17l-5-5" />,
|
||||||
|
alert: (
|
||||||
|
<>
|
||||||
|
<path d="M10.3 3.9 1.8 18a2 2 0 0 0 1.7 3h17a2 2 0 0 0 1.7-3L13.7 3.9a2 2 0 0 0-3.4 0Z" />
|
||||||
|
<path d="M12 9v4M12 17h.01" />
|
||||||
|
</>
|
||||||
|
),
|
||||||
|
fault: (
|
||||||
|
<>
|
||||||
|
<path d="M7.9 2h8.2L22 7.9v8.2L16.1 22H7.9L2 16.1V7.9Z" />
|
||||||
|
<path d="m15 9-6 6M9 9l6 6" />
|
||||||
|
</>
|
||||||
|
),
|
||||||
|
offline: (
|
||||||
|
<>
|
||||||
|
<path d="M12 20h.01M8.5 16.4a5 5 0 0 1 7 0M2 8.8a15 15 0 0 1 4.2-2.7M22 8.8a15 15 0 0 0-11.3-3.8M5 12.9a10 10 0 0 1 5.2-2.7M19 12.9a10 10 0 0 0-1.6-1.3" />
|
||||||
|
<path d="m2 2 20 20" />
|
||||||
|
</>
|
||||||
|
),
|
||||||
|
moon: <path d="M12 3a6 6 0 0 0 9 9 9 9 0 1 1-9-9Z" />,
|
||||||
|
unknown: (
|
||||||
|
<>
|
||||||
|
<circle cx="12" cy="12" r="10" />
|
||||||
|
<path d="M9.1 9a3 3 0 0 1 5.8 1c0 2-3 3-3 3M12 17h.01" />
|
||||||
|
</>
|
||||||
|
),
|
||||||
|
sun: (
|
||||||
|
<>
|
||||||
|
<circle cx="12" cy="12" r="4" />
|
||||||
|
<path d="M12 2v2M12 20v2M4.9 4.9l1.4 1.4M17.7 17.7l1.4 1.4M2 12h2M20 12h2M6.3 17.7l-1.4 1.4M19.1 4.9l-1.4 1.4" />
|
||||||
|
</>
|
||||||
|
),
|
||||||
|
back: <path d="m15 18-6-6 6-6" />,
|
||||||
|
chevron: <path d="m9 18 6-6-6-6" />,
|
||||||
|
edit: (
|
||||||
|
<>
|
||||||
|
<path d="M12 20h9" />
|
||||||
|
<path d="M16.5 3.5a2.1 2.1 0 0 1 3 3L7 19l-4 1 1-4Z" />
|
||||||
|
</>
|
||||||
|
),
|
||||||
|
download: (
|
||||||
|
<>
|
||||||
|
<path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" />
|
||||||
|
<path d="m7 10 5 5 5-5M12 15V3" />
|
||||||
|
</>
|
||||||
|
),
|
||||||
|
close: <path d="M18 6 6 18M6 6l12 12" />,
|
||||||
|
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" />
|
||||||
|
</>
|
||||||
|
),
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function Icon({ name, size = 16, className = '', strokeWidth = 2 }) {
|
||||||
|
return (
|
||||||
|
<svg
|
||||||
|
width={size}
|
||||||
|
height={size}
|
||||||
|
viewBox="0 0 24 24"
|
||||||
|
fill="none"
|
||||||
|
stroke="currentColor"
|
||||||
|
strokeWidth={strokeWidth}
|
||||||
|
strokeLinecap="round"
|
||||||
|
strokeLinejoin="round"
|
||||||
|
className={`shrink-0 ${className}`}
|
||||||
|
aria-hidden="true"
|
||||||
|
>
|
||||||
|
{PATHS[name]}
|
||||||
|
</svg>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,87 @@
|
|||||||
|
import { Link } from 'react-router-dom'
|
||||||
|
import { seriesCssVar } from '../lib/colors'
|
||||||
|
import { ago, energyParts, num, powerParts } from '../lib/format'
|
||||||
|
import { IssueList, OnlineDot, StatePill } from './Health'
|
||||||
|
import Icon from './Icon'
|
||||||
|
|
||||||
|
function Stat({ label, value, unit }) {
|
||||||
|
return (
|
||||||
|
<div className="min-w-0">
|
||||||
|
<div className="text-[11px] uppercase tracking-wide text-muted">{label}</div>
|
||||||
|
<div className="truncate tnum">
|
||||||
|
<span className="font-semibold">{value}</span>
|
||||||
|
{unit && <span className="ml-0.5 text-xs text-ink-2">{unit}</span>}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function InverterCard({ status, ids }) {
|
||||||
|
const { inverter, health, latest } = status
|
||||||
|
const r = latest ?? {}
|
||||||
|
const live = health.online
|
||||||
|
const [pw, pu] = powerParts(live ? r.ac_power_total_w : null)
|
||||||
|
// The daily counter only counts if the last reading is from today
|
||||||
|
const fromToday = r.timestamp && new Date(r.timestamp).toDateString() === new Date().toDateString()
|
||||||
|
const [today, todayU] = energyParts(fromToday ? r.daily_energy_wh : null)
|
||||||
|
const [life, lifeU] = energyParts(r.total_energy_wh)
|
||||||
|
const volts = [r.ac_voltage_l1_v, r.ac_voltage_l2_v, r.ac_voltage_l3_v]
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Link
|
||||||
|
to={`/inverters/${encodeURIComponent(inverter.id)}`}
|
||||||
|
className="card group flex flex-col gap-3 p-4 transition-colors hover:border-[var(--axis)]"
|
||||||
|
>
|
||||||
|
<div className="flex items-start justify-between gap-2">
|
||||||
|
<div className="min-w-0">
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<span
|
||||||
|
className="h-2.5 w-2.5 shrink-0 rounded-sm"
|
||||||
|
style={{ background: seriesCssVar(ids, inverter.id) }}
|
||||||
|
aria-hidden="true"
|
||||||
|
/>
|
||||||
|
<h3 className="truncate font-semibold">{inverter.name}</h3>
|
||||||
|
</div>
|
||||||
|
<div className="mt-1 flex items-center gap-2">
|
||||||
|
<OnlineDot online={live} />
|
||||||
|
<span className="text-xs text-muted">· {ago(r.timestamp)}</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<StatePill state={health.state} />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex items-baseline gap-1 tnum">
|
||||||
|
<span className="text-3xl font-semibold tracking-tight">{pw}</span>
|
||||||
|
<span className="text-sm text-ink-2">{pu}</span>
|
||||||
|
{inverter.capacity_kwp && live && r.ac_power_total_w != null && (
|
||||||
|
<span className="ml-auto text-xs text-muted">
|
||||||
|
{num(r.ac_power_total_w / inverter.capacity_kwp, 0)} W/kWp
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="grid grid-cols-3 gap-3 text-sm">
|
||||||
|
<Stat label="Today" value={today} unit={todayU} />
|
||||||
|
<Stat label="Lifetime" value={life} unit={lifeU} />
|
||||||
|
<Stat label="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>
|
||||||
|
{volts.map((v, i) => (
|
||||||
|
<span key={i}>
|
||||||
|
<span className="text-muted">L{i + 1} </span>
|
||||||
|
<span className="font-medium">{live ? num(v, 0) : '—'}</span>
|
||||||
|
<span className="text-muted"> V</span>
|
||||||
|
</span>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{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} />
|
||||||
|
</span>
|
||||||
|
</Link>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
export default function Segmented({ options, value, onChange, label }) {
|
||||||
|
return (
|
||||||
|
<div role="radiogroup" aria-label={label} className="inline-flex rounded-lg bg-surface-2 p-0.5 text-xs">
|
||||||
|
{options.map((o) => {
|
||||||
|
const active = o.value === value
|
||||||
|
return (
|
||||||
|
<button
|
||||||
|
key={o.value}
|
||||||
|
type="button"
|
||||||
|
role="radio"
|
||||||
|
aria-checked={active}
|
||||||
|
onClick={() => onChange(o.value)}
|
||||||
|
className={`min-h-8 rounded-md px-3 font-medium transition-colors ${
|
||||||
|
active ? 'bg-surface text-ink shadow-sm' : 'text-ink-2 hover:text-ink'
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
{o.label}
|
||||||
|
</button>
|
||||||
|
)
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
import { useEffect, useState } from 'react'
|
||||||
|
|
||||||
|
/** Chrome / Edge / Android "install app" prompt, when the browser offers one.
|
||||||
|
* Returns a function that shows it, or null. (iOS: Share → Add to Home Screen.) */
|
||||||
|
export function useInstallPrompt() {
|
||||||
|
const [event, setEvent] = useState(null)
|
||||||
|
useEffect(() => {
|
||||||
|
const onPrompt = (e) => {
|
||||||
|
e.preventDefault()
|
||||||
|
setEvent(e)
|
||||||
|
}
|
||||||
|
const onInstalled = () => setEvent(null)
|
||||||
|
window.addEventListener('beforeinstallprompt', onPrompt)
|
||||||
|
window.addEventListener('appinstalled', onInstalled)
|
||||||
|
return () => {
|
||||||
|
window.removeEventListener('beforeinstallprompt', onPrompt)
|
||||||
|
window.removeEventListener('appinstalled', onInstalled)
|
||||||
|
}
|
||||||
|
}, [])
|
||||||
|
if (!event) return null
|
||||||
|
return async () => {
|
||||||
|
event.prompt()
|
||||||
|
await event.userChoice
|
||||||
|
setEvent(null)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
import { useCallback, useEffect, useRef, useState } from 'react'
|
||||||
|
|
||||||
|
/** Calls `fetcher` now, every `intervalMs`, and whenever the app comes back to
|
||||||
|
* the foreground (phones suspend timers). Starts over when `key` changes. */
|
||||||
|
export function usePoll(fetcher, intervalMs, key = '') {
|
||||||
|
const [data, setData] = useState(null)
|
||||||
|
const [error, setError] = useState(null)
|
||||||
|
const [loading, setLoading] = useState(true)
|
||||||
|
const fetcherRef = useRef(fetcher)
|
||||||
|
fetcherRef.current = fetcher
|
||||||
|
|
||||||
|
const run = useCallback(async () => {
|
||||||
|
try {
|
||||||
|
setData(await fetcherRef.current())
|
||||||
|
setError(null)
|
||||||
|
} catch (e) {
|
||||||
|
setError(e)
|
||||||
|
} finally {
|
||||||
|
setLoading(false)
|
||||||
|
}
|
||||||
|
}, [])
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
setLoading(true)
|
||||||
|
run()
|
||||||
|
const id = setInterval(() => {
|
||||||
|
if (document.visibilityState === 'visible') run()
|
||||||
|
}, intervalMs)
|
||||||
|
const onVisible = () => document.visibilityState === 'visible' && run()
|
||||||
|
document.addEventListener('visibilitychange', onVisible)
|
||||||
|
return () => {
|
||||||
|
clearInterval(id)
|
||||||
|
document.removeEventListener('visibilitychange', onVisible)
|
||||||
|
}
|
||||||
|
}, [run, intervalMs, key])
|
||||||
|
|
||||||
|
return { data, error, loading, refresh: run }
|
||||||
|
}
|
||||||
@@ -0,0 +1,112 @@
|
|||||||
|
@import "tailwindcss";
|
||||||
|
|
||||||
|
/* Tokens: light by default, dark from the OS setting. Series colors are the
|
||||||
|
validated categorical order (one hue per inverter, fixed by position);
|
||||||
|
status colors are reserved for health and always paired with icon + text. */
|
||||||
|
:root {
|
||||||
|
color-scheme: light;
|
||||||
|
--page: #f9f9f7;
|
||||||
|
--surface: #fcfcfb;
|
||||||
|
--surface-2: #f0efec;
|
||||||
|
--ink: #0b0b0b;
|
||||||
|
--ink-2: #52514e;
|
||||||
|
--muted: #898781;
|
||||||
|
--grid: #e1e0d9;
|
||||||
|
--axis: #c3c2b7;
|
||||||
|
--border: rgba(11, 11, 11, 0.1);
|
||||||
|
--accent: #b77400;
|
||||||
|
|
||||||
|
--series-1: #2a78d6;
|
||||||
|
--series-2: #eb6834;
|
||||||
|
--series-3: #1baf7a;
|
||||||
|
--series-4: #eda100;
|
||||||
|
--series-5: #e87ba4;
|
||||||
|
--series-6: #008300;
|
||||||
|
--series-7: #6250d6;
|
||||||
|
--series-8: #e34948;
|
||||||
|
|
||||||
|
--good: #0ca30c;
|
||||||
|
--good-ink: #006300;
|
||||||
|
--warning: #fab219;
|
||||||
|
--warning-ink: #8a5a00;
|
||||||
|
--critical: #d03b3b;
|
||||||
|
--critical-ink: #b42828;
|
||||||
|
--good-wash: rgba(12, 163, 12, 0.1);
|
||||||
|
--warning-wash: rgba(250, 178, 25, 0.16);
|
||||||
|
--critical-wash: rgba(208, 59, 59, 0.1);
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (prefers-color-scheme: dark) {
|
||||||
|
:root {
|
||||||
|
color-scheme: dark;
|
||||||
|
--page: #0d0d0d;
|
||||||
|
--surface: #1a1a19;
|
||||||
|
--surface-2: #232322;
|
||||||
|
--ink: #f0efec;
|
||||||
|
--ink-2: #c3c2b7;
|
||||||
|
--muted: #898781;
|
||||||
|
--grid: #2c2c2a;
|
||||||
|
--axis: #383835;
|
||||||
|
--border: rgba(255, 255, 255, 0.1);
|
||||||
|
--accent: #f5b324;
|
||||||
|
|
||||||
|
--series-1: #3987e5;
|
||||||
|
--series-2: #d95926;
|
||||||
|
--series-3: #199e70;
|
||||||
|
--series-4: #c98500;
|
||||||
|
--series-5: #d55181;
|
||||||
|
--series-6: #008300;
|
||||||
|
--series-7: #9085e9;
|
||||||
|
--series-8: #e66767;
|
||||||
|
|
||||||
|
--good-ink: #0ca30c;
|
||||||
|
--warning-ink: #fab219;
|
||||||
|
--critical-ink: #e66767;
|
||||||
|
--good-wash: rgba(12, 163, 12, 0.14);
|
||||||
|
--warning-wash: rgba(250, 178, 25, 0.12);
|
||||||
|
--critical-wash: rgba(208, 59, 59, 0.18);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@theme {
|
||||||
|
--color-page: var(--page);
|
||||||
|
--color-surface: var(--surface);
|
||||||
|
--color-surface-2: var(--surface-2);
|
||||||
|
--color-ink: var(--ink);
|
||||||
|
--color-ink-2: var(--ink-2);
|
||||||
|
--color-muted: var(--muted);
|
||||||
|
--color-line: var(--border);
|
||||||
|
--color-accent: var(--accent);
|
||||||
|
--color-good: var(--good-ink);
|
||||||
|
--color-warn: var(--warning-ink);
|
||||||
|
--color-crit: var(--critical-ink);
|
||||||
|
--font-sans: system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;
|
||||||
|
}
|
||||||
|
|
||||||
|
html,
|
||||||
|
body {
|
||||||
|
background: var(--page);
|
||||||
|
color: var(--ink);
|
||||||
|
-webkit-tap-highlight-color: transparent;
|
||||||
|
}
|
||||||
|
|
||||||
|
body {
|
||||||
|
min-height: 100dvh;
|
||||||
|
padding-bottom: env(safe-area-inset-bottom);
|
||||||
|
}
|
||||||
|
|
||||||
|
.tnum {
|
||||||
|
font-variant-numeric: tabular-nums;
|
||||||
|
}
|
||||||
|
|
||||||
|
.card {
|
||||||
|
background: var(--surface);
|
||||||
|
border: 1px solid var(--border);
|
||||||
|
border-radius: 14px;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* recharts: keep focus outlines off the svg wrapper on tap */
|
||||||
|
.recharts-wrapper:focus,
|
||||||
|
.recharts-surface:focus {
|
||||||
|
outline: none;
|
||||||
|
}
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
async function request(path, { method = 'GET', body, apiKey } = {}) {
|
||||||
|
const headers = {}
|
||||||
|
if (body !== undefined) headers['Content-Type'] = 'application/json'
|
||||||
|
if (apiKey) headers['X-API-Key'] = apiKey
|
||||||
|
const res = await fetch(`/api${path}`, {
|
||||||
|
method,
|
||||||
|
headers,
|
||||||
|
body: body === undefined ? undefined : JSON.stringify(body),
|
||||||
|
})
|
||||||
|
if (!res.ok) {
|
||||||
|
let detail = res.statusText
|
||||||
|
try {
|
||||||
|
const data = await res.json()
|
||||||
|
detail = typeof data.detail === 'string' ? data.detail : JSON.stringify(data.detail)
|
||||||
|
} catch {
|
||||||
|
/* non-JSON error body */
|
||||||
|
}
|
||||||
|
const err = new Error(detail || `HTTP ${res.status}`)
|
||||||
|
err.status = res.status
|
||||||
|
throw err
|
||||||
|
}
|
||||||
|
return res.json()
|
||||||
|
}
|
||||||
|
|
||||||
|
function qs(params = {}) {
|
||||||
|
const q = new URLSearchParams()
|
||||||
|
for (const [k, v] of Object.entries(params)) {
|
||||||
|
if (v === undefined || v === null) continue
|
||||||
|
for (const item of [].concat(v)) q.append(k, item)
|
||||||
|
}
|
||||||
|
const s = q.toString()
|
||||||
|
return s ? `?${s}` : ''
|
||||||
|
}
|
||||||
|
|
||||||
|
const inv = (id) => `/inverters/${encodeURIComponent(id)}`
|
||||||
|
|
||||||
|
export const api = {
|
||||||
|
summary: () => request('/summary'),
|
||||||
|
fields: () => request('/meta/fields'),
|
||||||
|
power: (params) => request(`/power${qs(params)}`),
|
||||||
|
dailyEnergy: (params) => request(`/energy/daily${qs(params)}`),
|
||||||
|
inverter: (id) => request(inv(id)),
|
||||||
|
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 }),
|
||||||
|
}
|
||||||
|
|
||||||
|
export function isoAgo(seconds) {
|
||||||
|
return new Date(Date.now() - seconds * 1000).toISOString()
|
||||||
|
}
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
import { useEffect, useState } from 'react'
|
||||||
|
|
||||||
|
const SLOTS = 8
|
||||||
|
|
||||||
|
function read() {
|
||||||
|
const cs = getComputedStyle(document.documentElement)
|
||||||
|
const v = (name) => cs.getPropertyValue(name).trim()
|
||||||
|
return {
|
||||||
|
series: Array.from({ length: SLOTS }, (_, i) => v(`--series-${i + 1}`)),
|
||||||
|
ink: v('--ink'),
|
||||||
|
ink2: v('--ink-2'),
|
||||||
|
muted: v('--muted'),
|
||||||
|
grid: v('--grid'),
|
||||||
|
axis: v('--axis'),
|
||||||
|
surface: v('--surface'),
|
||||||
|
accent: v('--accent'),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Resolved token colors for the SVG charts; updates when the OS theme flips. */
|
||||||
|
export function useThemeColors() {
|
||||||
|
const [colors, setColors] = useState(read)
|
||||||
|
useEffect(() => {
|
||||||
|
const mq = window.matchMedia('(prefers-color-scheme: dark)')
|
||||||
|
const onChange = () => setColors(read())
|
||||||
|
mq.addEventListener('change', onChange)
|
||||||
|
return () => mq.removeEventListener('change', onChange)
|
||||||
|
}, [])
|
||||||
|
return colors
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Color for an inverter = its position in the full, stably sorted inverter
|
||||||
|
* list, so a color always follows the same inverter on every chart. */
|
||||||
|
export function seriesColor(colors, ids, id) {
|
||||||
|
const i = Math.max(0, ids.indexOf(id))
|
||||||
|
return colors.series[i % SLOTS]
|
||||||
|
}
|
||||||
|
|
||||||
|
export function seriesCssVar(ids, id) {
|
||||||
|
const i = Math.max(0, ids.indexOf(id))
|
||||||
|
return `var(--series-${(i % SLOTS) + 1})`
|
||||||
|
}
|
||||||
@@ -0,0 +1,70 @@
|
|||||||
|
const nf = (digits) =>
|
||||||
|
new Intl.NumberFormat(undefined, { minimumFractionDigits: digits, maximumFractionDigits: digits })
|
||||||
|
|
||||||
|
export function num(v, digits = 0) {
|
||||||
|
return v === null || v === undefined || Number.isNaN(v) ? '—' : nf(digits).format(v)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Power with an auto unit: 950 W, 12.4 kW, 1.20 MW. Returns [value, unit]. */
|
||||||
|
export function powerParts(w) {
|
||||||
|
if (w === null || w === undefined) return ['—', 'W']
|
||||||
|
const a = Math.abs(w)
|
||||||
|
if (a >= 1e6) return [num(w / 1e6, 2), 'MW']
|
||||||
|
if (a >= 1000) return [num(w / 1000, a >= 1e5 ? 0 : 1), 'kW']
|
||||||
|
return [num(w, 0), 'W']
|
||||||
|
}
|
||||||
|
|
||||||
|
export function power(w) {
|
||||||
|
const [v, u] = powerParts(w)
|
||||||
|
return `${v} ${u}`
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Energy with an auto unit: 850 Wh, 42.3 kWh, 123.4 MWh. Returns [value, unit]. */
|
||||||
|
export function energyParts(wh) {
|
||||||
|
if (wh === null || wh === undefined) return ['—', 'kWh']
|
||||||
|
const a = Math.abs(wh)
|
||||||
|
if (a >= 1e6) return [num(wh / 1e6, a >= 1e8 ? 0 : 1), 'MWh']
|
||||||
|
if (a >= 1000) return [num(wh / 1000, a >= 1e5 ? 0 : 1), 'kWh']
|
||||||
|
return [num(wh, 0), 'Wh']
|
||||||
|
}
|
||||||
|
|
||||||
|
export function energy(wh) {
|
||||||
|
const [v, u] = energyParts(wh)
|
||||||
|
return `${v} ${u}`
|
||||||
|
}
|
||||||
|
|
||||||
|
export function ago(iso) {
|
||||||
|
if (!iso) return '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`
|
||||||
|
}
|
||||||
|
|
||||||
|
export function pct(ratio) {
|
||||||
|
return ratio === null || ratio === undefined ? '—' : `${Math.round(ratio * 100)}%`
|
||||||
|
}
|
||||||
|
|
||||||
|
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' })
|
||||||
|
}
|
||||||
|
|
||||||
|
export function dateTimeLabel(unix) {
|
||||||
|
return new Date(unix * 1000).toLocaleString([], {
|
||||||
|
weekday: 'short',
|
||||||
|
day: 'numeric',
|
||||||
|
month: 'short',
|
||||||
|
hour: '2-digit',
|
||||||
|
minute: '2-digit',
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
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' })
|
||||||
|
}
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
import { StrictMode } from 'react'
|
||||||
|
import { createRoot } from 'react-dom/client'
|
||||||
|
import { BrowserRouter } from 'react-router-dom'
|
||||||
|
import App from './App'
|
||||||
|
import './index.css'
|
||||||
|
|
||||||
|
createRoot(document.getElementById('root')).render(
|
||||||
|
<StrictMode>
|
||||||
|
<BrowserRouter>
|
||||||
|
<App />
|
||||||
|
</BrowserRouter>
|
||||||
|
</StrictMode>,
|
||||||
|
)
|
||||||
@@ -0,0 +1,205 @@
|
|||||||
|
import { useMemo, useState } from 'react'
|
||||||
|
import { Link } from 'react-router-dom'
|
||||||
|
import { DayBars, Legend, TimeLines } from '../components/Charts'
|
||||||
|
import Comparison from '../components/Comparison'
|
||||||
|
import { IssueList } from '../components/Health'
|
||||||
|
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 { seriesColor, useThemeColors } from '../lib/colors'
|
||||||
|
import { energy, energyParts, num, power, powerParts } from '../lib/format'
|
||||||
|
|
||||||
|
function Hero({ summary }) {
|
||||||
|
const t = summary.totals
|
||||||
|
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="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">Today</dt>
|
||||||
|
<dd className="tnum">
|
||||||
|
<span className="text-lg font-semibold">{today}</span> <span className="text-ink-2">{todayU}</span>
|
||||||
|
</dd>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<dt className="text-xs text-muted">Lifetime</dt>
|
||||||
|
<dd className="tnum">
|
||||||
|
<span className="text-lg font-semibold">{life}</span> <span className="text-ink-2">{lifeU}</span>
|
||||||
|
</dd>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<dt className="text-xs text-muted">Online</dt>
|
||||||
|
<dd className="tnum">
|
||||||
|
<span className="text-lg font-semibold">{t.online_count}</span>
|
||||||
|
<span className="text-ink-2"> / {t.inverter_count}</span>
|
||||||
|
</dd>
|
||||||
|
</div>
|
||||||
|
</dl>
|
||||||
|
</section>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function Alerts({ summary }) {
|
||||||
|
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}` })),
|
||||||
|
)
|
||||||
|
if (!items.length) return null
|
||||||
|
return (
|
||||||
|
<section aria-label="Problems">
|
||||||
|
<IssueList issues={items} />
|
||||||
|
</section>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function DataloggerBanner({ summary }) {
|
||||||
|
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="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.
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function PowerCard({ ids, names }) {
|
||||||
|
const c = useThemeColors()
|
||||||
|
const { data } = usePoll(() => api.power(), 60_000)
|
||||||
|
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>
|
||||||
|
<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" />
|
||||||
|
)}
|
||||||
|
</section>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function EnergyCard({ ids, names }) {
|
||||||
|
const c = useThemeColors()
|
||||||
|
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 }]
|
||||||
|
: 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)
|
||||||
|
return (
|
||||||
|
<section className="card p-4">
|
||||||
|
<div className="mb-3 flex flex-wrap items-center justify-between gap-2">
|
||||||
|
<div>
|
||||||
|
<h2 className="text-sm font-semibold">Daily energy · last 30 days</h2>
|
||||||
|
{data && <div className="text-xs text-muted tnum">{energy(total)} total</div>}
|
||||||
|
</div>
|
||||||
|
<Segmented
|
||||||
|
label="Energy chart mode"
|
||||||
|
value={mode}
|
||||||
|
onChange={setMode}
|
||||||
|
options={[
|
||||||
|
{ value: 'combined', label: 'Combined' },
|
||||||
|
{ value: 'split', label: 'Per inverter' },
|
||||||
|
]}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
{mode === 'split' && (
|
||||||
|
<div className="mb-2">
|
||||||
|
<Legend series={series} />
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{data ? (
|
||||||
|
<DayBars days={data.days} series={series} format={energy} axisFormat={(wh) => num(wh / 1000, 0)} />
|
||||||
|
) : (
|
||||||
|
<div className="h-56" />
|
||||||
|
)}
|
||||||
|
<div className="mt-1 text-right text-[11px] text-muted">axis in kWh</div>
|
||||||
|
</section>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function Dashboard({ summaryPoll }) {
|
||||||
|
const { data: summary, error } = summaryPoll
|
||||||
|
const ids = useMemo(() => summary?.inverters.map((s) => s.inverter.id) ?? [], [summary])
|
||||||
|
const names = useMemo(
|
||||||
|
() => Object.fromEntries(summary?.inverters.map((s) => [s.inverter.id, s.inverter.name]) ?? []),
|
||||||
|
[summary],
|
||||||
|
)
|
||||||
|
|
||||||
|
if (!summary) {
|
||||||
|
return (
|
||||||
|
<div className="py-24 text-center text-sm text-ink-2">
|
||||||
|
{error ? `Can't reach the server: ${error.message}` : 'Loading…'}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!summary.inverters.length) {
|
||||||
|
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{' '}
|
||||||
|
<code className="text-ink">/api/readings</code>.
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="space-y-4">
|
||||||
|
<DataloggerBanner summary={summary} />
|
||||||
|
<div className="grid gap-4 lg:grid-cols-[minmax(0,5fr)_minmax(0,7fr)]">
|
||||||
|
<div className="space-y-4">
|
||||||
|
<Hero summary={summary} />
|
||||||
|
<Alerts summary={summary} />
|
||||||
|
<Comparison summary={summary} ids={ids} />
|
||||||
|
</div>
|
||||||
|
<div className="space-y-4">
|
||||||
|
<PowerCard ids={ids} names={names} />
|
||||||
|
<EnergyCard ids={ids} names={names} />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<section>
|
||||||
|
<h2 className="mb-2 px-1 text-sm font-semibold text-ink-2">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} />
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
<p className="pb-4 text-center text-xs text-muted">
|
||||||
|
<Link to="/api/docs" reloadDocument className="underline-offset-2 hover:underline">
|
||||||
|
API documentation
|
||||||
|
</Link>
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,281 @@
|
|||||||
|
import { useMemo, useState } from 'react'
|
||||||
|
import { Link, useParams } from 'react-router-dom'
|
||||||
|
import { DayBars, Legend, TimeLines } from '../components/Charts'
|
||||||
|
import EditInverterDialog from '../components/EditInverterDialog'
|
||||||
|
import { IssueList, OnlineDot, StatePill } from '../components/Health'
|
||||||
|
import Icon from '../components/Icon'
|
||||||
|
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'
|
||||||
|
|
||||||
|
const RANGES = {
|
||||||
|
'24h': { label: '24 h', seconds: 86400 },
|
||||||
|
'7d': { label: '7 days', seconds: 7 * 86400 },
|
||||||
|
'30d': { label: '30 days', seconds: 30 * 86400 },
|
||||||
|
}
|
||||||
|
|
||||||
|
const GROUPS = [
|
||||||
|
{ key: 'ac', label: 'AC output' },
|
||||||
|
{ key: 'dc', label: 'DC input' },
|
||||||
|
{ key: 'energy', label: 'Energy' },
|
||||||
|
{ key: 'device', label: 'Device' },
|
||||||
|
]
|
||||||
|
|
||||||
|
function formatField(field, value) {
|
||||||
|
if (value === null || value === undefined) return '—'
|
||||||
|
if (field.unit === 'Wh') return energy(value)
|
||||||
|
if (field.unit === 'W') return power(value)
|
||||||
|
if (typeof value !== 'number') return String(value)
|
||||||
|
return `${num(value, field.decimals)}${field.unit ? ` ${field.unit}` : ''}`
|
||||||
|
}
|
||||||
|
|
||||||
|
function KeyFigure({ label, parts }) {
|
||||||
|
return (
|
||||||
|
<div className="card px-4 py-3">
|
||||||
|
<div className="text-xs text-muted">{label}</div>
|
||||||
|
<div className="tnum">
|
||||||
|
<span className="text-2xl font-semibold tracking-tight">{parts[0]}</span>
|
||||||
|
<span className="ml-1 text-sm text-ink-2">{parts[1]}</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function Parameters({ fields, latest, live }) {
|
||||||
|
const extra = Object.entries(latest?.extra ?? {})
|
||||||
|
return (
|
||||||
|
<section className="card p-4">
|
||||||
|
<h2 className="mb-1 text-sm font-semibold">All parameters</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'}
|
||||||
|
</p>
|
||||||
|
<div className="grid gap-x-8 gap-y-4 sm:grid-cols-2">
|
||||||
|
{GROUPS.map((g) => {
|
||||||
|
const items = fields.filter((f) => f.group === g.key)
|
||||||
|
return (
|
||||||
|
<div key={g.key}>
|
||||||
|
<h3 className="mb-1 text-xs font-semibold uppercase tracking-wide text-muted">{g.label}</h3>
|
||||||
|
<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>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</dl>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
})}
|
||||||
|
{extra.length > 0 && (
|
||||||
|
<div>
|
||||||
|
<h3 className="mb-1 text-xs font-semibold uppercase tracking-wide text-muted">Other (unmapped)</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">
|
||||||
|
<dt className="font-mono text-xs text-ink-2">{k}</dt>
|
||||||
|
<dd className="tnum font-medium">{typeof v === 'object' ? JSON.stringify(v) : String(v)}</dd>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</dl>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function HistoryCharts({ id, fields }) {
|
||||||
|
const c = useThemeColors()
|
||||||
|
const [range, setRange] = useState('7d')
|
||||||
|
const [param, setParam] = useState('temperature_c')
|
||||||
|
const seconds = RANGES[range].seconds
|
||||||
|
const { data } = usePoll(() => api.history(id, { from: isoAgo(seconds) }), 120_000, `${id}:${range}`)
|
||||||
|
|
||||||
|
const powerSeries = [
|
||||||
|
{ key: 'ac_power_total_w', name: 'AC output', color: c.series[0] },
|
||||||
|
{ key: 'dc_power_mppt1_w', name: 'DC MPPT1', color: c.series[1] },
|
||||||
|
{ key: 'dc_power_mppt2_w', name: 'DC MPPT2', color: c.series[2] },
|
||||||
|
]
|
||||||
|
const chartable = fields.filter((f) => !f.derived && f.agg === 'avg' && f.key !== 'ac_power_total_w')
|
||||||
|
const paramField = fields.find((f) => f.key === param) ?? chartable[0]
|
||||||
|
const from = data ? Date.parse(data.from) / 1000 : 0
|
||||||
|
const to = data ? Date.parse(data.to) / 1000 : 1
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<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>
|
||||||
|
<Segmented
|
||||||
|
label="History range"
|
||||||
|
value={range}
|
||||||
|
onChange={setRange}
|
||||||
|
options={Object.entries(RANGES).map(([value, r]) => ({ value, label: r.label }))}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="mb-2">
|
||||||
|
<Legend series={powerSeries} />
|
||||||
|
</div>
|
||||||
|
{data ? (
|
||||||
|
<TimeLines
|
||||||
|
points={data.points}
|
||||||
|
series={powerSeries}
|
||||||
|
from={from}
|
||||||
|
to={to}
|
||||||
|
bucket={data.bucket}
|
||||||
|
format={power}
|
||||||
|
axisFormat={(w) => num(w / 1000, 0) + ' kW'}
|
||||||
|
/>
|
||||||
|
) : (
|
||||||
|
<div className="h-60" />
|
||||||
|
)}
|
||||||
|
<p className="mt-2 text-xs text-muted">
|
||||||
|
MPPT1 and MPPT2 should track each other when both carry similar strings — one dropping
|
||||||
|
away from the other points at that string.
|
||||||
|
</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>
|
||||||
|
<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"
|
||||||
|
>
|
||||||
|
{chartable.map((f) => (
|
||||||
|
<option key={f.key} value={f.key}>
|
||||||
|
{f.label}
|
||||||
|
{f.unit ? ` (${f.unit})` : ''}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
{data && paramField ? (
|
||||||
|
<TimeLines
|
||||||
|
points={data.points}
|
||||||
|
series={[{ key: paramField.key, name: paramField.label, color: c.series[0] }]}
|
||||||
|
from={from}
|
||||||
|
to={to}
|
||||||
|
bucket={data.bucket}
|
||||||
|
format={(v) => formatField(paramField, v)}
|
||||||
|
axisFormat={(v) => num(v, paramField.decimals > 1 ? 1 : 0)}
|
||||||
|
height={200}
|
||||||
|
/>
|
||||||
|
) : (
|
||||||
|
<div className="h-52" />
|
||||||
|
)}
|
||||||
|
</section>
|
||||||
|
</>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function YearEnergy({ id }) {
|
||||||
|
const c = useThemeColors()
|
||||||
|
const { data } = usePoll(() => api.inverterDaily(id, { days: 365 }), 600_000, id)
|
||||||
|
const total = data?.days.reduce((s, d) => s + (d.energy_wh ?? 0), 0)
|
||||||
|
return (
|
||||||
|
<section className="card p-4">
|
||||||
|
<h2 className="text-sm font-semibold">Daily energy · last 365 days</h2>
|
||||||
|
{data && <div className="mb-3 text-xs text-muted tnum">{energy(total)} total</div>}
|
||||||
|
{data ? (
|
||||||
|
<DayBars
|
||||||
|
days={data.days}
|
||||||
|
series={[{ key: 'energy_wh', name: 'Energy', color: c.accent }]}
|
||||||
|
format={energy}
|
||||||
|
axisFormat={(wh) => num(wh / 1000, 0)}
|
||||||
|
/>
|
||||||
|
) : (
|
||||||
|
<div className="h-56" />
|
||||||
|
)}
|
||||||
|
<div className="mt-1 text-right text-[11px] text-muted">axis in kWh</div>
|
||||||
|
</section>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function InverterDetail({ summaryPoll }) {
|
||||||
|
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 (!status) {
|
||||||
|
return (
|
||||||
|
<div className="py-24 text-center text-sm text-ink-2">
|
||||||
|
Unknown inverter “{id}”.{' '}
|
||||||
|
<Link to="/" className="underline">
|
||||||
|
Back to overview
|
||||||
|
</Link>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
const { inverter, health, latest } = status
|
||||||
|
const live = health.online
|
||||||
|
const fromToday = latest?.timestamp && new Date(latest.timestamp).toDateString() === new Date().toDateString()
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="space-y-4">
|
||||||
|
<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
|
||||||
|
</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>
|
||||||
|
{inverter.capacity_kwp && <span>· {num(inverter.capacity_kwp, 2)} kWp</span>}
|
||||||
|
{inverter.name !== inverter.id && <span>· {inverter.id}</span>}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<StatePill state={health.state} size="lg" />
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
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
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{inverter.notes && <p className="mt-2 text-sm text-ink-2">{inverter.notes}</p>}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<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="Today" parts={energyParts(fromToday ? latest?.daily_energy_wh : null)} />
|
||||||
|
<KeyFigure label="Lifetime" parts={energyParts(latest?.total_energy_wh)} />
|
||||||
|
<KeyFigure
|
||||||
|
label="vs fleet median"
|
||||||
|
parts={[health.relative_output == null ? '—' : num(health.relative_output * 100, 0), '%']}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{fields && <Parameters fields={fields} latest={latest} live={live} />}
|
||||||
|
{fields && <HistoryCharts id={id} fields={fields} />}
|
||||||
|
<YearEnergy id={id} />
|
||||||
|
|
||||||
|
{editing && (
|
||||||
|
<EditInverterDialog
|
||||||
|
inverter={inverter}
|
||||||
|
onClose={() => setEditing(false)}
|
||||||
|
onSaved={() => {
|
||||||
|
setEditing(false)
|
||||||
|
refresh()
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
import { defineConfig } from 'vite'
|
||||||
|
import react from '@vitejs/plugin-react'
|
||||||
|
import tailwindcss from '@tailwindcss/vite'
|
||||||
|
import { VitePWA } from 'vite-plugin-pwa'
|
||||||
|
|
||||||
|
export default defineConfig({
|
||||||
|
server: {
|
||||||
|
host: '0.0.0.0',
|
||||||
|
port: 5173,
|
||||||
|
proxy: {
|
||||||
|
'/api': {
|
||||||
|
target: process.env.VITE_API_PROXY || 'http://localhost:8000',
|
||||||
|
changeOrigin: true,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
plugins: [
|
||||||
|
react(),
|
||||||
|
tailwindcss(),
|
||||||
|
VitePWA({
|
||||||
|
registerType: 'autoUpdate',
|
||||||
|
manifest: {
|
||||||
|
name: 'Solar Monitor',
|
||||||
|
short_name: 'Solar',
|
||||||
|
description: 'Live status and output of the Refusol inverters',
|
||||||
|
start_url: '/',
|
||||||
|
display: 'standalone',
|
||||||
|
background_color: '#0d0d0d',
|
||||||
|
theme_color: '#0d0d0d',
|
||||||
|
icons: [
|
||||||
|
{ src: '/icons/icon-192.png', sizes: '192x192', type: 'image/png', purpose: 'any' },
|
||||||
|
{ src: '/icons/icon-512.png', sizes: '512x512', type: 'image/png', purpose: 'any' },
|
||||||
|
{ src: '/icons/icon-maskable-512.png', sizes: '512x512', type: 'image/png', purpose: 'maskable' },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
workbox: {
|
||||||
|
globPatterns: ['**/*.{js,css,html,ico,png,svg}'],
|
||||||
|
// Live data must never come from the cache
|
||||||
|
navigateFallbackDenylist: [/^\/api/],
|
||||||
|
runtimeCaching: [],
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
],
|
||||||
|
})
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
events {
|
||||||
|
worker_connections 1024;
|
||||||
|
}
|
||||||
|
|
||||||
|
http {
|
||||||
|
client_max_body_size 10m;
|
||||||
|
|
||||||
|
server {
|
||||||
|
listen 80;
|
||||||
|
server_name _;
|
||||||
|
|
||||||
|
resolver 127.0.0.11 valid=5s;
|
||||||
|
set $backend_upstream http://backend:8000;
|
||||||
|
set $frontend_upstream http://frontend:80;
|
||||||
|
|
||||||
|
location /api/ {
|
||||||
|
proxy_pass $backend_upstream$request_uri;
|
||||||
|
proxy_set_header Host $host;
|
||||||
|
proxy_set_header X-Real-IP $remote_addr;
|
||||||
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||||
|
proxy_set_header X-Forwarded-Proto $scheme;
|
||||||
|
proxy_read_timeout 60s;
|
||||||
|
add_header Cache-Control "no-store" always;
|
||||||
|
}
|
||||||
|
|
||||||
|
location / {
|
||||||
|
proxy_pass $frontend_upstream$request_uri;
|
||||||
|
proxy_set_header Host $host;
|
||||||
|
proxy_set_header X-Real-IP $remote_addr;
|
||||||
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||||
|
proxy_set_header X-Forwarded-Proto $scheme;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,60 @@
|
|||||||
|
# On-site poller
|
||||||
|
|
||||||
|
`refusol_poller.py` (not in this repo yet) reads the inverters over USS/TCP
|
||||||
|
(port 21062, USS address 0). It sends each cycle to the backend through
|
||||||
|
`backend_client.py` — copy that file next to the poller.
|
||||||
|
|
||||||
|
## Wiring it into `refusol_poller.py`
|
||||||
|
|
||||||
|
At the top of the file:
|
||||||
|
|
||||||
|
```python
|
||||||
|
from backend_client import BackendClient
|
||||||
|
|
||||||
|
BACKEND_URL = "https://solar.bonamin.net"
|
||||||
|
API_KEY = "same value as API_KEY in the server's .env"
|
||||||
|
|
||||||
|
backend = BackendClient(BACKEND_URL, API_KEY)
|
||||||
|
```
|
||||||
|
|
||||||
|
At the end of every poll cycle, one dict per inverter that answered:
|
||||||
|
|
||||||
|
```python
|
||||||
|
readings = []
|
||||||
|
for inverter_id, values in polled.items(): # however the poller holds them
|
||||||
|
readings.append({"inverter_id": inverter_id, **values})
|
||||||
|
backend.send(readings) # also call it when the list is empty
|
||||||
|
```
|
||||||
|
|
||||||
|
Each dict uses the keys below (all optional — send what was read). Anything
|
||||||
|
else you include (e.g. a newly discovered parameter as `"p0xx_raw": 1234`) is
|
||||||
|
stored too and shows under "Other (unmapped)" on the inverter page.
|
||||||
|
|
||||||
|
| key | unit | source |
|
||||||
|
|---|---|---|
|
||||||
|
| `ac_voltage_l1_v` / `_l2_v` / `_l3_v` | V | P050 / P05B / P064 raw / 40 |
|
||||||
|
| `dc_voltage_mppt1_v` / `_mppt2_v` | V | P052 / P054 raw / 40 |
|
||||||
|
| `dc_current_mppt1_a` / `_mppt2_a` | A | P05A / P05C raw / 10 |
|
||||||
|
| `ac_current_l1_a` / `_l2_a` / `_l3_a` | A | P068 / P069 / P06A raw / 100 |
|
||||||
|
| `ac_power_total_w` | W | P06D raw |
|
||||||
|
| `grid_frequency_hz` | Hz | P06C raw / 20 |
|
||||||
|
| `temperature_c` | °C | P070 raw >> 16 |
|
||||||
|
| `daily_energy_wh` | Wh | P063 IND=0 raw × 10 |
|
||||||
|
| `total_energy_wh` | Wh | P063 IND=11 raw |
|
||||||
|
| `status_code` | – | inverter state, once identified |
|
||||||
|
| `error_code` | – | non-zero = fault (shows the inverter as **Fault**) |
|
||||||
|
| `status_text` | – | optional human text for the code |
|
||||||
|
|
||||||
|
`send()` stamps each reading with the current UTC time, buffers to
|
||||||
|
`unsent_readings.jsonl` when the internet is down and re-sends later, and
|
||||||
|
never raises — a backend problem can't stop the polling loop.
|
||||||
|
|
||||||
|
**Call `send([])` even when no inverter answered.** That's the heartbeat that
|
||||||
|
lets the dashboard say "inverter not responding" (site online) instead of
|
||||||
|
"datalogger offline" (site/internet down).
|
||||||
|
|
||||||
|
## Trying the dashboard without the site
|
||||||
|
|
||||||
|
```bash
|
||||||
|
python fake_poller.py --url http://localhost:8090 --key change-me --backfill-days 30
|
||||||
|
```
|
||||||
@@ -0,0 +1,119 @@
|
|||||||
|
"""Sends each poll cycle's readings to the Solar Monitor backend.
|
||||||
|
|
||||||
|
Standard library only — nothing to pip install on the site laptop.
|
||||||
|
|
||||||
|
from backend_client import BackendClient
|
||||||
|
client = BackendClient(BACKEND_URL, API_KEY)
|
||||||
|
...
|
||||||
|
client.send(readings) # once per poll cycle, list of dicts (may be empty)
|
||||||
|
|
||||||
|
- Every reading gets a UTC `timestamp` at the moment `send()` is called,
|
||||||
|
unless it already has one.
|
||||||
|
- If the backend can't be reached, readings are kept in a local spool file
|
||||||
|
and re-sent (oldest first) on later cycles, so an internet outage leaves no
|
||||||
|
gap in the history. The backend ignores duplicates, so re-sending is safe.
|
||||||
|
- Call `send([])` when no inverter answered: it still tells the backend the
|
||||||
|
datalogger is alive, which is how the dashboard tells a dead inverter apart
|
||||||
|
from a dead internet link.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import json
|
||||||
|
import logging
|
||||||
|
import os
|
||||||
|
import urllib.error
|
||||||
|
import urllib.request
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
|
||||||
|
log = logging.getLogger("backend_client")
|
||||||
|
|
||||||
|
BATCH_LIMIT = 200 # backend accepts up to 200 readings per POST
|
||||||
|
|
||||||
|
|
||||||
|
class BackendClient:
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
backend_url: str,
|
||||||
|
api_key: str,
|
||||||
|
spool_path: str = "unsent_readings.jsonl",
|
||||||
|
max_spooled: int = 50_000, # ~1 week for 5 inverters at 1/min
|
||||||
|
timeout: float = 15,
|
||||||
|
):
|
||||||
|
self.url = backend_url.rstrip("/") + "/api/readings"
|
||||||
|
self.api_key = api_key
|
||||||
|
self.spool_path = spool_path
|
||||||
|
self.max_spooled = max_spooled
|
||||||
|
self.timeout = timeout
|
||||||
|
|
||||||
|
def send(self, readings: list[dict]) -> bool:
|
||||||
|
"""POST this cycle's readings (plus anything spooled). Never raises.
|
||||||
|
Returns True when everything was delivered."""
|
||||||
|
now = datetime.now(timezone.utc).isoformat(timespec="seconds")
|
||||||
|
readings = [{"timestamp": now, **r} for r in readings]
|
||||||
|
|
||||||
|
pending = self._load_spool()
|
||||||
|
if pending:
|
||||||
|
log.info("Re-sending %d spooled readings", len(pending))
|
||||||
|
queue = pending + readings
|
||||||
|
if not queue:
|
||||||
|
# Heartbeat: nothing to send, but the backend should know we're alive
|
||||||
|
return self._post([]) is not None
|
||||||
|
|
||||||
|
sent = 0
|
||||||
|
try:
|
||||||
|
while sent < len(queue):
|
||||||
|
chunk = queue[sent : sent + BATCH_LIMIT]
|
||||||
|
if self._post(chunk) is None:
|
||||||
|
break
|
||||||
|
sent += len(chunk)
|
||||||
|
finally:
|
||||||
|
self._save_spool(queue[sent:])
|
||||||
|
return sent == len(queue)
|
||||||
|
|
||||||
|
def _post(self, chunk: list[dict]) -> dict | None:
|
||||||
|
req = urllib.request.Request(
|
||||||
|
self.url,
|
||||||
|
data=json.dumps(chunk).encode(),
|
||||||
|
method="POST",
|
||||||
|
headers={"Content-Type": "application/json", "X-API-Key": self.api_key},
|
||||||
|
)
|
||||||
|
try:
|
||||||
|
with urllib.request.urlopen(req, timeout=self.timeout) as res:
|
||||||
|
return json.loads(res.read() or b"{}")
|
||||||
|
except urllib.error.HTTPError as e:
|
||||||
|
body = e.read().decode(errors="replace")[:300]
|
||||||
|
if e.code in (400, 422):
|
||||||
|
# The backend rejected the data itself — retrying won't help.
|
||||||
|
log.error("Backend rejected readings (%s): %s — dropping them", e.code, body)
|
||||||
|
return {}
|
||||||
|
log.warning("Backend error %s: %s", e.code, body)
|
||||||
|
except (urllib.error.URLError, TimeoutError, OSError) as e:
|
||||||
|
log.warning("Backend unreachable: %s", e)
|
||||||
|
return None
|
||||||
|
|
||||||
|
def _load_spool(self) -> list[dict]:
|
||||||
|
if not os.path.exists(self.spool_path):
|
||||||
|
return []
|
||||||
|
out = []
|
||||||
|
with open(self.spool_path, encoding="utf-8") as f:
|
||||||
|
for line in f:
|
||||||
|
line = line.strip()
|
||||||
|
if line:
|
||||||
|
try:
|
||||||
|
out.append(json.loads(line))
|
||||||
|
except json.JSONDecodeError:
|
||||||
|
pass
|
||||||
|
return out
|
||||||
|
|
||||||
|
def _save_spool(self, readings: list[dict]) -> None:
|
||||||
|
if len(readings) > self.max_spooled:
|
||||||
|
log.warning("Spool full — dropping %d oldest readings", len(readings) - self.max_spooled)
|
||||||
|
readings = readings[-self.max_spooled :]
|
||||||
|
if not readings:
|
||||||
|
if os.path.exists(self.spool_path):
|
||||||
|
os.remove(self.spool_path)
|
||||||
|
return
|
||||||
|
tmp = self.spool_path + ".tmp"
|
||||||
|
with open(tmp, "w", encoding="utf-8") as f:
|
||||||
|
for r in readings:
|
||||||
|
f.write(json.dumps(r) + "\n")
|
||||||
|
os.replace(tmp, self.spool_path)
|
||||||
@@ -0,0 +1,99 @@
|
|||||||
|
"""Simulated inverters for trying the dashboard without the real site.
|
||||||
|
|
||||||
|
python fake_poller.py --url http://localhost:8090 --key change-me --backfill-days 30
|
||||||
|
|
||||||
|
--backfill-days first loads that many days of history (one reading per
|
||||||
|
5 minutes), then it posts live readings every --interval seconds. Inverter
|
||||||
|
INV3 runs with a dead MPPT2 string so the warnings show up.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
import math
|
||||||
|
import random
|
||||||
|
import time
|
||||||
|
from datetime import datetime, timedelta, timezone
|
||||||
|
|
||||||
|
from backend_client import BackendClient
|
||||||
|
|
||||||
|
INVERTERS = ["INV1", "INV2", "INV3", "INV4", "INV5"]
|
||||||
|
PEAK_W = 18_000
|
||||||
|
|
||||||
|
|
||||||
|
def sun_factor(t: datetime) -> float:
|
||||||
|
# Rough local solar day 06:30–19:30 UTC+3, sine shaped
|
||||||
|
hour = (t.hour + 3 + t.minute / 60) % 24
|
||||||
|
x = (hour - 6.5) / 13
|
||||||
|
return max(0.0, math.sin(math.pi * x)) if 0 < x < 1 else 0.0
|
||||||
|
|
||||||
|
|
||||||
|
def reading(inv: str, t: datetime, state: dict) -> dict | None:
|
||||||
|
f = sun_factor(t) * random.uniform(0.93, 1.0)
|
||||||
|
if f <= 0.01:
|
||||||
|
return None # inverter asleep at night, doesn't answer
|
||||||
|
dead_mppt2 = inv == "INV3"
|
||||||
|
p_dc1 = PEAK_W / 2 * f
|
||||||
|
p_dc2 = 0 if dead_mppt2 else PEAK_W / 2 * f
|
||||||
|
v1, v2 = 560 + 60 * f, 560 + 60 * f
|
||||||
|
ac = int((p_dc1 + p_dc2) * 0.97)
|
||||||
|
day = t.date()
|
||||||
|
if state.get((inv, "day")) != day:
|
||||||
|
state[(inv, "day")] = day
|
||||||
|
state[(inv, "daily")] = 0
|
||||||
|
state[(inv, "daily")] += ac * state["step"] / 3600
|
||||||
|
state[(inv, "total")] = state.get((inv, "total"), 40_000_000) + ac * state["step"] / 3600
|
||||||
|
i_ac = ac / 3 / 230
|
||||||
|
return {
|
||||||
|
"inverter_id": inv,
|
||||||
|
"timestamp": t.isoformat(timespec="seconds"),
|
||||||
|
"ac_voltage_l1_v": round(random.uniform(228, 236), 1),
|
||||||
|
"ac_voltage_l2_v": round(random.uniform(228, 236), 1),
|
||||||
|
"ac_voltage_l3_v": round(random.uniform(228, 236), 1),
|
||||||
|
"dc_voltage_mppt1_v": round(v1, 1),
|
||||||
|
"dc_voltage_mppt2_v": round(v2 if not dead_mppt2 else 30.0, 1),
|
||||||
|
"dc_current_mppt1_a": round(p_dc1 / v1, 1),
|
||||||
|
"dc_current_mppt2_a": round(p_dc2 / v2, 1),
|
||||||
|
"ac_current_l1_a": round(i_ac, 2),
|
||||||
|
"ac_current_l2_a": round(i_ac, 2),
|
||||||
|
"ac_current_l3_a": round(i_ac, 2),
|
||||||
|
"ac_power_total_w": ac,
|
||||||
|
"grid_frequency_hz": round(random.uniform(49.95, 50.05), 2),
|
||||||
|
"temperature_c": int(30 + 25 * f),
|
||||||
|
"daily_energy_wh": int(state[(inv, "daily")] // 10 * 10),
|
||||||
|
"total_energy_wh": int(state[(inv, "total")]),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> None:
|
||||||
|
ap = argparse.ArgumentParser()
|
||||||
|
ap.add_argument("--url", default="http://localhost:8090")
|
||||||
|
ap.add_argument("--key", default="change-me")
|
||||||
|
ap.add_argument("--backfill-days", type=int, default=0)
|
||||||
|
ap.add_argument("--interval", type=int, default=60)
|
||||||
|
args = ap.parse_args()
|
||||||
|
client = BackendClient(args.url, args.key, spool_path="fake_unsent.jsonl")
|
||||||
|
|
||||||
|
state: dict = {}
|
||||||
|
if args.backfill_days:
|
||||||
|
state["step"] = 300
|
||||||
|
t = datetime.now(timezone.utc) - timedelta(days=args.backfill_days)
|
||||||
|
batch: list[dict] = []
|
||||||
|
while t < datetime.now(timezone.utc):
|
||||||
|
batch += [r for inv in INVERTERS if (r := reading(inv, t, state))]
|
||||||
|
if len(batch) >= 1000:
|
||||||
|
client.send(batch)
|
||||||
|
batch = []
|
||||||
|
t += timedelta(minutes=5)
|
||||||
|
client.send(batch)
|
||||||
|
print(f"Backfilled {args.backfill_days} days")
|
||||||
|
|
||||||
|
state["step"] = args.interval
|
||||||
|
while True:
|
||||||
|
now = datetime.now(timezone.utc)
|
||||||
|
batch = [r for inv in INVERTERS if (r := reading(inv, now, state))]
|
||||||
|
ok = client.send(batch)
|
||||||
|
print(f"{now:%H:%M:%S} sent {len(batch)} readings, ok={ok}")
|
||||||
|
time.sleep(args.interval)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
Reference in New Issue
Block a user