diff --git a/aaaSonstiges/micropython/testmicpywithmqtt/main.py b/aaaSonstiges/micropython/testmicpywithmqtt/main.py new file mode 100644 index 0000000..b29bba0 --- /dev/null +++ b/aaaSonstiges/micropython/testmicpywithmqtt/main.py @@ -0,0 +1,54 @@ +import urequests +import json +import socket +import network +import time +import ubinascii +from umqtt.simple import MQTTClient +import machine +host = "lires.de" + +# one time dns resolve, damit der arme ESP und nicht wegkocht. +def resolve_ip(hostname): + try: + print(f"🌐 Resolvieren von '{hostname}' ...") + addr_info = socket.getaddrinfo(hostname, 80) + ip = addr_info[0][4][0] + print(f"🔎 IP-Adresse gefunden: {ip}") + return ip + except Exception as e: + print("❌ Fehler beim Resolvieren:", e) + return None + +ip = resolve_ip(host) +if ip is None: + print("❌ Fehler: IP-Adresse konnte nicht aufgelöst werden.") + raise SystemExit(1) +MQTT_BROKER = ip +MQTT_TOPIC = b'iot/testdata' + +#callback +def mqtt_callback(topic, msg): + print("Neue Nachricht:", msg.decode()) + +#send data to the server on the given url +def main(): + client_id = ubinascii.hexlify(machine.unique_id()) + client = MQTTClient(client_id, MQTT_BROKER) + client.set_callback(mqtt_callback) + client.connect() + client.subscribe(MQTT_TOPIC) + print("Warte auf Nachrichten...") + + try: + while True: + client.wait_msg() # blockiert, bis Nachricht ankommt + finally: + client.disconnect() + +main() + + + + + diff --git a/routes/esp_routes.py b/routes/esp_routes.py index ffda1f7..293f682 100644 --- a/routes/esp_routes.py +++ b/routes/esp_routes.py @@ -1,10 +1,30 @@ from flask import Blueprint, render_template, request, jsonify import routes.shared as shared +from flask import Flask, jsonify, request +import paho.mqtt.client as mqtt esp = Blueprint('eps', __name__, url_prefix='/unsecure/esp') +MQTT_BROKER = "localhost" # oder IP/Domain +MQTT_PORT = 1883 +MQTT_TOPIC = "iot/machine" @esp.route('/') def fetch_command(): pCd = shared.pending_command shared.reset_command() - return jsonify(pCd) \ No newline at end of file + return jsonify(pCd) + +@esp.route('/toggle-machine', methods=['POST']) +def toggle_machine(): + pCd = shared.pending_command + pCd['command'] = 'machineToggle' + pCd['command-URL'] = 'NO_URL' + pCd['command-expected'] = 'machineStatusResponse' + pCd['command-expected-URL'] = 'http://lires.de/unsecure/esp/machine-status' + + client = mqtt.Client() + client.connect(MQTT_BROKER, MQTT_PORT, 60) + client.publish(MQTT_TOPIC, pCd) + client.disconnect() + + return jsonify({"status": pCd}) \ No newline at end of file diff --git a/templates/index.html b/templates/index.html index f1c6817..2efc449 100644 --- a/templates/index.html +++ b/templates/index.html @@ -23,16 +23,16 @@