]> rtime.felk.cvut.cz Git - eurobot/public.git/blob - src/robofsm/motion-control.cc
robofsm: EKF initialiation hopefully correct
[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.5
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 real_t beacon_xy[3][2] = {
177                 { 3.062, -0.05},
178                 {-0.062,  1.05},
179                 { 3.062,  2.162},
180         };
181         static ekf8_t ekf8;
182         static uint32_t odo0[2];
183         static real_t y[5] = {0.0, 0.0, 0.0, 0.0, 0.0};
184         static int missing_odo_count = 0;
185         uint32_t t[3], odo[2];
186         real_t x[8], P[8*8];
187         int i, odo_received, err[5];
188
189         /* locks should not be necessary, however... */
190         ROBOT_LOCK(corr_distances);
191         t[0] = robot.corr_distances.t1;
192         t[1] = robot.corr_distances.t2;
193         t[2] = robot.corr_distances.t3;
194         ROBOT_UNLOCK(corr_distances);
195         ROBOT_LOCK(motion_irc);
196         odo[0] = robot.motion_irc.left;
197         odo[1] = robot.motion_irc.right;
198         odo_received = robot.motion_irc_received;
199         robot.motion_irc_received = 0;
200         ROBOT_UNLOCK(motion_irc);
201
202         for (i = 0; i < 3; i++)
203                 y[i] = (XCORR2METER/32.0)*t[i];
204
205         /* missing odometry workaround :-( */
206         if (odo_received) {
207                 real_t c = 1.0/(real_t)(1 + missing_odo_count);
208                 y[3] = c*ODO_C*(real_t)((int32_t)(odo0[0] - odo[0]));
209                 y[4] = c*ODO_C*(real_t)((int32_t)(odo[1] - odo0[1]));
210                 missing_odo_count = 0;
211         }
212         else
213                 ++missing_odo_count;
214
215         odo0[0] = odo[0];  odo0[1] = odo[1];
216         DBG("UZV+ODO:  %f  %f  %f  %f  %f\n", y[0], y[1], y[2], y[3], y[4]);
217         //DBG("ODO:  %f  %f    %u  %u\n", y[3], y[4], odo[0], odo[1]);
218
219         if (init_ekf_flag) {
220                 /*FIXME:reflect init pos & beacon coords accord.to our color */
221                 ROBOT_LOCK(est_pos);
222                 real_t xy0[] = {robot.est_pos.x, robot.est_pos.y};
223                 y[3] = y[4] = 0.0;
224                 ekf8_init(&ekf8, (real_t*)beacon_xy, D_MAX, 30.0, xy0, y);
225                 ekf8.ekf.x[6] = robot.est_pos.phi;
226                 init_ekf_flag = false;
227                 ROBOT_UNLOCK(est_pos);
228         }
229
230         ekf8_step(&ekf8, x, P, err, y);
231
232         DBG("EKF: x=%f   y=%f   phi=%8.4f\n", x[0], x[1], x[6]*(180.0/M_PI));
233
234         ROBOT_LOCK(est_pos);
235         robot.est_pos.x = x[0] - ODO_D*cos(x[6]);
236         robot.est_pos.y = x[1] - ODO_D*sin(x[6]);
237         robot.est_pos.phi = x[6];
238         ROBOT_UNLOCK(est_pos);
239 }
240
241 static void do_control()
242 {
243         double speedl, speedr;
244
245         double t;
246         struct timeval tv;
247
248         // Calculate reference position
249         /***FIXME:should not rely on system clock, the period is fixed***/
250         gettimeofday(&tv, NULL);
251         t = (double)(tv.tv_usec - tv_start.tv_usec) / 1000000.0;
252         t += (tv.tv_sec - tv_start.tv_sec);
253 /*
254         // check for new trajectory to switch
255         // only if the trajectory is already prepared
256         if (switch_to_trajectory != NULL && t >= switch_time) {
257                 pthread_mutex_lock(&switch_to_trajectory_lock);
258
259                 DBG("SWITCHING to new trajectory\n");
260
261                 go(switch_to_trajectory);
262                 // nothing prepared now
263                 switch_to_trajectory = NULL;
264                 pthread_mutex_unlock(&switch_to_trajectory_lock);
265         }
266 */
267         pthread_mutex_lock(&actual_trajectory_lock);
268         Trajectory *w = actual_trajectory;
269         if (w) {
270                 Pos ref_pos, est_pos, balet_out;
271                 bool done;
272
273                 // Calculate reference position
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                 // if switch_to_trajectory is being prepared, it can not stop calculation
279                 // and start to count again, it could evoke overloading
280                 if (robot.obstacle_avoidance_enabled)
281                         check_for_collision_in_future(w, t);
282
283
284                 done = w->getRefPos(t, ref_pos);
285
286                 if (ref_pos.omega > actual_trajectory->constr.maxomega)
287                         DBG("Omega constraint problem %lf, max %lf -------------------- \n", ref_pos.omega, actual_trajectory->constr.maxomega);
288
289                 ROBOT_LOCK(ref_pos);
290                 robot.ref_pos.x = ref_pos.x;
291                 robot.ref_pos.y = ref_pos.y;
292                 robot.ref_pos.phi = ref_pos.phi;
293                 ROBOT_UNLOCK(ref_pos);
294
295                 ROBOT_LOCK(est_pos);
296                 est_pos.x = robot.est_pos.x;
297                 est_pos.y = robot.est_pos.y;
298                 est_pos.phi = robot.est_pos.phi;
299                 ROBOT_UNLOCK(est_pos);
300
301                 if (measurement_ok < 2) {
302                         // We don't have any feedback now. It is
303                         // supposed that the estimated position is
304                         // equal to the reference position.
305                         robot_set_est_pos_notrans(ref_pos.x, ref_pos.y, ref_pos.phi);
306                         est_pos.x = ref_pos.x;
307                         est_pos.y = ref_pos.y;
308                         est_pos.phi = ref_pos.phi;
309                 }
310
311 #ifdef MOTION_PRINT_REF
312                 static double last_t;
313                 if (t < last_t) last_t = t; // Switched to a new trajectory
314                 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);
315                 fflush(stdout);
316                 last_t = t;
317 #endif
318
319                 // Call the controller
320                 double error;
321                 error = balet(ref_pos, est_pos, k, balet_out);
322                 speedl = balet_out.v - ROBOT_ROTATION_RADIUS_M*balet_out.omega;
323                 speedr = balet_out.v + ROBOT_ROTATION_RADIUS_M*balet_out.omega;
324                 notify_fsm(done, error);
325         } else {
326                 speedl = 0;
327                 speedr = 0;
328         }
329
330
331         // Apply controller output
332         robot_send_speed(speedl, speedr);
333         pthread_mutex_unlock(&actual_trajectory_lock);
334 }
335
336 void dummy_handler(int)
337 {
338 }
339
340 static inline void next_period(struct timespec *next, long long interval_ns)
341 {
342         next->tv_nsec += interval_ns;
343         if (next->tv_nsec >= 1000000000) {
344                 next->tv_sec++;
345                 next->tv_nsec -= 1000000000;
346         }
347 }
348
349 /**
350  * A thread running the controller.
351  *
352  * This (high priority) thread executes the motion control
353  * algorithm. It calculates repference position based on actual
354  * trajectory and current time. Then it calls "balet" controller to
355  * close feedback.
356  *
357  * @param arg
358  *
359  * @return
360  */
361 void *thread_trajectory_follower(void *arg)
362 {
363         struct timespec next;
364         int ret;
365
366         clock_gettime(CLOCK_REALTIME, &next);
367         
368         while (1) {
369                 ret = sem_timedwait(&measurement_received, &next);
370                 
371                 if (ret == -1 && errno == ETIMEDOUT) {
372                         next_period(&next, MOTION_PERIOD_NS);
373                         if (measurement_ok) {
374                                 if (measurement_ok == 2) {
375                                         fprintf(stderr, "problem: measurement timeout!!!!!!!!!!!");
376                                 }
377                                 measurement_ok--;
378                         }
379
380                         
381                 } else {
382                         next_period(&next, MEASURE_TIMEOUT_NS);
383                         if (measurement_ok < 2) {
384                                 measurement_ok++;
385                         }
386                 }
387
388                 robot.localization_works = (measurement_ok == 2);
389                 if (measurement_ok == 2) {
390                         do_estimation();
391                 }
392                 do_control();
393
394         }
395 }
396
397 /**
398  * Tells trajctory_follower to start moving along trajectory @c t.
399  *
400  * @param t Trajectory to follow.
401  * @param append_time Relative time from the beginning of the @c actual_trajectory
402  * when to append the new one
403  */
404 void go(Trajectory *t, double append_time)
405 {
406         pthread_mutex_lock(&actual_trajectory_lock);
407         Trajectory *old;
408         if (actual_trajectory && append_time != 0) {
409                 // trajectory only connects a new one in some specific time
410                 if(!actual_trajectory->appendTrajectory(*t, append_time))
411                         DBG("Can not append trajectory\n");
412         } else {
413                 // trajectory starts from zero time
414                 old = actual_trajectory;
415                 gettimeofday(&tv_start, NULL);
416                 actual_trajectory = t;
417 #ifdef MOTION_LOG               
418                 t->logTraj(tv_start.tv_sec + 1e-6*tv_start.tv_usec);
419 #endif
420                 if (old)
421                         delete(old);
422         }
423         pthread_mutex_unlock(&actual_trajectory_lock);
424 }
425
426 /**
427  * switches to newly calculated trajectory to go on it at specific time
428  */
429 /*void switch_trajectory_at(Trajectory *t, double time)
430 {
431         pthread_mutex_lock(&switch_to_trajectory_lock);
432         switch_to_trajectory = t;
433         switch_time = time;    
434         pthread_mutex_unlock(&switch_to_trajectory_lock);
435
436         struct timeval tv;
437         gettimeofday(&tv, NULL);
438         double tm = (double)(tv.tv_usec - tv_start.tv_usec) / 1000000.0;
439         tm += (tv.tv_sec - tv_start.tv_sec);
440         if (switch_time <= tm)
441                 DBG("//// BAD SWITCH ////");
442 }
443 */
444 void stop()
445 {
446         delete_actual_trajectory();
447
448         // Interrupt sem_timedwait() in thread_trajectory_follower(),
449         // so we stop immediately.
450         sem_post(&measurement_received);
451 }
452
453 /** 
454  * Initializes motion controller.
455  * 
456  * 
457  * @return Zero on success, non-zero otherwise.
458  */
459 int motion_control_init()
460 {
461         pthread_attr_t tattr;
462         sched_param param;
463         pthread_mutexattr_t mattr;
464         int ret;
465
466         actual_trajectory = NULL;
467         //switch_to_trajectory = NULL;
468
469
470         ret = pthread_mutexattr_init(&mattr);
471 #ifdef HAVE_PRIO_INHERIT
472         ret = pthread_mutexattr_setprotocol(&mattr, PTHREAD_PRIO_INHERIT);
473 #endif
474         pthread_mutex_init(&actual_trajectory_lock, &mattr);
475
476         sem_init(&recalculation_not_running, 0, 1);
477
478         // Trajectory follower thread
479         sem_init(&measurement_received, 0, 0);
480         pthread_attr_init (&tattr);
481         pthread_attr_getschedparam (&tattr, &param);
482         pthread_attr_setschedpolicy(&tattr, SCHED_FIFO);
483         param.sched_priority = THREAD_PRIO_TRAJ_FOLLOWER;
484         ret = pthread_attr_setschedparam (&tattr, &param);
485         if(ret) {
486                 perror("move_init: pthread_attr_setschedparam(follower)");
487                 goto err;
488         }
489         ret = pthread_create(&thr_trajectory_follower, &tattr, thread_trajectory_follower, NULL);
490         if(ret) {
491                 perror("move_init: pthread_create");
492                 goto err;
493         }
494
495         return 0;
496   err:
497         return ret;
498 }
499
500 void motion_control_done()
501 {
502         pthread_cancel(thr_trajectory_follower);
503         pthread_join(thr_trajectory_follower, NULL);
504
505         robot.orte.motion_speed.right = 0;
506         robot.orte.motion_speed.left = 0;
507         ORTEPublicationSend(robot.orte.publication_motion_speed);                       
508 }
509
510
511 void get_future_pos(double rel_time_sec, Pos &pos, double &switch_time)
512 {
513         struct timeval tv;
514
515         gettimeofday(&tv, NULL);
516         switch_time = (double)(tv.tv_usec - tv_start.tv_usec) / 1000000.0;
517         switch_time += (tv.tv_sec - tv_start.tv_sec);
518         switch_time += rel_time_sec;
519
520         pthread_mutex_lock(&actual_trajectory_lock);
521         if (actual_trajectory) {
522                 actual_trajectory->getRefPos(switch_time, pos);
523                 pthread_mutex_unlock(&actual_trajectory_lock);
524         } else {
525                 // Robot doesn't move, so return current position
526                 pthread_mutex_unlock(&actual_trajectory_lock);
527
528                 ROBOT_LOCK(est_pos);
529                 pos.x = robot.est_pos.x;
530                 pos.y = robot.est_pos.y;
531                 pos.phi = robot.est_pos.phi;
532                 pos.v = 0;
533                 pos.omega = 0;
534                 ROBOT_UNLOCK(est_pos);
535         }
536 }