app.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  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) {
  25. const el = $("#status");
  26. el.classList.toggle("ok", ok === true);
  27. el.classList.toggle("err", ok === false);
  28. }
  29. function applyPreset(days) {
  30. const now = new Date();
  31. let from;
  32. if (days === "all") {
  33. const min = state.meta && state.meta.min ? new Date(state.meta.min.replace(" ", "T")) : null;
  34. from = min && !isNaN(min) ? min : new Date(now.getTime() - 7 * 864e5);
  35. } else {
  36. from = new Date(now.getTime() - Number(days) * 864e5);
  37. }
  38. state.from = toLocalInput(from);
  39. state.to = toLocalInput(now);
  40. $("#from").value = state.from;
  41. $("#to").value = state.to;
  42. load();
  43. }
  44. function buildOption(data) {
  45. const text = cssVar("--text");
  46. const muted = cssVar("--muted");
  47. const border = cssVar("--border");
  48. const tempColor = cssVar("--temp");
  49. const humColor = cssVar("--hum");
  50. const outColor = cssVar("--out");
  51. const series = [];
  52. const palette = ["#1f6feb", "#e8590c", "#2fb344", "#9c36b5", "#f08c00", "#0ca678"];
  53. const devices = Object.keys(data.series).sort();
  54. let pi = 0;
  55. const humAxis = state.showHum;
  56. for (const dev of devices) {
  57. const s = data.series[dev];
  58. const baseColor = palette[pi % palette.length];
  59. pi += 1;
  60. if (state.showTemp) {
  61. series.push({
  62. name: `${dev} · °C`,
  63. type: "line",
  64. yAxisIndex: 0,
  65. showSymbol: false,
  66. smooth: 0.25,
  67. lineStyle: { width: 2.4, color: tempColor },
  68. itemStyle: { color: tempColor },
  69. emphasis: { focus: "series" },
  70. data: s.t.map((t, i) => [t, s.temperature[i]]),
  71. });
  72. if (Array.isArray(s.taidetud) && s.taidetud.some(Boolean)) {
  73. series.push({
  74. name: `${dev} · täidetud`,
  75. type: "scatter",
  76. yAxisIndex: 0,
  77. symbol: "emptyCircle",
  78. symbolSize: 9,
  79. itemStyle: { color: tempColor, borderWidth: 2 },
  80. z: 3,
  81. data: s.t
  82. .map((t, i) => (s.taidetud[i] ? [t, s.temperature[i]] : null))
  83. .filter(Boolean),
  84. });
  85. }
  86. }
  87. if (state.showHum) {
  88. series.push({
  89. name: `${dev} · %`,
  90. type: "line",
  91. yAxisIndex: 1,
  92. showSymbol: false,
  93. smooth: 0.25,
  94. lineStyle: { width: 1.8, type: "dashed", color: humColor },
  95. itemStyle: { color: humColor },
  96. emphasis: { focus: "series" },
  97. data: s.t.map((t, i) => [t, s.humidity[i]]),
  98. });
  99. }
  100. }
  101. const out = data.outside;
  102. if (state.showOut && out && Array.isArray(out.t) && out.t.length) {
  103. series.push({
  104. name: "Väli · °C",
  105. type: "line",
  106. yAxisIndex: 0,
  107. showSymbol: false,
  108. smooth: 0.25,
  109. lineStyle: { width: 2, color: outColor },
  110. itemStyle: { color: outColor },
  111. emphasis: { focus: "series" },
  112. data: out.t.map((t, i) => [t, out.temperature[i]]),
  113. });
  114. if (Array.isArray(out.taidetud) && out.taidetud.some(Boolean)) {
  115. series.push({
  116. name: "Väli · täidetud",
  117. type: "scatter",
  118. yAxisIndex: 0,
  119. symbol: "emptyCircle",
  120. symbolSize: 9,
  121. itemStyle: { color: outColor, borderWidth: 2 },
  122. z: 3,
  123. data: out.t
  124. .map((t, i) => (out.taidetud[i] ? [t, out.temperature[i]] : null))
  125. .filter(Boolean),
  126. });
  127. }
  128. }
  129. return {
  130. backgroundColor: "transparent",
  131. animationDuration: 300,
  132. color: palette,
  133. grid: { left: 6, right: humAxis ? 6 : 6, top: 40, bottom: 62, containLabel: true },
  134. legend: {
  135. top: 4,
  136. type: "scroll",
  137. textStyle: { color: text, fontSize: 12 },
  138. inactiveColor: muted,
  139. },
  140. tooltip: {
  141. trigger: "axis",
  142. backgroundColor: cssVar("--panel"),
  143. borderColor: border,
  144. textStyle: { color: text, fontSize: 12 },
  145. axisPointer: { type: "cross", label: { backgroundColor: muted } },
  146. valueFormatter: null,
  147. formatter: (params) => {
  148. const items = (params || []).filter(
  149. (p) => !String(p.seriesName).endsWith("· täidetud")
  150. );
  151. if (!items.length) return "";
  152. const d = new Date(items[0].value[0]);
  153. const head = `${d.toLocaleDateString("et-EE")} ${pad(d.getHours())}:${pad(d.getMinutes())}`;
  154. const lines = items.map((p) => {
  155. const v = p.value[1];
  156. const unit = p.seriesName.endsWith("°C") ? " °C" : " %";
  157. return `<div style="display:flex;justify-content:space-between;gap:14px">
  158. <span>${p.marker} ${p.seriesName}</span><b>${v == null ? "–" : v + unit}</b></div>`;
  159. });
  160. return `<div style="font-weight:600;margin-bottom:4px">${head}</div>${lines.join("")}`;
  161. },
  162. },
  163. xAxis: {
  164. type: "time",
  165. axisLine: { lineStyle: { color: border } },
  166. axisLabel: { color: muted, hideOverlap: true },
  167. splitLine: { show: false },
  168. },
  169. yAxis: [
  170. {
  171. type: "value",
  172. name: "°C",
  173. scale: true,
  174. axisLine: { show: false },
  175. axisLabel: { color: muted },
  176. splitLine: { lineStyle: { color: border, type: "dashed" } },
  177. },
  178. ...(humAxis
  179. ? [
  180. {
  181. type: "value",
  182. name: "%",
  183. scale: true,
  184. position: "right",
  185. axisLine: { show: false },
  186. axisLabel: { color: muted },
  187. splitLine: { show: false },
  188. },
  189. ]
  190. : []),
  191. ],
  192. dataZoom: [
  193. { type: "inside", throttle: 50 },
  194. { type: "slider", height: 22, bottom: 14, borderColor: border, textStyle: { color: muted }, fillColor: cssVar("--accent-soft") },
  195. ],
  196. series,
  197. };
  198. }
  199. function render(data) {
  200. const chartEl = $("#chart");
  201. const hasData = Object.keys(data.series).length > 0 && Object.values(data.series).some((s) => s.t.length);
  202. $("#hint").hidden = hasData;
  203. if (!hasData) {
  204. $("#hint").textContent = "Valitud vahemikus andmeid ei ole. Andur salvestab andmeid alates 2026-09-17.";
  205. }
  206. if (!chart) chart = echarts.init(chartEl, null, { renderer: "canvas" });
  207. chart.setOption(buildOption(data), true);
  208. chart.resize();
  209. }
  210. async function load() {
  211. const params = new URLSearchParams({
  212. from: state.from,
  213. to: state.to,
  214. agg: state.agg,
  215. });
  216. if (state.device) params.set("device", state.device);
  217. setStatus(null);
  218. try {
  219. const [tempRes, outRes] = await Promise.all([
  220. fetch(`/api/temperatuur?${params}`),
  221. fetch(`/api/valisilm?${params}`),
  222. ]);
  223. if (!tempRes.ok) throw new Error(await tempRes.text());
  224. const data = await tempRes.json();
  225. if (outRes.ok) {
  226. try {
  227. data.outside = (await outRes.json()).series;
  228. } catch {
  229. data.outside = null;
  230. }
  231. }
  232. currentData = data;
  233. currentSeries = data.series;
  234. render(data);
  235. setStatus(true);
  236. const f = new Date(state.from.replace(" ", "T"));
  237. const t = new Date(state.to.replace(" ", "T"));
  238. $("#range-label").textContent = `${f.toLocaleString("et-EE")} → ${t.toLocaleString("et-EE")}`;
  239. } catch (err) {
  240. console.error(err);
  241. setStatus(false);
  242. $("#hint").hidden = false;
  243. $("#hint").textContent = "Andmete laadimine ebaõnnestus.";
  244. }
  245. }
  246. async function loadMeta() {
  247. try {
  248. const res = await fetch("/api/meta");
  249. if (!res.ok) throw new Error();
  250. state.meta = await res.json();
  251. const devs = state.meta.devices.length ? state.meta.devices.join(", ") : "—";
  252. $("#subtitle").textContent = `Zigbee andurid · ${devs}`;
  253. if (state.meta.min) {
  254. $("#range-label").textContent = `Andmed alates ${state.meta.min}`;
  255. }
  256. } catch {
  257. $("#subtitle").textContent = "Zigbee andurid";
  258. }
  259. }
  260. async function loadLatest() {
  261. try {
  262. const res = await fetch("/api/latest");
  263. if (!res.ok) return;
  264. const data = await res.json();
  265. renderCards(data);
  266. } catch {
  267. /* vaikne */
  268. }
  269. }
  270. function renderCards(data) {
  271. const cards = [];
  272. for (const r of data.readings) {
  273. cards.push(`<div class="card temp"><div class="k">🌡️ ${r.device} · temperatuur</div>
  274. <div class="v">${r.temperature ?? "–"}<small> °C</small></div></div>`);
  275. cards.push(`<div class="card hum"><div class="k">💧 ${r.device} · niiskus</div>
  276. <div class="v">${r.humidity ?? "–"}<small> %</small></div></div>`);
  277. }
  278. if (data.outside && data.outside.temperature != null) {
  279. cards.push(`<div class="card out"><div class="k">🌤️ Väli · temperatuur</div>
  280. <div class="v">${data.outside.temperature}<small> °C</small></div></div>`);
  281. }
  282. if (data.open_faults.length) {
  283. const items = data.open_faults
  284. .map((f) => `<div>⚠️ <b>${f.device}</b> · ${f.tyyp}${f.detail ? " · " + f.detail : ""}</div>`)
  285. .join("");
  286. cards.push(`<div class="card wide"><div class="k">Lahtised häired (${data.open_faults.length})</div>
  287. <div style="font-size:13px;margin-top:6px;line-height:1.7">${items}</div></div>`);
  288. }
  289. $("#cards").innerHTML = cards.join("");
  290. }
  291. function setTheme(theme) {
  292. document.documentElement.setAttribute("data-theme", theme);
  293. localStorage.setItem("nutikodu-theme", theme);
  294. $("#theme-toggle").textContent = theme === "dark" ? "☀️" : "🌙";
  295. const meta = $("#meta-theme");
  296. if (meta) meta.setAttribute("content", theme === "dark" ? "#0e1116" : "#1f6feb");
  297. if (chart) chart.setOption(buildOption(currentData), true);
  298. }
  299. let currentSeries = {};
  300. function init() {
  301. const saved = localStorage.getItem("nutikodu-theme");
  302. const prefersDark = window.matchMedia && window.matchMedia("(prefers-color-scheme: dark)").matches;
  303. setTheme(saved || (prefersDark ? "dark" : "light"));
  304. $("#theme-toggle").addEventListener("click", () => {
  305. setTheme(document.documentElement.getAttribute("data-theme") === "dark" ? "light" : "dark");
  306. });
  307. document.querySelectorAll("#presets button").forEach((btn) => {
  308. btn.addEventListener("click", () => {
  309. document.querySelectorAll("#presets button").forEach((b) => b.classList.remove("active"));
  310. btn.classList.add("active");
  311. applyPreset(btn.dataset.days);
  312. });
  313. });
  314. document.querySelectorAll("#agg button").forEach((btn) => {
  315. btn.addEventListener("click", () => {
  316. document.querySelectorAll("#agg button").forEach((b) => b.classList.remove("active"));
  317. btn.classList.add("active");
  318. state.agg = btn.dataset.agg;
  319. load();
  320. });
  321. });
  322. $("#show-temp").addEventListener("change", (e) => { state.showTemp = e.target.checked; load(); });
  323. $("#show-hum").addEventListener("change", (e) => { state.showHum = e.target.checked; load(); });
  324. $("#show-out").addEventListener("change", (e) => { state.showOut = e.target.checked; load(); });
  325. $("#apply").addEventListener("click", () => {
  326. state.from = $("#from").value;
  327. state.to = $("#to").value;
  328. document.querySelectorAll("#presets button").forEach((b) => b.classList.remove("active"));
  329. load();
  330. });
  331. window.addEventListener("resize", () => chart && chart.resize());
  332. window.addEventListener("orientationchange", () => setTimeout(() => chart && chart.resize(), 250));
  333. window.addEventListener("load", () => chart && chart.resize());
  334. loadMeta().then(() => applyPreset(7));
  335. loadLatest();
  336. setInterval(loadLatest, 60000);
  337. }
  338. document.addEventListener("DOMContentLoaded", init);