-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathweb_control.py
More file actions
117 lines (89 loc) · 2.63 KB
/
web_control.py
File metadata and controls
117 lines (89 loc) · 2.63 KB
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
import getopt
import os
import sys
from flask import Flask
from custom_modules.serial_command import control, direction, motor
OK = "ok"
ERROR = "error"
def printusage():
print("python3 " + os.path.basename(__file__) + " -c <COM_Port>")
print("<COM_Port>")
print(" Windows: COMx where x is a number")
print(" Linux: /dev/ttyXYZ where XYZ can be S2 or USB0 or any valid tty type")
print(" keep in mind you need root priviledges to acces serial ports in Linux")
print(
" so execute the command in priviledge mode like: sudo python3 "
+ os.path.basename(__file__)
+ " -c /dev/ttyS2"
)
print(" You can use as well environement variable COM_PORT. Arguments will prevent on environment variable")
def get_port_name(argv):
comPort = ""
try:
opts, args = getopt.getopt(argv, "c:h", ["com=", "help"])
except getopt.GetoptError:
printusage()
sys.exit(2)
for opt, arg in opts:
if opt in ("-h", "--help"):
printusage()
sys.exit()
elif opt in ("-c", "--com"):
comPort = arg.strip()
else:
printusage()
sys.exit(2)
if comPort == "":
try:
comPort = os.environ["COM_PORT"]
except KeyError:
printusage()
sys.exit(2)
return comPort
app = Flask(__name__)
ser = control(get_port_name(sys.argv[1:]))
def cleanargs(val):
retval = str(val).split("?")
return retval[0]
@app.route("/")
def hello():
return app.send_static_file("index.html")
@app.route("/motor/<name>/<dir>")
def pilotmotor(name, dir):
val = int(cleanargs(dir))
mot = str(name).lower()
if val in range(0, len(motor) - 1):
if mot == "a":
ser.ChangeMotorA(val)
else:
if mot == "b":
ser.ChangeMotorB(val)
else:
return ERROR
return OK
return ERROR
@app.route("/dir/<dir>")
def pilotdir(dir):
val = int(cleanargs(dir))
if val in range(0, len(direction) - 1):
ser.ChangeDirection(val)
return OK
return ERROR
@app.route("/pwm/<pwm>")
def pilotpwm(pwm):
val = int(cleanargs(pwm))
if val in range(0, 255):
ser.ChangePWM(val)
return OK
return ERROR
@app.route("/stop")
def pilotstop():
ser.ChangeAll(direction.DIR_STRAIGHT, motor.MOTOR_STOP, motor.MOTOR_STOP, 0)
return OK
@app.route("/turns")
def turns():
out = ser.GetTurns()
return str(out)
if __name__ == "__main__":
# run flask, host = 0.0.0.0 needed to get access to it outside of the host
app.run(host="0.0.0.0", port=1337)