commit 48a6aee18f711cb073420f2ed2a809a49ae3a5ea Author: IU2EUG Date: Sat Sep 6 20:49:49 2025 +0100 Primo commit: Modbus logger con API e frontend diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..c9bff22 --- /dev/null +++ b/.gitignore @@ -0,0 +1,7 @@ +# Virtualenv +.venv/ +# Database locale +modbus.db +# File temporanei / log +__pycache__/ +*.log diff --git a/README.md b/README.md new file mode 100644 index 0000000..377667c --- /dev/null +++ b/README.md @@ -0,0 +1,21 @@ +# Modbus Logger (SDM230) + Web UI + +- API FastAPI su `/api/...` +- Frontend web statico servito su `/` dalla cartella `web/` +- Log su SQLite `readings.db` + +## Avvio +```bash +python3 -m venv .venv +source .venv/bin/activate +pip install --upgrade pip +pip install -r requirements.txt +python main.py +``` +Apri il browser su `http://:8000/`. + +## Config +Vedi `config.yaml` (parametri seriali e registri). + +## Service (systemd) +Aggiorna `modbus-logger.service` per puntare al venv. diff --git a/config.yaml b/config.yaml new file mode 100644 index 0000000..406815f --- /dev/null +++ b/config.yaml @@ -0,0 +1,42 @@ +# === CONFIG PER EASTRON SDM230 Modbus V2 (monofase) === +# Tutti i registri di misura sono su Input Registers (Function Code 04) e sono float32 (2 registri). +# Byte order: ABCD (big-endian, registro alto -> registro basso). +# Nota: la potenza attiva รจ in W, quindi la scaliamo a kW con scale: 0.001. + +serial: + port: "/dev/ttyUSB0" + slave_id: 1 + baudrate: 9600 + bytesize: 8 + parity: "N" + stopbits: 1 + timeout: 2.0 + +poll_interval_seconds: 30 + +api: + host: "0.0.0.0" + port: 8000 + api_key: "alberto" + +registers: + voltage: + address: 0 + function_code: 4 + data_type: "float32" + byteorder: "ABCD" + scale: 1.0 + + power_kw: + address: 12 + function_code: 4 + data_type: "float32" + byteorder: "ABCD" + scale: 0.001 + + energy_kwh: + address: 342 + function_code: 4 + data_type: "float32" + byteorder: "ABCD" + scale: 1.0 diff --git a/main.py b/main.py new file mode 100644 index 0000000..614e01a --- /dev/null +++ b/main.py @@ -0,0 +1,279 @@ +#!/usr/bin/env python3 +import os +import time +import threading +import sqlite3 +import logging +from typing import Optional, Dict, Any, Tuple +from datetime import datetime, timedelta + +import minimalmodbus +import serial +import yaml +from fastapi import FastAPI, HTTPException, Depends, Query, Request +from fastapi.middleware.cors import CORSMiddleware +from fastapi.staticfiles import StaticFiles +from pydantic import BaseModel +import uvicorn + +DEFAULT_CONFIG_PATH = os.environ.get("CONFIG_PATH", "config.yaml") +DB_PATH = os.environ.get("DB_PATH", "readings.db") + +logger = logging.getLogger("modbus_logger") +logging.basicConfig(level=os.environ.get("LOG_LEVEL", "INFO"), + format="%(asctime)s %(levelname)s %(message)s") + +cfg: Dict[str, Any] = {} +instrument: Optional[minimalmodbus.Instrument] = None +poll_thread: Optional[threading.Thread] = None +stop_event = threading.Event() +modbus_lock = threading.Lock() + +app = FastAPI(title="Modbus Logger API", version="1.0.0") + +# CORS (adjust origins as needed) +app.add_middleware( + CORSMiddleware, + allow_origins=["*"], + allow_credentials=True, + allow_methods=["*"], + allow_headers=["*"], +) + +class LatestReading(BaseModel): + ts: str + voltage: Optional[float] = None + power_kw: Optional[float] = None + energy_kwh: Optional[float] = None + +BYTEORDER_MAP = { + "ABCD": minimalmodbus.BYTEORDER_BIG, + "DCBA": minimalmodbus.BYTEORDER_LITTLE, + "BADC": minimalmodbus.BYTEORDER_BIG_SWAP, + "CDAB": minimalmodbus.BYTEORDER_LITTLE_SWAP, +} + +def load_config(path: str) -> Dict[str, Any]: + with open(path, "r", encoding="utf-8") as f: + return yaml.safe_load(f) + +def init_db(db_path: str): + conn = sqlite3.connect(db_path) + cur = conn.cursor() + cur.execute(""" + CREATE TABLE IF NOT EXISTS readings ( + ts TEXT NOT NULL, + voltage REAL, + power_kw REAL, + energy_kwh REAL + ); + """) + cur.execute("CREATE INDEX IF NOT EXISTS idx_readings_ts ON readings(ts);") + conn.commit() + conn.close() + +def get_db_conn(): + return sqlite3.connect(DB_PATH, check_same_thread=False) + +def api_key_auth(request: Request): + key = cfg.get("api", {}).get("api_key", "") + if not key: + return + provided = request.headers.get("X-API-Key") + if provided != key: + raise HTTPException(status_code=401, detail="Invalid or missing API key. Provide X-API-Key header.") + +def build_instrument_from_config(config: Dict[str, Any]) -> minimalmodbus.Instrument: + serial_cfg = config.get("serial", {}) + port = serial_cfg.get("port", "/dev/ttyUSB0") + slave_id = int(serial_cfg.get("slave_id", 1)) + baudrate = int(serial_cfg.get("baudrate", 9600)) + bytesize = int(serial_cfg.get("bytesize", 8)) + parity = serial_cfg.get("parity", "N") + stopbits = int(serial_cfg.get("stopbits", 1)) + timeout = float(serial_cfg.get("timeout", 1.0)) + + instr = minimalmodbus.Instrument(port, slave_id, mode=minimalmodbus.MODE_RTU) + instr.serial.baudrate = baudrate + instr.serial.bytesize = bytesize + instr.serial.parity = getattr(serial, f"PARITY_{parity.upper()}", serial.PARITY_NONE) + instr.serial.stopbits = stopbits + instr.serial.timeout = timeout + instr.clear_buffers_before_each_transaction = True + instr.close_port_after_each_call = True + return instr + +def read_value(name: str, spec: Dict[str, Any]) -> Optional[float]: + address = int(spec.get("address", 0)) + function_code = int(spec.get("function_code", 4)) + data_type = spec.get("data_type", "float32") + scale = float(spec.get("scale", 1.0)) + + try: + with modbus_lock: + if data_type == "float32": + byteorder_str = spec.get("byteorder", "ABCD") + byteorder = BYTEORDER_MAP.get(byteorder_str, minimalmodbus.BYTEORDER_BIG) + val = instrument.read_float(address, functioncode=function_code, + number_of_registers=2, byteorder=byteorder) + return float(val) * scale + elif data_type == "uint16": + signed = bool(spec.get("signed", False)) + decimals = int(spec.get("decimals", 0)) + val = instrument.read_register(address, number_of_decimals=decimals, + functioncode=function_code, signed=signed) + return float(val) * scale + else: + logger.error(f"Unsupported data_type for {name}: {data_type}") + return None + except Exception as e: + logger.warning(f"Read failed for {name} at addr {address}: {e}") + return None + +def poll_once(config: Dict[str, Any]) -> Tuple[str, Optional[float], Optional[float], Optional[float]]: + regs = config.get("registers", {}) + voltage = read_value("voltage", regs.get("voltage", {})) + power_kw = read_value("power_kw", regs.get("power_kw", {})) + energy_kwh = read_value("energy_kwh", regs.get("energy_kwh", {})) + + # Arrotondamento qui + if voltage is not None: + voltage = round(voltage, 2) + if power_kw is not None: + power_kw = round(power_kw, 3) # se vuoi 2 decimali, cambia in 2 + if energy_kwh is not None: + energy_kwh = round(energy_kwh, 2) + + ts = datetime.utcnow().replace(microsecond=0).isoformat() + "Z" + return ts, voltage, power_kw, energy_kwh + +def insert_reading(conn, ts: str, voltage: Optional[float], power_kw: Optional[float], energy_kwh: Optional[float]): + cur = conn.cursor() + cur.execute("INSERT INTO readings (ts, voltage, power_kw, energy_kwh) VALUES (?,?,?,?)", + (ts, voltage, power_kw, energy_kwh)) + conn.commit() + +def polling_loop(): + interval = int(cfg.get("poll_interval_seconds", 10)) + conn = get_db_conn() + try: + while not stop_event.is_set(): + ts, v, p, e = poll_once(cfg) + insert_reading(conn, ts, v, p, e) + logger.info(f"Polled: ts={ts} V={v} kW={p} kWh={e}") + stop_event.wait(interval) + finally: + conn.close() + +@app.get("/api/v1/health") +def health(): + return {"status": "ok", "time_utc": datetime.utcnow().isoformat() + "Z"} + +@app.get("/api/v1/config") +def get_config(_: Any = Depends(api_key_auth)): + safe_cfg = dict(cfg) + if "api" in safe_cfg and "api_key" in safe_cfg["api"]: + safe_cfg["api"] = dict(safe_cfg["api"]) + safe_cfg["api"]["api_key"] = "***" + return safe_cfg + +@app.post("/api/v1/poll", response_model=LatestReading) +def manual_poll(_: Any = Depends(api_key_auth)): + ts, v, p, e = poll_once(cfg) + conn = get_db_conn() + try: + insert_reading(conn, ts, v, p, e) + finally: + conn.close() + return LatestReading(ts=ts, voltage=v, power_kw=p, energy_kwh=e) + +@app.get("/api/v1/metrics/latest", response_model=LatestReading) +def latest(_: Any = Depends(api_key_auth)): + conn = get_db_conn() + try: + cur = conn.cursor() + cur.execute("SELECT ts, voltage, power_kw, energy_kwh FROM readings ORDER BY ts DESC LIMIT 1;") + row = cur.fetchone() + finally: + conn.close() + if not row: + raise HTTPException(status_code=404, detail="No data yet") + return LatestReading( + ts=row[0], + voltage=round(row[1], 2) if row[1] is not None else None, + power_kw=round(row[2], 3) if row[2] is not None else None, + energy_kwh=round(row[3], 2) if row[3] is not None else None) +@app.get("/api/v1/metrics/history") +def history( + request: Request, + start: Optional[str] = Query(None, description="ISO8601 start (UTC). If omitted, defaults to now-24h."), + end: Optional[str] = Query(None, description="ISO8601 end (UTC). If omitted, defaults to now."), + limit: Optional[int] = Query(1000, ge=1, le=10000), + _: Any = Depends(api_key_auth) +): + now = datetime.utcnow() + if not end: + end_dt = now + else: + try: + end_dt = datetime.fromisoformat(end.replace("Z","")) + except Exception: + raise HTTPException(400, "Invalid 'end' timestamp. Use ISO8601.") + if not start: + start_dt = end_dt - timedelta(days=1) + else: + try: + start_dt = datetime.fromisoformat(start.replace("Z","")) + except Exception: + raise HTTPException(400, "Invalid 'start' timestamp. Use ISO8601.") + + conn = get_db_conn() + try: + cur = conn.cursor() + cur.execute(""" + SELECT ts, voltage, power_kw, energy_kwh + FROM readings + WHERE ts >= ? AND ts < ? + ORDER BY ts ASC + LIMIT ? + """, (start_dt.replace(microsecond=0).isoformat() + "Z", end_dt.replace(microsecond=0).isoformat() + "Z", limit)) + rows = cur.fetchall() + finally: + conn.close() + return [ + { + "ts": r[0], + "voltage": round(r[1], 2) if r[1] is not None else None, + "power_kw": round(r[2], 3) if r[2] is not None else None, + "energy_kwh": round(r[3], 2) if r[3] is not None else None + } + for r in rows +] +# Serve static frontend from ./web (index.html) +app.mount("/", StaticFiles(directory="web", html=True), name="web") + +@app.on_event("startup") +def on_startup(): + global cfg, instrument, poll_thread + cfg = load_config(DEFAULT_CONFIG_PATH) + init_db(DB_PATH) + instrument = build_instrument_from_config(cfg) + logger.info("Modbus instrument initialized") + stop_event.clear() + poll_thread = threading.Thread(target=polling_loop, name="poller", daemon=True) + poll_thread.start() + logger.info("Polling thread started") + +@app.on_event("shutdown") +def on_shutdown(): + stop_event.set() + if poll_thread and poll_thread.is_alive(): + poll_thread.join(timeout=5) + +if __name__ == "__main__": + cfg = load_config(DEFAULT_CONFIG_PATH) + init_db(DB_PATH) + instrument = build_instrument_from_config(cfg) + host = cfg.get("api", {}).get("host", "0.0.0.0") + port = int(cfg.get("api", {}).get("port", 8000)) + uvicorn.run("main:app", host=host, port=port, reload=False) diff --git a/modbus-logger.service b/modbus-logger.service new file mode 100644 index 0000000..dd4cb4c --- /dev/null +++ b/modbus-logger.service @@ -0,0 +1,15 @@ +[Unit] +Description=Modbus Logger API + Web +After=network-online.target + +[Service] +User=pi +WorkingDirectory=/home/pi/modbus-logger +Environment=CONFIG_PATH=/home/pi/modbus-logger/config.yaml +Environment=DB_PATH=/home/pi/modbus-logger/readings.db +Environment=LOG_LEVEL=INFO +ExecStart=/home/pi/modbus-logger/.venv/bin/python /home/pi/modbus-logger/main.py +Restart=on-failure + +[Install] +WantedBy=multi-user.target diff --git a/readings.db b/readings.db new file mode 100644 index 0000000..e45e4d0 Binary files /dev/null and b/readings.db differ diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..df4d7e2 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,5 @@ +fastapi==0.115.0 +uvicorn[standard]==0.30.6 +minimalmodbus==2.1.1 +pyserial==3.5 +PyYAML==6.0.2 diff --git a/web/app.js b/web/app.js new file mode 100644 index 0000000..534950f --- /dev/null +++ b/web/app.js @@ -0,0 +1,263 @@ +(function(){ + const qs = (s)=>document.querySelector(s); + const root = document.documentElement; + const baseInput = qs('#baseUrl'); + const keyInput = qs('#apiKey'); + const rangeSel = qs('#range'); + const autoChk = qs('#auto'); + const statusEl = qs('#status'); + const banner = qs('#banner'); + const dbg = qs('#dbg'); + const lastTS = qs('#lastTS'); + const qinfo = qs('#qinfo'); + const rinfo = qs('#rinfo'); + const minVInput = qs('#minV'); + const maxVInput = qs('#maxV'); + const maxKwInput = qs('#maxKw'); + const maxDkwhInput = qs('#maxDkwh'); + const themeToggle = qs('#themeToggle'); + + // Theme + const savedTheme = localStorage.getItem('sdm_theme') || 'dark'; + root.setAttribute('data-theme', savedTheme); + themeToggle.textContent = savedTheme === 'dark' ? '๐ŸŒ™' : 'โ˜€๏ธ'; + themeToggle.addEventListener('click', ()=>{ + const cur = root.getAttribute('data-theme') === 'dark' ? 'light':'dark'; + root.setAttribute('data-theme', cur); + localStorage.setItem('sdm_theme', cur); + themeToggle.textContent = cur === 'dark' ? '๐ŸŒ™' : 'โ˜€๏ธ'; + if(window._lastData){ setCharts(window._lastData.vP, window._lastData.pP, window._lastData.dP); } + }); + + baseInput.value = localStorage.getItem('sdm_base') || `${location.origin}`; + keyInput.value = localStorage.getItem('sdm_key') || ''; + autoChk.checked = (localStorage.getItem('sdm_auto') ?? '1') === '1'; + rangeSel.value = localStorage.getItem('sdm_range') || '24h'; + minVInput.value = localStorage.getItem('sdm_minv') || '180'; + maxVInput.value = localStorage.getItem('sdm_maxv') || '260'; + maxKwInput.value = localStorage.getItem('sdm_maxkw') || '3.0'; + maxDkwhInput.value = localStorage.getItem('sdm_maxdkwh') || ''; + + function savePrefs(){ + localStorage.setItem('sdm_base', baseInput.value); + localStorage.setItem('sdm_key', keyInput.value); + localStorage.setItem('sdm_auto', autoChk.checked ? '1':'0'); + localStorage.setItem('sdm_range', rangeSel.value); + localStorage.setItem('sdm_minv', minVInput.value || ''); + localStorage.setItem('sdm_maxv', maxVInput.value || ''); + localStorage.setItem('sdm_maxkw', maxKwInput.value || ''); + localStorage.setItem('sdm_maxdkwh', maxDkwhInput.value || ''); + } + + function tsRange(range){ + const end = new Date(); + const start = new Date(end); + if(range==='1h') start.setHours(end.getHours()-1); + else if(range==='6h') start.setHours(end.getHours()-6); + else if(range==='24h') start.setDate(end.getDate()-1); + else if(range==='7d') start.setDate(end.getDate()-7); + return {start:start.toISOString(), end:end.toISOString()}; + } + + async function apiGet(path){ + const headers = keyInput.value ? {'X-API-Key': keyInput.value} : {}; + const res = await fetch(`${baseInput.value}${path}`, {headers}); + if(!res.ok){ + const text = await res.text(); + throw new Error(text || res.statusText); + } + return res.json(); + } + + // ECharts instances + let ecV = echarts.init(document.getElementById('chartV')); + let ecP = echarts.init(document.getElementById('chartP')); + let ecE = echarts.init(document.getElementById('chartE')); + window.addEventListener('resize', ()=>{ ecV.resize(); ecP.resize(); ecE.resize(); }); + + function axisStyle(){ + const cs = getComputedStyle(document.documentElement); + return { + axisLine:{lineStyle:{color: cs.getPropertyValue('--axis').trim()}}, + axisLabel:{color: cs.getPropertyValue('--muted').trim()}, + splitLine:{show:true,lineStyle:{color: cs.getPropertyValue('--split').trim()}}, + nameTextStyle:{color: cs.getPropertyValue('--muted').trim()} + }; + } + + function optionTemplate(yMin, yMax, yName){ + const cs = getComputedStyle(document.documentElement); + const muted = cs.getPropertyValue('--muted').trim(); + return { + backgroundColor: 'transparent', + textStyle:{color: cs.getPropertyValue('--text').trim()}, + animation: false, + grid: { left: 45, right: 10, top: 10, bottom: 35 }, + tooltip: { + backgroundColor: cs.getPropertyValue('--card').trim(), + borderColor: cs.getPropertyValue('--border').trim(), + textStyle:{color: cs.getPropertyValue('--text').trim()}, + trigger: 'axis', + axisPointer: { type: 'cross', label:{backgroundColor: cs.getPropertyValue('--btn').trim()} }, + formatter: (params) => { + if(!params || !params.length) return ''; + const x = params[0].axisValue; + const d = new Date(x); + const loc = d.toLocaleString(); + const utc = d.toISOString().replace('.000',''); + let html = `
${loc}
UTC: ${utc}
`; + for(const p of params){ + const val = Array.isArray(p.data)? p.data[1] : (p.data?.value ?? p.data); + html += `
${p.seriesName}: ${Number(val).toFixed(3)}
`; + } + return html + '
'; + } + }, + xAxis: Object.assign({ type: 'time' }, axisStyle()), + yAxis: Object.assign({ type: 'value', min: yMin, max: yMax, name: yName }, axisStyle() ), + dataZoom: [{type:'inside'}, {type:'slider', handleStyle:{color: cs.getPropertyValue('--accent').trim()}}], + series: [] + }; + } + + function setCharts(volts, pkw, dkwh){ + window._lastData = {vP: volts, pP: pkw, dP: dkwh}; + + ecV.dispose(); ecP.dispose(); ecE.dispose(); + ecV = echarts.init(document.getElementById('chartV')); + ecP = echarts.init(document.getElementById('chartP')); + ecE = echarts.init(document.getElementById('chartE')); + + const colV = '#60a5fa'; + const colP = '#34d399'; + const colE = '#f59e0b'; + + const optV = optionTemplate(Number(minVInput.value)||180, Number(maxVInput.value)||260, 'V'); + const optP = optionTemplate(0, Number(maxKwInput.value)||3, 'kW'); + const optE = optionTemplate(0, (Number(maxDkwhInput.value) || null), 'ฮ”kWh'); + + optV.series = [{ name:'Volt', type:'line', showSymbol:false, lineStyle:{width:2,color:colV}, data: volts }]; + optP.series = [{ name:'kW', type:'line', showSymbol:false, lineStyle:{width:2,color:colP}, data: pkw }]; + + if(!optE.yAxis.max){ + const max = dkwh.reduce((m,pt)=> Math.max(m, pt[1]||0), 0); + optE.yAxis.max = max>0 ? max*1.1 : 0.1; + } + optE.series = [{ name:'ฮ”kWh', type:'line', step:'middle', showSymbol:false, lineStyle:{width:2,color:colE}, data: dkwh }]; + + ecV.setOption(optV, {notMerge:true, lazyUpdate:false}); + ecP.setOption(optP, {notMerge:true, lazyUpdate:false}); + ecE.setOption(optE, {notMerge:true, lazyUpdate:false}); + } + + function toPairs(arr){ + return arr.filter(r => r.ts && r.value!=null && isFinite(+r.value)).map(r => [r.ts, +r.value]); + } + + function setLatest(l){ + const v = +l.voltage, p = +l.power_kw, e = +l.energy_kwh; + qs('#v').textContent = isFinite(v) ? v.toFixed(2) : 'โ€”'; + qs('#p').textContent = isFinite(p) ? p.toFixed(2) : 'โ€”'; + qs('#e').textContent = isFinite(e) ? e.toFixed(2) : 'โ€”'; + if(l.ts){ + const d = new Date(l.ts); + const loc = d.toLocaleString(); + qs('#tsV').textContent = 'Agg.: ' + loc + ` (UTC: ${l.ts})`; + qs('#tsP').textContent = 'Agg.: ' + loc + ` (UTC: ${l.ts})`; + qs('#tsE').textContent = 'Agg.: ' + loc + ` (UTC: ${l.ts})`; + lastTS.textContent = `Ultimo dato โ€” Locale: ${loc} | UTC: ${l.ts}`; + } + } + + function setHistory(raw){ + let firstE; + const volts=[], pkw=[], dkwh=[]; + for(const r of raw){ + const ts = r.ts; + if(r.voltage!=null) volts.push({ts, value:+r.voltage}); + if(r.power_kw!=null) pkw.push({ts, value:+r.power_kw}); + if(r.energy_kwh!=null){ + const ek = +r.energy_kwh; + if(firstE==null) firstE = ek; + dkwh.push({ts, value:+(ek-firstE).toFixed(3)}); + } + } + const vP = toPairs(volts), pP = toPairs(pkw), dP = toPairs(dkwh); + setCharts(vP, pP, dP); + dbg.textContent = `Punti: V=${vP.length} P=${pP.length} ฮ”kWh=${dP.length}`; + + if(vP.length || pP.length || dP.length){ + const allTs = [...vP, ...pP, ...dP].map(p=>p[0]).sort(); + const first = new Date(allTs[0]).toLocaleString(); + const last = new Date(allTs[allTs.length-1]).toLocaleString(); + rinfo.textContent = `Intervallo dati ricevuti โ€” ${first} โ†’ ${last}`; + } else { + rinfo.textContent = 'Intervallo dati ricevuti โ€” nessun punto'; + } + } + + async function fetchHistoryChunked(startISO, endISO){ + const MAX_LIMIT = 10000; + const start = new Date(startISO).getTime(); + const end = new Date(endISO).getTime(); + const totalMs = Math.max(0, end - start); + const CHUNKS = Math.min(8, Math.max(1, Math.ceil(totalMs / (24*3600*1000)))); + const promises = []; + for(let i=0;i (a.ts < b.ts ? -1 : a.ts > b.ts ? 1 : 0)); + } + + async function refresh(){ + savePrefs(); banner.style.display = 'none'; + statusEl.textContent = 'Carico...'; + try{ + const range = tsRange(rangeSel.value); + qinfo.textContent = `Intervallo richiesto โ€” ${new Date(range.start).toLocaleString()} โ†’ ${new Date(range.end).toLocaleString()} (UTC: ${range.start} โ†’ ${range.end})`; + + const [latest, hist] = await Promise.all([ + apiGet('/api/v1/metrics/latest'), + fetchHistoryChunked(range.start, range.end), + ]); + setLatest(latest); + setHistory(hist); + statusEl.textContent = 'OK'; + }catch(e){ + statusEl.textContent = 'Errore'; + banner.textContent = String(e.message||e); + banner.style.display = 'block'; + console.error(e); + } + } + + document.getElementById('refresh').addEventListener('click', refresh); + document.getElementById('resetZoom').addEventListener('click', ()=>{ + ecV.dispatchAction({type:'dataZoom', start:0, end:100}); + ecP.dispatchAction({type:'dataZoom', start:0, end:100}); + ecE.dispatchAction({type:'dataZoom', start:0, end:100}); + }); + baseInput.addEventListener('change', savePrefs); + keyInput.addEventListener('change', ()=>{ savePrefs(); banner.style.display='none'; }); + rangeSel.addEventListener('change', ()=>{ savePrefs(); refresh(); }); + autoChk.addEventListener('change', ()=>{ savePrefs(); if(autoChk.checked){ tick(); }}); + + let timer = null; + async function tick(){ + clearInterval(timer); + await refresh(); + if(autoChk.checked){ + timer = setInterval(refresh, 5000); + } + } + tick(); +})(); \ No newline at end of file diff --git a/web/index.html b/web/index.html new file mode 100644 index 0000000..72ae5f6 --- /dev/null +++ b/web/index.html @@ -0,0 +1,96 @@ + + + + + + WallBox by Alberto Tilaro + + + + + +
+
+
+ +

WallBox by Alberto Tilaro

+
+
+ + + + + + + + + + +
+ +
+
+ +
+ +
+
+
Tensione
+
โ€” V
+
Agg.: โ€”
+
+
+
Potenza
+
โ€” kW
+
Agg.: โ€”
+
+
+
Energia
+
โ€” kWh
+
Agg.: โ€”
+
+
+ +
+
+

Tensione (ora locale)

+ X in ora locale (Europe/Rome), dati in UTC. +
+
+
+ +
+
+

Potenza (ora locale)

+ X in ora locale (Europe/Rome), dati in UTC. +
+
+
+ +
+
+

Energia ฮ” dal primo punto (ora locale)

+ X in ora locale (Europe/Rome), dati in UTC. +
+
+
+ +
+ Pronto + + + + +
+
+ + + + diff --git a/web/styles.css b/web/styles.css new file mode 100644 index 0000000..56b2d52 --- /dev/null +++ b/web/styles.css @@ -0,0 +1,54 @@ + +*{box-sizing:border-box} +:root{ /* light */ + --bg:#f5f7fb; + --panel:#ffffff; + --card:#ffffff; + --muted:#475569; + --text:#0f172a; + --accent:#ca8a04; + --border:#e5e7eb; + --btn:#0f172a; + --btn-hover:#1f2937; + --axis:#94a3b8; + --split:#e5e7eb; +} +:root[data-theme="dark"]{ + --bg:#0b1220; + --panel:#0f172a; + --card:#111827; + --muted:#94a3b8; + --text:#e5e7eb; + --accent:#facc15; + --border:#1f2937; + --btn:#1f2937; + --btn-hover:#374151; + --axis:#334155; + --split:#1f2937; +} +html,body{height:100%} +body{margin:0;font-family:ui-sans-serif,system-ui,-apple-system,Segoe UI,Roboto,Helvetica,Arial,sans-serif;background:var(--bg);color:var(--text)} +.container{max-width:1150px;margin:0 auto;padding:18px} +header{display:flex;flex-direction:column;gap:12px;margin-bottom:14px} +.brand{display:flex;align-items:center;gap:10px} +h1{margin:0;font-size:24px;letter-spacing:.3px} +.logo{width:28px;height:28px;border-radius:6px} +.controls{display:flex;flex-wrap:wrap;gap:10px;background:var(--panel);padding:10px;border-radius:12px;border:1px solid var(--border)} +label{font-size:12px;color:var(--muted);display:flex;align-items:center;gap:8px} +input,select,button{padding:8px 10px;border:1px solid var(--border);border-radius:10px;font-size:14px;background:var(--card);color:var(--text)} +button{background:var(--btn);cursor:pointer;color:#fff} +button:hover{background:var(--btn-hover)} +.banner{background:#3f1d1d;color:#fecaca;border:1px solid #7f1d1d;padding:10px 12px;border-radius:10px} +.cards{display:grid;grid-template-columns:repeat(3,1fr);gap:12px;margin:12px 0} +.card{background:var(--panel);border:1px solid var(--border);border-radius:14px;padding:14px;box-shadow:0 1px 2px rgba(0,0,0,.1)} +.card-title{font-size:12px;color:var(--muted)} +.card-value{font-size:30px;font-weight:700;margin-top:6px;color:var(--text)} +.card-value small{font-weight:400;color:var(--muted)} +.card-ts{font-size:11px;color:var(--muted);margin-top:6px} +.chart-block{background:var(--panel);border:1px solid var(--border);border-radius:14px;padding:14px;margin-top:12px} +.chart-header{display:flex;justify-content:space-between;align-items:center;gap:8px;margin-bottom:6px} +.tz-note{font-size:12px;color:var(--muted)} +.chart-fixed{height:280px;width:100%} +footer{margin-top:12px;font-size:12px;color:var(--muted);display:flex;gap:16px;align-items:center;flex-wrap:wrap} +.switch{display:flex;align-items:center;gap:6px} +.theme button{border-color:var(--accent)}