forked from udacity/nd013-c6-control-starter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.cpp
428 lines (338 loc) · 12.4 KB
/
main.cpp
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
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
/**********************************************
* Self-Driving Car Nano-degree - Udacity
* Created on: September 20, 2020
* Author: Munir Jojo-Verge
Aaron Brown
**********************************************/
/**
* @file main.cpp
**/
#include <string>
#include <array>
#include <cfloat>
#include <chrono>
#include <cmath>
#include <iostream>
#include <random>
#include <sstream>
#include <stdexcept>
#include <string>
#include <thread>
#include <tuple>
#include <vector>
#include <iostream>
#include <fstream>
#include <typeinfo>
#include "json.hpp"
#include <carla/client/ActorBlueprint.h>
#include <carla/client/BlueprintLibrary.h>
#include <carla/client/Client.h>
#include <carla/client/Map.h>
#include <carla/client/Sensor.h>
#include <carla/client/TimeoutException.h>
#include <carla/client/World.h>
#include <carla/geom/Transform.h>
#include <carla/image/ImageIO.h>
#include <carla/image/ImageView.h>
#include <carla/sensor/data/Image.h>
#include "Eigen/QR"
#include "behavior_planner_FSM.h"
#include "motion_planner.h"
#include "planning_params.h"
#include "utils.h"
#include "pid_controller.h"
#include <limits>
#include <iostream>
#include <fstream>
#include <uWS/uWS.h>
#include <math.h>
#include <vector>
#include <cmath>
#include <time.h>
using namespace std;
using json = nlohmann::json;
#define _USE_MATH_DEFINES
string hasData(string s) {
auto found_null = s.find("null");
auto b1 = s.find_first_of("{");
auto b2 = s.find_first_of("}");
if (found_null != string::npos) {
return "";
}
else if (b1 != string::npos && b2 != string::npos) {
return s.substr(b1, b2 - b1 + 1);
}
return "";
}
template <typename T> int sgn(T val) {
return (T(0) < val) - (val < T(0));
}
double angle_between_points(double x1, double y1, double x2, double y2){
return atan2(y2-y1, x2-x1);
}
BehaviorPlannerFSM behavior_planner(
P_LOOKAHEAD_TIME, P_LOOKAHEAD_MIN, P_LOOKAHEAD_MAX, P_SPEED_LIMIT,
P_STOP_THRESHOLD_SPEED, P_REQ_STOPPED_TIME, P_REACTION_TIME,
P_MAX_ACCEL, P_STOP_LINE_BUFFER);
// Decalre and initialized the Motion Planner and all its class requirements
MotionPlanner motion_planner(P_NUM_PATHS, P_GOAL_OFFSET, P_ERR_TOLERANCE);
bool have_obst = false;
vector<State> obstacles;
void path_planner(vector<double>& x_points, vector<double>& y_points, vector<double>& v_points, double yaw, double velocity, State goal, bool is_junction, string tl_state, vector< vector<double> >& spirals_x, vector< vector<double> >& spirals_y, vector< vector<double> >& spirals_v, vector<int>& best_spirals){
State ego_state;
ego_state.location.x = x_points[x_points.size()-1];
ego_state.location.y = y_points[y_points.size()-1];
ego_state.velocity.x = velocity;
if( x_points.size() > 1 ){
ego_state.rotation.yaw = angle_between_points(x_points[x_points.size()-2], y_points[y_points.size()-2], x_points[x_points.size()-1], y_points[y_points.size()-1]);
ego_state.velocity.x = v_points[v_points.size()-1];
if(velocity < 0.01)
ego_state.rotation.yaw = yaw;
}
Maneuver behavior = behavior_planner.get_active_maneuver();
goal = behavior_planner.state_transition(ego_state, goal, is_junction, tl_state);
if(behavior == STOPPED){
int max_points = 20;
double point_x = x_points[x_points.size()-1];
double point_y = y_points[x_points.size()-1];
while( x_points.size() < max_points ){
x_points.push_back(point_x);
y_points.push_back(point_y);
v_points.push_back(0);
}
return;
}
auto goal_set = motion_planner.generate_offset_goals(goal);
auto spirals = motion_planner.generate_spirals(ego_state, goal_set);
auto desired_speed = utils::magnitude(goal.velocity);
State lead_car_state; // = to the vehicle ahead...
if(spirals.size() == 0){
cout << "Error: No spirals generated " << endl;
return;
}
for(int i = 0; i < spirals.size(); i++){
auto trajectory = motion_planner._velocity_profile_generator.generate_trajectory( spirals[i], desired_speed, ego_state,
lead_car_state, behavior);
vector<double> spiral_x;
vector<double> spiral_y;
vector<double> spiral_v;
for(int j = 0; j < trajectory.size(); j++){
double point_x = trajectory[j].path_point.x;
double point_y = trajectory[j].path_point.y;
double velocity = trajectory[j].v;
spiral_x.push_back(point_x);
spiral_y.push_back(point_y);
spiral_v.push_back(velocity);
}
spirals_x.push_back(spiral_x);
spirals_y.push_back(spiral_y);
spirals_v.push_back(spiral_v);
}
best_spirals = motion_planner.get_best_spiral_idx(spirals, obstacles, goal);
int best_spiral_idx = -1;
if(best_spirals.size() > 0)
best_spiral_idx = best_spirals[best_spirals.size()-1];
int index = 0;
int max_points = 20;
int add_points = spirals_x[best_spiral_idx].size();
while( x_points.size() < max_points && index < add_points ){
double point_x = spirals_x[best_spiral_idx][index];
double point_y = spirals_y[best_spiral_idx][index];
double velocity = spirals_v[best_spiral_idx][index];
index++;
x_points.push_back(point_x);
y_points.push_back(point_y);
v_points.push_back(velocity);
}
}
void set_obst(vector<double> x_points, vector<double> y_points, vector<State>& obstacles, bool& obst_flag){
for( int i = 0; i < x_points.size(); i++){
State obstacle;
obstacle.location.x = x_points[i];
obstacle.location.y = y_points[i];
obstacles.push_back(obstacle);
}
obst_flag = true;
}
int main ()
{
cout << "starting server" << endl;
uWS::Hub h;
double new_delta_time;
int i = 0;
fstream file_steer;
file_steer.open("steer_pid_data.txt", std::ofstream::out | std::ofstream::trunc);
file_steer.close();
fstream file_throttle;
file_throttle.open("throttle_pid_data.txt", std::ofstream::out | std::ofstream::trunc);
file_throttle.close();
time_t prev_timer;
time_t timer;
time(&prev_timer);
// initialize pid steer
/**
* TODO (Step 1): create pid (pid_steer) for steer command and initialize values
**/
// initialize pid throttle
/**
* TODO (Step 1): create pid (pid_throttle) for throttle command and initialize values
**/
PID pid_steer = PID();
PID pid_throttle = PID();
pid_steer.Init(0.32, 0.003, 0.1, 1.2, -1.2);
pid_throttle.Init(0.2, 0.0009, 0.1, 1.0, -1.0);
h.onMessage([&pid_steer, &pid_throttle, &new_delta_time, &timer, &prev_timer, &i, &prev_timer](uWS::WebSocket<uWS::SERVER> ws, char *data, size_t length, uWS::OpCode opCode)
{
auto s = hasData(data);
if (s != "") {
auto data = json::parse(s);
// create file to save values
fstream file_steer;
file_steer.open("steer_pid_data.txt");
fstream file_throttle;
file_throttle.open("throttle_pid_data.txt");
vector<double> x_points = data["traj_x"];
vector<double> y_points = data["traj_y"];
vector<double> v_points = data["traj_v"];
double yaw = data["yaw"];
double velocity = data["velocity"];
double sim_time = data["time"];
double waypoint_x = data["waypoint_x"];
double waypoint_y = data["waypoint_y"];
double waypoint_t = data["waypoint_t"];
bool is_junction = data["waypoint_j"];
string tl_state = data["tl_state"];
double x_position = data["location_x"];
double y_position = data["location_y"];
double z_position = data["location_z"];
if(!have_obst){
vector<double> x_obst = data["obst_x"];
vector<double> y_obst = data["obst_y"];
set_obst(x_obst, y_obst, obstacles, have_obst);
}
State goal;
goal.location.x = waypoint_x;
goal.location.y = waypoint_y;
goal.rotation.yaw = waypoint_t;
vector< vector<double> > spirals_x;
vector< vector<double> > spirals_y;
vector< vector<double> > spirals_v;
vector<int> best_spirals;
path_planner(x_points, y_points, v_points, yaw, velocity, goal, is_junction, tl_state, spirals_x, spirals_y, spirals_v, best_spirals);
// Save time and compute delta time
time(&timer);
new_delta_time = difftime(timer, prev_timer);
prev_timer = timer;
////////////////////////////////////////
// Steering control
////////////////////////////////////////
/**
* TODO (step 3): uncomment these lines
**/
// // Update the delta time with the previous command
pid_steer.UpdateDeltaTime(new_delta_time);
// Compute steer error
double error_steer;
double steer_output;
/**
* TODO (step 3): compute the steer error (error_steer) from the position and the desired trajectory
**/
error_steer = angle_between_points(x_position, y_position, x_points[x_points.size() - 1], y_points[y_points.size() - 1]) -yaw;
/**
* TODO (step 3): uncomment these lines
**/
// // Compute control to apply
pid_steer.UpdateError(error_steer);
steer_output = pid_steer.TotalError();
// Save data
file_steer.seekg(std::ios::beg);
for(int j=0; j < i - 1; ++j) {
file_steer.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
file_steer << i ;
file_steer << " " << error_steer;
file_steer << " " << steer_output << endl;
////////////////////////////////////////
// Throttle control
////////////////////////////////////////
/**
* TODO (step 2): uncomment these lines
**/
// // Update the delta time with the previous command
pid_throttle.UpdateDeltaTime(new_delta_time);
// Compute error of speed
double error_throttle;
/**
* TODO (step 2): compute the throttle error (error_throttle) from the position and the desired speed
**/
// modify the following line for step 2
error_throttle = v_points[v_points.size() - 1] - velocity;
double throttle_output;
double brake_output;
/**
* TODO (step 2): uncomment these lines
**/
// // Compute control to apply
pid_throttle.UpdateError(error_throttle);
double throttle = pid_throttle.TotalError();
// Adapt the negative throttle to break
if (throttle > 0.0) {
throttle_output = throttle;
brake_output = 0;
} else {
throttle_output = 0;
brake_output = -throttle;
}
// Save data
file_throttle.seekg(std::ios::beg);
for(int j=0; j < i - 1; ++j){
file_throttle.ignore(std::numeric_limits<std::streamsize>::max(),'\n');
}
file_throttle << i ;
file_throttle << " " << error_throttle;
file_throttle << " " << brake_output;
file_throttle << " " << throttle_output << endl;
// Send control
json msgJson;
msgJson["brake"] = brake_output;
msgJson["throttle"] = throttle_output;
msgJson["steer"] = steer_output;
msgJson["trajectory_x"] = x_points;
msgJson["trajectory_y"] = y_points;
msgJson["trajectory_v"] = v_points;
msgJson["spirals_x"] = spirals_x;
msgJson["spirals_y"] = spirals_y;
msgJson["spirals_v"] = spirals_v;
msgJson["spiral_idx"] = best_spirals;
msgJson["active_maneuver"] = behavior_planner.get_active_maneuver();
// min point threshold before doing the update
// for high update rate use 19 for slow update rate use 4
msgJson["update_point_thresh"] = 16;
auto msg = msgJson.dump();
i = i + 1;
file_steer.close();
file_throttle.close();
ws.send(msg.data(), msg.length(), uWS::OpCode::TEXT);
}
});
h.onConnection([](uWS::WebSocket<uWS::SERVER> ws, uWS::HttpRequest req)
{
cout << "Connected!!!" << endl;
});
h.onDisconnection([&h](uWS::WebSocket<uWS::SERVER> ws, int code, char *message, size_t length)
{
ws.close();
cout << "Disconnected" << endl;
});
int port = 4567;
if (h.listen("0.0.0.0", port))
{
cout << "Listening to port " << port << endl;
h.run();
}
else
{
cerr << "Failed to listen to port" << endl;
return -1;
}
}