app.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597
  1. "use strict";
  2. const state = {
  3. from: null,
  4. to: null,
  5. agg: "hour",
  6. device: "",
  7. showTemp: true,
  8. showHum: true,
  9. showOut: true,
  10. meta: null,
  11. };
  12. let chart = null;
  13. let currentData = { series: {} };
  14. const $ = (sel) => document.querySelector(sel);
  15. function cssVar(name) {
  16. return getComputedStyle(document.documentElement).getPropertyValue(name).trim();
  17. }
  18. function pad(n) {
  19. return String(n).padStart(2, "0");
  20. }
  21. function toLocalInput(date) {
  22. return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}T${pad(date.getHours())}:${pad(date.getMinutes())}`;
  23. }
  24. function setStatus(ok) { const el = $("#status");
  25. el.classList.toggle("ok", ok === true);
  26. el.classList.toggle("err", ok === false);
  27. }
  28. function applyPreset(days) {
  29. const now = new Date();
  30. let from;
  31. if (days === "all") {
  32. const min = state.meta && state.meta.min ? new Date(state.meta.min.replace(" ", "T")) : null;
  33. from = min && !isNaN(min) ? min : new Date(now.getTime() - 7 * 864e5);
  34. } else {
  35. from = new Date(now.getTime() - Number(days) * 864e5);
  36. }
  37. state.from = toLocalInput(from);
  38. state.to = toLocalInput(now);
  39. $("#from").value = state.from;
  40. $("#to").value = state.to;
  41. load();
  42. }
  43. // Kärbi kõik seeriad ühisesse ajavahemikku, et jooned algaksid ja lõpeksid koos.
  44. function clipToCommonRange(series) {
  45. const active = series.filter((s) => Array.isArray(s.data) && s.data.length);
  46. if (active.length < 2) return series;
  47. const start = Math.max(...active.map((s) => s.data[0][0]));
  48. const end = Math.min(...active.map((s) => s.data[s.data.length - 1][0]));
  49. if (!(start < end)) return series;
  50. return series.map((s) => {
  51. if (!Array.isArray(s.data)) return s;
  52. return { ...s, data: s.data.filter((d) => d && d[0] >= start && d[0] <= end) };
  53. });
  54. }
  55. function buildOption(data) {
  56. const text = cssVar("--text");
  57. const muted = cssVar("--muted");
  58. const border = cssVar("--border");
  59. const tempColor = cssVar("--temp");
  60. const humColor = cssVar("--hum");
  61. const outColor = cssVar("--out");
  62. const series = [];
  63. const palette = ["#1f6feb", "#e8590c", "#2fb344", "#9c36b5", "#f08c00", "#0ca678"];
  64. const devices = Object.keys(data.series).sort();
  65. let pi = 0;
  66. const humAxis = state.showHum;
  67. for (const dev of devices) {
  68. const s = data.series[dev];
  69. const baseColor = palette[pi % palette.length];
  70. pi += 1;
  71. if (state.showTemp) {
  72. series.push({
  73. name: `${dev} · °C`,
  74. type: "line",
  75. yAxisIndex: 0,
  76. showSymbol: false,
  77. smooth: 0.25,
  78. lineStyle: { width: 2.4, color: tempColor },
  79. itemStyle: { color: tempColor },
  80. emphasis: { focus: "series" },
  81. data: s.t.map((t, i) => [t, s.temperature[i]]),
  82. });
  83. if (Array.isArray(s.taidetud) && s.taidetud.some(Boolean)) {
  84. series.push({
  85. name: `${dev} · täidetud`,
  86. type: "scatter",
  87. yAxisIndex: 0,
  88. symbol: "emptyCircle",
  89. symbolSize: 9,
  90. itemStyle: { color: tempColor, borderWidth: 2 },
  91. z: 3,
  92. data: s.t
  93. .map((t, i) => (s.taidetud[i] ? [t, s.temperature[i]] : null))
  94. .filter(Boolean),
  95. });
  96. }
  97. }
  98. if (state.showHum) {
  99. series.push({
  100. name: `${dev} · %`,
  101. type: "line",
  102. yAxisIndex: 1,
  103. showSymbol: false,
  104. smooth: 0.25,
  105. lineStyle: { width: 1.8, type: "dashed", color: humColor },
  106. itemStyle: { color: humColor },
  107. emphasis: { focus: "series" },
  108. data: s.t.map((t, i) => [t, s.humidity[i]]),
  109. });
  110. }
  111. }
  112. const out = data.outside;
  113. if (state.showOut && out && Array.isArray(out.t) && out.t.length) {
  114. series.push({
  115. name: "Väli · °C",
  116. type: "line",
  117. yAxisIndex: 0,
  118. showSymbol: false,
  119. smooth: 0.25,
  120. lineStyle: { width: 2, color: outColor },
  121. itemStyle: { color: outColor },
  122. emphasis: { focus: "series" },
  123. data: out.t.map((t, i) => [t, out.temperature[i]]),
  124. });
  125. if (Array.isArray(out.taidetud) && out.taidetud.some(Boolean)) {
  126. series.push({
  127. name: "Väli · täidetud",
  128. type: "scatter",
  129. yAxisIndex: 0,
  130. symbol: "emptyCircle",
  131. symbolSize: 9,
  132. itemStyle: { color: outColor, borderWidth: 2 },
  133. z: 3,
  134. data: out.t
  135. .map((t, i) => (out.taidetud[i] ? [t, out.temperature[i]] : null))
  136. .filter(Boolean),
  137. });
  138. }
  139. }
  140. return {
  141. backgroundColor: "transparent",
  142. animationDuration: 300,
  143. color: palette,
  144. grid: { left: 6, right: humAxis ? 6 : 6, top: 40, bottom: 62, containLabel: true },
  145. legend: {
  146. top: 4,
  147. type: "scroll",
  148. textStyle: { color: text, fontSize: 12 },
  149. inactiveColor: muted,
  150. },
  151. tooltip: {
  152. trigger: "axis",
  153. backgroundColor: cssVar("--panel"),
  154. borderColor: border,
  155. textStyle: { color: text, fontSize: 12 },
  156. axisPointer: { type: "cross", label: { backgroundColor: muted } },
  157. valueFormatter: null,
  158. formatter: (params) => {
  159. const items = (params || []).filter(
  160. (p) => !String(p.seriesName).endsWith("· täidetud")
  161. );
  162. if (!items.length) return "";
  163. const d = new Date(items[0].value[0]);
  164. const head = `${d.toLocaleDateString("et-EE")} ${pad(d.getHours())}:${pad(d.getMinutes())}`;
  165. const lines = items.map((p) => {
  166. const v = p.value[1];
  167. const unit = p.seriesName.endsWith("°C") ? " °C" : " %";
  168. return `<div style="display:flex;justify-content:space-between;gap:14px">
  169. <span>${p.marker} ${p.seriesName}</span><b>${v == null ? "–" : v + unit}</b></div>`;
  170. });
  171. return `<div style="font-weight:600;margin-bottom:4px">${head}</div>${lines.join("")}`;
  172. },
  173. },
  174. xAxis: {
  175. type: "time",
  176. axisLine: { lineStyle: { color: border } },
  177. axisLabel: { color: muted, hideOverlap: true },
  178. splitLine: { show: false },
  179. },
  180. yAxis: [
  181. {
  182. type: "value",
  183. name: "°C",
  184. scale: true,
  185. axisLine: { show: false },
  186. axisLabel: { color: muted },
  187. splitLine: { lineStyle: { color: border, type: "dashed" } },
  188. },
  189. ...(humAxis
  190. ? [
  191. {
  192. type: "value",
  193. name: "%",
  194. scale: true,
  195. position: "right",
  196. axisLine: { show: false },
  197. axisLabel: { color: muted },
  198. splitLine: { show: false },
  199. },
  200. ]
  201. : []),
  202. ],
  203. dataZoom: [
  204. { type: "inside", throttle: 50 },
  205. { type: "slider", height: 22, bottom: 14, borderColor: border, textStyle: { color: muted }, fillColor: cssVar("--accent-soft") },
  206. ],
  207. series: clipToCommonRange(series),
  208. };
  209. }
  210. function render(data) {
  211. const chartEl = $("#chart");
  212. const hasData = Object.keys(data.series).length > 0 && Object.values(data.series).some((s) => s.t.length);
  213. $("#hint").hidden = hasData;
  214. if (!hasData) {
  215. $("#hint").textContent = "Valitud vahemikus andmeid ei ole. Andur salvestab andmeid alates 2026-09-17.";
  216. }
  217. if (!chart) chart = echarts.init(chartEl, null, { renderer: "canvas" });
  218. chart.setOption(buildOption(data), true);
  219. chart.resize();
  220. }
  221. async function load() {
  222. const params = new URLSearchParams({
  223. from: state.from,
  224. to: state.to,
  225. agg: state.agg,
  226. });
  227. if (state.device) params.set("device", state.device);
  228. setStatus(null);
  229. try {
  230. const [tempRes, outRes] = await Promise.all([
  231. fetch(`/api/temperatuur?${params}`),
  232. fetch(`/api/valisilm?${params}`),
  233. ]);
  234. if (!tempRes.ok) throw new Error(await tempRes.text());
  235. const data = await tempRes.json();
  236. if (outRes.ok) {
  237. try {
  238. data.outside = (await outRes.json()).series;
  239. } catch {
  240. data.outside = null;
  241. }
  242. }
  243. currentData = data;
  244. currentSeries = data.series;
  245. render(data);
  246. loadProtected();
  247. setStatus(true);
  248. const f = new Date(state.from.replace(" ", "T"));
  249. const t = new Date(state.to.replace(" ", "T"));
  250. $("#range-label").textContent = `${f.toLocaleString("et-EE")} → ${t.toLocaleString("et-EE")}`;
  251. } catch (err) {
  252. console.error(err);
  253. setStatus(false);
  254. $("#hint").hidden = false;
  255. $("#hint").textContent = "Andmete laadimine ebaõnnestus.";
  256. }
  257. }
  258. async function loadMeta() {
  259. try {
  260. const res = await fetch("/api/meta");
  261. if (!res.ok) throw new Error();
  262. state.meta = await res.json();
  263. $("#subtitle").textContent = "Zigbee andurid";
  264. if (state.meta.min) {
  265. $("#range-label").textContent = `Andmed alates ${state.meta.min}`;
  266. }
  267. } catch {
  268. $("#subtitle").textContent = "Zigbee andurid";
  269. }
  270. }
  271. async function loadLatest() {
  272. try {
  273. const res = await fetch("/api/latest");
  274. if (!res.ok) return;
  275. const data = await res.json();
  276. renderCards(data);
  277. } catch {
  278. /* vaikne */
  279. }
  280. }
  281. function renderCards(data) {
  282. const cards = [];
  283. for (const r of data.readings) {
  284. cards.push(`<div class="card temp"><div class="k">🌡️ ${r.device} · temperatuur</div>
  285. <div class="v">${r.temperature ?? "–"}<small> °C</small></div></div>`);
  286. cards.push(`<div class="card hum"><div class="k">💧 ${r.device} · niiskus</div>
  287. <div class="v">${r.humidity ?? "–"}<small> %</small></div></div>`);
  288. }
  289. if (data.outside && data.outside.temperature != null) {
  290. cards.push(`<div class="card out"><div class="k">🌤️ Väli · temperatuur</div>
  291. <div class="v">${data.outside.temperature}<small> °C</small></div></div>`);
  292. }
  293. if (data.open_faults.length) {
  294. const items = data.open_faults
  295. .map((f) => `<div>⚠️ <b>${f.device}</b> · ${f.tyyp}${f.detail ? " · " + f.detail : ""}</div>`)
  296. .join("");
  297. cards.push(`<div class="card wide"><div class="k">Lahtised häired (${data.open_faults.length})</div>
  298. <div style="font-size:13px;margin-top:6px;line-height:1.7">${items}</div></div>`);
  299. }
  300. $("#cards").innerHTML = cards.join("");
  301. }
  302. function setTheme(theme) {
  303. document.documentElement.setAttribute("data-theme", theme);
  304. localStorage.setItem("nutikodu-theme", theme);
  305. $("#theme-toggle").textContent = theme === "dark" ? "☀️" : "🌙";
  306. const meta = $("#meta-theme");
  307. if (meta) meta.setAttribute("content", theme === "dark" ? "#0e1116" : "#1f6feb");
  308. if (chart) chart.setOption(buildOption(currentData), true);
  309. }
  310. let currentSeries = {};
  311. function init() {
  312. const saved = localStorage.getItem("nutikodu-theme");
  313. const prefersDark = window.matchMedia && window.matchMedia("(prefers-color-scheme: dark)").matches;
  314. setTheme(saved || (prefersDark ? "dark" : "light"));
  315. $("#theme-toggle").addEventListener("click", () => {
  316. setTheme(document.documentElement.getAttribute("data-theme") === "dark" ? "light" : "dark");
  317. });
  318. document.querySelectorAll("#presets button").forEach((btn) => {
  319. btn.addEventListener("click", () => {
  320. document.querySelectorAll("#presets button").forEach((b) => b.classList.remove("active"));
  321. btn.classList.add("active");
  322. applyPreset(btn.dataset.days);
  323. });
  324. });
  325. document.querySelectorAll("#agg button").forEach((btn) => {
  326. btn.addEventListener("click", () => {
  327. document.querySelectorAll("#agg button").forEach((b) => b.classList.remove("active"));
  328. btn.classList.add("active");
  329. state.agg = btn.dataset.agg;
  330. load();
  331. });
  332. });
  333. $("#show-temp").addEventListener("change", (e) => { state.showTemp = e.target.checked; load(); });
  334. $("#show-hum").addEventListener("change", (e) => { state.showHum = e.target.checked; load(); });
  335. $("#show-out").addEventListener("change", (e) => { state.showOut = e.target.checked; load(); });
  336. $("#apply").addEventListener("click", () => {
  337. state.from = $("#from").value;
  338. state.to = $("#to").value;
  339. document.querySelectorAll("#presets button").forEach((b) => b.classList.remove("active"));
  340. load();
  341. });
  342. const awayBtn = document.getElementById("away-toggle");
  343. if (awayBtn) awayBtn.addEventListener("click", toggleAway);
  344. window.addEventListener("resize", () => chart && chart.resize());
  345. window.addEventListener("orientationchange", () => setTimeout(() => chart && chart.resize(), 250));
  346. window.addEventListener("load", () => chart && chart.resize());
  347. checkAuth().then(() => loadMeta().then(() => applyPreset(7)));
  348. loadLatest();
  349. setInterval(loadLatest, 60000);
  350. setInterval(loadProtected, 60000);
  351. }
  352. // --- Uus67: energia + liikumine ---
  353. let chartEnergy = null;
  354. let chartMotion = null;
  355. function palColors() {
  356. return ["#1f6feb", "#e8590c", "#2fb344", "#9c36b7", "#f08c00", "#0ca678"];
  357. }
  358. async function loadEnergy() {
  359. if (!state.from) return;
  360. const params = new URLSearchParams({ from: state.from, to: state.to, agg: state.agg });
  361. try {
  362. const res = await fetch(`/api/energia?${params}`);
  363. if (!res.ok) return;
  364. renderEnergy(await res.json());
  365. } catch (e) { console.error(e); }
  366. }
  367. function renderEnergy(data) {
  368. const el = document.getElementById("chart-energy");
  369. if (!el) return;
  370. const seriesData = data.series || {};
  371. const hasData = Object.keys(seriesData).length > 0 && Object.values(seriesData).some((s) => s.t.length);
  372. const hint = document.getElementById("hint-energy");
  373. if (hint) { hint.hidden = hasData; if (!hasData) hint.textContent = "Energia andmeid veel pole (koguneb tunnipõhiselt, esimene rida täistunnil)."; }
  374. if (!hasData) { if (chartEnergy) chartEnergy.clear(); return; }
  375. if (!chartEnergy) chartEnergy = echarts.init(el, null, { renderer: "canvas" });
  376. const pal = palColors();
  377. const series = Object.keys(seriesData).sort().map((dev, i) => {
  378. const s = seriesData[dev];
  379. return {
  380. name: `${dev} · W`,
  381. type: "line",
  382. showSymbol: false,
  383. smooth: 0.25,
  384. lineStyle: { width: 2.2, color: pal[i % pal.length] },
  385. itemStyle: { color: pal[i % pal.length] },
  386. data: s.t.map((t, k) => [t, s.power[k]]),
  387. };
  388. });
  389. chartEnergy.setOption({
  390. backgroundColor: "transparent",
  391. tooltip: { trigger: "axis" },
  392. legend: { top: 0, type: "scroll", textStyle: { color: cssVar("--text") } },
  393. grid: { left: 6, right: 6, top: 34, bottom: 44, containLabel: true },
  394. xAxis: { type: "time", axisLabel: { color: cssVar("--muted") }, axisLine: { lineStyle: { color: cssVar("--border") } } },
  395. yAxis: { type: "value", name: "W", scale: true, axisLabel: { color: cssVar("--muted") }, splitLine: { lineStyle: { color: cssVar("--border"), type: "dashed" } } },
  396. dataZoom: [{ type: "inside" }, { type: "slider", height: 18, bottom: 8, borderColor: cssVar("--border") }],
  397. series,
  398. }, true);
  399. chartEnergy.resize();
  400. }
  401. async function loadMotion() {
  402. if (!state.from) return;
  403. const params = new URLSearchParams({ from: state.from, to: state.to });
  404. try {
  405. const res = await fetch(`/api/liikumine?${params}`);
  406. if (!res.ok) return;
  407. renderMotion(await res.json());
  408. } catch (e) { console.error(e); }
  409. }
  410. function renderMotion(data) {
  411. const el = document.getElementById("chart-motion");
  412. if (!el) return;
  413. const ev = data.events || [];
  414. const hint = document.getElementById("hint-motion");
  415. if (hint) { hint.hidden = ev.length > 0; if (!ev.length) hint.textContent = "Liikumise sündmusi veel pole."; }
  416. if (!ev.length) { if (chartMotion) chartMotion.clear(); return; }
  417. if (!chartMotion) chartMotion = echarts.init(el, null, { renderer: "canvas" });
  418. const pal = palColors();
  419. const devices = [...new Set(ev.map((e) => e.device))].sort();
  420. const series = devices.map((dev, i) => ({
  421. name: dev,
  422. type: "scatter",
  423. symbolSize: 13,
  424. itemStyle: { color: pal[i % pal.length] },
  425. data: ev.filter((e) => e.device === dev && e.occupancy).map((e) => [e.t, 1]),
  426. }));
  427. chartMotion.setOption({
  428. backgroundColor: "transparent",
  429. tooltip: {
  430. trigger: "axis",
  431. formatter: (p) => {
  432. if (!p || !p.length) return "";
  433. const d = new Date(p[0].value[0]);
  434. return `${d.toLocaleString("et-EE")}<br>${p.map((x) => x.seriesName).join(", ")}`;
  435. },
  436. },
  437. legend: { top: 0, textStyle: { color: cssVar("--text") } },
  438. grid: { left: 6, right: 6, top: 34, bottom: 44, containLabel: true },
  439. xAxis: { type: "time", axisLabel: { color: cssVar("--muted") }, axisLine: { lineStyle: { color: cssVar("--border") } } },
  440. yAxis: { type: "value", min: 0, max: 1.4, axisLabel: { show: false }, splitLine: { show: false } },
  441. dataZoom: [{ type: "inside" }, { type: "slider", height: 18, bottom: 8, borderColor: cssVar("--border") }],
  442. series,
  443. }, true);
  444. chartMotion.resize();
  445. }
  446. async function loadUus67Latest() {
  447. try {
  448. const res = await fetch("/api/uus67_latest");
  449. if (!res.ok) return;
  450. const data = await res.json();
  451. renderUus67Cards(data);
  452. } catch (e) { console.error(e); }
  453. }
  454. function renderUus67Cards(data) {
  455. const host = document.getElementById("cards-uus67");
  456. if (!host) return;
  457. const cards = [];
  458. for (const e of data.energy || []) {
  459. cards.push(`<div class="card"><div class="k">⚡ ${e.device} · võimsus</div>
  460. <div class="v">${e.power ?? "–"}<small> W</small></div></div>`);
  461. if (e.energy != null) {
  462. cards.push(`<div class="card"><div class="k">🔌 ${e.device} · kWh</div>
  463. <div class="v">${e.energy}<small> kWh</small></div></div>`);
  464. }
  465. }
  466. for (const m of data.motion || []) {
  467. cards.push(`<div class="card ${m.occupancy ? "temp" : ""}"><div class="k">🚶 ${m.device}</div>
  468. <div class="v">${m.occupancy ? "liikumine" : "rahu"}</div></div>`);
  469. }
  470. host.innerHTML = cards.join("");
  471. }
  472. // --- Autentimine ---
  473. function applyAuth(authed) {
  474. state.authed = authed;
  475. const awayBtn = document.getElementById("away-toggle");
  476. if (awayBtn) awayBtn.hidden = !authed;
  477. const prot = document.getElementById("protected");
  478. if (prot) prot.hidden = !authed;
  479. if (authed) loadAway();
  480. const link = document.getElementById("auth-link");
  481. if (link) {
  482. link.href = authed ? "/logout" : "/login";
  483. link.title = authed ? "Logi välja" : "Sisselogimine";
  484. link.textContent = authed ? "🔓" : "🔒";
  485. }
  486. }
  487. async function checkAuth() {
  488. try {
  489. const res = await fetch("/api/me");
  490. if (!res.ok) { applyAuth(false); return; }
  491. const data = await res.json();
  492. applyAuth(!!data.authed);
  493. } catch { applyAuth(false); }
  494. }
  495. async function loadProtected() {
  496. if (!state.authed) return;
  497. loadEnergy();
  498. loadMotion();
  499. loadUus67Latest();
  500. }
  501. // --- Kodust eemal (HA input_boolean) ---
  502. let awayState = null;
  503. async function loadAway() {
  504. if (!state.authed) return;
  505. try {
  506. const res = await fetch("/api/away");
  507. if (!res.ok) return;
  508. const d = await res.json();
  509. awayState = d.away;
  510. renderAway(d.away, d.available);
  511. } catch (e) { console.error(e); }
  512. }
  513. function renderAway(away, available) {
  514. const btn = document.getElementById("away-toggle");
  515. if (!btn) return;
  516. const ico = btn.querySelector(".away-ico");
  517. const title = document.getElementById("away-title");
  518. if (away === true) {
  519. btn.classList.add("away-on");
  520. if (ico) ico.textContent = "🚨";
  521. if (title) title.textContent = "Eemal";
  522. } else {
  523. btn.classList.remove("away-on");
  524. if (ico) ico.textContent = "🏠";
  525. if (title) title.textContent = "Kodus";
  526. if (available === false && title) title.textContent = "HA offline";
  527. }
  528. }
  529. async function toggleAway() {
  530. const on = !(awayState === true);
  531. awayState = on;
  532. renderAway(on, true);
  533. try {
  534. const res = await fetch("/api/away", {
  535. method: "POST",
  536. headers: { "Content-Type": "application/json" },
  537. body: JSON.stringify({ on }),
  538. });
  539. if (!res.ok) throw new Error("HTTP " + res.status);
  540. const d = await res.json();
  541. awayState = d.away;
  542. renderAway(d.away, true);
  543. } catch (e) {
  544. console.error(e);
  545. loadAway();
  546. }
  547. }
  548. document.addEventListener("DOMContentLoaded", init);