263 lines
11 KiB
JavaScript
263 lines
11 KiB
JavaScript
(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();
|
|
})(); |