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
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,
|
||||
}
|
||||
Reference in new issue
Block a user