from flask import Flask, request, render_template, jsonify import paho.mqtt.client as mqtt from flask_mysqldb import MySQL app = Flask(__name__) kobuki_message = "empty" def on_message(client, userdata, message): global kobuki_message #set scope for this variable kobuki_message = str(message.payload.decode("utf-8")) print(kobuki_message) # Create an MQTT client instance mqtt_client = mqtt.Client() mqtt_client.username_pw_set("server", "serverwachtwoordofzo") mqtt_client.connect("localhost", 80, 60) mqtt_client.loop_start() mqtt_client.subscribe("kobuki/data") mqtt_client.on_message = on_message # this lines needs to be under the function definition otherwise it cant find which function it needs to use app.config['MYSQL_HOST'] = 'localhost' app.config["MYSQL_USER"] = 'admin' app.config["MYSQL_PASSWORD"] = 'kobuki' app.config["MYSQL_DB"] = 'kobuki' mysql = MySQL(app) @app.route('/') def index(): return render_template('index.html') @app.route('/control', methods=["GET","POST"]) def control(): if request.authorization and request.authorization.username == 'ishak' and request.authorization.password == 'kobuki': return render_template('control.html') else: return ('Unauthorized', 401, {'WWW-Authenticate': 'Basic realm="Login Required"'}) @app.route('/move', methods=['POST']) def move(): data = request.get_json() direction = data.get("direction") # Verstuur de richting via MQTT if direction: mqtt_client.publish("home/commands", direction) # Het topic kan aangepast worden return jsonify({"status": "success", "direction": direction}) @app.route('/data', methods=['GET']) def data(): return kobuki_message @app.route('/phpmyadmin/') def phpmyadmin_passthrough(path): # Laat Apache deze route direct afhandelen return "", 404 @app.route("/database") def database(): cur = mysql.connection.cursor() cur.execute("SELECT * FROM kobuki") if __name__ == '__main__': app.run(debug=True, port=5000)