GruppeC/backend/simulator.py

62 lines
2.7 KiB
Python

# Simuliert den ESP8266: schickt alle 2 s Fantasiewerte an den Server (Entwicklung ohne Hardware).
# Start: python simulator.py [Server-URL] [--szenario NAME] z. B. http://localhost:3000 --szenario hitze
#
# Szenarien (fuer die Vorfuehrung mit dem Unity-Zwilling, Modus "Backend"):
# wechsel (Standard) Temperatur und CO2 schwanken, CO2 ueberschreitet zeitweise 1000 ppm
# normal angenehmes Raumklima (22 °C, ca. 650 ppm)
# hitze Temperatur steigt langsam auf ca. 30 °C -> Unity oeffnet die Fenster
# stickig CO2 steigt langsam auf ca. 1600 ppm -> Unity lueftet (Fenster oder Lueftungsanlage)
# kalt Temperatur faellt auf ca. 17 °C -> Unity heizt
# demo laeuft nacheinander normal -> stickig -> normal -> hitze -> kalt durch (je ca. 1 min)
import argparse
import json
import math
import time
import urllib.request
parser = argparse.ArgumentParser(description="Fake-Messwerte wie vom ESP8266")
parser.add_argument("basis", nargs="?", default="http://localhost:3000", help="Server-URL")
parser.add_argument("--szenario", default="wechsel", choices=["wechsel", "normal", "hitze", "stickig", "kalt", "demo"])
args = parser.parse_args()
ZIELE = { # Zielwerte (Temperatur °C, eCO2 ppm), auf die sich die Werte langsam zubewegen
"normal": (22.0, 650),
"hitze": (30.0, 750),
"stickig": (23.0, 1600),
"kalt": (17.0, 600),
}
DEMO_ABLAUF = ["normal", "stickig", "normal", "hitze", "kalt"]
DEMO_SCHRITTE = 30 # 30 x 2 s = 1 min je Abschnitt
temperatur, eco2 = 22.0, 650.0
schritt = 0
while True:
schritt += 1
if args.szenario == "wechsel":
temperatur = 22 + 2 * math.sin(schritt / 20)
eco2 = 800 + 400 * math.sin(schritt / 25) # ueberschreitet zeitweise 1000 ppm
aktiv = "wechsel"
else:
aktiv = args.szenario
if aktiv == "demo":
aktiv = DEMO_ABLAUF[(schritt // DEMO_SCHRITTE) % len(DEMO_ABLAUF)]
ziel_t, ziel_co2 = ZIELE[aktiv]
temperatur += max(-0.4, min(0.4, ziel_t - temperatur))
eco2 += max(-60.0, min(60.0, ziel_co2 - eco2))
messwert = {
"temperatur": round(temperatur + 0.1 * math.sin(schritt), 1),
"luftfeuchte": round(45 + 5 * math.sin(schritt / 15), 1),
"eco2": round(eco2 + 10 * math.sin(schritt / 3)),
"tvoc": round(70 + 30 * math.sin(schritt / 10) + max(0.0, eco2 - 800) / 10),
}
anfrage = urllib.request.Request(args.basis + "/api/messwerte", data=json.dumps(messwert).encode(),
headers={"Content-Type": "application/json"})
try:
urllib.request.urlopen(anfrage, timeout=3).read()
print(f"gesendet [{aktiv}]", json.dumps(messwert))
except OSError as fehler:
print("Server nicht erreichbar:", fehler)
time.sleep(2)