Primo commit: Modbus logger con API e frontend
This commit is contained in:
commit
48a6aee18f
10 files changed
+782
No files matched your search
+263
@@ -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 = `<div><b>${loc}</b><div style='color:${muted}'>UTC: ${utc}</div>`;
|
||||
for(const p of params){
|
||||
const val = Array.isArray(p.data)? p.data[1] : (p.data?.value ?? p.data);
|
||||
html += `<div><span style="display:inline-block;width:9px;height:9px;background:${p.color};margin-right:6px;border-radius:2px"></span>${p.seriesName}: ${Number(val).toFixed(3)}</div>`;
|
||||
}
|
||||
return html + '</div>';
|
||||
}
|
||||
},
|
||||
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<CHUNKS;i++){
|
||||
const s = new Date(start + totalMs * (i/CHUNKS)).toISOString();
|
||||
const e = new Date(start + totalMs * ((i+1)/CHUNKS)).toISOString();
|
||||
promises.push(apiGet(`/api/v1/metrics/history?start=${encodeURIComponent(s)}&end=${encodeURIComponent(e)}&limit=${MAX_LIMIT}`));
|
||||
}
|
||||
const results = await Promise.all(promises);
|
||||
const map = new Map();
|
||||
for(const arr of results){
|
||||
for(const r of arr){
|
||||
if(!map.has(r.ts)) map.set(r.ts, r);
|
||||
}
|
||||
}
|
||||
return Array.from(map.values()).sort((a,b)=> (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();
|
||||
})();
|
||||
@@ -0,0 +1,96 @@
|
||||
<!doctype html>
|
||||
<html lang="it" data-theme="dark">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width,initial-scale=1.0">
|
||||
<title>WallBox by Alberto Tilaro</title>
|
||||
<link rel="icon" href="data:image/svg+xml,<svg xmlns=%22http://www.w3.org/2000/svg%22 viewBox=%220 0 64 64%22><rect width=%2264%22 height=%2264%22 rx=%2212%22 fill=%22%230b1220%22/><path d=%22M38 6L14 36h14l-2 22 24-30H36l2-22z%22 fill=%22%23facc15%22 stroke=%22%23fde68a%22 stroke-width=%222%22/></svg>">
|
||||
<link rel="stylesheet" href="styles.css">
|
||||
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/echarts.min.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
<div class="container">
|
||||
<header>
|
||||
<div class="brand">
|
||||
<img class="logo" src="data:image/svg+xml,<svg xmlns=%22http://www.w3.org/2000/svg%22 viewBox=%220 0 64 64%22><rect width=%2264%22 height=%2264%22 rx=%2212%22 fill=%22%230b1220%22/><path d=%22M38 6L14 36h14l-2 22 24-30H36l2-22z%22 fill=%22%23facc15%22 stroke=%22%23fde68a%22 stroke-width=%222%22/></svg>" alt="⚡" />
|
||||
<h1>WallBox by Alberto Tilaro</h1>
|
||||
</div>
|
||||
<div class="controls">
|
||||
<label>Base URL <input id="baseUrl" placeholder="http://wallbox:8000"></label>
|
||||
<label>API Key <input id="apiKey" placeholder="X-API-Key"></label>
|
||||
<label>Intervallo
|
||||
<select id="range">
|
||||
<option value="1h">Ultima 1h</option>
|
||||
<option value="6h">Ultime 6h</option>
|
||||
<option value="24h" selected>Ultime 24h</option>
|
||||
<option value="7d">Ultimi 7 giorni</option>
|
||||
</select>
|
||||
</label>
|
||||
<label>Min V <input id="minV" type="number" step="1" min="0" value="180"></label>
|
||||
<label>Max V <input id="maxV" type="number" step="1" min="0" value="260"></label>
|
||||
<label>Max kW <input id="maxKw" type="number" step="0.1" min="0" value="3.0"></label>
|
||||
<label>Max ΔkWh <input id="maxDkwh" type="number" step="0.01" min="0" placeholder="auto"></label>
|
||||
<button id="refresh">Aggiorna</button>
|
||||
<button id="resetZoom">Reset zoom</button>
|
||||
<label class="switch">Auto <input id="auto" type="checkbox" checked></label>
|
||||
<div class="theme">
|
||||
<button id="themeToggle" title="Dark/Light">🌙/☀️</button>
|
||||
</div>
|
||||
</div>
|
||||
<div id="banner" class="banner" style="display:none"></div>
|
||||
</header>
|
||||
|
||||
<section class="cards">
|
||||
<div class="card">
|
||||
<div class="card-title">Tensione</div>
|
||||
<div class="card-value"><span id="v">—</span> <small>V</small></div>
|
||||
<div class="card-ts" id="tsV">Agg.: —</div>
|
||||
</div>
|
||||
<div class="card">
|
||||
<div class="card-title">Potenza</div>
|
||||
<div class="card-value"><span id="p">—</span> <small>kW</small></div>
|
||||
<div class="card-ts" id="tsP">Agg.: —</div>
|
||||
</div>
|
||||
<div class="card">
|
||||
<div class="card-title">Energia</div>
|
||||
<div class="card-value"><span id="e">—</span> <small>kWh</small></div>
|
||||
<div class="card-ts" id="tsE">Agg.: —</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="chart-block">
|
||||
<div class="chart-header">
|
||||
<h2>Tensione (ora locale)</h2>
|
||||
<span class="tz-note">X in ora locale (Europe/Rome), dati in UTC.</span>
|
||||
</div>
|
||||
<div id="chartV" class="chart-fixed"></div>
|
||||
</section>
|
||||
|
||||
<section class="chart-block">
|
||||
<div class="chart-header">
|
||||
<h2>Potenza (ora locale)</h2>
|
||||
<span class="tz-note">X in ora locale (Europe/Rome), dati in UTC.</span>
|
||||
</div>
|
||||
<div id="chartP" class="chart-fixed"></div>
|
||||
</section>
|
||||
|
||||
<section class="chart-block">
|
||||
<div class="chart-header">
|
||||
<h2>Energia Δ dal primo punto (ora locale)</h2>
|
||||
<span class="tz-note">X in ora locale (Europe/Rome), dati in UTC.</span>
|
||||
</div>
|
||||
<div id="chartE" class="chart-fixed"></div>
|
||||
</section>
|
||||
|
||||
<footer>
|
||||
<span id="status">Pronto</span>
|
||||
<span id="dbg" class="dbg"></span>
|
||||
<span id="lastTS" class="dbg"></span>
|
||||
<span id="qinfo" class="dbg"></span>
|
||||
<span id="rinfo" class="dbg"></span>
|
||||
</footer>
|
||||
</div>
|
||||
|
||||
<script src="app.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -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)}
|
||||
Reference in new issue
Block a user