373 lines
13 KiB
JavaScript
373 lines
13 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');
|
|
const connectionState = qs('#connectionState');
|
|
|
|
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;
|
|
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 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_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 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);
|
|
}
|
|
return res.json();
|
|
}
|
|
|
|
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(){
|
|
return {
|
|
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 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: cssVar('--text')},
|
|
animation: false,
|
|
grid: {left: 12, right: 18, top: 22, bottom: 56, containLabel: true},
|
|
tooltip: {
|
|
backgroundColor: cssVar('--surface'),
|
|
borderColor: cssVar('--border'),
|
|
textStyle: {color: cssVar('--text')},
|
|
trigger: 'axis',
|
|
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>`;
|
|
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,
|
|
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};
|
|
|
|
const colV = cssVar('--voltage');
|
|
const colP = cssVar('--power');
|
|
const colE = cssVar('--energy');
|
|
|
|
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');
|
|
|
|
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;
|
|
}
|
|
|
|
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]);
|
|
}
|
|
|
|
function setLatest(l){
|
|
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 = `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 = [];
|
|
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){
|
|
const ek = +r.energy_kwh;
|
|
if(firstE == null) firstE = ek;
|
|
dkwh.push({ts, value: +(ek - firstE).toFixed(3)});
|
|
}
|
|
}
|
|
|
|
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} Delta 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 = `Dati ricevuti: ${first} -> ${last}`;
|
|
} else {
|
|
rinfo.textContent = '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...';
|
|
setConnectionState('Carico', 'loading');
|
|
|
|
try{
|
|
const range = tsRange(rangeSel.value);
|
|
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);
|
|
const now = new Date().toLocaleTimeString();
|
|
statusEl.textContent = `Aggiornato alle ${now}`;
|
|
setConnectionState('Online', 'ok');
|
|
}catch(e){
|
|
statusEl.textContent = 'Errore';
|
|
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});
|
|
});
|
|
|
|
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();
|
|
});
|
|
|
|
[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(){
|
|
clearInterval(timer);
|
|
await refresh();
|
|
if(autoChk.checked){
|
|
timer = setInterval(refresh, 5000);
|
|
}
|
|
}
|
|
|
|
tick();
|
|
})();
|