srivatsavdamaraju's picture
Update app.py
33feeaf verified
raw
history blame
2.31 kB
from flask import Flask, render_template, request
from flask_socketio import SocketIO, emit
app = Flask(__name__)
# Allow all origins for Socket.IO connections
socketio = SocketIO(app, cors_allowed_origins="*")
# Global variables to store the rover commands
forward = False
backward = False
left = False
right = False
stop = False
# Event handler for sending commands to the rover
def command_for_moment_rover():
global forward, backward, left, right, stop
# Check the flag and emit the corresponding command
if forward:
print("Moving Forward")
socketio.emit('rover_control', {'data': 'forward'}, namespace='/')
elif backward:
print("Moving Backward")
socketio.emit('rover_control', {'data': 'backward'}, namespace='/')
elif left:
print("Turning Left")
socketio.emit('rover_control', {'data': 'left'}, namespace='/')
elif right:
print("Turning Right")
socketio.emit('rover_control', {'data': 'right'}, namespace='/')
elif stop:
print("Stopping the rover")
socketio.emit('rover_control', {'data': 'stop'}, namespace='/')
# Route for the UI and buttons
@app.route('/')
def index():
return render_template('index.html')
# Route to handle commands from the UI buttons (POST method)
@app.route('/command_for_the_rover', methods=['POST'])
def command():
global forward, backward, left, right, stop
# Reset all flags
forward = backward = left = right = stop = False
# Check which button was pressed and set corresponding flags
if 'forward' in request.form:
forward = True
if 'backward' in request.form:
backward = True
if 'left' in request.form:
left = True
if 'right' in request.form:
right = True
if 'stop' in request.form:
stop = True
# Call the rover command function to send the socket message
command_for_moment_rover()
# Return to the main page with a confirmation message
return render_template('index.html', message="Command Sent!")
# Socket.IO event listener for connection (for communication purposes)
@socketio.on('connect')
def handle_connect():
print("Client connected")
# Start the Flask-SocketIO app
if __name__ == '__main__':
socketio.run(app, host='0.0.0.0', port=5000)