rifacimento grafic

This commit is contained in:
alberto committed 2026-04-11 20:00:45 +02:00
1 parent 48a6aee18f
commit b52e14b965
3 files changed
+777 -217

No files matched your search

+209 -100
View File
@@ -1,5 +1,5 @@
(function(){
const qs = (s)=>document.querySelector(s);
const qs = (s) => document.querySelector(s);
const root = document.documentElement;
const baseInput = qs('#baseUrl');
const keyInput = qs('#apiKey');
@@ -16,20 +16,29 @@
const maxKwInput = qs('#maxKw');
const maxDkwhInput = qs('#maxDkwh');
const themeToggle = qs('#themeToggle');
const connectionState = qs('#connectionState');
// 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); }
function cssVar(name){
return getComputedStyle(root).getPropertyValue(name).trim();
}
function setTheme(theme){
root.setAttribute('data-theme', theme);
localStorage.setItem('sdm_theme', theme);
themeToggle.textContent = theme === 'dark' ? 'Tema chiaro' : 'Tema scuro';
themeToggle.setAttribute('aria-label', theme === 'dark' ? 'Passa al tema chiaro' : 'Passa al tema scuro');
}
setTheme(localStorage.getItem('sdm_theme') || 'dark');
themeToggle.addEventListener('click', () => {
const next = root.getAttribute('data-theme') === 'dark' ? 'light' : 'dark';
setTheme(next);
if(window._lastData){
setCharts(window._lastData.vP, window._lastData.pP, window._lastData.dP);
}
});
baseInput.value = localStorage.getItem('sdm_base') || `${location.origin}`;
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';
@@ -38,10 +47,15 @@
maxKwInput.value = localStorage.getItem('sdm_maxkw') || '3.0';
maxDkwhInput.value = localStorage.getItem('sdm_maxdkwh') || '';
function setConnectionState(text, state){
connectionState.textContent = text;
connectionState.className = `state-pill${state ? ` is-${state}` : ''}`;
}
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_auto', autoChk.checked ? '1' : '0');
localStorage.setItem('sdm_range', rangeSel.value);
localStorage.setItem('sdm_minv', minVInput.value || '');
localStorage.setItem('sdm_maxv', maxVInput.value || '');
@@ -52,16 +66,17 @@
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()};
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});
const baseUrl = (baseInput.value || location.origin).replace(/\/+$/, '');
const res = await fetch(`${baseUrl}${path}`, {headers});
if(!res.ok){
const text = await res.text();
throw new Error(text || res.statusText);
@@ -69,130 +84,196 @@
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(); });
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()}
axisLine: {lineStyle: {color: cssVar('--axis')}},
axisTick: {lineStyle: {color: cssVar('--axis')}},
axisLabel: {color: cssVar('--muted'), hideOverlap: true},
splitLine: {show: true, lineStyle: {color: cssVar('--split')}},
nameTextStyle: {color: cssVar('--muted'), fontWeight: 700}
};
}
function optionTemplate(yMin, yMax, yName){
const cs = getComputedStyle(document.documentElement);
const muted = cs.getPropertyValue('--muted').trim();
const muted = cssVar('--muted');
const yAxis = Object.assign({type: 'value', min: yMin, name: yName}, axisStyle());
if(Number.isFinite(yMax)) yAxis.max = yMax;
return {
backgroundColor: 'transparent',
textStyle:{color: cs.getPropertyValue('--text').trim()},
textStyle: {color: cssVar('--text')},
animation: false,
grid: { left: 45, right: 10, top: 10, bottom: 35 },
grid: {left: 12, right: 18, top: 22, bottom: 56, containLabel: true},
tooltip: {
backgroundColor: cs.getPropertyValue('--card').trim(),
borderColor: cs.getPropertyValue('--border').trim(),
textStyle:{color: cs.getPropertyValue('--text').trim()},
backgroundColor: cssVar('--surface'),
borderColor: cssVar('--border'),
textStyle: {color: cssVar('--text')},
trigger: 'axis',
axisPointer: { type: 'cross', label:{backgroundColor: cs.getPropertyValue('--btn').trim()} },
axisPointer: {type: 'cross', label: {backgroundColor: cssVar('--primary')}},
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>`;
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);
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>';
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()}}],
xAxis: Object.assign({type: 'time'}, axisStyle()),
yAxis,
dataZoom: [
{type: 'inside'},
{
type: 'slider',
height: 22,
bottom: 10,
borderColor: cssVar('--border'),
fillerColor: 'rgba(38, 184, 149, 0.16)',
dataBackground: {
lineStyle: {color: cssVar('--muted')},
areaStyle: {color: cssVar('--surface-2')}
},
selectedDataBackground: {
lineStyle: {color: cssVar('--primary')},
areaStyle: {color: 'rgba(38, 184, 149, 0.18)'}
},
handleStyle: {color: cssVar('--primary')}
}
],
series: []
};
}
function lineSeries(name, color, data, extra){
return Object.assign({
name,
type: 'line',
showSymbol: false,
sampling: 'lttb',
lineStyle: {width: 2.5, color},
itemStyle: {color},
areaStyle: {color, opacity: 0.12},
emphasis: {focus: 'series'},
data
}, extra || {});
}
function applyNoDataState(option, data){
if(data.length) return;
option.graphic = [{
type: 'text',
left: 'center',
top: 'middle',
style: {
text: 'Nessun dato per questo intervallo',
fill: cssVar('--muted'),
fontSize: 14,
fontWeight: 700
}
}];
}
function numberOrDefault(value, fallback){
const n = Number(value);
return Number.isFinite(n) ? n : fallback;
}
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 = cssVar('--voltage');
const colP = cssVar('--power');
const colE = cssVar('--energy');
const colV = '#60a5fa';
const colP = '#34d399';
const colE = '#f59e0b';
const optV = optionTemplate(numberOrDefault(minVInput.value, 180), numberOrDefault(maxVInput.value, 260), 'V');
const optP = optionTemplate(0, numberOrDefault(maxKwInput.value, 3), 'kW');
const maxDkwh = Number(maxDkwhInput.value);
const optE = optionTemplate(0, Number.isFinite(maxDkwh) && maxDkwh > 0 ? maxDkwh : undefined, 'kWh');
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;
if(!Number.isFinite(optE.yAxis.max)){
const max = dkwh.reduce((m, pt) => Math.max(m, pt[1] || 0), 0);
optE.yAxis.max = max > 0 ? Number((max * 1.1).toFixed(3)) : 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});
optV.series = [lineSeries('Volt', colV, volts)];
optP.series = [lineSeries('kW', colP, pkw)];
optE.series = [lineSeries('Delta kWh', colE, dkwh, {step: 'middle'})];
applyNoDataState(optV, volts);
applyNoDataState(optP, pkw);
applyNoDataState(optE, 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]);
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) : '—';
const v = +l.voltage;
const p = +l.power_kw;
const 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}`;
qs('#tsV').textContent = `Aggiornamento: ${loc} | UTC: ${l.ts}`;
qs('#tsP').textContent = `Aggiornamento: ${loc} | UTC: ${l.ts}`;
qs('#tsE').textContent = `Aggiornamento: ${loc} | UTC: ${l.ts}`;
lastTS.textContent = `Ultimo dato: ${loc} | UTC: ${l.ts}`;
}
}
function setHistory(raw){
let firstE;
const volts=[], pkw=[], dkwh=[];
const volts = [];
const pkw = [];
const 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){
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)});
if(firstE == null) firstE = ek;
dkwh.push({ts, value: +(ek - firstE).toFixed(3)});
}
}
const vP = toPairs(volts), pP = toPairs(pkw), dP = toPairs(dkwh);
const vP = toPairs(volts);
const pP = toPairs(pkw);
const dP = toPairs(dkwh);
setCharts(vP, pP, dP);
dbg.textContent = `Punti: V=${vP.length} P=${pP.length} ΔkWh=${dP.length}`;
dbg.textContent = `Punti: V=${vP.length} P=${pP.length} Delta kWh=${dP.length}`;
if(vP.length || pP.length || dP.length){
const allTs = [...vP, ...pP, ...dP].map(p=>p[0]).sort();
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}`;
const last = new Date(allTs[allTs.length - 1]).toLocaleString();
rinfo.textContent = `Dati ricevuti: ${first} -> ${last}`;
} else {
rinfo.textContent = 'Intervallo dati ricevuti — nessun punto';
rinfo.textContent = 'Dati ricevuti: nessun punto';
}
}
@@ -201,13 +282,14 @@
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 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();
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){
@@ -215,41 +297,67 @@
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));
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';
savePrefs();
banner.style.display = 'none';
statusEl.textContent = 'Carico...';
setConnectionState('Carico', 'loading');
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})`;
qinfo.textContent = `Richiesta: ${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';
const now = new Date().toLocaleTimeString();
statusEl.textContent = `Aggiornato alle ${now}`;
setConnectionState('Online', 'ok');
}catch(e){
statusEl.textContent = 'Errore';
banner.textContent = String(e.message||e);
setConnectionState('Errore API', 'error');
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});
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(); }});
keyInput.addEventListener('change', () => {
savePrefs();
banner.style.display = 'none';
});
rangeSel.addEventListener('change', () => {
savePrefs();
refresh();
});
autoChk.addEventListener('change', () => {
savePrefs();
if(autoChk.checked) tick();
});
[minVInput, maxVInput, maxKwInput, maxDkwhInput].forEach((input) => {
input.addEventListener('change', () => {
savePrefs();
if(window._lastData){
setCharts(window._lastData.vP, window._lastData.pP, window._lastData.dP);
}
});
});
let timer = null;
async function tick(){
@@ -259,5 +367,6 @@
timer = setInterval(refresh, 5000);
}
}
tick();
})();
})();