"use strict";
const state = {
from: null,
to: null,
agg: "hour",
device: "",
showTemp: true,
showHum: true,
meta: null,
};
let chart = null;
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 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 (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]]),
});
}
}
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) => {
if (!params || !params.length) return "";
const d = new Date(params[0].value[0]);
const head = `${d.toLocaleDateString("et-EE")} ${pad(d.getHours())}:${pad(d.getMinutes())}`;
const lines = params.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 res = await fetch(`/api/temperatuur?${params}`);
if (!res.ok) throw new Error(await res.text());
const data = await res.json();
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.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({ series: currentSeries }), 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(); });
$("#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);