fix: 1.4.0 добавил фалйы форм в отслеживание
This commit is contained in:
@@ -0,0 +1,190 @@
|
||||
import { configureTheme, showToast } from "./api.js";
|
||||
|
||||
const requestedLayout = new URLSearchParams(window.location.search).get("layout");
|
||||
const layoutMode = ["horizontal", "vertical"].includes(requestedLayout) ? requestedLayout : null;
|
||||
const wideLayout = window.matchMedia("(min-width: 800px)");
|
||||
|
||||
function applyLayout() {
|
||||
document.documentElement.dataset.widgetLayout = layoutMode || (wideLayout.matches ? "horizontal" : "vertical");
|
||||
}
|
||||
|
||||
applyLayout();
|
||||
wideLayout.addEventListener("change", () => !layoutMode && applyLayout());
|
||||
|
||||
const $ = selector => document.querySelector(selector);
|
||||
const $$ = selector => [...document.querySelectorAll(selector)];
|
||||
const themeMode = configureTheme($("#theme-button"));
|
||||
|
||||
let state = null;
|
||||
let busy = false;
|
||||
let polling = false;
|
||||
|
||||
function setPill(label, tone) {
|
||||
const element = $("#connection");
|
||||
element.textContent = label;
|
||||
element.className = `pill ${tone}`;
|
||||
}
|
||||
|
||||
function drawToggle(selector, active, label = null) {
|
||||
const button = $(selector);
|
||||
const enabled = Boolean(active);
|
||||
button.setAttribute("aria-pressed", String(enabled));
|
||||
button.textContent = label || (enabled ? "ON" : "OFF");
|
||||
}
|
||||
|
||||
function ready(status) {
|
||||
return Boolean(status?.running && status?.mqtt_connected && status?.device_online);
|
||||
}
|
||||
|
||||
function feedbackReady(status) {
|
||||
return ready(status) && Boolean(status?.feedback_ready);
|
||||
}
|
||||
|
||||
function drawSpeed(value) {
|
||||
const speed = Math.max(0, Math.min(4, Number(value) || 0));
|
||||
const output = $("#speed");
|
||||
output.textContent = speed || "—";
|
||||
output.classList.remove("skeleton");
|
||||
$$('[data-speed]').forEach(button => {
|
||||
const segment = Number(button.dataset.speed);
|
||||
button.classList.toggle("active", speed > 0 && segment <= speed);
|
||||
button.setAttribute("aria-pressed", String(segment === speed));
|
||||
});
|
||||
}
|
||||
|
||||
function render(status) {
|
||||
state = status;
|
||||
const elica = status?.elica || {};
|
||||
const external = status?.external_fan || {};
|
||||
const controllerOnline = ready(status);
|
||||
const panelOnline = feedbackReady(status);
|
||||
|
||||
if (!status?.running) setPill("Сервис остановлен", "bad");
|
||||
else if (!status?.mqtt_connected) setPill("MQTT нет связи", "bad");
|
||||
else if (!status?.device_online) setPill("ESP32 offline", "bad");
|
||||
else if (!status?.feedback_ready) setPill("Синхронизация", "warn");
|
||||
else setPill("Online", "good");
|
||||
|
||||
$("#header-detail").textContent = elica.power
|
||||
? `Вытяжка включена${elica.speed ? ` · скорость ${elica.speed}` : ""}`
|
||||
: "Вытяжная вентиляция";
|
||||
|
||||
drawSpeed(elica.speed);
|
||||
$("#speed-note").textContent = panelOnline
|
||||
? (elica.power ? "Фактическая ступень по индикаторам Elica" : "Выбор скорости включит вытяжку")
|
||||
: "Ждём синхронизацию панели Elica";
|
||||
|
||||
drawToggle("#power-toggle", elica.power);
|
||||
$("#power-detail").textContent = elica.power ? "Включена" : "Выключена";
|
||||
|
||||
if (external.available && typeof external.on === "boolean") {
|
||||
drawToggle("#external-fan-toggle", external.on);
|
||||
$("#external-fan-card").dataset.on = String(external.on);
|
||||
$("#external-fan-detail").textContent = external.on ? "Работает · NC замкнут" : "Остановлен · NC разомкнут";
|
||||
} else {
|
||||
drawToggle("#external-fan-toggle", false, "—");
|
||||
$("#external-fan-card").dataset.on = "false";
|
||||
$("#external-fan-detail").textContent = "Ждём OUT5";
|
||||
}
|
||||
|
||||
drawToggle("#timer-toggle", elica.timer);
|
||||
$("#timer-detail").textContent = elica.timer ? "Активен" : "Выключен";
|
||||
|
||||
const hoodDisabled = busy || !panelOnline;
|
||||
$("#power-toggle").disabled = hoodDisabled;
|
||||
$$('[data-speed]').forEach(button => { button.disabled = hoodDisabled; });
|
||||
$("#timer-toggle").disabled = hoodDisabled;
|
||||
$("#light-toggle").disabled = hoodDisabled;
|
||||
$("#external-fan-toggle").disabled = busy || !controllerOnline || !external.available;
|
||||
}
|
||||
|
||||
async function request(path, options = {}) {
|
||||
const response = await fetch(path, {
|
||||
cache: "no-store",
|
||||
headers: { Accept: "application/json" },
|
||||
...options,
|
||||
});
|
||||
if (!response.ok) {
|
||||
let message = `Ошибка ${response.status}`;
|
||||
try {
|
||||
const body = await response.json();
|
||||
if (body?.detail && typeof body.detail === "object") {
|
||||
message = [body.detail.message, body.detail.error].filter(Boolean).join(": ") || message;
|
||||
} else message = body?.detail || body?.message || message;
|
||||
} catch (_) {}
|
||||
throw new Error(String(message));
|
||||
}
|
||||
return response.json();
|
||||
}
|
||||
|
||||
async function refresh(silent = false) {
|
||||
if (polling) return;
|
||||
polling = true;
|
||||
try { render(await request("/api/elica/status")); }
|
||||
catch (error) {
|
||||
setPill("API недоступен", "bad");
|
||||
if (!silent) showToast(error.message, true);
|
||||
} finally { polling = false; }
|
||||
}
|
||||
|
||||
async function act(path, source, optimistic = null) {
|
||||
if (busy) return;
|
||||
busy = true;
|
||||
optimistic?.();
|
||||
if (state) render(state);
|
||||
source?.setAttribute("disabled", "");
|
||||
try { render(await request(path, { method: "POST" })); }
|
||||
catch (error) { showToast(error.message, true); await refresh(true); }
|
||||
finally {
|
||||
busy = false;
|
||||
source?.removeAttribute("disabled");
|
||||
if (state) render(state);
|
||||
}
|
||||
}
|
||||
|
||||
$("#power-toggle").addEventListener("click", event => {
|
||||
const next = !Boolean(state?.elica?.power);
|
||||
act(`/api/elica/power/${next ? "on" : "off"}`, event.currentTarget, () => {
|
||||
if (state?.elica) state.elica.power = next;
|
||||
drawToggle("#power-toggle", next);
|
||||
});
|
||||
});
|
||||
|
||||
$$('[data-speed]').forEach(button => button.addEventListener("click", () => {
|
||||
const speed = Number(button.dataset.speed);
|
||||
act(`/api/elica/speed/${speed}`, button, () => {
|
||||
if (state?.elica) { state.elica.power = true; state.elica.speed = speed; }
|
||||
drawSpeed(speed);
|
||||
});
|
||||
}));
|
||||
|
||||
$("#timer-toggle").addEventListener("click", event => {
|
||||
const next = !Boolean(state?.elica?.timer);
|
||||
act(`/api/elica/timer/${next ? "on" : "off"}`, event.currentTarget, () => {
|
||||
if (state?.elica) state.elica.timer = next;
|
||||
drawToggle("#timer-toggle", next);
|
||||
});
|
||||
});
|
||||
|
||||
$("#light-toggle").addEventListener("click", event => {
|
||||
act("/api/elica/light/toggle", event.currentTarget);
|
||||
});
|
||||
|
||||
$("#external-fan-toggle").addEventListener("click", event => {
|
||||
const next = !Boolean(state?.external_fan?.on);
|
||||
act(`/api/elica/external-fan/${next ? "on" : "off"}`, event.currentTarget, () => {
|
||||
if (state?.external_fan) state.external_fan.on = next;
|
||||
drawToggle("#external-fan-toggle", next);
|
||||
$("#external-fan-card").dataset.on = String(next);
|
||||
});
|
||||
});
|
||||
|
||||
$("#open-panel").addEventListener("click", () => {
|
||||
const url = new URL("/ui/elica", window.location.origin);
|
||||
url.searchParams.set("theme", themeMode());
|
||||
window.open(url.toString(), "_blank", "noopener");
|
||||
});
|
||||
|
||||
document.addEventListener("visibilitychange", () => { if (!document.hidden) refresh(true); });
|
||||
refresh();
|
||||
setInterval(() => !document.hidden && !busy && refresh(true), 1500);
|
||||
+241
@@ -0,0 +1,241 @@
|
||||
import { configureTheme, showToast } from "./api.js";
|
||||
|
||||
const $ = selector => document.querySelector(selector);
|
||||
const $$ = selector => [...document.querySelectorAll(selector)];
|
||||
|
||||
const connection = $("#connection");
|
||||
const powerToggle = $("#power-toggle");
|
||||
const powerCaption = $("#power-caption");
|
||||
const speedValue = $("#speed-value");
|
||||
const speedCaption = $("#speed-caption");
|
||||
const speedButtons = $$("[data-speed]");
|
||||
const timerToggle = $("#timer-toggle");
|
||||
const timerCaption = $("#timer-caption");
|
||||
const lightToggle = $("#light-toggle");
|
||||
const externalFanToggle = $("#external-fan-toggle");
|
||||
const externalFanCaption = $("#external-fan-caption");
|
||||
const externalFanCard = $("#external-fan-card");
|
||||
const mqttStatus = $("#mqtt-status");
|
||||
const deviceStatus = $("#device-status");
|
||||
const feedbackStatus = $("#feedback-status");
|
||||
const relay5Status = $("#relay5-status");
|
||||
const diagnosticNote = $("#diagnostic-note");
|
||||
const updatedAt = $("#updated-at");
|
||||
const refreshButton = $("#refresh-button");
|
||||
const themeButton = $("#theme-button");
|
||||
|
||||
configureTheme(themeButton);
|
||||
|
||||
let latest = null;
|
||||
let polling = false;
|
||||
let commandBusy = false;
|
||||
let refreshTimer = null;
|
||||
|
||||
function setTextState(element, text, tone = "") {
|
||||
element.textContent = text;
|
||||
element.className = tone;
|
||||
}
|
||||
|
||||
function setPill(text, tone) {
|
||||
connection.textContent = text;
|
||||
connection.className = `pill ${tone}`;
|
||||
}
|
||||
|
||||
function setToggle(button, enabled, label = null) {
|
||||
const isOn = Boolean(enabled);
|
||||
button.setAttribute("aria-pressed", String(isOn));
|
||||
const text = button.querySelector("span");
|
||||
if (text) text.textContent = label || (isOn ? "ON" : "OFF");
|
||||
else button.textContent = label || (isOn ? "ON" : "OFF");
|
||||
}
|
||||
|
||||
function controllerReady(status) {
|
||||
return Boolean(
|
||||
status?.running &&
|
||||
status?.mqtt_connected &&
|
||||
status?.device_online
|
||||
);
|
||||
}
|
||||
|
||||
function hoodReady(status) {
|
||||
return controllerReady(status) && Boolean(status?.feedback_ready);
|
||||
}
|
||||
|
||||
function render(status) {
|
||||
latest = status;
|
||||
const logical = status?.elica || {};
|
||||
const external = status?.external_fan || {};
|
||||
const ready = controllerReady(status);
|
||||
const feedbackReady = hoodReady(status);
|
||||
|
||||
if (!status?.running) setPill("Сервис остановлен", "bad");
|
||||
else if (!status?.mqtt_connected) setPill("MQTT нет связи", "bad");
|
||||
else if (!status?.device_online) setPill("ESP32 offline", "bad");
|
||||
else if (!status?.feedback_ready) setPill("Синхронизация", "warn");
|
||||
else setPill("Online", "good");
|
||||
|
||||
setToggle(powerToggle, logical.power);
|
||||
powerCaption.textContent = logical.power
|
||||
? `Включена${logical.speed ? ` · скорость ${logical.speed}` : ""}`
|
||||
: "Вытяжка выключена";
|
||||
|
||||
const speed = Number(logical.speed) || 0;
|
||||
speedValue.textContent = speed || "—";
|
||||
speedButtons.forEach(button => {
|
||||
button.classList.toggle("active", speed > 0 && Number(button.dataset.speed) <= speed);
|
||||
});
|
||||
speedCaption.textContent = feedbackReady
|
||||
? (logical.power ? "Фактическая скорость по индикаторам Elica." : "При выборе скорости вытяжка включится автоматически.")
|
||||
: "Ждём синхронизацию входов панели Elica.";
|
||||
|
||||
setToggle(timerToggle, logical.timer);
|
||||
timerCaption.textContent = logical.timer
|
||||
? "Таймер активен · индикатор скорости мигает"
|
||||
: "Таймер выключен";
|
||||
|
||||
if (external.available && typeof external.on === "boolean") {
|
||||
setToggle(externalFanToggle, external.on);
|
||||
externalFanCard.dataset.on = String(external.on);
|
||||
externalFanCaption.textContent = external.on
|
||||
? "Включён · NC замкнут, OUT5 выключен"
|
||||
: "Выключен · NC разомкнут, OUT5 включен";
|
||||
} else {
|
||||
setToggle(externalFanToggle, false, "—");
|
||||
externalFanCard.dataset.on = "false";
|
||||
externalFanCaption.textContent = "Ждём обратную связь OUT5";
|
||||
}
|
||||
|
||||
setTextState(mqttStatus, status?.mqtt_connected ? "Подключён" : "Нет связи", status?.mqtt_connected ? "good" : "bad");
|
||||
setTextState(deviceStatus, status?.device_online ? "Online" : "Offline", status?.device_online ? "good" : "bad");
|
||||
setTextState(feedbackStatus, status?.feedback_ready ? "Синхронизирована" : "Ожидание", status?.feedback_ready ? "good" : "warn");
|
||||
|
||||
if (external.available) {
|
||||
setTextState(relay5Status, external.relay_on ? "ON · NC открыт" : "OFF · NC закрыт", external.relay_on ? "warn" : "good");
|
||||
} else {
|
||||
setTextState(relay5Status, "Нет данных", "warn");
|
||||
}
|
||||
|
||||
const missing = status?.missing_feedback_inputs || [];
|
||||
diagnosticNote.textContent = missing.length
|
||||
? `Не получены входы Elica: ${missing.join(", ")}.`
|
||||
: "Состояния вытяжки подтверждаются по MQTT и физическим входам ESP32.";
|
||||
|
||||
const stamp = status?.last_message_at ? new Date(status.last_message_at) : new Date();
|
||||
updatedAt.textContent = Number.isNaN(stamp.getTime())
|
||||
? "—"
|
||||
: `Обновлено ${stamp.toLocaleTimeString("ru-RU", { hour: "2-digit", minute: "2-digit", second: "2-digit" })}`;
|
||||
|
||||
const disableHood = commandBusy || !feedbackReady;
|
||||
powerToggle.disabled = disableHood;
|
||||
speedButtons.forEach(button => { button.disabled = disableHood; });
|
||||
timerToggle.disabled = disableHood;
|
||||
lightToggle.disabled = disableHood;
|
||||
externalFanToggle.disabled = commandBusy || !ready || !external.available;
|
||||
|
||||
document.body.classList.toggle("pending", commandBusy);
|
||||
}
|
||||
|
||||
async function request(path, options = {}) {
|
||||
const response = await fetch(path, {
|
||||
cache: "no-store",
|
||||
headers: { Accept: "application/json" },
|
||||
...options,
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
let message = `Ошибка ${response.status}`;
|
||||
try {
|
||||
const body = await response.json();
|
||||
if (body?.detail && typeof body.detail === "object") {
|
||||
message = [body.detail.message, body.detail.error].filter(Boolean).join(": ") || message;
|
||||
} else {
|
||||
message = body?.detail || body?.message || message;
|
||||
}
|
||||
} catch (_) {}
|
||||
throw new Error(String(message));
|
||||
}
|
||||
|
||||
return response.json();
|
||||
}
|
||||
|
||||
async function refresh({ silent = false } = {}) {
|
||||
if (polling) return;
|
||||
polling = true;
|
||||
try {
|
||||
render(await request("/api/elica/status"));
|
||||
} catch (error) {
|
||||
setPill("API недоступен", "bad");
|
||||
if (!silent) showToast(error.message, true);
|
||||
} finally {
|
||||
polling = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function command(path, optimistic = null) {
|
||||
if (commandBusy) return;
|
||||
commandBusy = true;
|
||||
if (latest) render(latest);
|
||||
if (optimistic) optimistic();
|
||||
|
||||
try {
|
||||
const status = await request(path, { method: "POST" });
|
||||
render(status);
|
||||
} catch (error) {
|
||||
showToast(error.message, true);
|
||||
await refresh({ silent: true });
|
||||
} finally {
|
||||
commandBusy = false;
|
||||
if (latest) render(latest);
|
||||
}
|
||||
}
|
||||
|
||||
powerToggle.addEventListener("click", () => {
|
||||
const next = !Boolean(latest?.elica?.power);
|
||||
command(`/api/elica/power/${next ? "on" : "off"}`, () => {
|
||||
setToggle(powerToggle, next);
|
||||
powerCaption.textContent = next ? "Включаем…" : "Выключаем…";
|
||||
});
|
||||
});
|
||||
|
||||
speedButtons.forEach(button => button.addEventListener("click", () => {
|
||||
const speed = Number(button.dataset.speed);
|
||||
command(`/api/elica/speed/${speed}`, () => {
|
||||
speedValue.textContent = String(speed);
|
||||
speedButtons.forEach(item => item.classList.toggle("active", item === button));
|
||||
speedCaption.textContent = `Устанавливаем скорость ${speed}…`;
|
||||
});
|
||||
}));
|
||||
|
||||
timerToggle.addEventListener("click", () => {
|
||||
const next = !Boolean(latest?.elica?.timer);
|
||||
command(`/api/elica/timer/${next ? "on" : "off"}`, () => {
|
||||
setToggle(timerToggle, next);
|
||||
timerCaption.textContent = next ? "Включаем таймер…" : "Выключаем таймер…";
|
||||
});
|
||||
});
|
||||
|
||||
lightToggle.addEventListener("click", () => {
|
||||
command("/api/elica/light/toggle", () => {
|
||||
lightToggle.textContent = "Команда…";
|
||||
setTimeout(() => { lightToggle.textContent = "Переключить"; }, 700);
|
||||
});
|
||||
});
|
||||
|
||||
externalFanToggle.addEventListener("click", () => {
|
||||
const next = !Boolean(latest?.external_fan?.on);
|
||||
command(`/api/elica/external-fan/${next ? "on" : "off"}`, () => {
|
||||
setToggle(externalFanToggle, next);
|
||||
externalFanCard.dataset.on = String(next);
|
||||
externalFanCaption.textContent = next ? "Включаем…" : "Выключаем…";
|
||||
});
|
||||
});
|
||||
|
||||
refreshButton.addEventListener("click", () => refresh());
|
||||
|
||||
document.addEventListener("visibilitychange", () => {
|
||||
if (!document.hidden) refresh({ silent: true });
|
||||
});
|
||||
|
||||
refresh();
|
||||
refreshTimer = window.setInterval(() => refresh({ silent: true }), 1000);
|
||||
window.addEventListener("beforeunload", () => window.clearInterval(refreshTimer));
|
||||
Reference in New Issue
Block a user