]> rtime.felk.cvut.cz Git - eurobot/public.git/blob - src/robofsm/motion-control.cc
robofsm: Unified access to estimated position
[eurobot/public.git] / src / robofsm / motion-control.cc
1 /**
2  * @file   motion-control.cc
3  * @author Michal Sojka <sojkam1@fel.cvut.cz>, Petr Beneš
4  * @date   Fri Mar 20 10:36:59 2009
5  * 
6  * @brief  
7  * 
8  * 
9  */
10
11 //#define MOTION_DEBUG
12
13 #ifdef MOTION_DEBUG
14     #define DBG(format, ...) printf(format, ##__VA_ARGS__)
15     #define DBGflush() fflush(stdout)
16 #else
17     #define DBG(format, ...)
18     #define DBGflush()
19 #endif
20
21 #include <sys/time.h>
22 #include <time.h>
23 #include "trgen.h"
24 #include "balet.h"
25 #include <robodata.h>
26 #include <robot.h>
27 #include <pthread.h>
28 #include <path_planner.h>
29 #include <signal.h>
30 #include <movehelper.h>
31 #include <sharp.h>
32 #include <unistd.h>
33 #include <map.h>
34 #include "robot_config.h"
35 #include <robomath.h>
36
37 #define MOTION_CONTROL
38 #include "motion-control.h"
39
40 /* ULoPoS EKF */
41 #include <ekf.h>
42 #include <geom.h>
43
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)
48
49 /*******************************************************************************
50  * Controller thread and helper functions for that thread
51  *******************************************************************************/
52
53 /**
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.
57  */
58 #define MAX_POS_ERROR_M 0.25
59
60 /**
61  * If trajectory end is reached and robot's estimated position is
62  * closer than this distance, the movement is considered as "done".
63  */
64 #define CLOSE_TO_TARGET_M 0.1
65
66 //Controller gains
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
74 };
75
76 #define MOTION_PERIOD_NS (50/*ms*/*1000*1000)
77 #define MEASURE_TIMEOUT_NS (100/*ms*/*1000*1000)
78
79 #define SIG_DO_CONTROL_NOW (SIGRTMIN+1)
80
81 // Global varibles
82 static pthread_t thr_trajectory_follower;
83 static struct timeval tv_start; /**< Absolute time, when trajectory started. */
84
85 /** Stores the actually followed trajectory object */
86 static Trajectory *actual_trajectory;
87 static pthread_mutex_t actual_trajectory_lock;
88
89 // Trajectory recalculation 
90 sem_t recalculation_not_running;
91 sem_t measurement_received;
92
93 /**
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
98  */
99 int measurement_ok = 0;
100
101
102
103 static void delete_actual_trajectory()
104 {
105         Trajectory *old;
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);
112 }
113
114 /** Sends events from follower thread to FSM. */
115 static void notify_fsm(bool done, double error)
116 {
117         static bool done_sent;
118         static bool lost_sent = false;
119
120         if (error > MAX_POS_ERROR_M) {
121                 if (!lost_sent) {
122                         lost_sent = true;
123                         FSM_SIGNAL(MOTION, EV_TRAJECTORY_LOST, NULL);
124                 }
125         } else {
126                 lost_sent = false;
127                 if (done) {
128                         if (error < CLOSE_TO_TARGET_M) {
129                                 FSM_SIGNAL(MOTION, EV_TRAJECTORY_DONE_AND_CLOSE, NULL);
130                         } else if (!done_sent) {
131                                 done_sent = true;
132                                 FSM_SIGNAL(MOTION, EV_TRAJECTORY_DONE, NULL);
133                         }
134                 } else {
135                         done_sent = false;
136                 }
137         }
138 }
139
140 static void check_for_collision_in_future(Trajectory *traj, double current_time)
141 {
142         Pos future_pos;
143         struct map *map = robot.map;
144         int xcell, ycell;
145         double x, y;
146         bool valid;
147         unsigned i;
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
150
151
152         for (i=0; i < sizeof(times)/sizeof(times[0]); i++) {
153                 traj->getRefPos(current_time+times[i], future_pos);
154
155                 /* Ignore obstacles when turning */
156                 if (fabs(future_pos.v) < 0.01)
157                         continue;
158
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;
161         
162                 ShmapPoint2Cell(x, y, &xcell, &ycell, &valid);
163                 if (!valid)
164                         continue;
165                 if (map->cells[ycell][xcell].detected_obstacle > 0) {
166                         if (sem_trywait(&recalculation_not_running) == 0) {
167                                 FSM_SIGNAL(MOTION, EV_OBSTACLE, NULL);
168                                 break;
169                         }
170                 }
171         }
172 }
173
174 static void do_estimation()
175 {
176         static bool virgo = true;
177
178 //#define WE_ARE_RED
179 #define WE_ARE_GREEN
180
181 #ifdef WE_ARE_GREEN
182 #ifndef WE_ARE_RED
183         static real_t beacon_xy[3][2] = {
184                 { 3.062, -0.05},
185                 {-0.062,  1.05},
186                 { 3.062,  2.162},
187         };
188 #endif
189 #else
190 #ifdef WE_ARE_RED
191         static real_t beacon_xy[3][2] = {
192                 {-0.062, -0.05},
193                 { 3.062,  1.05},
194                 {-0.062,  2.162},
195         };
196 #endif
197 #endif
198         static ekf8_t ekf8;
199         static uint32_t odo0[2];
200         static real_t y[5] = {0.0, 0.0, 0.0, 0.0, 0.0};
201         static int missing_odo_count = 0;
202         uint32_t t[3], odo[2];
203         real_t x[8], P[8*8];
204         int i, odo_received, err[5];
205
206 #ifdef WE_ARE_RED
207         robot.team_color = RED;
208 #else
209         robot.team_color = GREEN;
210 #endif
211
212         /* locks should not be necessary, however... */
213         ROBOT_LOCK(corr_distances);
214         t[0] = robot.corr_distances.t1;
215         t[1] = robot.corr_distances.t2;
216         t[2] = robot.corr_distances.t3;
217         ROBOT_UNLOCK(corr_distances);
218         ROBOT_LOCK(motion_irc);
219         odo[0] = robot.motion_irc.left;
220         odo[1] = robot.motion_irc.right;
221         odo_received = robot.motion_irc_received;
222         robot.motion_irc_received = 0;
223         ROBOT_UNLOCK(motion_irc);
224
225         for (i = 0; i < 3; i++)
226                 y[i] = (XCORR2METER/32.0)*t[i];
227
228         /* missing odometry workaround :-( */
229         if (odo_received) {
230                 real_t c = 1.0/(real_t)(1 + missing_odo_count);
231                 y[3] = c*ODO_C*(real_t)((int32_t)(odo0[0] - odo[0]));
232                 y[4] = c*ODO_C*(real_t)((int32_t)(odo[1] - odo0[1]));
233                 missing_odo_count = 0;
234         }
235         else
236                 ++missing_odo_count;
237
238         odo0[0] = odo[0];  odo0[1] = odo[1];
239         DBG("UZV+ODO:  %f  %f  %f  %f  %f\n", y[0], y[1], y[2], y[3], y[4]);
240         //DBG("ODO:  %f  %f    %u  %u\n", y[3], y[4], odo[0], odo[1]);
241
242         if (virgo || init_ekf_flag) {
243                 /*FIXME:reflect init pos & beacon coords accord.to our color */
244                 ROBOT_LOCK(est_pos_uzv);
245                 real_t xy0[] = {robot.est_pos_uzv.x, robot.est_pos_uzv.y};
246                 y[3] = y[4] = 0.0;
247                 ekf8_init(&ekf8, (real_t*)beacon_xy, D_MAX, 30.0, xy0, y);
248                 ekf8.ekf.x[6] = robot.est_pos_uzv.phi;
249                 init_ekf_flag = false;
250                 virgo = false;
251                 ROBOT_UNLOCK(est_pos_uzv);
252         }
253
254         ekf8_step(&ekf8, x, P, err, y);
255
256         DBG("EKF: x=%f   y=%f   phi=%8.4f\n", x[0], x[1], x[6]*(180.0/M_PI));
257
258         ROBOT_LOCK(est_pos_uzv);
259         robot.est_pos_uzv.x = x[0] - ODO_D*cos(x[6]);
260         robot.est_pos_uzv.y = x[1] - ODO_D*sin(x[6]);
261         robot.est_pos_uzv.phi = x[6];
262         ROBOT_UNLOCK(est_pos_uzv);
263 }
264
265 static void do_control()
266 {
267         double speedl, speedr;
268
269         double t;
270         struct timeval tv;
271
272         // Calculate reference position
273         /***FIXME:should not rely on system clock, the period is fixed***/
274         gettimeofday(&tv, NULL);
275         t = (double)(tv.tv_usec - tv_start.tv_usec) / 1000000.0;
276         t += (tv.tv_sec - tv_start.tv_sec);
277 /*
278         // check for new trajectory to switch
279         // only if the trajectory is already prepared
280         if (switch_to_trajectory != NULL && t >= switch_time) {
281                 pthread_mutex_lock(&switch_to_trajectory_lock);
282
283                 DBG("SWITCHING to new trajectory\n");
284
285                 go(switch_to_trajectory);
286                 // nothing prepared now
287                 switch_to_trajectory = NULL;
288                 pthread_mutex_unlock(&switch_to_trajectory_lock);
289         }
290 */
291         pthread_mutex_lock(&actual_trajectory_lock);
292         Trajectory *w = actual_trajectory;
293         if (w) {
294                 Pos ref_pos, est_pos, balet_out;
295                 bool done;
296
297                 // Calculate reference position
298                 gettimeofday(&tv, NULL);
299                 t = (double)(tv.tv_usec - tv_start.tv_usec) / 1000000.0;
300                 t += (tv.tv_sec - tv_start.tv_sec);
301
302                 // if switch_to_trajectory is being prepared, it can not stop calculation
303                 // and start to count again, it could evoke overloading
304                 if (robot.obstacle_avoidance_enabled)
305                         check_for_collision_in_future(w, t);
306
307
308                 done = w->getRefPos(t, ref_pos);
309
310                 if (ref_pos.omega > actual_trajectory->constr.maxomega)
311                         DBG("Omega constraint problem %lf, max %lf -------------------- \n", ref_pos.omega, actual_trajectory->constr.maxomega);
312
313                 ROBOT_LOCK(ref_pos);
314                 robot.ref_pos.x = ref_pos.x;
315                 robot.ref_pos.y = ref_pos.y;
316                 robot.ref_pos.phi = ref_pos.phi;
317                 ROBOT_UNLOCK(ref_pos);
318
319                 robot_get_est_pos(&est_pos.x, &est_pos.y, &est_pos.phi);
320
321 #ifdef MOTION_PRINT_REF
322                 static double last_t;
323                 if (t < last_t) last_t = t; // Switched to a new trajectory
324                 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);
325                 fflush(stdout);
326                 last_t = t;
327 #endif
328
329                 // Call the controller
330                 double error;
331                 error = balet(ref_pos, est_pos, k, balet_out);
332                 speedl = balet_out.v - ROBOT_ROTATION_RADIUS_M*balet_out.omega;
333                 speedr = balet_out.v + ROBOT_ROTATION_RADIUS_M*balet_out.omega;
334                 notify_fsm(done, error);
335         } else {
336                 speedl = 0;
337                 speedr = 0;
338         }
339
340
341         // Apply controller output
342         robot_send_speed(speedl, speedr);
343         pthread_mutex_unlock(&actual_trajectory_lock);
344 }
345
346 void dummy_handler(int)
347 {
348 }
349
350 static inline void next_period(struct timespec *next, long long interval_ns)
351 {
352         next->tv_nsec += interval_ns;
353         if (next->tv_nsec >= 1000000000) {
354                 next->tv_sec++;
355                 next->tv_nsec -= 1000000000;
356         }
357 }
358
359 /**
360  * A thread running the controller.
361  *
362  * This (high priority) thread executes the motion control
363  * algorithm. It calculates repference position based on actual
364  * trajectory and current time. Then it calls "balet" controller to
365  * close feedback.
366  *
367  * @param arg
368  *
369  * @return
370  */
371 void *thread_trajectory_follower(void *arg)
372 {
373         struct timespec next;
374         int ret;
375
376         clock_gettime(CLOCK_REALTIME, &next);
377         
378         while (1) {
379                 ret = sem_timedwait(&measurement_received, &next);
380                 
381                 if (ret == -1 && errno == ETIMEDOUT) {
382                         next_period(&next, MOTION_PERIOD_NS);
383                         if (measurement_ok) {
384                                 if (measurement_ok == 2) {
385                                         fprintf(stderr, "problem: measurement timeout!!!!!!!!!!!");
386                                 }
387                                 measurement_ok--;
388                         }
389
390                         
391                 } else {
392                         next_period(&next, MEASURE_TIMEOUT_NS);
393                         if (measurement_ok < 2) {
394                                 measurement_ok++;
395                         }
396                 }
397
398                 robot.localization_works = (measurement_ok == 2);
399                 if (measurement_ok == 2) {
400                         do_estimation();
401                 }
402                 do_control();
403
404         }
405 }
406
407 /**
408  * Tells trajctory_follower to start moving along trajectory @c t.
409  *
410  * @param t Trajectory to follow.
411  * @param append_time Relative time from the beginning of the @c actual_trajectory
412  * when to append the new one
413  */
414 void go(Trajectory *t, double append_time)
415 {
416         pthread_mutex_lock(&actual_trajectory_lock);
417         Trajectory *old;
418         if (actual_trajectory && append_time != 0) {
419                 // trajectory only connects a new one in some specific time
420                 if(!actual_trajectory->appendTrajectory(*t, append_time))
421                         DBG("Can not append trajectory\n");
422         } else {
423                 // trajectory starts from zero time
424                 old = actual_trajectory;
425                 gettimeofday(&tv_start, NULL);
426                 actual_trajectory = t;
427 #ifdef MOTION_LOG               
428                 t->logTraj(tv_start.tv_sec + 1e-6*tv_start.tv_usec);
429 #endif
430                 if (old)
431                         delete(old);
432         }
433         pthread_mutex_unlock(&actual_trajectory_lock);
434 }
435
436 /**
437  * switches to newly calculated trajectory to go on it at specific time
438  */
439 /*void switch_trajectory_at(Trajectory *t, double time)
440 {
441         pthread_mutex_lock(&switch_to_trajectory_lock);
442         switch_to_trajectory = t;
443         switch_time = time;    
444         pthread_mutex_unlock(&switch_to_trajectory_lock);
445
446         struct timeval tv;
447         gettimeofday(&tv, NULL);
448         double tm = (double)(tv.tv_usec - tv_start.tv_usec) / 1000000.0;
449         tm += (tv.tv_sec - tv_start.tv_sec);
450         if (switch_time <= tm)
451                 DBG("//// BAD SWITCH ////");
452 }
453 */
454 void stop()
455 {
456         delete_actual_trajectory();
457
458         // Interrupt sem_timedwait() in thread_trajectory_follower(),
459         // so we stop immediately.
460         sem_post(&measurement_received);
461 }
462
463 /** 
464  * Initializes motion controller.
465  * 
466  * 
467  * @return Zero on success, non-zero otherwise.
468  */
469 int motion_control_init()
470 {
471         pthread_attr_t tattr;
472         sched_param param;
473         pthread_mutexattr_t mattr;
474         int ret;
475
476         actual_trajectory = NULL;
477         //switch_to_trajectory = NULL;
478
479
480         ret = pthread_mutexattr_init(&mattr);
481 #ifdef HAVE_PRIO_INHERIT
482         ret = pthread_mutexattr_setprotocol(&mattr, PTHREAD_PRIO_INHERIT);
483 #endif
484         pthread_mutex_init(&actual_trajectory_lock, &mattr);
485
486         sem_init(&recalculation_not_running, 0, 1);
487
488         // Trajectory follower thread
489         sem_init(&measurement_received, 0, 0);
490         pthread_attr_init (&tattr);
491         pthread_attr_getschedparam (&tattr, &param);
492         pthread_attr_setschedpolicy(&tattr, SCHED_FIFO);
493         param.sched_priority = THREAD_PRIO_TRAJ_FOLLOWER;
494         ret = pthread_attr_setschedparam (&tattr, &param);
495         if(ret) {
496                 perror("move_init: pthread_attr_setschedparam(follower)");
497                 goto err;
498         }
499         ret = pthread_create(&thr_trajectory_follower, &tattr, thread_trajectory_follower, NULL);
500         if(ret) {
501                 perror("move_init: pthread_create");
502                 goto err;
503         }
504
505         return 0;
506   err:
507         return ret;
508 }
509
510 void motion_control_done()
511 {
512         pthread_cancel(thr_trajectory_follower);
513         pthread_join(thr_trajectory_follower, NULL);
514
515         robot.orte.motion_speed.right = 0;
516         robot.orte.motion_speed.left = 0;
517         ORTEPublicationSend(robot.orte.publication_motion_speed);                       
518 }
519
520
521 void get_future_pos(double rel_time_sec, Pos &pos, double &switch_time)
522 {
523         struct timeval tv;
524
525         gettimeofday(&tv, NULL);
526         switch_time = (double)(tv.tv_usec - tv_start.tv_usec) / 1000000.0;
527         switch_time += (tv.tv_sec - tv_start.tv_sec);
528         switch_time += rel_time_sec;
529
530         pthread_mutex_lock(&actual_trajectory_lock);
531         if (actual_trajectory) {
532                 actual_trajectory->getRefPos(switch_time, pos);
533                 pthread_mutex_unlock(&actual_trajectory_lock);
534         } else {
535                 // Robot doesn't move, so return current position
536                 pthread_mutex_unlock(&actual_trajectory_lock);
537
538                 robot_get_est_pos(&pos.x, &pos.y, &pos.phi);
539                 pos.v = 0;
540                 pos.omega = 0;
541         }
542 }