Etap 3: broker EMQX z TLS i ACL, symulator czujnika ciśnienia, instrukcja
- 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]>
This commit is contained in:
1 parent
76c79e18e8
commit
9bcca5d9e3
35 files changed
+2162
No files matched your search
@@ -0,0 +1,19 @@
|
||||
FROM python:3.12-slim
|
||||
|
||||
ENV PYTHONUNBUFFERED=1 \
|
||||
PYTHONDONTWRITEBYTECODE=1 \
|
||||
PIP_NO_CACHE_DIR=1 \
|
||||
PIP_DISABLE_PIP_VERSION_CHECK=1
|
||||
|
||||
WORKDIR /srv
|
||||
COPY requirements.txt .
|
||||
RUN pip install -r requirements.txt
|
||||
|
||||
COPY app/ ./app/
|
||||
COPY static/ ./static/
|
||||
|
||||
RUN useradd --uid 1000 --create-home sim
|
||||
USER sim
|
||||
|
||||
EXPOSE 8000
|
||||
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000", "--no-access-log"]
|
||||
Whitespace-only changes.
@@ -0,0 +1,266 @@
|
||||
"""Symulator czujnika ciśnienia MQTT z panelem WWW (FastAPI)."""
|
||||
import json
|
||||
import os
|
||||
import socket
|
||||
import threading
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
from fastapi import FastAPI
|
||||
from fastapi.responses import FileResponse, JSONResponse
|
||||
from fastapi.staticfiles import StaticFiles
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from app.mqtt_manager import EventLog, MqttManager
|
||||
from app.sensor import PressureSensor
|
||||
|
||||
STATIC = Path(__file__).resolve().parent.parent / "static"
|
||||
|
||||
|
||||
def env(name: str, default: str) -> str:
|
||||
return os.getenv(name, default)
|
||||
|
||||
|
||||
DEFAULTS = {
|
||||
"host": env("MQTT_HOST", "emqx"),
|
||||
"plain_port": int(env("MQTT_PLAIN_PORT", "1883")),
|
||||
"tls_port": int(env("MQTT_TLS_PORT", "8883")),
|
||||
"tls": env("MQTT_TLS", "false").lower() in ("1", "true", "yes"),
|
||||
"tls_version": env("MQTT_TLS_VERSION", "1.2"),
|
||||
"verify": True,
|
||||
"ca_file": env("MQTT_CA_FILE", "/certs/ca.crt"),
|
||||
"client_id": env("MQTT_CLIENT_ID", f"pt101-{socket.gethostname()[:6]}"),
|
||||
"username": env("MQTT_USERNAME", "czujnik_cisnienia"),
|
||||
"password": env("MQTT_PASSWORD", ""),
|
||||
"scada_password": env("SCADA_PASSWORD", ""),
|
||||
"sensor_id": env("SENSOR_ID", "PT-101"),
|
||||
"telemetry_topic": env("TOPIC_TELEMETRY", "zaklad/hala1/cisnienie/telemetria"),
|
||||
"status_topic": env("TOPIC_STATUS", "zaklad/hala1/cisnienie/status"),
|
||||
"command_topic": env("TOPIC_COMMANDS", "zaklad/hala1/cisnienie/komendy"),
|
||||
"interval": float(env("PUBLISH_INTERVAL", "2")),
|
||||
"qos": int(env("PUBLISH_QOS", "1")),
|
||||
}
|
||||
|
||||
log = EventLog()
|
||||
sensor = PressureSensor(DEFAULTS["sensor_id"])
|
||||
history: list[dict] = []
|
||||
history_lock = threading.Lock()
|
||||
|
||||
|
||||
class Publisher:
|
||||
"""Wątek cyklicznie wysyłający pomiary."""
|
||||
|
||||
def __init__(self):
|
||||
self.running = False
|
||||
self.interval = DEFAULTS["interval"]
|
||||
self.qos = DEFAULTS["qos"]
|
||||
self.topic = DEFAULTS["telemetry_topic"]
|
||||
self._wake = threading.Event()
|
||||
self._last = time.monotonic()
|
||||
threading.Thread(target=self._loop, daemon=True, name="publisher").start()
|
||||
|
||||
def publish_once(self) -> dict:
|
||||
now = time.monotonic()
|
||||
reading = sensor.read(now - self._last)
|
||||
self._last = now
|
||||
with history_lock:
|
||||
history.append({"t": time.time(), "p": reading["pressure"], "s": reading["status"]})
|
||||
del history[:-120]
|
||||
return mqtt_mgr.publish(self.topic, reading, qos=self.qos, kind="telemetry")
|
||||
|
||||
def _loop(self):
|
||||
while True:
|
||||
self._wake.wait(self.interval)
|
||||
self._wake.clear()
|
||||
if self.running:
|
||||
res = self.publish_once()
|
||||
if not res["ok"] and mqtt_mgr.state == "disconnected":
|
||||
self.running = False
|
||||
log.add("warn", "Zatrzymano wysyłanie pomiarów - brak połączenia")
|
||||
|
||||
def poke(self):
|
||||
self._wake.set()
|
||||
|
||||
|
||||
def handle_command(topic: str, text: str) -> None:
|
||||
"""Komendy od SCADA, np. {"cmd":"set_interval","value":1} lub {"cmd":"set_setpoint","value":5.5}."""
|
||||
if topic != mqtt_mgr.settings.get("command_topic"):
|
||||
return
|
||||
try:
|
||||
cmd = json.loads(text)
|
||||
except json.JSONDecodeError:
|
||||
log.add("warn", "Komenda nie jest poprawnym JSON-em - zignorowano")
|
||||
return
|
||||
name, value = cmd.get("cmd"), cmd.get("value")
|
||||
if name == "set_interval" and isinstance(value, (int, float)) and 0.2 <= value <= 3600:
|
||||
publisher.interval = float(value)
|
||||
publisher.poke()
|
||||
log.add("ok", f"Komenda SCADA: zmieniono interwał na {value} s")
|
||||
elif name == "set_setpoint" and isinstance(value, (int, float)) and 0 <= value <= 50:
|
||||
sensor.setpoint = float(value)
|
||||
log.add("ok", f"Komenda SCADA: wartość zadana = {value} bar")
|
||||
elif name == "start":
|
||||
publisher.running = True
|
||||
publisher.poke()
|
||||
log.add("ok", "Komenda SCADA: start pomiarów")
|
||||
elif name == "stop":
|
||||
publisher.running = False
|
||||
log.add("ok", "Komenda SCADA: stop pomiarów")
|
||||
else:
|
||||
log.add("warn", f"Nieznana komenda: {text}")
|
||||
|
||||
|
||||
mqtt_mgr = MqttManager(log, on_message=handle_command)
|
||||
publisher = Publisher()
|
||||
|
||||
app = FastAPI(title="Symulator czujnika ciśnienia MQTT")
|
||||
app.mount("/static", StaticFiles(directory=STATIC), name="static")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- modele żądań
|
||||
class ConnectReq(BaseModel):
|
||||
host: str = Field(min_length=1, max_length=253)
|
||||
port: int = Field(ge=1, le=65535)
|
||||
tls: bool = False
|
||||
tls_version: str = "1.2"
|
||||
verify: bool = True
|
||||
ca_file: str = "/certs/ca.crt"
|
||||
client_id: str = Field(min_length=1, max_length=64)
|
||||
username: str = ""
|
||||
password: str = ""
|
||||
sensor_id: str = "PT-101"
|
||||
status_topic: str = ""
|
||||
command_topic: str = ""
|
||||
|
||||
|
||||
class SensorReq(BaseModel):
|
||||
topic: str | None = None
|
||||
interval: float | None = Field(default=None, ge=0.2, le=3600)
|
||||
qos: int | None = Field(default=None, ge=0, le=2)
|
||||
setpoint: float | None = Field(default=None, ge=0, le=50)
|
||||
sensor_id: str | None = None
|
||||
|
||||
|
||||
class PublishReq(BaseModel):
|
||||
topic: str = Field(min_length=1)
|
||||
payload: str = ""
|
||||
qos: int = Field(default=1, ge=0, le=2)
|
||||
retain: bool = False
|
||||
|
||||
|
||||
class SubscribeReq(BaseModel):
|
||||
topic: str = Field(min_length=1)
|
||||
qos: int = Field(default=1, ge=0, le=2)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- endpointy
|
||||
@app.get("/")
|
||||
def index():
|
||||
return FileResponse(STATIC / "index.html")
|
||||
|
||||
|
||||
@app.get("/api/defaults")
|
||||
def defaults():
|
||||
return DEFAULTS
|
||||
|
||||
|
||||
@app.get("/api/state")
|
||||
def state(after: int = 0):
|
||||
with history_lock:
|
||||
hist = list(history)
|
||||
return {
|
||||
"mqtt": mqtt_mgr.status(),
|
||||
"sensor": {
|
||||
"running": publisher.running,
|
||||
"interval": publisher.interval,
|
||||
"qos": publisher.qos,
|
||||
"topic": publisher.topic,
|
||||
"sensor_id": sensor.sensor_id,
|
||||
"setpoint": sensor.setpoint,
|
||||
"alarm_low": sensor.alarm_low,
|
||||
"alarm_high": sensor.alarm_high,
|
||||
"last": hist[-1] if hist else None,
|
||||
},
|
||||
"history": hist,
|
||||
"events": log.since(after),
|
||||
}
|
||||
|
||||
|
||||
@app.post("/api/connect")
|
||||
def connect(req: ConnectReq):
|
||||
publisher.running = False
|
||||
sensor.sensor_id = req.sensor_id or sensor.sensor_id
|
||||
res = mqtt_mgr.connect(req.model_dump())
|
||||
return JSONResponse(res, status_code=200 if res["ok"] else 400)
|
||||
|
||||
|
||||
@app.post("/api/disconnect")
|
||||
def disconnect():
|
||||
publisher.running = False
|
||||
mqtt_mgr.disconnect()
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
@app.post("/api/sensor/config")
|
||||
def sensor_config(req: SensorReq):
|
||||
if req.topic is not None:
|
||||
publisher.topic = req.topic.strip()
|
||||
if req.interval is not None:
|
||||
publisher.interval = req.interval
|
||||
publisher.poke()
|
||||
if req.qos is not None:
|
||||
publisher.qos = req.qos
|
||||
if req.setpoint is not None:
|
||||
sensor.setpoint = req.setpoint
|
||||
if req.sensor_id:
|
||||
sensor.sensor_id = req.sensor_id
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
@app.post("/api/sensor/start")
|
||||
def sensor_start():
|
||||
if mqtt_mgr.state != "connected":
|
||||
return JSONResponse({"ok": False, "error": "Najpierw połącz się z brokerem"}, status_code=400)
|
||||
publisher.running = True
|
||||
publisher.poke()
|
||||
log.add("info", f"Start cyklicznego wysyłania co {publisher.interval:g} s na '{publisher.topic}'")
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
@app.post("/api/sensor/stop")
|
||||
def sensor_stop():
|
||||
if publisher.running:
|
||||
log.add("info", "Zatrzymano cykliczne wysyłanie")
|
||||
publisher.running = False
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
@app.post("/api/sensor/once")
|
||||
def sensor_once():
|
||||
res = publisher.publish_once()
|
||||
return JSONResponse(res, status_code=200 if res["ok"] else 400)
|
||||
|
||||
|
||||
@app.post("/api/sensor/spike")
|
||||
def sensor_spike():
|
||||
sensor.spike()
|
||||
log.add("info", "Wymuszono skok ciśnienia (symulacja zakłócenia procesu)")
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
@app.post("/api/publish")
|
||||
def publish(req: PublishReq):
|
||||
res = mqtt_mgr.publish(req.topic.strip(), req.payload, qos=req.qos, retain=req.retain)
|
||||
return JSONResponse(res, status_code=200 if res["ok"] else 400)
|
||||
|
||||
|
||||
@app.post("/api/subscribe")
|
||||
def subscribe(req: SubscribeReq):
|
||||
res = mqtt_mgr.subscribe(req.topic.strip(), qos=req.qos)
|
||||
return JSONResponse(res, status_code=200 if res["ok"] else 400)
|
||||
|
||||
|
||||
@app.post("/api/log/clear")
|
||||
def clear_log():
|
||||
log.clear()
|
||||
return {"ok": True}
|
||||
@@ -0,0 +1,341 @@
|
||||
"""Obsługa połączenia MQTT (paho-mqtt 2.x, protokół MQTT 5) - jawnie lub przez TLS."""
|
||||
import json
|
||||
import os
|
||||
import ssl
|
||||
import threading
|
||||
import time
|
||||
from collections import deque
|
||||
from datetime import datetime
|
||||
|
||||
import paho.mqtt.client as mqtt
|
||||
from paho.mqtt.properties import Properties
|
||||
from paho.mqtt.packettypes import PacketTypes
|
||||
|
||||
TLS_VERSIONS = {
|
||||
"auto": (ssl.TLSVersion.TLSv1_2, ssl.TLSVersion.MAXIMUM_SUPPORTED),
|
||||
"1.2": (ssl.TLSVersion.TLSv1_2, ssl.TLSVersion.TLSv1_2),
|
||||
"1.3": (ssl.TLSVersion.TLSv1_3, ssl.TLSVersion.TLSv1_3),
|
||||
}
|
||||
|
||||
|
||||
class EventLog:
|
||||
"""Bufor zdarzeń wyświetlanych w panelu (z rosnącym ID do odpytywania przyrostowego)."""
|
||||
|
||||
def __init__(self, maxlen: int = 600):
|
||||
self._items = deque(maxlen=maxlen)
|
||||
self._next_id = 1
|
||||
self._lock = threading.Lock()
|
||||
|
||||
def add(self, level: str, message: str, detail: str | None = None) -> None:
|
||||
with self._lock:
|
||||
self._items.append({
|
||||
"id": self._next_id,
|
||||
"time": datetime.now().strftime("%H:%M:%S.%f")[:-3],
|
||||
"level": level, # info | ok | warn | error | tx | rx
|
||||
"message": message,
|
||||
"detail": detail,
|
||||
})
|
||||
self._next_id += 1
|
||||
print(f"[{level.upper():5}] {message}" + (f" | {detail}" if detail else ""), flush=True)
|
||||
|
||||
def since(self, after: int) -> list[dict]:
|
||||
with self._lock:
|
||||
return [e for e in self._items if e["id"] > after]
|
||||
|
||||
def clear(self) -> None:
|
||||
with self._lock:
|
||||
self._items.clear()
|
||||
|
||||
|
||||
class MqttManager:
|
||||
def __init__(self, log: EventLog, on_message=None):
|
||||
self.log = log
|
||||
self.on_message_cb = on_message
|
||||
self.client: mqtt.Client | None = None
|
||||
self.settings: dict = {}
|
||||
self.state = "disconnected" # disconnected | connecting | connected
|
||||
self.tls_info: dict | None = None
|
||||
self.stats = {"sent": 0, "acked": 0, "denied": 0, "received": 0}
|
||||
self._lock = threading.RLock()
|
||||
self._pending: dict[int, dict] = {} # mid -> opis publikacji/subskrypcji
|
||||
self._early: dict[int, tuple] = {} # odpowiedzi, które przyszły przed zapisaniem mid
|
||||
self._connack = threading.Event()
|
||||
self._connack_result: tuple[bool, str] = (False, "")
|
||||
self._subscriptions: list[str] = []
|
||||
|
||||
# ------------------------------------------------------------------ connect
|
||||
def connect(self, s: dict) -> dict:
|
||||
self.disconnect(quiet=True)
|
||||
self.settings = dict(s)
|
||||
mode = "TLS" if s["tls"] else "bez szyfrowania"
|
||||
self.log.add("info", f"Łączenie z {s['host']}:{s['port']} ({mode}) jako '{s['username'] or '(anonim)'}'"
|
||||
f", client_id='{s['client_id']}'")
|
||||
|
||||
client = mqtt.Client(callback_api_version=mqtt.CallbackAPIVersion.VERSION2,
|
||||
client_id=s["client_id"], protocol=mqtt.MQTTv5)
|
||||
if s["username"]:
|
||||
client.username_pw_set(s["username"], s["password"] or None)
|
||||
|
||||
if s["tls"]:
|
||||
client.tls_set_context(self._build_tls_context(s))
|
||||
|
||||
# Ostatnia wola (LWT): broker sam opublikuje "offline", gdy czujnik zniknie bez pożegnania.
|
||||
if s.get("status_topic"):
|
||||
client.will_set(s["status_topic"], json.dumps({"sensor_id": s.get("sensor_id"), "state": "offline"}),
|
||||
qos=1, retain=True)
|
||||
|
||||
client.on_connect = self._on_connect
|
||||
client.on_disconnect = self._on_disconnect
|
||||
client.on_publish = self._on_publish
|
||||
client.on_subscribe = self._on_subscribe
|
||||
client.on_message = self._on_message
|
||||
client.reconnect_delay_set(min_delay=2, max_delay=10)
|
||||
|
||||
with self._lock:
|
||||
self.client = client
|
||||
self.state = "connecting"
|
||||
self.tls_info = None
|
||||
self._connack.clear()
|
||||
|
||||
try:
|
||||
client.connect(s["host"], int(s["port"]), keepalive=30, clean_start=True)
|
||||
except ssl.SSLCertVerificationError as e:
|
||||
return self._fail(f"Błąd weryfikacji certyfikatu TLS: {e.verify_message}", str(e))
|
||||
except ssl.SSLError as e:
|
||||
return self._fail(f"Błąd TLS: {e.reason or e}", str(e))
|
||||
except (OSError, ValueError) as e:
|
||||
return self._fail(f"Nie można połączyć z {s['host']}:{s['port']}: {e}", None)
|
||||
|
||||
if s["tls"]:
|
||||
self._capture_tls_info(client)
|
||||
client.loop_start()
|
||||
|
||||
if not self._connack.wait(8):
|
||||
self.disconnect(quiet=True)
|
||||
return self._fail("Brak odpowiedzi CONNACK od brokera (timeout)", None)
|
||||
ok, msg = self._connack_result
|
||||
if not ok:
|
||||
with self._lock:
|
||||
self.client = None
|
||||
threading.Thread(target=client.loop_stop, daemon=True).start()
|
||||
return {"ok": False, "error": msg}
|
||||
return {"ok": True}
|
||||
|
||||
def _build_tls_context(self, s: dict) -> ssl.SSLContext:
|
||||
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
|
||||
lo, hi = TLS_VERSIONS.get(s.get("tls_version", "auto"), TLS_VERSIONS["auto"])
|
||||
ctx.minimum_version, ctx.maximum_version = lo, hi
|
||||
if s.get("verify", True):
|
||||
ca = s.get("ca_file") or "/certs/ca.crt"
|
||||
if not os.path.isfile(ca):
|
||||
raise ValueError(f"Brak pliku CA: {ca}")
|
||||
ctx.load_verify_locations(cafile=ca)
|
||||
ctx.check_hostname = True
|
||||
ctx.verify_mode = ssl.CERT_REQUIRED
|
||||
else:
|
||||
ctx.check_hostname = False
|
||||
ctx.verify_mode = ssl.CERT_NONE
|
||||
# Opcjonalnie: zapis kluczy sesji TLS, aby Wireshark mógł odszyfrować ruch (demonstracja).
|
||||
keylog = os.getenv("TLS_KEYLOG_FILE")
|
||||
if keylog:
|
||||
ctx.keylog_filename = keylog
|
||||
return ctx
|
||||
|
||||
def _capture_tls_info(self, client: mqtt.Client) -> None:
|
||||
sock = client.socket()
|
||||
if not isinstance(sock, ssl.SSLSocket):
|
||||
return
|
||||
cert = sock.getpeercert() or {}
|
||||
subject = ", ".join("=".join(x) for rdn in cert.get("subject", ()) for x in rdn)
|
||||
issuer = ", ".join("=".join(x) for rdn in cert.get("issuer", ()) for x in rdn)
|
||||
cipher = sock.cipher()
|
||||
self.tls_info = {
|
||||
"version": sock.version(),
|
||||
"cipher": cipher[0] if cipher else None,
|
||||
"subject": subject or "(certyfikat niezweryfikowany)",
|
||||
"issuer": issuer or "-",
|
||||
"not_after": cert.get("notAfter"),
|
||||
}
|
||||
self.log.add("ok", f"Uścisk dłoni TLS zakończony: {sock.version()}, {cipher[0] if cipher else '?'}",
|
||||
f"serwer: {subject or '?'} | wystawca: {issuer or '?'}")
|
||||
|
||||
def _fail(self, msg: str, detail: str | None) -> dict:
|
||||
self.log.add("error", msg, detail)
|
||||
with self._lock:
|
||||
client, self.client = self.client, None
|
||||
self.state = "disconnected"
|
||||
if client:
|
||||
try:
|
||||
client.loop_stop()
|
||||
except Exception:
|
||||
pass
|
||||
return {"ok": False, "error": msg}
|
||||
|
||||
def disconnect(self, quiet: bool = False) -> None:
|
||||
with self._lock:
|
||||
client, self.client = self.client, None
|
||||
was = self.state
|
||||
self.state = "disconnected"
|
||||
self.tls_info = None
|
||||
self._subscriptions = []
|
||||
if client is None:
|
||||
return
|
||||
try:
|
||||
if was == "connected" and self.settings.get("status_topic"):
|
||||
client.publish(self.settings["status_topic"],
|
||||
json.dumps({"sensor_id": self.settings.get("sensor_id"), "state": "offline"}),
|
||||
qos=1, retain=True).wait_for_publish(2)
|
||||
except Exception:
|
||||
pass
|
||||
client.disconnect()
|
||||
client.loop_stop()
|
||||
if not quiet:
|
||||
self.log.add("info", "Rozłączono z brokerem")
|
||||
|
||||
# ------------------------------------------------------------------ callbacks
|
||||
def _on_connect(self, client, userdata, flags, reason_code, properties):
|
||||
if client is not self.client:
|
||||
return
|
||||
if reason_code.is_failure:
|
||||
msg = f"Broker odrzucił połączenie: {reason_code} (kod 0x{reason_code.value:02X})"
|
||||
self.log.add("error", msg)
|
||||
self._connack_result = (False, msg)
|
||||
client.disconnect()
|
||||
with self._lock:
|
||||
self.state = "disconnected"
|
||||
else:
|
||||
with self._lock:
|
||||
self.state = "connected"
|
||||
self._connack_result = (True, "")
|
||||
self.log.add("ok", f"Połączono (CONNACK: {reason_code})")
|
||||
s = self.settings
|
||||
if s.get("status_topic"):
|
||||
self.publish(s["status_topic"], {"sensor_id": s.get("sensor_id"), "state": "online"},
|
||||
qos=1, retain=True, kind="status")
|
||||
if s.get("command_topic"):
|
||||
self.subscribe(s["command_topic"], qos=1)
|
||||
self._connack.set()
|
||||
|
||||
def _on_disconnect(self, client, userdata, flags, reason_code, properties):
|
||||
if client is not self.client:
|
||||
return
|
||||
with self._lock:
|
||||
if self.state == "connected":
|
||||
self.state = "connecting"
|
||||
self.log.add("warn", f"Utracono połączenie z brokerem ({reason_code}) - ponawiam...")
|
||||
|
||||
def _on_publish(self, client, userdata, mid, reason_code, properties):
|
||||
with self._lock:
|
||||
info = self._pending.pop(mid, None)
|
||||
if info is None:
|
||||
self._early[mid] = (reason_code,)
|
||||
return
|
||||
self._report_publish(info, reason_code)
|
||||
|
||||
def _report_publish(self, info: dict, reason_code) -> None:
|
||||
if info["qos"] == 0:
|
||||
return # QoS 0 - brak potwierdzenia od brokera (wpis TX dodany przy wysyłce)
|
||||
if reason_code.is_failure:
|
||||
with self._lock:
|
||||
self.stats["denied"] += 1
|
||||
self.log.add("error", f"ODMOWA publikacji na '{info['topic']}': PUBACK {reason_code} "
|
||||
f"(0x{reason_code.value:02X})",
|
||||
"Broker odrzucił wiadomość - sprawdź logi brokera (authorization_permission_denied).")
|
||||
else:
|
||||
with self._lock:
|
||||
self.stats["acked"] += 1
|
||||
if info.get("kind") != "telemetry":
|
||||
self.log.add("ok", f"Broker potwierdził publikację na '{info['topic']}' (PUBACK: {reason_code})")
|
||||
|
||||
def _on_subscribe(self, client, userdata, mid, reason_codes, properties):
|
||||
with self._lock:
|
||||
info = self._pending.pop(mid, None)
|
||||
if info is None:
|
||||
self._early[mid] = (reason_codes,)
|
||||
return
|
||||
self._report_subscribe(info, reason_codes)
|
||||
|
||||
def _report_subscribe(self, info: dict, reason_codes) -> None:
|
||||
for rc in reason_codes:
|
||||
if rc.is_failure:
|
||||
with self._lock:
|
||||
self.stats["denied"] += 1
|
||||
self.log.add("error", f"ODMOWA subskrypcji '{info['topic']}': SUBACK {rc} (0x{rc.value:02X})")
|
||||
else:
|
||||
with self._lock:
|
||||
if info["topic"] not in self._subscriptions:
|
||||
self._subscriptions.append(info["topic"])
|
||||
self.log.add("ok", f"Zasubskrybowano '{info['topic']}' (przyznane QoS {rc.value})")
|
||||
|
||||
def _on_message(self, client, userdata, msg):
|
||||
with self._lock:
|
||||
self.stats["received"] += 1
|
||||
text = msg.payload.decode("utf-8", errors="replace")
|
||||
self.log.add("rx", f"Odebrano z '{msg.topic}'", text)
|
||||
if self.on_message_cb:
|
||||
try:
|
||||
self.on_message_cb(msg.topic, text)
|
||||
except Exception as e: # nie przerywamy pętli MQTT
|
||||
self.log.add("warn", f"Błąd obsługi wiadomości: {e}")
|
||||
|
||||
# ------------------------------------------------------------------ actions
|
||||
def publish(self, topic: str, payload, qos: int = 1, retain: bool = False, kind: str = "custom") -> dict:
|
||||
with self._lock:
|
||||
client = self.client
|
||||
connected = self.state == "connected"
|
||||
if not client or not connected:
|
||||
return {"ok": False, "error": "Brak połączenia z brokerem"}
|
||||
if not topic or any(c in topic for c in "+#"):
|
||||
return {"ok": False, "error": "Nieprawidłowy temat publikacji (bez znaków + i #)"}
|
||||
data = payload if isinstance(payload, str) else json.dumps(payload, ensure_ascii=False)
|
||||
info = {"topic": topic, "qos": qos, "kind": kind}
|
||||
props = Properties(PacketTypes.PUBLISH)
|
||||
props.ContentType = "application/json"
|
||||
result = client.publish(topic, data, qos=qos, retain=retain, properties=props)
|
||||
if result.rc != mqtt.MQTT_ERR_SUCCESS:
|
||||
msg = f"Publikacja nieudana: {mqtt.error_string(result.rc)}"
|
||||
self.log.add("error", msg)
|
||||
return {"ok": False, "error": msg}
|
||||
with self._lock:
|
||||
self.stats["sent"] += 1
|
||||
early = self._early.pop(result.mid, None)
|
||||
if early is None:
|
||||
self._pending[result.mid] = info
|
||||
self.log.add("tx", f"Wysłano PUBLISH na '{topic}' (QoS {qos}{', retain' if retain else ''})", data)
|
||||
if early is not None:
|
||||
self._report_publish(info, early[0])
|
||||
return {"ok": True, "mid": result.mid}
|
||||
|
||||
def subscribe(self, topic: str, qos: int = 1) -> dict:
|
||||
with self._lock:
|
||||
client = self.client
|
||||
connected = self.state == "connected"
|
||||
if not client or not connected:
|
||||
return {"ok": False, "error": "Brak połączenia z brokerem"}
|
||||
rc, mid = client.subscribe(topic, qos=qos)
|
||||
if rc != mqtt.MQTT_ERR_SUCCESS:
|
||||
return {"ok": False, "error": mqtt.error_string(rc)}
|
||||
info = {"topic": topic}
|
||||
with self._lock:
|
||||
early = self._early.pop(mid, None)
|
||||
if early is None:
|
||||
self._pending[mid] = info
|
||||
self.log.add("tx", f"Wysłano SUBSCRIBE '{topic}' (QoS {qos})")
|
||||
if early is not None:
|
||||
self._report_subscribe(info, early[0])
|
||||
return {"ok": True}
|
||||
|
||||
def status(self) -> dict:
|
||||
with self._lock:
|
||||
s = self.settings
|
||||
return {
|
||||
"state": self.state,
|
||||
"host": s.get("host"),
|
||||
"port": s.get("port"),
|
||||
"tls": bool(s.get("tls")),
|
||||
"username": s.get("username"),
|
||||
"client_id": s.get("client_id"),
|
||||
"tls_info": self.tls_info,
|
||||
"subscriptions": list(self._subscriptions),
|
||||
"stats": dict(self.stats),
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
"""Model fizyczny czujnika ciśnienia (np. przetwornik PT-101 na rurociągu)."""
|
||||
import math
|
||||
import random
|
||||
import threading
|
||||
from datetime import datetime, timezone
|
||||
|
||||
|
||||
class PressureSensor:
|
||||
"""Ciśnienie oscyluje wokół wartości zadanej (proces Ornsteina-Uhlenbecka)
|
||||
z drobnym szumem pomiarowym; można wymusić chwilowy skok ciśnienia."""
|
||||
|
||||
def __init__(self, sensor_id: str = "PT-101", setpoint: float = 6.0):
|
||||
self.sensor_id = sensor_id
|
||||
self.setpoint = setpoint # bar
|
||||
self.alarm_low = 4.5 # bar
|
||||
self.alarm_high = 7.5 # bar
|
||||
self.theta = 0.35 # szybkość powrotu do wartości zadanej
|
||||
self.sigma = 0.12 # zmienność procesu
|
||||
self.noise = 0.01 # szum przetwornika
|
||||
self.value = setpoint
|
||||
self.seq = 0
|
||||
self._lock = threading.Lock()
|
||||
|
||||
def spike(self, delta: float | None = None) -> None:
|
||||
with self._lock:
|
||||
self.value += delta if delta is not None else random.choice([-1, 1]) * random.uniform(1.8, 2.6)
|
||||
|
||||
def read(self, dt: float = 1.0) -> dict:
|
||||
with self._lock:
|
||||
dt = max(0.1, min(dt, 10.0))
|
||||
self.value += self.theta * (self.setpoint - self.value) * dt \
|
||||
+ self.sigma * math.sqrt(dt) * random.gauss(0, 1)
|
||||
self.value = max(0.0, self.value)
|
||||
measured = max(0.0, self.value + random.gauss(0, self.noise))
|
||||
self.seq += 1
|
||||
if measured >= self.alarm_high:
|
||||
status = "ALARM_HIGH"
|
||||
elif measured <= self.alarm_low:
|
||||
status = "ALARM_LOW"
|
||||
else:
|
||||
status = "OK"
|
||||
return {
|
||||
"sensor_id": self.sensor_id,
|
||||
"seq": self.seq,
|
||||
"ts": datetime.now(timezone.utc).isoformat(timespec="milliseconds").replace("+00:00", "Z"),
|
||||
"pressure": round(measured, 3),
|
||||
"unit": "bar",
|
||||
"setpoint": self.setpoint,
|
||||
"status": status,
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fastapi==0.115.6
|
||||
uvicorn==0.34.0
|
||||
paho-mqtt==2.1.0
|
||||
@@ -0,0 +1,304 @@
|
||||
"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();
|
||||
@@ -0,0 +1,158 @@
|
||||
<!doctype html>
|
||||
<html lang="pl">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>Symulator PT-101 · MQTT</title>
|
||||
<link rel="stylesheet" href="/static/style.css">
|
||||
</head>
|
||||
<body>
|
||||
<header class="topbar">
|
||||
<div class="brand">
|
||||
<svg viewBox="0 0 24 24" class="gauge" aria-hidden="true"><path d="M12 4a9 9 0 0 0-9 9 9 9 0 0 0 2 5.6h14A9 9 0 0 0 21 13a9 9 0 0 0-9-9Z" fill="none" stroke="currentColor" stroke-width="1.8"/><path d="m12 13 4-4" stroke="currentColor" stroke-width="2" stroke-linecap="round"/><circle cx="12" cy="13" r="1.6" fill="currentColor"/></svg>
|
||||
<div>
|
||||
<h1>Symulator czujnika ciśnienia</h1>
|
||||
<p class="sub">MQTT 5 · broker EMQX · <span id="sensorIdLabel">PT-101</span></p>
|
||||
</div>
|
||||
</div>
|
||||
<div id="connPill" class="pill pill-off"><span class="dot"></span><span id="connText">Rozłączono</span></div>
|
||||
</header>
|
||||
|
||||
<main class="grid">
|
||||
<!-- ======================= POŁĄCZENIE ======================= -->
|
||||
<section class="card" id="connCard">
|
||||
<h2>1. Połączenie z brokerem</h2>
|
||||
|
||||
<div class="segmented" role="radiogroup" aria-label="Tryb transmisji">
|
||||
<button type="button" class="seg" data-mode="plain" role="radio">
|
||||
<svg viewBox="0 0 24 24"><rect x="5" y="11" width="14" height="10" rx="2"/><path d="M8 11V7a4 4 0 0 1 7.5-2"/></svg>
|
||||
<span><b>Bez szyfrowania</b><small>MQTT · port 1883</small></span>
|
||||
</button>
|
||||
<button type="button" class="seg" data-mode="tls" role="radio">
|
||||
<svg viewBox="0 0 24 24"><rect x="5" y="11" width="14" height="10" rx="2"/><path d="M8 11V7a4 4 0 0 1 8 0v4"/></svg>
|
||||
<span><b>Szyfrowane TLS</b><small>MQTTS · port 8883</small></span>
|
||||
</button>
|
||||
</div>
|
||||
<p class="hint" id="modeHint"></p>
|
||||
|
||||
<div class="row">
|
||||
<label class="grow">Host brokera<input id="host" autocomplete="off"></label>
|
||||
<label class="w-port">Port<input id="port" type="number" min="1" max="65535"></label>
|
||||
</div>
|
||||
|
||||
<div id="tlsBox" class="subbox">
|
||||
<div class="row">
|
||||
<label class="grow">Wersja TLS
|
||||
<select id="tlsVersion">
|
||||
<option value="1.2">TLS 1.2 (pełny handshake widoczny w Wiresharku)</option>
|
||||
<option value="1.3">TLS 1.3</option>
|
||||
<option value="auto">Automatycznie (najwyższa)</option>
|
||||
</select>
|
||||
</label>
|
||||
</div>
|
||||
<label class="check"><input type="checkbox" id="verify"> Weryfikuj certyfikat brokera (zaufane CA + nazwa hosta)</label>
|
||||
<label>Plik certyfikatu CA (w kontenerze)<input id="caFile" autocomplete="off"></label>
|
||||
</div>
|
||||
|
||||
<div class="row">
|
||||
<label class="grow">Konto
|
||||
<select id="account">
|
||||
<option value="czujnik">czujnik_cisnienia (urządzenie)</option>
|
||||
<option value="scada">scada_panel (SCADA)</option>
|
||||
<option value="bad">czujnik_cisnienia + błędne hasło</option>
|
||||
<option value="anon">anonimowo (bez loginu)</option>
|
||||
<option value="custom">własne…</option>
|
||||
</select>
|
||||
</label>
|
||||
</div>
|
||||
<div class="row">
|
||||
<label class="grow">Użytkownik<input id="username" autocomplete="off"></label>
|
||||
<label class="grow">Hasło<input id="password" type="password" autocomplete="off"></label>
|
||||
</div>
|
||||
<label>Client ID<input id="clientId" autocomplete="off"></label>
|
||||
|
||||
<div class="actions">
|
||||
<button id="btnConnect" class="btn primary">Połącz</button>
|
||||
<button id="btnDisconnect" class="btn">Rozłącz</button>
|
||||
</div>
|
||||
|
||||
<dl id="tlsInfo" class="kv" hidden></dl>
|
||||
</section>
|
||||
|
||||
<!-- ======================= POMIAR ======================= -->
|
||||
<section class="card" id="sensorCard">
|
||||
<h2>2. Czujnik — pomiary</h2>
|
||||
<div class="readout">
|
||||
<div>
|
||||
<div class="value"><span id="pValue">—</span><span class="unit">bar</span></div>
|
||||
<div class="meta">wartość zadana <b id="spLabel">6.0</b> bar · alarm < <span id="loLabel">4.5</span> / > <span id="hiLabel">7.5</span></div>
|
||||
</div>
|
||||
<span id="pStatus" class="badge">—</span>
|
||||
</div>
|
||||
<canvas id="chart" height="150" aria-label="Wykres ciśnienia"></canvas>
|
||||
|
||||
<div class="row">
|
||||
<label class="grow">Temat telemetrii<input id="topic" autocomplete="off"></label>
|
||||
</div>
|
||||
<div class="row">
|
||||
<label>Interwał [s]<input id="interval" type="number" step="0.5" min="0.2"></label>
|
||||
<label>QoS
|
||||
<select id="qos"><option>0</option><option>1</option><option>2</option></select>
|
||||
</label>
|
||||
<label>Wartość zadana [bar]<input id="setpoint" type="number" step="0.1" min="0"></label>
|
||||
</div>
|
||||
<div class="actions">
|
||||
<button id="btnStart" class="btn primary">Start</button>
|
||||
<button id="btnStop" class="btn">Stop</button>
|
||||
<button id="btnOnce" class="btn">Wyślij 1 pomiar</button>
|
||||
<button id="btnSpike" class="btn ghost">Skok ciśnienia</button>
|
||||
</div>
|
||||
<p class="stats" id="stats"></p>
|
||||
</section>
|
||||
|
||||
<!-- ======================= TEST ACL ======================= -->
|
||||
<section class="card" id="aclCard">
|
||||
<h2>3. Test uprawnień (ACL)</h2>
|
||||
<p class="hint">Wyślij wiadomość na temat, do którego zalogowane konto nie ma prawa. Przy QoS 1 broker odpowie
|
||||
<code>PUBACK 0x87 Not authorized</code>, a w logach EMQX pojawi się wpis o odmowie.</p>
|
||||
<div class="chips" id="pubPresets">
|
||||
<button type="button" class="chip deny" data-topic="zaklad/hala1/cisnienie/komendy" data-payload='{"cmd":"otworz_zawor","value":100}'>czujnik → komendy ✕</button>
|
||||
<button type="button" class="chip deny" data-topic="zaklad/hala2/cisnienie/telemetria" data-payload='{"pressure":99.9}'>inna hala ✕</button>
|
||||
<button type="button" class="chip ok" data-topic="zaklad/hala1/cisnienie/telemetria" data-payload='{"sensor_id":"PT-101","pressure":6.0,"unit":"bar"}'>telemetria ✓</button>
|
||||
<button type="button" class="chip" data-topic="zaklad/hala1/cisnienie/komendy" data-payload='{"cmd":"set_interval","value":1}'>komenda SCADA</button>
|
||||
</div>
|
||||
<label>Temat<input id="pubTopic" autocomplete="off"></label>
|
||||
<label>Treść (payload)<textarea id="pubPayload" rows="2" spellcheck="false"></textarea></label>
|
||||
<div class="row end">
|
||||
<label>QoS
|
||||
<select id="pubQos"><option>0</option><option selected>1</option><option>2</option></select>
|
||||
</label>
|
||||
<label class="check inline"><input type="checkbox" id="pubRetain"> retain</label>
|
||||
<button id="btnPublish" class="btn primary">Publikuj</button>
|
||||
</div>
|
||||
|
||||
<div class="divider"></div>
|
||||
<div class="row end">
|
||||
<label class="grow">Subskrybuj temat<input id="subTopic" value="#" autocomplete="off"></label>
|
||||
<button id="btnSubscribe" class="btn">Subskrybuj</button>
|
||||
</div>
|
||||
<p class="hint">Np. <code>#</code> lub <code>$SYS/#</code> — oba zabronione dla każdego konta.</p>
|
||||
</section>
|
||||
|
||||
<!-- ======================= DZIENNIK ======================= -->
|
||||
<section class="card" id="logCard">
|
||||
<div class="card-head">
|
||||
<h2>4. Dziennik zdarzeń</h2>
|
||||
<div class="log-tools">
|
||||
<label class="check inline"><input type="checkbox" id="hideTelemetry"> ukryj pomiary</label>
|
||||
<button id="btnClear" class="btn small ghost">Wyczyść</button>
|
||||
</div>
|
||||
</div>
|
||||
<ol id="log" class="log" aria-live="polite"></ol>
|
||||
</section>
|
||||
</main>
|
||||
|
||||
<div id="toast" class="toast" hidden></div>
|
||||
<script src="/static/app.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,181 @@
|
||||
:root {
|
||||
--bg: #f4f5f7;
|
||||
--card: #ffffff;
|
||||
--ink: #1b1f24;
|
||||
--muted: #646d78;
|
||||
--line: #e1e4e8;
|
||||
--field: #fbfbfc;
|
||||
--accent: #0f6e8c;
|
||||
--accent-ink: #ffffff;
|
||||
--ok: #1d7a46;
|
||||
--ok-bg: #e5f4eb;
|
||||
--warn: #9a6400;
|
||||
--warn-bg: #fdf3dc;
|
||||
--err: #b42318;
|
||||
--err-bg: #fde8e6;
|
||||
--tx: #3d5a9e;
|
||||
--rx: #6b3fa0;
|
||||
--plain: #b45309;
|
||||
--tls: #1d7a46;
|
||||
--radius: 10px;
|
||||
color-scheme: light;
|
||||
}
|
||||
@media (prefers-color-scheme: dark) {
|
||||
:root {
|
||||
--bg: #111418;
|
||||
--card: #1a1e24;
|
||||
--ink: #e6e8eb;
|
||||
--muted: #98a1ab;
|
||||
--line: #2c323a;
|
||||
--field: #14181d;
|
||||
--accent: #3aa6c6;
|
||||
--accent-ink: #06161c;
|
||||
--ok: #4fc483;
|
||||
--ok-bg: #143322;
|
||||
--warn: #e6b450;
|
||||
--warn-bg: #33290f;
|
||||
--err: #f2786d;
|
||||
--err-bg: #3a1a17;
|
||||
--tx: #8aa6ea;
|
||||
--rx: #c19ae9;
|
||||
--plain: #f0a04b;
|
||||
--tls: #4fc483;
|
||||
color-scheme: dark;
|
||||
}
|
||||
}
|
||||
|
||||
* { box-sizing: border-box; }
|
||||
[hidden] { display: none !important; }
|
||||
body {
|
||||
margin: 0;
|
||||
background: var(--bg);
|
||||
color: var(--ink);
|
||||
font: 14px/1.45 system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;
|
||||
}
|
||||
code, .mono { font-family: ui-monospace, "JetBrains Mono", "Fira Code", Consolas, monospace; font-size: 12.5px; }
|
||||
|
||||
.topbar {
|
||||
display: flex; align-items: center; justify-content: space-between; gap: 16px; flex-wrap: wrap;
|
||||
padding: 14px 24px; background: var(--card); border-bottom: 1px solid var(--line);
|
||||
position: sticky; top: 0; z-index: 5;
|
||||
}
|
||||
.brand { display: flex; align-items: center; gap: 12px; }
|
||||
.gauge { width: 34px; height: 34px; color: var(--accent); }
|
||||
h1 { font-size: 17px; margin: 0; }
|
||||
.sub { margin: 0; color: var(--muted); font-size: 12.5px; }
|
||||
|
||||
.pill { display: inline-flex; align-items: center; gap: 8px; padding: 6px 12px; border-radius: 999px;
|
||||
font-weight: 600; font-size: 13px; border: 1px solid var(--line); }
|
||||
.pill .dot { width: 9px; height: 9px; border-radius: 50%; background: currentColor; }
|
||||
.pill-off { color: var(--muted); }
|
||||
.pill-wait { color: var(--warn); background: var(--warn-bg); border-color: transparent; }
|
||||
.pill-plain { color: var(--plain); background: var(--warn-bg); border-color: transparent; }
|
||||
.pill-tls { color: var(--tls); background: var(--ok-bg); border-color: transparent; }
|
||||
|
||||
.grid {
|
||||
display: grid; gap: 18px; padding: 20px 24px 40px;
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
max-width: 1400px; margin: 0 auto;
|
||||
}
|
||||
@media (max-width: 960px) { .grid { grid-template-columns: 1fr; padding: 16px; } }
|
||||
|
||||
.card { background: var(--card); border: 1px solid var(--line); border-radius: var(--radius);
|
||||
padding: 18px 20px; min-width: 0; }
|
||||
.card h2 { font-size: 15px; margin: 0 0 14px; }
|
||||
.card-head { display: flex; justify-content: space-between; align-items: center; gap: 12px; margin-bottom: 10px; }
|
||||
.card-head h2 { margin: 0; }
|
||||
|
||||
label { display: flex; flex-direction: column; gap: 4px; color: var(--muted); font-size: 12.5px; margin-bottom: 10px; }
|
||||
input, select, textarea {
|
||||
font: inherit; color: var(--ink); background: var(--field);
|
||||
border: 1px solid var(--line); border-radius: 7px; padding: 7px 9px; width: 100%;
|
||||
}
|
||||
textarea { font-family: ui-monospace, Consolas, monospace; font-size: 12.5px; resize: vertical; }
|
||||
input:focus, select:focus, textarea:focus { outline: 2px solid var(--accent); outline-offset: -1px; }
|
||||
.check { flex-direction: row; align-items: center; gap: 8px; color: var(--ink); }
|
||||
.check input { width: auto; }
|
||||
.check.inline { margin: 0 0 10px; }
|
||||
|
||||
.row { display: flex; gap: 12px; flex-wrap: wrap; }
|
||||
.row > label { flex: 1 1 120px; }
|
||||
.row .grow { flex: 3 1 200px; }
|
||||
.row .w-port { flex: 0 1 110px; }
|
||||
.row.end { align-items: flex-end; }
|
||||
.row.end .btn { margin-bottom: 10px; }
|
||||
|
||||
.segmented { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; margin-bottom: 8px; }
|
||||
.seg {
|
||||
display: flex; align-items: center; gap: 10px; text-align: left; cursor: pointer;
|
||||
padding: 10px 12px; border-radius: 9px; border: 1.5px solid var(--line);
|
||||
background: var(--field); color: var(--ink); font: inherit;
|
||||
}
|
||||
.seg svg { width: 24px; height: 24px; flex: none; fill: none; stroke: currentColor; stroke-width: 1.8; }
|
||||
.seg span { display: flex; flex-direction: column; }
|
||||
.seg small { color: var(--muted); }
|
||||
.seg[data-mode="plain"][aria-checked="true"] { border-color: var(--plain); color: var(--plain); background: var(--warn-bg); }
|
||||
.seg[data-mode="tls"][aria-checked="true"] { border-color: var(--tls); color: var(--tls); background: var(--ok-bg); }
|
||||
.seg[aria-checked="true"] small { color: inherit; opacity: .85; }
|
||||
|
||||
.subbox { border-left: 3px solid var(--tls); padding: 8px 0 2px 12px; margin: 4px 0 12px; }
|
||||
.hint { color: var(--muted); font-size: 12.5px; margin: 0 0 12px; }
|
||||
|
||||
.actions { display: flex; gap: 10px; flex-wrap: wrap; margin-top: 4px; }
|
||||
.btn {
|
||||
font: inherit; font-weight: 600; cursor: pointer; padding: 8px 14px; border-radius: 7px;
|
||||
border: 1px solid var(--line); background: var(--field); color: var(--ink);
|
||||
}
|
||||
.btn:hover { border-color: var(--accent); }
|
||||
.btn.primary { background: var(--accent); color: var(--accent-ink); border-color: var(--accent); }
|
||||
.btn.ghost { background: transparent; }
|
||||
.btn.small { padding: 4px 10px; font-size: 12.5px; }
|
||||
.btn:disabled { opacity: .45; cursor: not-allowed; }
|
||||
|
||||
.kv { display: grid; grid-template-columns: max-content 1fr; gap: 4px 12px; margin: 14px 0 0;
|
||||
padding: 10px 12px; border-radius: 8px; background: var(--ok-bg); font-size: 12.5px; }
|
||||
.kv dt { color: var(--muted); }
|
||||
.kv dd { margin: 0; word-break: break-word; }
|
||||
|
||||
.readout { display: flex; justify-content: space-between; align-items: flex-start; gap: 12px; }
|
||||
.value { font-size: 44px; font-weight: 700; letter-spacing: -.02em; font-variant-numeric: tabular-nums; line-height: 1.05; }
|
||||
.value .unit { font-size: 18px; font-weight: 600; color: var(--muted); margin-left: 6px; }
|
||||
.meta { color: var(--muted); font-size: 12.5px; margin-top: 4px; }
|
||||
.badge { padding: 4px 10px; border-radius: 6px; font-weight: 700; font-size: 12px; background: var(--line); color: var(--muted); }
|
||||
.badge.ok { background: var(--ok-bg); color: var(--ok); }
|
||||
.badge.alarm { background: var(--err-bg); color: var(--err); }
|
||||
#chart { width: 100%; height: 150px; display: block; margin: 12px 0 14px; }
|
||||
.stats { color: var(--muted); font-size: 12.5px; margin: 12px 0 0; }
|
||||
|
||||
.chips { display: flex; flex-wrap: wrap; gap: 8px; margin-bottom: 12px; }
|
||||
.chip { font: inherit; font-size: 12.5px; cursor: pointer; padding: 4px 10px; border-radius: 999px;
|
||||
border: 1px solid var(--line); background: var(--field); color: var(--ink); }
|
||||
.chip.deny { color: var(--err); border-color: color-mix(in srgb, var(--err) 40%, transparent); }
|
||||
.chip.ok { color: var(--ok); border-color: color-mix(in srgb, var(--ok) 40%, transparent); }
|
||||
.divider { border-top: 1px solid var(--line); margin: 6px 0 14px; }
|
||||
|
||||
.log-tools { display: flex; align-items: center; gap: 12px; }
|
||||
.log-tools .check.inline { margin: 0; }
|
||||
.log { list-style: none; margin: 0; padding: 0; max-height: 520px; overflow: auto;
|
||||
border: 1px solid var(--line); border-radius: 8px; background: var(--field); }
|
||||
.log li { display: grid; grid-template-columns: 86px 44px 1fr; gap: 8px; padding: 6px 10px;
|
||||
border-bottom: 1px solid var(--line); font-size: 12.5px; }
|
||||
.log li:last-child { border-bottom: 0; }
|
||||
.log .t { color: var(--muted); font-family: ui-monospace, Consolas, monospace; }
|
||||
.log .lv { font-weight: 700; font-size: 11px; text-transform: uppercase; padding-top: 1px; }
|
||||
.log .msg { min-width: 0; }
|
||||
.log .det { display: block; color: var(--muted); font-family: ui-monospace, Consolas, monospace;
|
||||
word-break: break-all; margin-top: 2px; }
|
||||
.lv-ok { color: var(--ok); } .lv-info { color: var(--muted); } .lv-warn { color: var(--warn); }
|
||||
.lv-error { color: var(--err); } .lv-tx { color: var(--tx); } .lv-rx { color: var(--rx); }
|
||||
.log li.e-error { background: var(--err-bg); }
|
||||
.log .empty { display: block; color: var(--muted); padding: 14px; }
|
||||
|
||||
.toast { position: fixed; right: 20px; bottom: 20px; max-width: 420px; padding: 12px 16px; border-radius: 9px;
|
||||
background: var(--ink); color: var(--bg); font-weight: 600; box-shadow: 0 8px 24px rgb(0 0 0 / .2); z-index: 10; }
|
||||
.toast.err { background: var(--err); color: #fff; }
|
||||
|
||||
@media (max-width: 520px) {
|
||||
.topbar { padding: 12px 16px; }
|
||||
.segmented { grid-template-columns: 1fr; }
|
||||
.log li { grid-template-columns: 70px 1fr; }
|
||||
.log .lv { display: none; }
|
||||
}
|
||||
Reference in new issue
Block a user