forked from RyanZotti/Self-Driving-Car
-
Notifications
You must be signed in to change notification settings - Fork 0
/
drive_api.py
239 lines (203 loc) · 9.01 KB
/
drive_api.py
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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
import argparse
import tornado.ioloop
import tornado.web
from datetime import datetime
import os
from operator import itemgetter
import RPi.GPIO as GPIO
import requests
from time import sleep
class PostHandler(tornado.web.RequestHandler):
# I don't understand decorators, but this fixed my "can't set attribute" error
@property
def settings(self):
return self._settings
@settings.setter
def settings(self,settings):
self._settings = settings
def initialize(self, settings):
self.settings = settings
def post(self):
timestamp = datetime.now()
data_json = tornado.escape.json_decode(self.request.body)
allowed_commands = set(['37','38','39','40'])
command = data_json['command']
command = list(command.keys())
command = set(command)
command = allowed_commands & command
file_path = str(os.path.dirname(os.path.realpath(__file__)))+"/session.txt"
log_entry = str(command)+" "+str(timestamp)
log_entries.append((command,timestamp))
with open(file_path,"a") as writer:
writer.write(log_entry+"\n")
print(log_entry)
speed = self.settings['speed']
if '37' in command:
motor.forward_left(speed)
elif '38' in command:
motor.forward(speed)
elif '39' in command:
motor.forward_right(speed)
elif '40' in command:
motor.backward(100)
else:
motor.stop()
# This only works on data from the same live python process. It doesn't
# read from the session.txt file. It only sorts data from the active
# python process. This is required because it reads from a list instead
# of a file on data from the same live python process. It doesn't
# read from the session.txt file. It only sorts data from the active
# log_entries python list
class StoreLogEntriesHandler(tornado.web.RequestHandler):
def get(self):
file_path = str(os.path.dirname(os.path.realpath(__file__)))+"/clean_session.txt"
sorted_log_entries = sorted(log_entries,key=itemgetter(1))
prev_command = set()
allowed_commands = set(['38','37','39','40'])
for log_entry in sorted_log_entries:
command = log_entry[0]
timestamp = log_entry[1]
if len(command ^ prev_command) > 0:
prev_command = command
with open(file_path,"a") as writer:
readable_command = []
for element in list(command):
if element == '37':
readable_command.append("left")
if element == '38':
readable_command.append("up")
if element == '39':
readable_command.append("right")
if element == '40':
readable_command.append("down")
log_entry = str(list(readable_command))+" "+str(timestamp)
writer.write(log_entry+"\n")
print(log_entry)
self.write("Finished")
class MultipleKeysHandler(tornado.web.RequestHandler):
def get(self):
print("HelloWorld")
self.write('''
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script>
var keys = {};
$(document).keydown(function (e) {
keys[e.which] = true;
var json_upload = JSON.stringify({command:keys});
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST", "/post");
xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlhttp.send(json_upload);
printKeys();
});
$(document).keyup(function (e) {
delete keys[e.which];
var json_upload = JSON.stringify({command:keys});
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST", "/post");
xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlhttp.send(json_upload);
printKeys();
});
function printKeys() {
var html = '';
for (var i in keys) {
if (!keys.hasOwnProperty(i)) continue;
html += '<p>' + i + '</p>';
}
$('#out').html(html);
}
</script>
</head>
<body>
Click in this frame, then try holding down some keys
<div id="out"></div>
</body>
</html>
''')
class Motor:
def __init__(self, pinForward, pinBackward, pinControlStraight,pinLeft, pinRight, pinControlSteering):
""" Initialize the motor with its control pins and start pulse-width
modulation """
self.pinForward = pinForward
self.pinBackward = pinBackward
self.pinControlStraight = pinControlStraight
self.pinLeft = pinLeft
self.pinRight = pinRight
self.pinControlSteering = pinControlSteering
GPIO.setup(self.pinForward, GPIO.OUT)
GPIO.setup(self.pinBackward, GPIO.OUT)
GPIO.setup(self.pinControlStraight, GPIO.OUT)
GPIO.setup(self.pinLeft, GPIO.OUT)
GPIO.setup(self.pinRight, GPIO.OUT)
GPIO.setup(self.pinControlSteering, GPIO.OUT)
self.pwm_forward = GPIO.PWM(self.pinForward, 100)
self.pwm_backward = GPIO.PWM(self.pinBackward, 100)
self.pwm_forward.start(0)
self.pwm_backward.start(0)
self.pwm_left = GPIO.PWM(self.pinLeft, 100)
self.pwm_right = GPIO.PWM(self.pinRight, 100)
self.pwm_left.start(0)
self.pwm_right.start(0)
GPIO.output(self.pinControlStraight,GPIO.HIGH)
GPIO.output(self.pinControlSteering,GPIO.HIGH)
def forward(self, speed):
""" pinForward is the forward Pin, so we change its duty
cycle according to speed. """
self.pwm_backward.ChangeDutyCycle(0)
self.pwm_forward.ChangeDutyCycle(speed)
def forward_left(self, speed):
""" pinForward is the forward Pin, so we change its duty
cycle according to speed. """
self.pwm_backward.ChangeDutyCycle(0)
self.pwm_forward.ChangeDutyCycle(speed)
self.pwm_right.ChangeDutyCycle(0)
self.pwm_left.ChangeDutyCycle(100)
def forward_right(self, speed):
""" pinForward is the forward Pin, so we change its duty
cycle according to speed. """
self.pwm_backward.ChangeDutyCycle(0)
self.pwm_forward.ChangeDutyCycle(speed)
self.pwm_left.ChangeDutyCycle(0)
self.pwm_right.ChangeDutyCycle(100)
def backward(self, speed):
""" pinBackward is the forward Pin, so we change its duty
cycle according to speed. """
self.pwm_forward.ChangeDutyCycle(0)
self.pwm_backward.ChangeDutyCycle(speed)
def left(self, speed):
""" pinForward is the forward Pin, so we change its duty
cycle according to speed. """
self.pwm_right.ChangeDutyCycle(0)
self.pwm_left.ChangeDutyCycle(speed)
def right(self, speed):
""" pinForward is the forward Pin, so we change its duty
cycle according to speed. """
self.pwm_left.ChangeDutyCycle(0)
self.pwm_right.ChangeDutyCycle(speed)
def stop(self):
""" Set the duty cycle of both control pins to zero to stop the motor. """
self.pwm_forward.ChangeDutyCycle(0)
self.pwm_backward.ChangeDutyCycle(0)
self.pwm_left.ChangeDutyCycle(0)
self.pwm_right.ChangeDutyCycle(0)
def make_app(settings):
return tornado.web.Application([
(r"/drive",MultipleKeysHandler),(r"/post", PostHandler, {'settings':settings}),
(r"/StoreLogEntries",StoreLogEntriesHandler)
])
if __name__ == "__main__":
# Parse CLI args
ap = argparse.ArgumentParser()
ap.add_argument("-s", "--speed_percent", required=True, help="Between 0 and 100")
args = vars(ap.parse_args())
GPIO.setmode(GPIO.BOARD)
motor = Motor(16, 18, 22, 19, 21, 23)
log_entries = []
settings = {'speed':float(args['speed_percent'])}
app = make_app(settings)
app.listen(81)
tornado.ioloop.IOLoop.current().start()