app.js 9.5 KB

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