I have a problem with Flask and Javascript. I want to use a website to control a minirobot with joysticks. I have found nippleJS (https://github.com/yoannmoinet/nipplejs) and included it to my website. I can print the joystick values to the web console, but i need those values at my pythonscript for the robot control. Can anybody help me please? Here is my code: HTML:
<script src="{{url_for('static', filename='nippleJS.js')}}"></script>
<script>
var joystickL = nipplejs.create({
zone: document.getElementById('left'),
mode: 'static',
position: { left: '20%', top: '50%' },
color: 'green',
size: 200
});
var joystickR = nipplejs.create({
zone: document.getElementById('right'),
mode: 'static',
position: { left: '80%', top: '50%' },
color: 'red',
size: 200,
lockY: 1
});
joystickL.on('move', function (evt, nipple) {
var dis = nipple.distance;
var angle = nipple.angle.radian;
var pos = nipple.position;
console.log(dis);
console.log(angle); </script>
And here is my Flask Code:
from flask import Flask, render_template, request, redirect, url_for, jsonify
app = Flask(__name__)
@app.route("/", methods=['GET', 'POST'])
def home():
if request.method == 'POST':
if request.form['btn'] == 'Demo Programme':
return redirect(url_for('demo'))
elif request.form['btn'] == 'Manuelle Steuerung':
return redirect(url_for('steuerung'))
elif request.form['btn'] == 'Erweiterte Optionen':
return redirect(url_for('optionen'))
return render_template('home.html')
Theoretically you could use the fetch() API to send a request to your server which has a JSON body holding the values.
Your on("move") could then look something like this.
joystickL.on('move', function (evt, nipple) {
const data = {
"distance": nipple.distance,
"radian": nipple.angle.radian,
"position": nipple.position,
}
try {
// call to your server with the correct host and username
const response = await fetch("localhost:5000/your-endpoint", {
method: "POST",
data: JSON.parse(data)
})
if(!response.ok){
// your error handling here (if necessary)
}
} catch (error) {
console.log("Something went wrong")
}
}
Depending on the frequency you need to send data e.g. you want more or less realtime data it would be better to use WebSockets. You might also wanna have a look at socket.io.
I believe there also is a socket.io package specific for Flask as you need to adjust frontend and backend if you want to use WebSockets.