debug backend No.1
This commit is contained in:
@@ -22,8 +22,10 @@ from modules.persistence import load_dict, save_dict
|
|||||||
from modules.socketio import resend_static_data
|
from modules.socketio import resend_static_data
|
||||||
from modules.db import create_coffee_entry
|
from modules.db import create_coffee_entry
|
||||||
|
|
||||||
|
oldDataSet = None
|
||||||
|
|
||||||
|
|
||||||
def track_coffee_made(data, flanksUp, flanksDown):
|
def track_coffee_made(data, flanksUp, flanksDown):
|
||||||
"""Track if coffee has been made based on the ESP data."""
|
|
||||||
coffee_made = False
|
coffee_made = False
|
||||||
#logic for tracking coffee made
|
#logic for tracking coffee made
|
||||||
|
|
||||||
@@ -35,21 +37,18 @@ def track_coffee_made(data, flanksUp, flanksDown):
|
|||||||
return
|
return
|
||||||
|
|
||||||
def track_error_water(data, flanksUp, flanksDown):
|
def track_error_water(data, flanksUp, flanksDown):
|
||||||
"""Track if there could be an error with water."""
|
|
||||||
water = load_dict("water")
|
water = load_dict("water")
|
||||||
if water["fill"] <= 7:
|
if water["fill"] <= 7:
|
||||||
return True
|
return True
|
||||||
return False
|
return False
|
||||||
|
|
||||||
def track_error_beans(data, flanksUp, flanksDown):
|
def track_error_beans(data, flanksUp, flanksDown):
|
||||||
"""Track if there could be an error with beans."""
|
|
||||||
beans = load_dict("beans")
|
beans = load_dict("beans")
|
||||||
if beans["fill"] <= 7:
|
if beans["fill"] <= 7:
|
||||||
return True
|
return True
|
||||||
return False
|
return False
|
||||||
|
|
||||||
def track_error(data, flanksUp, flanksDown):
|
def track_error(data, flanksUp, flanksDown):
|
||||||
"""Backrrack an Coffee machine error."""
|
|
||||||
if track_error_water(data, flanksUp, flanksDown):
|
if track_error_water(data, flanksUp, flanksDown):
|
||||||
return "Wasser Leer"
|
return "Wasser Leer"
|
||||||
elif track_error_beans(data, flanksUp, flanksDown):
|
elif track_error_beans(data, flanksUp, flanksDown):
|
||||||
@@ -57,30 +56,36 @@ def track_error(data, flanksUp, flanksDown):
|
|||||||
return "Unbekannter Fehler"
|
return "Unbekannter Fehler"
|
||||||
|
|
||||||
def refactor_and_use_esp_data(data):
|
def refactor_and_use_esp_data(data):
|
||||||
"""Refactor and use the ESP data to update the machine state.
|
"""
|
||||||
Calls track_coffee_made() and track_error functions()."""
|
This function processes the cyclic data from the ESP and updates the machine state accordingly.
|
||||||
# global oldDataSet
|
It also tracks changes in the machine state and handles errors.
|
||||||
|
:param data: Dictionary containing the ESP data.
|
||||||
|
:return: None
|
||||||
|
"""
|
||||||
|
global oldDataSet
|
||||||
|
|
||||||
if 'oldDataSet' not in globals() or oldDataSet is None:
|
if 'oldDataSet' not in globals() or oldDataSet is None:
|
||||||
oldDataSet = data # Initialize oldDataSet with default values
|
oldDataSet = data # Initialize oldDataSet with default values
|
||||||
|
|
||||||
|
|
||||||
flanksUp = {key: (oldDataSet[key] == 0 and data[key] == 1) for key in data}
|
flanksUp = {key: (oldDataSet[key] == 0 and data[key] == 1) for key in data}
|
||||||
flanksDown = {key: (oldDataSet[key] == 1 and data[key] == 0) for key in data}
|
flanksDown = {key: (oldDataSet[key] == 1 and data[key] == 0) for key in data}
|
||||||
|
|
||||||
machine = load_dict("machine")
|
machine = load_dict("machine")
|
||||||
if data["an"] == 0:
|
if data["an"] == 1:
|
||||||
machine["state"] = "ON"
|
machine["state"] = "ON"
|
||||||
elif data["an"] == 1: #elif die Sängerin xD
|
elif data["an"] == 0: #elif die Sängerin xD
|
||||||
machine["state"] = "OFF"
|
machine["state"] = "OFF"
|
||||||
|
|
||||||
if data["bereit"] == 0:
|
if data["bereit"] == 1:
|
||||||
machine["ready"] = True
|
machine["ready"] = True
|
||||||
elif data["bereit"] == 1:
|
elif data["bereit"] == 0:
|
||||||
machine["ready"] = False
|
machine["ready"] = False
|
||||||
|
|
||||||
if data["fehler"] == 0:
|
if data["fehler"] == 1:
|
||||||
machine["berror"] = True
|
machine["berror"] = True
|
||||||
machine["error"] = track_error(data, flanksUp, flanksDown)
|
machine["error"] = track_error(data, flanksUp, flanksDown)
|
||||||
elif data["fehler"] == 1:
|
elif data["fehler"] == 0:
|
||||||
machine["berror"] = False
|
machine["berror"] = False
|
||||||
machine["error"] = "Keine Fehler"
|
machine["error"] = "Keine Fehler"
|
||||||
|
|
||||||
|
|||||||
20
server.py
20
server.py
@@ -32,7 +32,6 @@ app.register_blueprint(esp)
|
|||||||
|
|
||||||
# MQTT Callback-Funktionen
|
# MQTT Callback-Funktionen
|
||||||
def on_connect(client, userdata, flags, rc):
|
def on_connect(client, userdata, flags, rc):
|
||||||
"""Callback-Funktion, die aufgerufen wird, wenn der Client sich mit dem Broker verbindet."""
|
|
||||||
print(f"[MQTT] Verbunden mit Code {rc}")
|
print(f"[MQTT] Verbunden mit Code {rc}")
|
||||||
client.subscribe(MQTT_TOPIC_SUB)
|
client.subscribe(MQTT_TOPIC_SUB)
|
||||||
client.subscribe(MQTT_TOPIC_RETURN)
|
client.subscribe(MQTT_TOPIC_RETURN)
|
||||||
@@ -40,18 +39,20 @@ def on_connect(client, userdata, flags, rc):
|
|||||||
print(f"[MQTT] Subscribed to topic: {MQTT_TOPIC_SUB}")
|
print(f"[MQTT] Subscribed to topic: {MQTT_TOPIC_SUB}")
|
||||||
|
|
||||||
def on_message(client, userdata, msg):
|
def on_message(client, userdata, msg):
|
||||||
"""Callback-Funktion, die aufgerufen wird, wenn eine Nachricht empfangen wird."""
|
|
||||||
if msg.topic == MQTT_TOPIC_SUB:
|
if msg.topic == MQTT_TOPIC_SUB:
|
||||||
print(f"[MQTT] Nachricht empfangen: {msg.topic} -> {msg.payload.decode()}")
|
print(f"[MQTT] Nachricht empfangen: {msg.topic} -> {msg.payload.decode()}")
|
||||||
esp_conn_infos["last_seen"] = datetime.now()
|
esp_conn_infos["last_seen"] = datetime.now()
|
||||||
refactor_and_use_esp_data(msg.payload.decode()) # form modules other
|
payload = json.loads(msg.payload.decode())
|
||||||
|
refactor_and_use_esp_data(payload) # form modules other
|
||||||
elif msg.topic == MQTT_TOPIC_RETURN:
|
elif msg.topic == MQTT_TOPIC_RETURN:
|
||||||
print(f"[MQTT] Nachricht empfangen: {msg.topic} -> {msg.payload.decode()}")
|
print(f"[MQTT] Nachricht empfangen: {msg.topic} -> {msg.payload.decode()}")
|
||||||
try:
|
try:
|
||||||
payload = json.loads(msg.payload.decode())
|
payload = json.loads(msg.payload.decode())
|
||||||
command_id = payload.get("command_id")
|
command_id = payload.get("command_id")
|
||||||
if command_id:
|
if command_id and payload["status"] == "served":
|
||||||
update_command_status(command_id, "served") # form modules db
|
update_command_status(command_id, "served")
|
||||||
|
elif command_id:
|
||||||
|
update_command_status(command_id, "rejected")
|
||||||
else:
|
else:
|
||||||
print("[MQTT] Keine command_id im Payload gefunden.")
|
print("[MQTT] Keine command_id im Payload gefunden.")
|
||||||
except json.JSONDecodeError as e:
|
except json.JSONDecodeError as e:
|
||||||
@@ -62,7 +63,6 @@ def on_message(client, userdata, msg):
|
|||||||
|
|
||||||
# MQTT-Thread
|
# MQTT-Thread
|
||||||
def mqtt_thread():
|
def mqtt_thread():
|
||||||
"""Thread, der die MQTT-Verbindung aufbaut und Nachrichten verarbeitet."""
|
|
||||||
client = mqtt.Client()
|
client = mqtt.Client()
|
||||||
client.on_connect = on_connect
|
client.on_connect = on_connect
|
||||||
client.on_message = on_message
|
client.on_message = on_message
|
||||||
@@ -71,7 +71,7 @@ def mqtt_thread():
|
|||||||
|
|
||||||
# DB-Cleanup-Thread
|
# DB-Cleanup-Thread
|
||||||
def cleanup_old_commands():
|
def cleanup_old_commands():
|
||||||
"""Thread, der alle 5 Minuten die Datenbank nach 'pending' Befehlen durchsucht und diese auf 'failed' setzt, wenn sie älter als 5 Minuten sind."""
|
|
||||||
db_path = os.path.join(os.path.dirname(__file__), "db", "commands.db")
|
db_path = os.path.join(os.path.dirname(__file__), "db", "commands.db")
|
||||||
|
|
||||||
while True:
|
while True:
|
||||||
@@ -100,7 +100,6 @@ def cleanup_old_commands():
|
|||||||
|
|
||||||
# Clear commands DB
|
# Clear commands DB
|
||||||
def clear_commands_db():
|
def clear_commands_db():
|
||||||
"""Löscht alle Einträge in der commands- und coffee-Tabelle der Datenbank."""
|
|
||||||
import os
|
import os
|
||||||
import sqlite3
|
import sqlite3
|
||||||
|
|
||||||
@@ -125,12 +124,14 @@ def clear_commands_db():
|
|||||||
|
|
||||||
# Motitior ESP-Connection
|
# Motitior ESP-Connection
|
||||||
def monitor_esp_connection():
|
def monitor_esp_connection():
|
||||||
"""Überwacht die Verbindung zum ESP und setzt die Verbindung auf ungültig, wenn der ESP länger als 3 Minuten nicht gesehen wurde."""
|
|
||||||
while True:
|
while True:
|
||||||
if esp_conn_infos["last_seen"]:
|
if esp_conn_infos["last_seen"]:
|
||||||
time_diff = datetime.now() - esp_conn_infos["last_seen"]
|
time_diff = datetime.now() - esp_conn_infos["last_seen"]
|
||||||
if time_diff > timedelta(minutes=3):
|
if time_diff > timedelta(minutes=3):
|
||||||
esp_conn_infos["connection_valid"] = False
|
esp_conn_infos["connection_valid"] = False
|
||||||
|
data = load_dict("machine")
|
||||||
|
data["state"] = "OFF"
|
||||||
|
save_dict("machine", data)
|
||||||
resend_static_data()
|
resend_static_data()
|
||||||
time.sleep(60) # einmal pro Minute die Verbindung zum ESP prüfen
|
time.sleep(60) # einmal pro Minute die Verbindung zum ESP prüfen
|
||||||
|
|
||||||
@@ -141,7 +142,6 @@ threading.Thread(target=monitor_esp_connection, daemon=True).start()
|
|||||||
threading.Thread(target=mqtt_thread, daemon=True).start()
|
threading.Thread(target=mqtt_thread, daemon=True).start()
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
#
|
|
||||||
#clear_commands_db()
|
#clear_commands_db()
|
||||||
socketio.run(app, host='0.0.0.0', port=3060, allow_unsafe_werkzeug=True)
|
socketio.run(app, host='0.0.0.0', port=3060, allow_unsafe_werkzeug=True)
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user