feat: implement command status update and enhance MQTT message handling

This commit is contained in:
derlole
2025-05-08 13:26:43 +00:00
parent c3d27b9e37
commit 20fa37b0d9
6 changed files with 54 additions and 14 deletions

View File

@@ -30,4 +30,4 @@ CREATE TABLE IF NOT EXISTS commands (
conn.commit()
conn.close()
print(f"Datenbank erstellt unter: {db_path}")
print(f"[DB]Datenbank erstellt unter: {db_path}")

22
modules/db.py Normal file
View File

@@ -0,0 +1,22 @@
import sqlite3
import os
from datetime import datetime, timedelta
DB_PATH = os.path.join(os.path.dirname(__file__), '../db/commands.db')
### THIS CODE IS NOT PROOFED BUT LOOKS RIGHT###
def update_command_status(command_id, status):
conn = sqlite3.connect(DB_PATH)
cursor = conn.cursor()
cursor.execute("""
UPDATE commands
SET status = ?
WHERE command_id = ?
""", (status, command_id))
conn.commit()
conn.close()
print(f"[DB] Befehl {command_id} auf {status} aktualisiert.")
return status
### THIS CODE IS NOT PROOFED BUT LOOKS RIGHT###

4
modules/other.py Normal file
View File

@@ -0,0 +1,4 @@
def refactor_and_use_esp_data(data):
return

View File

@@ -29,16 +29,12 @@ def esp_online():
esp_conn_infos["last_seen"] = datetime.now()
esp_conn_infos["connection_valid"] = True
resend_static_data()
print(f"ESP ONLINE von IP: {esp_ip}, roher IP: {sender_ip}")
return jsonify({"status": "ok"})
@esp.route('/toggle-machine', methods=['POST'])
def toggle_machine():
print("ESP: toggle-machine")
randID = random.randint(1000, 9999)
fullCommand = {'command': 'toggle_machine', 'status': 'pending', 'command_id': randID}
print("ESP: toggle-machine 1")
conn = sqlite3.connect(DB_PATH)
cursor = conn.cursor()
@@ -49,10 +45,9 @@ def toggle_machine():
conn.commit()
conn.close()
print("ESP: toggle-machine 2")
client = mqtt.Client()
client.connect(MQTT_BROKER, MQTT_PORT, 60)
client.publish(MQTT_TOPIC, json.dumps(fullCommand))
client.disconnect()
print("ESP: toggle-machine 3")
return jsonify({"status": json.dumps(fullCommand)})

View File

@@ -9,11 +9,15 @@ from datetime import datetime, timedelta
import sqlite3
from modules.persistence import load_dict, save_dict, esp_conn_infos
from modules.socketio import socketio, resend_static_data
from modules.db import update_command_status
import json
from modules.other import refactor_and_use_esp_data
MQTT_BROKER = "localhost"
MQTT_PORT = 1883
MQTT_TOPIC_SUB = "coffee/status"
MQTT_TOPIC_SEND = "coffee/command"
MQTT_TOPIC_RETURN = "coffee/return"
app = Flask(__name__, static_url_path='/unsecure/static')
@@ -30,15 +34,29 @@ app.register_blueprint(esp)
def on_connect(client, userdata, flags, rc):
print(f"[MQTT] Verbunden mit Code {rc}")
client.subscribe(MQTT_TOPIC_SUB)
client.subscribe(MQTT_TOPIC_RETURN)
print(f"[MQTT] Subscribed to topic: {MQTT_TOPIC_RETURN}")
print(f"[MQTT] Subscribed to topic: {MQTT_TOPIC_SUB}")
def on_message(client, userdata, msg):
if msg.topic == MQTT_TOPIC_SUB:
print(f"[MQTT] Nachricht empfangen: {msg.topic} -> {msg.payload.decode()}")
# Optional an Clients senden
socketio.emit('mqtt_message', {
'topic': msg.topic,
'message': msg.payload.decode()
})
refactor_and_use_esp_data(msg.payload.decode())
elif msg.topic == MQTT_TOPIC_RETURN:
print(f"[MQTT] Nachricht empfangen: {msg.topic} -> {msg.payload.decode()}")
try:
payload = json.loads(msg.payload.decode())
command_id = payload.get("command_id")
if command_id:
update_command_status(command_id, "served") # form modules
else:
print("[MQTT] Keine command_id im Payload gefunden.")
except json.JSONDecodeError as e:
print(f"[MQTT] Fehler beim Dekodieren der Nachricht: {e}")
else:
print(f"[MQTT] Unbekanntes Topic: {msg.topic}")
return
# MQTT-Thread
def mqtt_thread():
@@ -108,7 +126,7 @@ def monitor_esp_connection():
threading.Thread(target=cleanup_old_commands, daemon=True).start()
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__':
#clear_commands_db()

View File

@@ -174,6 +174,7 @@ header {
}
.not:hover {
background: #5f5f5f;
cursor: default;
}
.clickable .top-left-text {
position: absolute;