app.js 10 KB

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