| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377 |
- "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();
- }
- // Kärbi kõik seeriad ühisesse ajavahemikku, et jooned algaksid ja lõpeksid koos.
- function clipToCommonRange(series) {
- const active = series.filter((s) => Array.isArray(s.data) && s.data.length);
- if (active.length < 2) return series;
- const start = Math.max(...active.map((s) => s.data[0][0]));
- const end = Math.min(...active.map((s) => s.data[s.data.length - 1][0]));
- if (!(start < end)) return series;
- return series.map((s) => {
- if (!Array.isArray(s.data)) return s;
- return { ...s, data: s.data.filter((d) => d && d[0] >= start && d[0] <= end) };
- });
- }
- 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 `<div style="display:flex;justify-content:space-between;gap:14px">
- <span>${p.marker} ${p.seriesName}</span><b>${v == null ? "–" : v + unit}</b></div>`;
- });
- return `<div style="font-weight:600;margin-bottom:4px">${head}</div>${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: clipToCommonRange(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(`<div class="card temp"><div class="k">🌡️ ${r.device} · temperatuur</div>
- <div class="v">${r.temperature ?? "–"}<small> °C</small></div></div>`);
- cards.push(`<div class="card hum"><div class="k">💧 ${r.device} · niiskus</div>
- <div class="v">${r.humidity ?? "–"}<small> %</small></div></div>`);
- }
- if (data.outside && data.outside.temperature != null) {
- cards.push(`<div class="card out"><div class="k">🌤️ Väli · temperatuur</div>
- <div class="v">${data.outside.temperature}<small> °C</small></div></div>`);
- }
- if (data.open_faults.length) {
- const items = data.open_faults
- .map((f) => `<div>⚠️ <b>${f.device}</b> · ${f.tyyp}${f.detail ? " · " + f.detail : ""}</div>`)
- .join("");
- cards.push(`<div class="card wide"><div class="k">Lahtised häired (${data.open_faults.length})</div>
- <div style="font-size:13px;margin-top:6px;line-height:1.7">${items}</div></div>`);
- }
- $("#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);
|