"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 `
${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: 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);
loadProtected();
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();
$("#subtitle").textContent = "Zigbee andurid";
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();
});
const awayBtn = document.getElementById("away-toggle");
if (awayBtn) awayBtn.addEventListener("click", toggleAway);
window.addEventListener("resize", () => chart && chart.resize());
window.addEventListener("orientationchange", () => setTimeout(() => chart && chart.resize(), 250));
window.addEventListener("load", () => chart && chart.resize());
checkAuth().then(() => loadMeta().then(() => applyPreset(7)));
loadLatest();
setInterval(loadLatest, 60000);
setInterval(loadProtected, 60000);
}
// --- Uus67: energia + liikumine ---
let chartEnergy = null;
let chartMotion = null;
function palColors() {
return ["#1f6feb", "#e8590c", "#2fb344", "#9c36b7", "#f08c00", "#0ca678"];
}
async function loadEnergy() {
if (!state.from) return;
const params = new URLSearchParams({ from: state.from, to: state.to, agg: state.agg });
try {
const res = await fetch(`/api/energia?${params}`);
if (!res.ok) return;
renderEnergy(await res.json());
} catch (e) { console.error(e); }
}
function renderEnergy(data) {
const el = document.getElementById("chart-energy");
if (!el) return;
const seriesData = data.series || {};
const hasData = Object.keys(seriesData).length > 0 && Object.values(seriesData).some((s) => s.t.length);
const hint = document.getElementById("hint-energy");
if (hint) { hint.hidden = hasData; if (!hasData) hint.textContent = "Energia andmeid veel pole (koguneb tunnipõhiselt, esimene rida täistunnil)."; }
if (!hasData) { if (chartEnergy) chartEnergy.clear(); return; }
if (!chartEnergy) chartEnergy = echarts.init(el, null, { renderer: "canvas" });
const pal = palColors();
const series = Object.keys(seriesData).sort().map((dev, i) => {
const s = seriesData[dev];
return {
name: `${dev} · W`,
type: "line",
showSymbol: false,
smooth: 0.25,
lineStyle: { width: 2.2, color: pal[i % pal.length] },
itemStyle: { color: pal[i % pal.length] },
data: s.t.map((t, k) => [t, s.power[k]]),
};
});
chartEnergy.setOption({
backgroundColor: "transparent",
tooltip: { trigger: "axis" },
legend: { top: 0, type: "scroll", textStyle: { color: cssVar("--text") } },
grid: { left: 6, right: 6, top: 34, bottom: 44, containLabel: true },
xAxis: { type: "time", axisLabel: { color: cssVar("--muted") }, axisLine: { lineStyle: { color: cssVar("--border") } } },
yAxis: { type: "value", name: "W", scale: true, axisLabel: { color: cssVar("--muted") }, splitLine: { lineStyle: { color: cssVar("--border"), type: "dashed" } } },
dataZoom: [{ type: "inside" }, { type: "slider", height: 18, bottom: 8, borderColor: cssVar("--border") }],
series,
}, true);
chartEnergy.resize();
}
async function loadMotion() {
if (!state.from) return;
const params = new URLSearchParams({ from: state.from, to: state.to });
try {
const res = await fetch(`/api/liikumine?${params}`);
if (!res.ok) return;
renderMotion(await res.json());
} catch (e) { console.error(e); }
}
function renderMotion(data) {
const el = document.getElementById("chart-motion");
if (!el) return;
const ev = data.events || [];
const hint = document.getElementById("hint-motion");
if (hint) { hint.hidden = ev.length > 0; if (!ev.length) hint.textContent = "Liikumise sündmusi veel pole."; }
if (!ev.length) { if (chartMotion) chartMotion.clear(); return; }
if (!chartMotion) chartMotion = echarts.init(el, null, { renderer: "canvas" });
const pal = palColors();
const devices = [...new Set(ev.map((e) => e.device))].sort();
const series = devices.map((dev, i) => ({
name: dev,
type: "scatter",
symbolSize: 13,
itemStyle: { color: pal[i % pal.length] },
data: ev.filter((e) => e.device === dev && e.occupancy).map((e) => [e.t, 1]),
}));
chartMotion.setOption({
backgroundColor: "transparent",
tooltip: {
trigger: "axis",
formatter: (p) => {
if (!p || !p.length) return "";
const d = new Date(p[0].value[0]);
return `${d.toLocaleString("et-EE")}
${p.map((x) => x.seriesName).join(", ")}`;
},
},
legend: { top: 0, textStyle: { color: cssVar("--text") } },
grid: { left: 6, right: 6, top: 34, bottom: 44, containLabel: true },
xAxis: { type: "time", axisLabel: { color: cssVar("--muted") }, axisLine: { lineStyle: { color: cssVar("--border") } } },
yAxis: { type: "value", min: 0, max: 1.4, axisLabel: { show: false }, splitLine: { show: false } },
dataZoom: [{ type: "inside" }, { type: "slider", height: 18, bottom: 8, borderColor: cssVar("--border") }],
series,
}, true);
chartMotion.resize();
}
async function loadUus67Latest() {
try {
const res = await fetch("/api/uus67_latest");
if (!res.ok) return;
const data = await res.json();
renderUus67Cards(data);
} catch (e) { console.error(e); }
}
function renderUus67Cards(data) {
const host = document.getElementById("cards-uus67");
if (!host) return;
const cards = [];
for (const e of data.energy || []) {
cards.push(`⚡ ${e.device} · võimsus
${e.power ?? "–"} W
`);
if (e.energy != null) {
cards.push(`🔌 ${e.device} · kWh
${e.energy} kWh
`);
}
}
for (const m of data.motion || []) {
cards.push(`🚶 ${m.device}
${m.occupancy ? "liikumine" : "rahu"}
`);
}
host.innerHTML = cards.join("");
}
// --- Autentimine ---
function applyAuth(authed) {
state.authed = authed;
const awayBtn = document.getElementById("away-toggle");
if (awayBtn) awayBtn.hidden = !authed;
const prot = document.getElementById("protected");
if (prot) prot.hidden = !authed;
if (authed) loadAway();
const link = document.getElementById("auth-link");
if (link) {
link.href = authed ? "/logout" : "/login";
link.title = authed ? "Logi välja" : "Sisselogimine";
link.textContent = authed ? "🔓" : "🔒";
}
}
async function checkAuth() {
try {
const res = await fetch("/api/me");
if (!res.ok) { applyAuth(false); return; }
const data = await res.json();
applyAuth(!!data.authed);
} catch { applyAuth(false); }
}
async function loadProtected() {
if (!state.authed) return;
loadEnergy();
loadMotion();
loadUus67Latest();
}
// --- Kodust eemal (HA input_boolean) ---
let awayState = null;
async function loadAway() {
if (!state.authed) return;
try {
const res = await fetch("/api/away");
if (!res.ok) return;
const d = await res.json();
awayState = d.away;
renderAway(d.away, d.available);
} catch (e) { console.error(e); }
}
function renderAway(away, available) {
const btn = document.getElementById("away-toggle");
if (!btn) return;
const ico = btn.querySelector(".away-ico");
const title = document.getElementById("away-title");
if (away === true) {
btn.classList.add("away-on");
if (ico) ico.textContent = "🚨";
if (title) title.textContent = "Eemal";
} else {
btn.classList.remove("away-on");
if (ico) ico.textContent = "🏠";
if (title) title.textContent = "Kodus";
if (available === false && title) title.textContent = "HA offline";
}
}
async function toggleAway() {
const on = !(awayState === true);
awayState = on;
renderAway(on, true);
try {
const res = await fetch("/api/away", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ on }),
});
if (!res.ok) throw new Error("HTTP " + res.status);
const d = await res.json();
awayState = d.away;
renderAway(d.away, true);
} catch (e) {
console.error(e);
loadAway();
}
}
document.addEventListener("DOMContentLoaded", init);