let chart = null; window.onload = init; async function init() { let start = new Date(); start.setDate(start.getDate() - 7); const end = new Date(); document.getElementById("date-start").valueAsDate = start; document.getElementById("date-end").valueAsDate = end; document.getElementById("btn-refresh").addEventListener("click", loadData); await loadDevices(); await loadData(); } async function loadData() { const start = document.getElementById("date-start").value; const end = document.getElementById("date-end").value; const granularity = document.getElementById("granularity").value; const device_eui = document.getElementById("device").value; const points = await fetchConsumption({ device_eui: device_eui, start: start, end: end, granularity: granularity, }); if (chart) { chart.destroy(); } chart = renderChart(points, granularity); updateKPIs(points); } function updateKPIs(points) { const totalDisplay = document.getElementById("kpi-total"); const avgDisplay = document.getElementById("kpi-avg"); const countDisplay = document.getElementById("kpi-count"); if (!points || points.length === 0) { total.textContent = "-"; avg.textContent = "-"; count.textContent = "-"; return; } const totalValue = points.reduce((acc, p) => acc + p.delta_m3, 0); const avgValue = totalValue / points.length; totalDisplay.textContent = totalValue.toFixed(3); avgDisplay.textContent = avgValue.toFixed(3); countDisplay.textContent = points.length; } async function loadDevices() { const selectDeviceElmt = document.getElementById("device"); const devices = await fetchDevices(); devices.forEach((device) => { selectDeviceElmt.add(new Option(device.device_eui)) }); selectDeviceElmt.value = devices[0]?.device_eui ?? ""; }