File size: 2,310 Bytes
33feeaf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
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)