- docker-compose: EMQX 5.8.6 (1883/8883/18083), symulator (FastAPI, MQTT 5), sniffer tcpdump - emqx.conf, acl.conf: uwierzytelnianie, autoryzacja (default deny), TLS - hasła wyłącznie w pliku .env (poza repozytorium), konta tworzone przy starcie brokera - skrypty: generowanie certyfikatów, podgląd w Wiresharku, klient SCADA - INSTRUKCJA.md: wykonanie zadań i zbieranie dowodów do sprawozdania - screeny/: zrzuty ekranu do sprawozdania Co-Authored-By: Claude Opus 5.5 <[email protected]>
305 lines
12 KiB
JavaScript
305 lines
12 KiB
JavaScript
"use strict";
|
|
|
|
const $ = (id) => document.getElementById(id);
|
|
let D = {}; // wartości domyślne z serwera
|
|
let mode = "plain"; // plain | tls
|
|
let lastEventId = 0;
|
|
let lastState = null;
|
|
let formDirty = false; // nie nadpisuj pól czujnika, gdy użytkownik je edytuje
|
|
|
|
// ------------------------------------------------------------------ helpers
|
|
async function api(path, body) {
|
|
const opts = body === undefined ? { method: "POST" } :
|
|
{ method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) };
|
|
const res = await fetch(path, opts);
|
|
let data = {};
|
|
try { data = await res.json(); } catch (_) { /* brak treści */ }
|
|
if (!res.ok) {
|
|
const msg = data.error || (data.detail && JSON.stringify(data.detail)) || res.statusText;
|
|
toast(msg, true);
|
|
throw new Error(msg);
|
|
}
|
|
return data;
|
|
}
|
|
|
|
let toastTimer;
|
|
function toast(msg, isErr = false) {
|
|
const t = $("toast");
|
|
t.textContent = msg;
|
|
t.className = "toast" + (isErr ? " err" : "");
|
|
t.hidden = false;
|
|
clearTimeout(toastTimer);
|
|
toastTimer = setTimeout(() => { t.hidden = true; }, 4500);
|
|
}
|
|
|
|
// ------------------------------------------------------------------ połączenie
|
|
function setMode(m, setPort = true) {
|
|
mode = m;
|
|
document.querySelectorAll(".seg").forEach((b) =>
|
|
b.setAttribute("aria-checked", String(b.dataset.mode === m)));
|
|
$("tlsBox").hidden = m !== "tls";
|
|
if (setPort) $("port").value = m === "tls" ? D.tls_port : D.plain_port;
|
|
$("modeHint").textContent = m === "tls"
|
|
? "Ruch szyfrowany: w Wiresharku zobaczysz handshake TLS i „Application Data” zamiast treści."
|
|
: "Ruch jawny: temat, treść oraz login i hasło widać w Wiresharku jako zwykły tekst.";
|
|
}
|
|
|
|
const ACCOUNTS = () => ({
|
|
czujnik: ["czujnik_cisnienia", D.password],
|
|
scada: ["scada_panel", D.scada_password],
|
|
bad: ["czujnik_cisnienia", "zle-haslo"],
|
|
anon: ["", ""],
|
|
});
|
|
|
|
function applyAccount() {
|
|
const acc = ACCOUNTS()[$("account").value];
|
|
if (!acc) return;
|
|
[$("username").value, $("password").value] = acc;
|
|
}
|
|
|
|
async function connect() {
|
|
const btn = $("btnConnect");
|
|
btn.disabled = true;
|
|
btn.textContent = "Łączenie…";
|
|
try {
|
|
await api("/api/connect", {
|
|
host: $("host").value.trim(),
|
|
port: Number($("port").value),
|
|
tls: mode === "tls",
|
|
tls_version: $("tlsVersion").value,
|
|
verify: $("verify").checked,
|
|
ca_file: $("caFile").value.trim(),
|
|
client_id: $("clientId").value.trim(),
|
|
username: $("username").value.trim(),
|
|
password: $("password").value,
|
|
sensor_id: D.sensor_id,
|
|
// status/komendy tylko dla konta czujnika (inne konta nie mają do nich praw)
|
|
status_topic: $("username").value.trim() === "czujnik_cisnienia" ? D.status_topic : "",
|
|
command_topic: $("username").value.trim() === "czujnik_cisnienia" ? D.command_topic : "",
|
|
});
|
|
toast(mode === "tls" ? "Połączono przez TLS" : "Połączono (bez szyfrowania)");
|
|
} catch (_) { /* toast już pokazany */ }
|
|
finally {
|
|
btn.disabled = false;
|
|
btn.textContent = "Połącz";
|
|
poll();
|
|
}
|
|
}
|
|
|
|
// ------------------------------------------------------------------ czujnik
|
|
async function pushSensorConfig() {
|
|
await api("/api/sensor/config", {
|
|
topic: $("topic").value.trim(),
|
|
interval: Number($("interval").value),
|
|
qos: Number($("qos").value),
|
|
setpoint: Number($("setpoint").value),
|
|
});
|
|
formDirty = false;
|
|
}
|
|
|
|
// ------------------------------------------------------------------ render
|
|
function renderConn(m) {
|
|
const pill = $("connPill");
|
|
let cls = "pill-off", txt = "Rozłączono";
|
|
if (m.state === "connecting") { cls = "pill-wait"; txt = "Łączenie…"; }
|
|
if (m.state === "connected") {
|
|
cls = m.tls ? "pill-tls" : "pill-plain";
|
|
txt = `${m.tls ? "TLS" : "Bez szyfrowania"} · ${m.host}:${m.port} · ${m.username || "anonim"}`;
|
|
}
|
|
pill.className = "pill " + cls;
|
|
$("connText").textContent = txt;
|
|
$("btnDisconnect").disabled = m.state === "disconnected";
|
|
|
|
const info = $("tlsInfo");
|
|
if (m.state === "connected" && m.tls_info) {
|
|
const t = m.tls_info;
|
|
info.innerHTML = "";
|
|
for (const [k, v] of [["Protokół", t.version], ["Szyfr", t.cipher], ["Certyfikat", t.subject],
|
|
["Wystawca", t.issuer], ["Ważny do", t.not_after || "—"]]) {
|
|
const dt = document.createElement("dt"); dt.textContent = k;
|
|
const dd = document.createElement("dd"); dd.textContent = v;
|
|
info.append(dt, dd);
|
|
}
|
|
info.hidden = false;
|
|
} else {
|
|
info.hidden = true;
|
|
}
|
|
}
|
|
|
|
function renderSensor(s, m) {
|
|
$("sensorIdLabel").textContent = s.sensor_id;
|
|
$("spLabel").textContent = s.setpoint.toFixed(1);
|
|
$("loLabel").textContent = s.alarm_low;
|
|
$("hiLabel").textContent = s.alarm_high;
|
|
if (s.last) {
|
|
$("pValue").textContent = s.last.p.toFixed(3);
|
|
const b = $("pStatus");
|
|
b.textContent = s.last.s;
|
|
b.className = "badge " + (s.last.s === "OK" ? "ok" : "alarm");
|
|
}
|
|
if (!formDirty && document.activeElement?.closest("#sensorCard") == null) {
|
|
$("topic").value = s.topic;
|
|
$("interval").value = s.interval;
|
|
$("qos").value = String(s.qos);
|
|
$("setpoint").value = s.setpoint;
|
|
}
|
|
$("btnStart").disabled = s.running || m.state !== "connected";
|
|
$("btnStop").disabled = !s.running;
|
|
$("btnStart").textContent = s.running ? "Wysyłanie…" : "Start";
|
|
const st = m.stats;
|
|
$("stats").textContent =
|
|
`Wysłane: ${st.sent} · potwierdzone (PUBACK): ${st.acked} · odrzucone: ${st.denied} · odebrane: ${st.received}` +
|
|
(m.subscriptions.length ? ` · subskrypcje: ${m.subscriptions.join(", ")}` : "");
|
|
}
|
|
|
|
const LV = { ok: "OK", info: "info", warn: "uwaga", error: "błąd", tx: "TX", rx: "RX" };
|
|
|
|
function renderEvents(events) {
|
|
const ol = $("log");
|
|
if (events.length === 0 && ol.children.length === 0) {
|
|
ol.innerHTML = '<li class="empty">Brak zdarzeń — połącz się z brokerem.</li>';
|
|
return;
|
|
}
|
|
const empty = ol.querySelector(".empty");
|
|
if (events.length && empty) empty.remove();
|
|
const atTop = ol.scrollTop < 10;
|
|
for (const e of events) {
|
|
const li = document.createElement("li");
|
|
li.className = "e-" + e.level;
|
|
if (e.level === "tx" && e.message.includes("PUBLISH") && e.detail?.includes('"seq"')) li.dataset.telemetry = "1";
|
|
const t = document.createElement("span"); t.className = "t"; t.textContent = e.time;
|
|
const lv = document.createElement("span"); lv.className = "lv lv-" + e.level; lv.textContent = LV[e.level] || e.level;
|
|
const msg = document.createElement("span"); msg.className = "msg"; msg.textContent = e.message;
|
|
if (e.detail) {
|
|
const d = document.createElement("span"); d.className = "det"; d.textContent = e.detail;
|
|
msg.append(d);
|
|
}
|
|
li.append(t, lv, msg);
|
|
li.hidden = $("hideTelemetry").checked && li.dataset.telemetry === "1";
|
|
ol.prepend(li);
|
|
lastEventId = Math.max(lastEventId, e.id);
|
|
}
|
|
while (ol.children.length > 400) ol.lastElementChild.remove();
|
|
if (atTop) ol.scrollTop = 0;
|
|
}
|
|
|
|
function drawChart(hist, s) {
|
|
const c = $("chart");
|
|
const dpr = window.devicePixelRatio || 1;
|
|
const w = c.clientWidth, h = c.clientHeight;
|
|
if (c.width !== w * dpr) { c.width = w * dpr; c.height = h * dpr; }
|
|
const g = c.getContext("2d");
|
|
g.setTransform(dpr, 0, 0, dpr, 0, 0);
|
|
g.clearRect(0, 0, w, h);
|
|
const css = getComputedStyle(document.documentElement);
|
|
const col = (n) => css.getPropertyValue(n).trim();
|
|
const vals = hist.map((x) => x.p);
|
|
const lo = Math.min(s.alarm_low - 0.5, ...vals), hi = Math.max(s.alarm_high + 0.5, ...vals);
|
|
const y = (v) => h - 18 - ((v - lo) / (hi - lo)) * (h - 28);
|
|
const padL = 34;
|
|
|
|
g.font = "11px system-ui"; g.fillStyle = col("--muted"); g.textBaseline = "middle";
|
|
for (const [v, c2] of [[s.alarm_high, "--err"], [s.setpoint, "--muted"], [s.alarm_low, "--err"]]) {
|
|
g.strokeStyle = col(c2); g.globalAlpha = 0.5; g.setLineDash([4, 4]);
|
|
g.beginPath(); g.moveTo(padL, y(v)); g.lineTo(w, y(v)); g.stroke();
|
|
g.globalAlpha = 1; g.setLineDash([]);
|
|
g.fillText(v.toFixed(1), 2, y(v));
|
|
}
|
|
if (vals.length < 2) {
|
|
g.fillText("Brak pomiarów", padL + 8, h / 2);
|
|
return;
|
|
}
|
|
const n = 60, pts = vals.slice(-n);
|
|
const x = (i) => padL + (i / (n - 1)) * (w - padL - 4);
|
|
g.strokeStyle = col("--accent"); g.lineWidth = 2; g.lineJoin = "round";
|
|
g.beginPath();
|
|
pts.forEach((v, i) => (i ? g.lineTo(x(i), y(v)) : g.moveTo(x(i), y(v))));
|
|
g.stroke();
|
|
const last = pts[pts.length - 1];
|
|
g.fillStyle = col("--accent");
|
|
g.beginPath(); g.arc(x(pts.length - 1), y(last), 3.5, 0, Math.PI * 2); g.fill();
|
|
}
|
|
|
|
// ------------------------------------------------------------------ polling
|
|
async function poll() {
|
|
try {
|
|
const res = await fetch(`/api/state?after=${lastEventId}`);
|
|
const st = await res.json();
|
|
lastState = st;
|
|
renderConn(st.mqtt);
|
|
renderSensor(st.sensor, st.mqtt);
|
|
renderEvents(st.events);
|
|
drawChart(st.history, st.sensor);
|
|
} catch (_) {
|
|
$("connText").textContent = "Brak kontaktu z symulatorem";
|
|
}
|
|
}
|
|
|
|
// ------------------------------------------------------------------ init
|
|
async function init() {
|
|
D = await (await fetch("/api/defaults")).json();
|
|
$("host").value = D.host;
|
|
$("tlsVersion").value = D.tls_version;
|
|
$("verify").checked = D.verify;
|
|
$("caFile").value = D.ca_file;
|
|
$("clientId").value = D.client_id;
|
|
applyAccount();
|
|
setMode(D.tls ? "tls" : "plain");
|
|
$("pubTopic").value = D.command_topic;
|
|
$("pubPayload").value = '{"cmd":"otworz_zawor","value":100}';
|
|
|
|
document.querySelectorAll(".seg").forEach((b) => b.addEventListener("click", () => setMode(b.dataset.mode)));
|
|
$("account").addEventListener("change", applyAccount);
|
|
["username", "password"].forEach((id) => $(id).addEventListener("input", () => { $("account").value = "custom"; }));
|
|
$("btnConnect").addEventListener("click", connect);
|
|
$("btnDisconnect").addEventListener("click", () => api("/api/disconnect").then(poll));
|
|
|
|
["topic", "interval", "qos", "setpoint"].forEach((id) => {
|
|
$(id).addEventListener("input", () => { formDirty = true; });
|
|
$(id).addEventListener("change", () => pushSensorConfig().catch(() => {}));
|
|
});
|
|
$("btnStart").addEventListener("click", async () => {
|
|
if (formDirty) await pushSensorConfig();
|
|
await api("/api/sensor/start").catch(() => {});
|
|
poll();
|
|
});
|
|
$("btnStop").addEventListener("click", () => api("/api/sensor/stop").then(poll));
|
|
$("btnOnce").addEventListener("click", async () => {
|
|
if (formDirty) await pushSensorConfig();
|
|
await api("/api/sensor/once").catch(() => {});
|
|
poll();
|
|
});
|
|
$("btnSpike").addEventListener("click", () => api("/api/sensor/spike").then(poll));
|
|
|
|
document.querySelectorAll("#pubPresets .chip").forEach((c) => c.addEventListener("click", () => {
|
|
$("pubTopic").value = c.dataset.topic;
|
|
$("pubPayload").value = c.dataset.payload;
|
|
}));
|
|
$("btnPublish").addEventListener("click", () => api("/api/publish", {
|
|
topic: $("pubTopic").value, payload: $("pubPayload").value,
|
|
qos: Number($("pubQos").value), retain: $("pubRetain").checked,
|
|
}).then(poll).catch(() => {}));
|
|
$("btnSubscribe").addEventListener("click", () =>
|
|
api("/api/subscribe", { topic: $("subTopic").value, qos: 1 }).then(poll).catch(() => {}));
|
|
|
|
$("hideTelemetry").addEventListener("change", () => {
|
|
document.querySelectorAll("#log li[data-telemetry]").forEach((li) => { li.hidden = $("hideTelemetry").checked; });
|
|
});
|
|
$("btnClear").addEventListener("click", () => api("/api/log/clear").then(() => { $("log").innerHTML = ""; }));
|
|
window.addEventListener("resize", () => lastState && drawChart(lastState.history, lastState.sensor));
|
|
|
|
await poll();
|
|
// po odświeżeniu strony pokaż ustawienia aktywnego połączenia
|
|
const m = lastState?.mqtt;
|
|
if (m && m.state !== "disconnected") {
|
|
setMode(m.tls ? "tls" : "plain", false);
|
|
$("host").value = m.host;
|
|
$("port").value = m.port;
|
|
$("clientId").value = m.client_id;
|
|
if (m.username) $("username").value = m.username;
|
|
}
|
|
setInterval(poll, 1000);
|
|
}
|
|
|
|
init();
|