app.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377
  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. setStatus(true);
  247. const f = new Date(state.from.replace(" ", "T"));
  248. const t = new Date(state.to.replace(" ", "T"));
  249. $("#range-label").textContent = `${f.toLocaleString("et-EE")} → ${t.toLocaleString("et-EE")}`;
  250. } catch (err) {
  251. console.error(err);
  252. setStatus(false);
  253. $("#hint").hidden = false;
  254. $("#hint").textContent = "Andmete laadimine ebaõnnestus.";
  255. }
  256. }
  257. async function loadMeta() {
  258. try {
  259. const res = await fetch("/api/meta");
  260. if (!res.ok) throw new Error();
  261. state.meta = await res.json();
  262. const devs = state.meta.devices.length ? state.meta.devices.join(", ") : "—";
  263. $("#subtitle").textContent = `Zigbee andurid · ${devs}`;
  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. window.addEventListener("resize", () => chart && chart.resize());
  343. window.addEventListener("orientationchange", () => setTimeout(() => chart && chart.resize(), 250));
  344. window.addEventListener("load", () => chart && chart.resize());
  345. loadMeta().then(() => applyPreset(7));
  346. loadLatest();
  347. setInterval(loadLatest, 60000);
  348. }
  349. document.addEventListener("DOMContentLoaded", init);