"use strict"; const state = { from: null, to: null, agg: "hour", device: "", showTemp: true, showHum: true, showOut: true, meta: null, }; let chart = null; let currentData = { series: {} }; const $ = (sel) => document.querySelector(sel); function cssVar(name) { return getComputedStyle(document.documentElement).getPropertyValue(name).trim(); } function pad(n) { return String(n).padStart(2, "0"); } function toLocalInput(date) { return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}T${pad(date.getHours())}:${pad(date.getMinutes())}`; } function setStatus(ok) { const el = $("#status"); el.classList.toggle("ok", ok === true); el.classList.toggle("err", ok === false); } function applyPreset(days) { const now = new Date(); let from; if (days === "all") { const min = state.meta && state.meta.min ? new Date(state.meta.min.replace(" ", "T")) : null; from = min && !isNaN(min) ? min : new Date(now.getTime() - 7 * 864e5); } else { from = new Date(now.getTime() - Number(days) * 864e5); } state.from = toLocalInput(from); state.to = toLocalInput(now); $("#from").value = state.from; $("#to").value = state.to; load(); } function buildOption(data) { const text = cssVar("--text"); const muted = cssVar("--muted"); const border = cssVar("--border"); const tempColor = cssVar("--temp"); const humColor = cssVar("--hum"); const outColor = cssVar("--out"); const series = []; const palette = ["#1f6feb", "#e8590c", "#2fb344", "#9c36b5", "#f08c00", "#0ca678"]; const devices = Object.keys(data.series).sort(); let pi = 0; const humAxis = state.showHum; for (const dev of devices) { const s = data.series[dev]; const baseColor = palette[pi % palette.length]; pi += 1; if (state.showTemp) { series.push({ name: `${dev} · °C`, type: "line", yAxisIndex: 0, showSymbol: false, smooth: 0.25, lineStyle: { width: 2.4, color: tempColor }, itemStyle: { color: tempColor }, emphasis: { focus: "series" }, data: s.t.map((t, i) => [t, s.temperature[i]]), }); if (Array.isArray(s.taidetud) && s.taidetud.some(Boolean)) { series.push({ name: `${dev} · täidetud`, type: "scatter", yAxisIndex: 0, symbol: "emptyCircle", symbolSize: 9, itemStyle: { color: tempColor, borderWidth: 2 }, z: 3, data: s.t .map((t, i) => (s.taidetud[i] ? [t, s.temperature[i]] : null)) .filter(Boolean), }); } } if (state.showHum) { series.push({ name: `${dev} · %`, type: "line", yAxisIndex: 1, showSymbol: false, smooth: 0.25, lineStyle: { width: 1.8, type: "dashed", color: humColor }, itemStyle: { color: humColor }, emphasis: { focus: "series" }, data: s.t.map((t, i) => [t, s.humidity[i]]), }); } } const out = data.outside; if (state.showOut && out && Array.isArray(out.t) && out.t.length) { series.push({ name: "Väli · °C", type: "line", yAxisIndex: 0, showSymbol: false, smooth: 0.25, lineStyle: { width: 2, color: outColor }, itemStyle: { color: outColor }, emphasis: { focus: "series" }, data: out.t.map((t, i) => [t, out.temperature[i]]), }); if (Array.isArray(out.taidetud) && out.taidetud.some(Boolean)) { series.push({ name: "Väli · täidetud", type: "scatter", yAxisIndex: 0, symbol: "emptyCircle", symbolSize: 9, itemStyle: { color: outColor, borderWidth: 2 }, z: 3, data: out.t .map((t, i) => (out.taidetud[i] ? [t, out.temperature[i]] : null)) .filter(Boolean), }); } } return { backgroundColor: "transparent", animationDuration: 300, color: palette, grid: { left: 6, right: humAxis ? 6 : 6, top: 40, bottom: 62, containLabel: true }, legend: { top: 4, type: "scroll", textStyle: { color: text, fontSize: 12 }, inactiveColor: muted, }, tooltip: { trigger: "axis", backgroundColor: cssVar("--panel"), borderColor: border, textStyle: { color: text, fontSize: 12 }, axisPointer: { type: "cross", label: { backgroundColor: muted } }, valueFormatter: null, formatter: (params) => { const items = (params || []).filter( (p) => !String(p.seriesName).endsWith("· täidetud") ); if (!items.length) return ""; const d = new Date(items[0].value[0]); const head = `${d.toLocaleDateString("et-EE")} ${pad(d.getHours())}:${pad(d.getMinutes())}`; const lines = items.map((p) => { const v = p.value[1]; const unit = p.seriesName.endsWith("°C") ? " °C" : " %"; return `
${p.marker} ${p.seriesName}${v == null ? "–" : v + unit}
`; }); return `
${head}
${lines.join("")}`; }, }, xAxis: { type: "time", axisLine: { lineStyle: { color: border } }, axisLabel: { color: muted, hideOverlap: true }, splitLine: { show: false }, }, yAxis: [ { type: "value", name: "°C", scale: true, axisLine: { show: false }, axisLabel: { color: muted }, splitLine: { lineStyle: { color: border, type: "dashed" } }, }, ...(humAxis ? [ { type: "value", name: "%", scale: true, position: "right", axisLine: { show: false }, axisLabel: { color: muted }, splitLine: { show: false }, }, ] : []), ], dataZoom: [ { type: "inside", throttle: 50 }, { type: "slider", height: 22, bottom: 14, borderColor: border, textStyle: { color: muted }, fillColor: cssVar("--accent-soft") }, ], series, }; } function render(data) { const chartEl = $("#chart"); const hasData = Object.keys(data.series).length > 0 && Object.values(data.series).some((s) => s.t.length); $("#hint").hidden = hasData; if (!hasData) { $("#hint").textContent = "Valitud vahemikus andmeid ei ole. Andur salvestab andmeid alates 2026-09-17."; } if (!chart) chart = echarts.init(chartEl, null, { renderer: "canvas" }); chart.setOption(buildOption(data), true); chart.resize(); } async function load() { const params = new URLSearchParams({ from: state.from, to: state.to, agg: state.agg, }); if (state.device) params.set("device", state.device); setStatus(null); try { const [tempRes, outRes] = await Promise.all([ fetch(`/api/temperatuur?${params}`), fetch(`/api/valisilm?${params}`), ]); if (!tempRes.ok) throw new Error(await tempRes.text()); const data = await tempRes.json(); if (outRes.ok) { try { data.outside = (await outRes.json()).series; } catch { data.outside = null; } } currentData = data; currentSeries = data.series; render(data); setStatus(true); const f = new Date(state.from.replace(" ", "T")); const t = new Date(state.to.replace(" ", "T")); $("#range-label").textContent = `${f.toLocaleString("et-EE")} → ${t.toLocaleString("et-EE")}`; } catch (err) { console.error(err); setStatus(false); $("#hint").hidden = false; $("#hint").textContent = "Andmete laadimine ebaõnnestus."; } } async function loadMeta() { try { const res = await fetch("/api/meta"); if (!res.ok) throw new Error(); state.meta = await res.json(); const devs = state.meta.devices.length ? state.meta.devices.join(", ") : "—"; $("#subtitle").textContent = `Zigbee andurid · ${devs}`; if (state.meta.min) { $("#range-label").textContent = `Andmed alates ${state.meta.min}`; } } catch { $("#subtitle").textContent = "Zigbee andurid"; } } async function loadLatest() { try { const res = await fetch("/api/latest"); if (!res.ok) return; const data = await res.json(); renderCards(data); } catch { /* vaikne */ } } function renderCards(data) { const cards = []; for (const r of data.readings) { cards.push(`
🌡️ ${r.device} · temperatuur
${r.temperature ?? "–"} °C
`); cards.push(`
💧 ${r.device} · niiskus
${r.humidity ?? "–"} %
`); } if (data.outside && data.outside.temperature != null) { cards.push(`
🌤️ Väli · temperatuur
${data.outside.temperature} °C
`); } if (data.open_faults.length) { const items = data.open_faults .map((f) => `
⚠️ ${f.device} · ${f.tyyp}${f.detail ? " · " + f.detail : ""}
`) .join(""); cards.push(`
Lahtised häired (${data.open_faults.length})
${items}
`); } $("#cards").innerHTML = cards.join(""); } function setTheme(theme) { document.documentElement.setAttribute("data-theme", theme); localStorage.setItem("nutikodu-theme", theme); $("#theme-toggle").textContent = theme === "dark" ? "☀️" : "🌙"; const meta = $("#meta-theme"); if (meta) meta.setAttribute("content", theme === "dark" ? "#0e1116" : "#1f6feb"); if (chart) chart.setOption(buildOption(currentData), true); } let currentSeries = {}; function init() { const saved = localStorage.getItem("nutikodu-theme"); const prefersDark = window.matchMedia && window.matchMedia("(prefers-color-scheme: dark)").matches; setTheme(saved || (prefersDark ? "dark" : "light")); $("#theme-toggle").addEventListener("click", () => { setTheme(document.documentElement.getAttribute("data-theme") === "dark" ? "light" : "dark"); }); document.querySelectorAll("#presets button").forEach((btn) => { btn.addEventListener("click", () => { document.querySelectorAll("#presets button").forEach((b) => b.classList.remove("active")); btn.classList.add("active"); applyPreset(btn.dataset.days); }); }); document.querySelectorAll("#agg button").forEach((btn) => { btn.addEventListener("click", () => { document.querySelectorAll("#agg button").forEach((b) => b.classList.remove("active")); btn.classList.add("active"); state.agg = btn.dataset.agg; load(); }); }); $("#show-temp").addEventListener("change", (e) => { state.showTemp = e.target.checked; load(); }); $("#show-hum").addEventListener("change", (e) => { state.showHum = e.target.checked; load(); }); $("#show-out").addEventListener("change", (e) => { state.showOut = e.target.checked; load(); }); $("#apply").addEventListener("click", () => { state.from = $("#from").value; state.to = $("#to").value; document.querySelectorAll("#presets button").forEach((b) => b.classList.remove("active")); load(); }); window.addEventListener("resize", () => chart && chart.resize()); window.addEventListener("orientationchange", () => setTimeout(() => chart && chart.resize(), 250)); window.addEventListener("load", () => chart && chart.resize()); loadMeta().then(() => applyPreset(7)); loadLatest(); setInterval(loadLatest, 60000); } document.addEventListener("DOMContentLoaded", init);