2 * @file motion-control.cc
3 * @author Michal Sojka <sojkam1@fel.cvut.cz>, Petr Beneš
4 * @date Fri Mar 20 10:36:59 2009
11 //#define MOTION_DEBUG
14 #define DBG(format, ...) printf(format, ##__VA_ARGS__)
15 #define DBGflush() fflush(stdout)
17 #define DBG(format, ...)
28 #include <path_planner.h>
30 #include <movehelper.h>
34 #include "robot_config.h"
37 #define MOTION_CONTROL
38 #include "motion-control.h"
44 /* ULoPoS constants (-%-TEMPERATURE-%- dependent!) */
45 #define SOUND_VELOCITY (331.3+0.606*20)
46 #define XCORR2METER (SOUND_VELOCITY*(127.0/508.0)/3000.0)
47 #define D_MAX (XCORR2METER*508.0)
49 /*******************************************************************************
50 * Controller thread and helper functions for that thread
51 *******************************************************************************/
54 * If the distance of robot's estimated position from robot's
55 * requested position if above this value, the robot lost and we try
56 * to reset localization.
58 #define MAX_POS_ERROR_M 0.25
61 * If trajectory end is reached and robot's estimated position is
62 * closer than this distance, the movement is considered as "done".
64 #define CLOSE_TO_TARGET_M 0.1
67 const struct balet_params k = {
68 p_tangent: 3, // dx gain
69 p_angle: 2, // dphi gain
70 p_perpen: 5 // dy gain
71 // p_tangent: 0.2, // dx gain
72 // p_angle: 0.15, // dphi gain
73 // p_perpen: 1 // dy gain
76 #define MOTION_PERIOD_NS (50/*ms*/*1000*1000)
77 #define MEASURE_TIMEOUT_NS (100/*ms*/*1000*1000)
79 #define SIG_DO_CONTROL_NOW (SIGRTMIN+1)
82 static pthread_t thr_trajectory_follower;
83 static struct timeval tv_start; /**< Absolute time, when trajectory started. */
85 /** Stores the actually followed trajectory object */
86 static Trajectory *actual_trajectory;
87 static pthread_mutex_t actual_trajectory_lock;
89 // Trajectory recalculation
90 sem_t recalculation_not_running;
91 sem_t measurement_received;
94 * Determines way of thread_trajectory_follower() operation:
95 * - 0 measurement doesn't work, controller invocation based on time (formerly CONFIG_OPEN_LOOP)
96 * - 2 measurement works, controller invocation based on sem_post
97 * - 1 measurement doesn't work and stop() was called
99 int measurement_ok = 0;
103 static void delete_actual_trajectory()
106 pthread_mutex_lock(&actual_trajectory_lock);
107 old = actual_trajectory;
108 actual_trajectory = NULL;
109 pthread_mutex_unlock(&actual_trajectory_lock);
110 robot_send_speed(0,0);
111 if (old) delete(actual_trajectory);
114 /** Sends events from follower thread to FSM. */
115 static void notify_fsm(bool done, double error)
117 static bool done_sent;
118 static bool lost_sent = false;
120 if (error > MAX_POS_ERROR_M) {
123 FSM_SIGNAL(MOTION, EV_TRAJECTORY_LOST, NULL);
128 if (error < CLOSE_TO_TARGET_M) {
129 FSM_SIGNAL(MOTION, EV_TRAJECTORY_DONE_AND_CLOSE, NULL);
130 } else if (!done_sent) {
132 FSM_SIGNAL(MOTION, EV_TRAJECTORY_DONE, NULL);
140 static void check_for_collision_in_future(Trajectory *traj, double current_time)
143 struct map *map = robot.map;
148 // const double times[] = { 0.5, 0.3, 0.1 }; // seconds
149 const double times[] = { 0.3, 0.4, 0.5, 0.7, 0.9, 1.1 }; // seconds
152 for (i=0; i < sizeof(times)/sizeof(times[0]); i++) {
153 traj->getRefPos(current_time+times[i], future_pos);
155 /* Ignore obstacles when turning */
156 if (fabs(future_pos.v) < 0.01)
159 x = future_pos.x + cos(future_pos.phi)*ROBOT_AXIS_TO_BRUSH_M;
160 y = future_pos.y + sin(future_pos.phi)*ROBOT_AXIS_TO_BRUSH_M;
162 ShmapPoint2Cell(x, y, &xcell, &ycell, &valid);
165 if (map->cells[ycell][xcell].detected_obstacle > 0) {
166 if (sem_trywait(&recalculation_not_running) == 0) {
167 FSM_SIGNAL(MOTION, EV_OBSTACLE, NULL);
174 static void do_estimation()
176 static bool virgo = true;
177 static real_t beacon_xy[3][2] = {
183 static uint32_t odo0[2];
184 static real_t y[5] = {0.0, 0.0, 0.0, 0.0, 0.0};
185 static int missing_odo_count = 0;
186 uint32_t t[3], odo[2];
188 int i, odo_received, err[5];
190 /* locks should not be necessary, however... */
191 ROBOT_LOCK(corr_distances);
192 t[0] = robot.corr_distances.t1;
193 t[1] = robot.corr_distances.t2;
194 t[2] = robot.corr_distances.t3;
195 ROBOT_UNLOCK(corr_distances);
196 ROBOT_LOCK(motion_irc);
197 odo[0] = robot.motion_irc.left;
198 odo[1] = robot.motion_irc.right;
199 odo_received = robot.motion_irc_received;
200 robot.motion_irc_received = 0;
201 ROBOT_UNLOCK(motion_irc);
203 for (i = 0; i < 3; i++)
204 y[i] = (XCORR2METER/32.0)*t[i];
206 /* missing odometry workaround :-( */
208 real_t c = 1.0/(real_t)(1 + missing_odo_count);
209 y[3] = c*ODO_C*(real_t)((int32_t)(odo0[0] - odo[0]));
210 y[4] = c*ODO_C*(real_t)((int32_t)(odo[1] - odo0[1]));
211 missing_odo_count = 0;
216 odo0[0] = odo[0]; odo0[1] = odo[1];
217 DBG("UZV+ODO: %f %f %f %f %f\n", y[0], y[1], y[2], y[3], y[4]);
218 //DBG("ODO: %f %f %u %u\n", y[3], y[4], odo[0], odo[1]);
220 if (virgo || init_ekf_flag) {
221 /*FIXME:reflect init pos & beacon coords accord.to our color */
223 real_t xy0[] = {robot.est_pos.x, robot.est_pos.y};
225 ekf8_init(&ekf8, (real_t*)beacon_xy, D_MAX, 30.0, xy0, y);
226 ekf8.ekf.x[6] = robot.est_pos.phi;
227 init_ekf_flag = false;
229 ROBOT_UNLOCK(est_pos);
232 ekf8_step(&ekf8, x, P, err, y);
234 DBG("EKF: x=%f y=%f phi=%8.4f\n", x[0], x[1], x[6]*(180.0/M_PI));
237 robot.est_pos.x = x[0] - ODO_D*cos(x[6]);
238 robot.est_pos.y = x[1] - ODO_D*sin(x[6]);
239 robot.est_pos.phi = x[6];
240 ROBOT_UNLOCK(est_pos);
243 static void do_control()
245 double speedl, speedr;
250 // Calculate reference position
251 /***FIXME:should not rely on system clock, the period is fixed***/
252 gettimeofday(&tv, NULL);
253 t = (double)(tv.tv_usec - tv_start.tv_usec) / 1000000.0;
254 t += (tv.tv_sec - tv_start.tv_sec);
256 // check for new trajectory to switch
257 // only if the trajectory is already prepared
258 if (switch_to_trajectory != NULL && t >= switch_time) {
259 pthread_mutex_lock(&switch_to_trajectory_lock);
261 DBG("SWITCHING to new trajectory\n");
263 go(switch_to_trajectory);
264 // nothing prepared now
265 switch_to_trajectory = NULL;
266 pthread_mutex_unlock(&switch_to_trajectory_lock);
269 pthread_mutex_lock(&actual_trajectory_lock);
270 Trajectory *w = actual_trajectory;
272 Pos ref_pos, est_pos, balet_out;
275 // Calculate reference position
276 gettimeofday(&tv, NULL);
277 t = (double)(tv.tv_usec - tv_start.tv_usec) / 1000000.0;
278 t += (tv.tv_sec - tv_start.tv_sec);
280 // if switch_to_trajectory is being prepared, it can not stop calculation
281 // and start to count again, it could evoke overloading
282 if (robot.obstacle_avoidance_enabled)
283 check_for_collision_in_future(w, t);
286 done = w->getRefPos(t, ref_pos);
288 if (ref_pos.omega > actual_trajectory->constr.maxomega)
289 DBG("Omega constraint problem %lf, max %lf -------------------- \n", ref_pos.omega, actual_trajectory->constr.maxomega);
292 robot.ref_pos.x = ref_pos.x;
293 robot.ref_pos.y = ref_pos.y;
294 robot.ref_pos.phi = ref_pos.phi;
295 ROBOT_UNLOCK(ref_pos);
298 est_pos.x = robot.est_pos.x;
299 est_pos.y = robot.est_pos.y;
300 est_pos.phi = robot.est_pos.phi;
301 ROBOT_UNLOCK(est_pos);
303 if (measurement_ok < 2) {
304 // We don't have any feedback now. It is
305 // supposed that the estimated position is
306 // equal to the reference position.
307 robot_set_est_pos_notrans(ref_pos.x, ref_pos.y, ref_pos.phi);
308 est_pos.x = ref_pos.x;
309 est_pos.y = ref_pos.y;
310 est_pos.phi = ref_pos.phi;
313 #ifdef MOTION_PRINT_REF
314 static double last_t;
315 if (t < last_t) last_t = t; // Switched to a new trajectory
316 printf("rx=%5.02f ry=%5.02f, rphi=%4.0f v=%-4.02f omega=%-4.02f, time=%lf dt=%lf \n", ref_pos.x, ref_pos.y, ref_pos.phi/M_PI*180, ref_pos.v, ref_pos.omega, t, t-last_t);
321 // Call the controller
323 error = balet(ref_pos, est_pos, k, balet_out);
324 speedl = balet_out.v - ROBOT_ROTATION_RADIUS_M*balet_out.omega;
325 speedr = balet_out.v + ROBOT_ROTATION_RADIUS_M*balet_out.omega;
326 notify_fsm(done, error);
333 // Apply controller output
334 robot_send_speed(speedl, speedr);
335 pthread_mutex_unlock(&actual_trajectory_lock);
338 void dummy_handler(int)
342 static inline void next_period(struct timespec *next, long long interval_ns)
344 next->tv_nsec += interval_ns;
345 if (next->tv_nsec >= 1000000000) {
347 next->tv_nsec -= 1000000000;
352 * A thread running the controller.
354 * This (high priority) thread executes the motion control
355 * algorithm. It calculates repference position based on actual
356 * trajectory and current time. Then it calls "balet" controller to
363 void *thread_trajectory_follower(void *arg)
365 struct timespec next;
368 clock_gettime(CLOCK_REALTIME, &next);
371 ret = sem_timedwait(&measurement_received, &next);
373 if (ret == -1 && errno == ETIMEDOUT) {
374 next_period(&next, MOTION_PERIOD_NS);
375 if (measurement_ok) {
376 if (measurement_ok == 2) {
377 fprintf(stderr, "problem: measurement timeout!!!!!!!!!!!");
384 next_period(&next, MEASURE_TIMEOUT_NS);
385 if (measurement_ok < 2) {
390 robot.localization_works = (measurement_ok == 2);
391 if (measurement_ok == 2) {
400 * Tells trajctory_follower to start moving along trajectory @c t.
402 * @param t Trajectory to follow.
403 * @param append_time Relative time from the beginning of the @c actual_trajectory
404 * when to append the new one
406 void go(Trajectory *t, double append_time)
408 pthread_mutex_lock(&actual_trajectory_lock);
410 if (actual_trajectory && append_time != 0) {
411 // trajectory only connects a new one in some specific time
412 if(!actual_trajectory->appendTrajectory(*t, append_time))
413 DBG("Can not append trajectory\n");
415 // trajectory starts from zero time
416 old = actual_trajectory;
417 gettimeofday(&tv_start, NULL);
418 actual_trajectory = t;
420 t->logTraj(tv_start.tv_sec + 1e-6*tv_start.tv_usec);
425 pthread_mutex_unlock(&actual_trajectory_lock);
429 * switches to newly calculated trajectory to go on it at specific time
431 /*void switch_trajectory_at(Trajectory *t, double time)
433 pthread_mutex_lock(&switch_to_trajectory_lock);
434 switch_to_trajectory = t;
436 pthread_mutex_unlock(&switch_to_trajectory_lock);
439 gettimeofday(&tv, NULL);
440 double tm = (double)(tv.tv_usec - tv_start.tv_usec) / 1000000.0;
441 tm += (tv.tv_sec - tv_start.tv_sec);
442 if (switch_time <= tm)
443 DBG("//// BAD SWITCH ////");
448 delete_actual_trajectory();
450 // Interrupt sem_timedwait() in thread_trajectory_follower(),
451 // so we stop immediately.
452 sem_post(&measurement_received);
456 * Initializes motion controller.
459 * @return Zero on success, non-zero otherwise.
461 int motion_control_init()
463 pthread_attr_t tattr;
465 pthread_mutexattr_t mattr;
468 actual_trajectory = NULL;
469 //switch_to_trajectory = NULL;
472 ret = pthread_mutexattr_init(&mattr);
473 #ifdef HAVE_PRIO_INHERIT
474 ret = pthread_mutexattr_setprotocol(&mattr, PTHREAD_PRIO_INHERIT);
476 pthread_mutex_init(&actual_trajectory_lock, &mattr);
478 sem_init(&recalculation_not_running, 0, 1);
480 // Trajectory follower thread
481 sem_init(&measurement_received, 0, 0);
482 pthread_attr_init (&tattr);
483 pthread_attr_getschedparam (&tattr, ¶m);
484 pthread_attr_setschedpolicy(&tattr, SCHED_FIFO);
485 param.sched_priority = THREAD_PRIO_TRAJ_FOLLOWER;
486 ret = pthread_attr_setschedparam (&tattr, ¶m);
488 perror("move_init: pthread_attr_setschedparam(follower)");
491 ret = pthread_create(&thr_trajectory_follower, &tattr, thread_trajectory_follower, NULL);
493 perror("move_init: pthread_create");
502 void motion_control_done()
504 pthread_cancel(thr_trajectory_follower);
505 pthread_join(thr_trajectory_follower, NULL);
507 robot.orte.motion_speed.right = 0;
508 robot.orte.motion_speed.left = 0;
509 ORTEPublicationSend(robot.orte.publication_motion_speed);
513 void get_future_pos(double rel_time_sec, Pos &pos, double &switch_time)
517 gettimeofday(&tv, NULL);
518 switch_time = (double)(tv.tv_usec - tv_start.tv_usec) / 1000000.0;
519 switch_time += (tv.tv_sec - tv_start.tv_sec);
520 switch_time += rel_time_sec;
522 pthread_mutex_lock(&actual_trajectory_lock);
523 if (actual_trajectory) {
524 actual_trajectory->getRefPos(switch_time, pos);
525 pthread_mutex_unlock(&actual_trajectory_lock);
527 // Robot doesn't move, so return current position
528 pthread_mutex_unlock(&actual_trajectory_lock);
531 pos.x = robot.est_pos.x;
532 pos.y = robot.est_pos.y;
533 pos.phi = robot.est_pos.phi;
536 ROBOT_UNLOCK(est_pos);