fix: 1.4.0 добавил фалйы форм в отслеживание
This commit is contained in:
+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