Files
J2S1-Kobuki/src/Python/flask/web/app.py
2024-12-02 12:58:14 +00:00

57 lines
1.7 KiB
Python

from flask import Flask, request, render_template, jsonify
import paho.mqtt.client as mqtt
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", 1884, 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.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/<path:path>')
def phpmyadmin_passthrough(path):
# Laat Apache deze route direct afhandelen
return "", 404
if __name__ == '__main__':
app.run(debug=True, port=5000)