-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
223 lines (179 loc) · 6.09 KB
/
Copy pathserver.py
File metadata and controls
223 lines (179 loc) · 6.09 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
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
# from PIL import ImageGrab
import random
from flask import Flask, render_template, url_for, jsonify, request, Response
import json
import os
import pickle
import matplotlib.pyplot as plt, mpld3
from optimize import SwerveOptimize
app = Flask(__name__, static_url_path="/static", static_folder="static")
max_v = None
max_a = None
max_theta_dot = None
max_omega = None
max_omega_dot = None
points = []
swerve_opti = None
x = []
y = []
heading = []
v = []
theta = []
t = []
w = []
heading_waypoints = []
def velocity_to_acceleration(time, velocity):
"""
This function converts velocity by time points to acceleration by time points.
:param time:
:param velocity:
:return:
"""
slop = lambda v1, v2, t1, t2: (v1 - v2) / (t1 - t2)
new_time = []
acceleration = []
for i in range(1, len(time)):
try:
s = slop(velocity[i], velocity[i - 1], time[i], time[i - 1])
except ZeroDivisionError:
s = 0
acceleration.append(s)
acceleration.append(s)
new_time.append(time[i-1])
new_time.append(time[i])
return new_time, acceleration
@app.route('/', methods=['GET'])
def index():
return render_template('index.html')
@app.route('/calculate', methods=['POST'])
def calculate():
global max_v, max_a, max_theta_dot, max_omega, max_omega_dot, points
global swerve_opti, x, y, heading, v, theta, t, w, heading_waypoints
content = request.get_json()
# print(content)
try:
kinematics = content['kinematics']
max_v = kinematics['maxV']
max_a = kinematics['maxA']
max_theta_dot = kinematics['maxThetaDot']
max_omega = kinematics['maxOmega']
max_omega_dot = kinematics['maxOmegaDot']
new_points = content['points']
except KeyError:
return "Failed", 402
# print(new_points)
points = [[new_points[0]['x'], new_points[0]['y'], [new_points[0]['rotation'], 0]]]
for i, point in enumerate(new_points):
rotation = None
if 'rotation' not in point:
rotation = None
else:
rotation = point['rotation']
vel = None
if i == len(new_points) - 1:
vel = 0
points.append([point['x'], point['y'], [rotation, vel]])
# print(points)
swerve_opti = SwerveOptimize(max_v, max_a, max_theta_dot, max_omega, max_omega_dot, points)
result = swerve_opti.calculate()
if result == 'Failed':
msg = {'message': 'Calculate failed'}
return jsonify(msg), 417
x, y, heading, v, theta, t, w, heading_waypoints = result
msg = {'message': 'Calculate successed'}
return jsonify(msg), 200
@app.route('/graphs', methods=['GET'])
def graphs():
if not all((any(x), any(y), any(v), any(t))):
return "You must calculate to show the graphs.", 418
fig = plt.figure(figsize=(14, 6))
# plot the trajectory path
plt.subplot2grid(shape=(2, 6), loc=(0, 0), colspan=2)
plt.plot(x, y)
plt.title('Trajectory Path')
# plot the angle
plt.subplot2grid(shape=(2, 6), loc=(0, 2), colspan=2)
plt.plot(t, heading)
plt.title('Heading')
# plot the velocity
plt.subplot2grid(shape=(2, 6), loc=(0, 4), colspan=2)
plt.plot(t, v)
plt.title('Velocity')
# plot theta and omega
plt.subplot2grid(shape=(2, 6), loc=(1, 1), colspan=2)
plt.plot(t, theta)
plt.plot(t, w)
plt.title('Theta and Omega')
# plot the acceleration
plt.subplot2grid(shape=(2,6), loc=(1,3), colspan=2)
plt.plot(*velocity_to_acceleration(t, v))
plt.title('Acceleration')
html_str = mpld3.fig_to_html(fig)
return Response(html_str, mimetype='text/html', status=200)
@app.route('/save', methods=['POST'])
@app.route('/save/<filename>', methods=['POST'])
def save(filename=None):
if filename is None:
msg = {'message': 'There isn\'t file name entered'}
return jsonify(msg), 406
try:
start_dir = os.getcwd()
os.chdir(start_dir + '\\curves')
if not os.path.exists('./' + filename + '/'):
os.makedirs('./' + filename + '/')
os.chdir('./' + filename + '/')
with open(r'{}.pkl'.format(filename), 'wb') as f:
list_points = [[filename, max_v, max_a, max_theta_dot, max_omega, max_omega_dot]]
for index in range(len(points)):
list_points.append(
[points[index][0], points[index][1], points[index][2], points[index][3], points[index][4]])
pickle.dump(list_points, f)
f.close()
# im = ImageGrab.grab()
# im.save(r'{}-field.jpg'.format(filename))
swerve_opti.trajectory(False)
os.chdir(start_dir)
except Exception as e:
print(e)
msg = {'message': 'Save failed'}
return jsonify(msg), 417
msg = {'message': 'Save successed'}
return jsonify(msg), 200
def get_curves_names():
load_curves = []
start_dir = os.getcwd()
os.chdir(start_dir + '\\curves')
for name in os.listdir('.'):
load_curves.append(name)
os.chdir(start_dir)
return load_curves
def get_points_of_load_curve(filename):
load_points = []
with open(r'curves\\{}\\{}.pkl'.format(filename, filename), 'rb') as input_file:
list_points = pickle.load(input_file)
for point in list_points:
if point[3] != '':
load_points.append(point)
return load_points
def point_to_json(point):
return {
'x': point[0],
'y': point[1],
'rotation': point[2],
'v': point[3],
'theta': point[4],
}
@app.route('/load', methods=['GET'])
@app.route('/load/<filename>', methods=['GET'])
def load(filename=None):
if filename is None:
curves_names = get_curves_names()
return jsonify([curve_name for curve_name in curves_names])
curves_names = get_curves_names()
if not filename in curves_names:
msg = {'message': f'This file name: {filename} isn\'t exists'}
return jsonify(msg), 406
load_points = get_points_of_load_curve(filename)
return jsonify([point_to_json(point) for point in load_points])
if __name__ == "__main__":
app.run(debug=True)