Files
J2S1-Kobuki/src/Python/flask/web/app.py
2024-12-11 14:54:33 +01:00

77 lines
2.3 KiB
Python

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/<path:path>')
def phpmyadmin_passthrough(path):
# Laat Apache deze route direct afhandelen
return "", 404
@app.route("/database")
def database():
try:
cur = mysql.connection.cursor()
cur.execute("SELECT * FROM kobuki_data")
rows = cur.fetchall() # Haal alle rijen op uit het resultaat
cur.close()
return str(rows)
except Exception as e:
print(f"Database error: {e}")
return "Er is een fout opgetreden bij het ophalen van de databasegegevens.", 500
if __name__ == '__main__':
app.run(debug=True, port=5000)