Project

General

Profile

Statistics
| Revision:

root / branches / simulator / projects / simulator / simulator / core / robot.c @ 1101

History | View | Annotate | Download (8.49 KB)

1
/**
2
 * @file robot.c
3
 * @author Colony Project
4
 * @brief Simulator Robot Management
5
 *
6
 * Contains implementations of functions managing robots
7
 * in the simulator, including process control and memory
8
 * management.
9
 **/
10

    
11
#include <stdlib.h>
12
#include <stdio.h>
13
#include <string.h>
14

    
15
#include <unistd.h>
16
#include <signal.h>
17
#include <sys/wait.h>
18
#include <robot_shared.h>
19
#include <sys/ipc.h>
20
#include <sys/types.h>
21
#include <sys/shm.h>
22
#include <errno.h>
23
#include <pthread.h>
24
#include <err.h>
25
#include <unistd.h>
26

    
27
#include "gtk_gui.h"
28

    
29
#include "robot.h"
30
#include "motion.h"
31
#include "rangefinders.h"
32
#include "world.h"
33
#include "logger.h"
34
#include "gtk_gui.h"
35

    
36

    
37
void sig_chld_handler(int sig);
38
void robot_update(int i);
39

    
40
// global variables
41
int first_available_id = 0;
42
// an expanding array of robots
43
Robot* robots = NULL;
44
int robots_size = 0;
45
int num_robots = 0;
46

    
47
int iterator_pos = 0;
48

    
49
int timeStep = 0;
50

    
51
// signalled when all robots have run for a bit
52
pthread_mutex_t all_finished_mutex;
53
pthread_cond_t all_finished_cond;
54
int finished = 0;
55

    
56
int pausing = 0;
57
int paused = 0;
58

    
59
int robots_initialize(void)
60
{
61
        int i;
62
        if (signal(SIGCHLD, sig_chld_handler) == SIG_ERR)
63
                return -1;
64

    
65
        robots_size = 10;
66
        robots = (Robot*)malloc(sizeof(Robot) * robots_size);
67
        if (!robots)
68
                return -1;
69
        memset(robots, 0, sizeof(Robot) * robots_size);
70
        for (i = 0; i < robots_size; i++)
71
                robots[i].id = -1;
72

    
73
        finished = 0;
74
        pthread_mutex_init(&all_finished_mutex, NULL);
75
        pthread_cond_init(&all_finished_cond, NULL);
76

    
77
        return 0;
78
}
79

    
80
int robots_cleanup(void)
81
{
82
  int i,ret;
83

    
84
  //wait for all robots to be suspended to avoid race conditions
85
  //TODO: what if this never comes...
86
  ret = pthread_cond_wait(&all_finished_cond, &all_finished_mutex);
87
  if(ret)
88
    err(errno, "error waiting on condition variable");
89

    
90
  //clear the sigchild handler
91
  signal(SIGCHLD, SIG_DFL);
92

    
93
  //destroy the robots
94
  for(i=0; i<num_robots; i++)
95
    robot_destroy(i);
96

    
97
  free(robots);
98

    
99
  return 0;
100
}
101

    
102
void robots_pause(void)
103
{
104
        pausing++;
105
        while (!paused) usleep(10000);
106
}
107

    
108
void robots_resume(void)
109
{
110
        pausing--;
111
        if (pausing < 0)
112
                fprintf(stderr, "More resuming than pausing....\n");
113
}
114

    
115
/**
116
 * Creates a new robot. Returns its id on
117
 * success, or a negative integer on failure.
118
 **/
119
int robot_create(char *execname)
120
{
121
          int pid,i;
122
        int id = first_available_id;
123
        Robot* r = &robots[id];
124
        // do shared memory stuff here
125
        key_t key = IPC_PRIVATE;
126

    
127

    
128
        /* colony simulator executable must end in .csim */
129
        if(strstr(execname, ".csim") - execname != strlen(execname) - 5)
130
        {
131
          fprintf(stderr, "Error, \"%s\" is not recognized as a colony simulator executable\n", execname);
132
          return -1;
133
        }
134

    
135
        //Memory accessible only to children with r/w privileges
136
        r->sharedMemID = shmget(key, sizeof(RobotShared), IPC_CREAT | 0666);
137

    
138

    
139
        //hack!! TODO: remove!!
140
        r->pose.x=first_available_id*100;
141
        r->pose.y=first_available_id*50;
142

    
143

    
144
        if(r->sharedMemID < 0)
145
        {
146
                fprintf(stderr, "Failed to get shared memory.\n");
147
                return -1;
148
        }
149

    
150
        r->shared = (RobotShared*)shmat(r->sharedMemID, NULL, 0);
151

    
152
        if(!(r->shared))
153
        {
154
                //Free shared memory region
155
                if (!shmctl(r->sharedMemID, IPC_RMID, NULL))
156
                        fprintf(stderr, "Failed to free shared memory.\n");
157

    
158
                fprintf(stderr, "Error attaching memory to parent.\n");
159
                return -1;
160
        }
161

    
162
        // Initialize robot structure here
163
        r->shared->motor1 = 0;
164
        r->shared->motor2 = 0;
165
        r->id = id;
166

    
167
        if(execname != NULL)
168
        {
169
                if((pid = fork()) < 0)
170
                {
171
                        //Free Shared Memory Region
172
                        //TODO: this doesn't work
173
                        if (!shmdt(r->shared))
174
                                fprintf(stderr, "Failed to free shared memory.\n");
175

    
176
                        if (!shmctl(r->sharedMemID, IPC_RMID, NULL))
177
                                fprintf(stderr, "Failed to free shared memory.\n");
178

    
179
                        r->id = -1;
180
                        fprintf(stderr, "Failed to fork robot process.\n");
181
                        return -1;
182
                }
183
        }
184

    
185

    
186
        if(!pid && execname)
187
        {
188
          char var[21];
189
          /* restore default sigchld handler */
190
          signal(SIGCHLD, SIG_DFL);
191
          sprintf(var, "memory_id=%d", r->sharedMemID);
192
          putenv(var);
193
          //TODO: keep the other env. stuff around
194
          execv(execname, NULL);
195
          err(errno, "exec failed to run child process.\n");
196
        }
197
        else
198
        {
199
                r->pid = pid;
200
                do {
201
                        first_available_id++;
202
                } while (first_available_id < robots_size &&
203
                                robots[first_available_id].id != -1);
204
                // resize the array if necessary
205
                if (first_available_id >= robots_size)
206
                {
207
                        robots_size *= 2;
208
                        robots = realloc(robots, sizeof(Robot) * robots_size);
209
                        if (!robots)
210
                        {
211
                                fprintf(stderr, "Out of memory.\n");
212
                                return -1;
213
                        }
214
                        for (i = robots_size=first_available_id; i < robots_size; i++)
215
                          robots[i].id = -1;
216

    
217
                }
218
        }
219

    
220
        //Log creation
221
        if(execname != NULL)
222
        {
223
                //printf("commiting %d\n", num_robots);
224
                commit(r, num_robots, CREATE_STEP);
225
        }
226
        num_robots++;
227

    
228
        return id;
229
}
230

    
231
/**
232
 * Frees all resources associated with a robot, including
233
 * killing its process if necessary.
234
 *
235
 * @return zero on success, nonzero on failure
236
 **/
237
int robot_destroy(int id)
238
{
239
        Robot* r;
240

    
241

    
242
        if (id < 0 || id >= robots_size)
243
                return -1;
244
        r = &robots[id];
245
        if (r->id == -1)
246
                return -1;
247
        
248
        // TODO: this doesn't work
249
        if (shmdt(r->shared))
250
        {
251
          warn("Failed to free shared memory.");
252
          return -1;
253
        }
254
        //mark the shared meory to be destroyed
255
        if (shmctl(r->sharedMemID, IPC_RMID, NULL))
256
        {
257
                warn("Failed to mark shared memory for deletion\n");
258
                return -1;
259
        }
260
        //TODO: send a signal that the robot can catch to detach its shared mem
261
        if (kill(r->pid, SIGKILL))
262
        {
263
                warn( "Failed to kill robot process.\n");
264
                return -1;
265
        }
266

    
267
        memset(r, 0, sizeof(Robot));
268
        r->id = -1;
269

    
270

    
271
        if (id < first_available_id)
272
                first_available_id = 0;
273

    
274

    
275
        return 0;
276
}
277

    
278
void robot_destroy_all()
279
{
280
        int i;
281
        for(i = 0; i < num_robots; i++)
282
                robot_destroy(i);
283
}
284

    
285
void robot_iterator_reset(void)
286
{
287
        iterator_pos = -1;
288
}
289

    
290
// note: addresses may change, replace with
291
// allocated memory
292
Robot* robot_iterator_next(void)
293
{
294
        if (iterator_pos >= robots_size)
295
                return NULL;
296
        do iterator_pos++;
297
        while (iterator_pos < robots_size &&
298
                        robots[iterator_pos].id == -1);
299

    
300
        if (iterator_pos >= robots_size)
301
                return NULL;
302

    
303
        return &(robots[iterator_pos]);
304
}
305

    
306
Robot* robot_get(int id)
307
{
308
        if (id >= 0 && id < robots_size)
309
                return &(robots[id]);
310
        else
311
                return NULL;
312
}
313

    
314
void sig_chld_handler(int sig)
315
{
316
  int ret,stat;
317

    
318
  pthread_mutex_lock(&all_finished_mutex);
319

    
320
  while((ret = waitpid(-1, &stat, WUNTRACED | WNOHANG)))
321
  {
322
    if(ret==-1)
323
      err(errno,"error waiting on robot");
324

    
325
    if(WIFSTOPPED(stat))
326
      finished++;
327
  }
328

    
329
  if (finished >= num_robots)
330
  {
331
    pthread_cond_signal(&all_finished_cond);
332
  }
333
  pthread_mutex_unlock(&all_finished_mutex);
334
}
335

    
336
void* robot_event_loop(void* arg)
337
{
338
        int i;
339
        int ret;
340

    
341
        //TODO: not exit if there is an error?
342

    
343
        while (1)
344
        {
345
                //sleep to avoid 100% CPU usage
346
                usleep(10000);
347
                while (pausing)
348
                {
349
                        paused = 1;
350
                        usleep(50000);
351
                }
352
                paused = 0;
353

    
354
                ret = pthread_mutex_lock(&all_finished_mutex);
355
                if(ret)
356
                        err(errno, "error locking mutex in even loop");
357
                // TODO: race condition for adding robots?
358
                if (finished < num_robots)
359
                {
360
                        ret = pthread_cond_wait(&all_finished_cond, &all_finished_mutex);
361
                        if(ret)
362
                          err(errno, "error waiting on condition variable");
363
                }
364
                finished = 0;
365
                
366
                ret = pthread_mutex_unlock(&all_finished_mutex);
367

    
368
                if(ret)
369
                  fprintf(stderr, "hmmm, error unlocking. errno: %d", errno);
370

    
371
                timeStep++;
372
                for (i = 0; i < robots_size; i++)
373
                        if (robots[i].id != -1)
374
                        {
375
                                robot_update(i);
376
                                commit(&robots[i],i,timeStep);
377
                        }
378
                for (i = 0; i < robots_size; i++)
379
                {
380
                        if (robots[i].id == -1)
381
                                continue;
382
                        ret = kill(robots[i].pid, SIGCONT);
383
                        if(ret)
384
                          warn("error: could not kill resume robot proc.");
385
                }
386

    
387
                if (timeStep % 5 == 0)
388
                        gui_refresh();
389
        }
390
}
391

    
392
void* logger_step_loop(void* arg)
393
{
394
        printf("going into logger\n");
395
        int timeStep;
396
        int index;
397

    
398
        int prevStep = -1;
399

    
400
        if(fread(&timeStep, sizeof(int), 1, file) < 1)
401
        {
402
                robot_destroy_all();
403
                fprintf(stderr, "problem reading timestep\n");
404

    
405
            return (void*)-1;
406
        }
407

    
408
         while(1){
409
                prevStep = timeStep;
410
                do
411
                   {
412
                        if(fread(&index, sizeof(int), 1, file) < 1)
413
                        {
414
                                robot_destroy_all();
415
                                 return (void*) -1;
416
                        }
417

    
418
            //Update the robot
419
                        if(timeStep == CREATE_STEP)
420
                        {
421
                            robot_create(NULL);
422
                        }
423

    
424

    
425
                        if(getLog(&robots[index]) < 0)
426
                        {
427
                                robot_destroy_all();
428
                                 return (void*) -1;
429
                        }
430

    
431
                        //Read in next logfile and check number
432
                           if(fread(&timeStep, sizeof(int), 1, file) < 1)
433
                        {
434
                                robot_destroy_all();
435
                                return (void*)-1;
436
                        }
437

    
438
                   if (prevStep < 0)
439
                                   prevStep = timeStep;
440
                   }while(timeStep == prevStep || timeStep == CREATE_STEP);
441

    
442

    
443
                gui_refresh();
444

    
445
                usleep(100);
446
        }
447

    
448
}
449

    
450
void robot_update(int i)
451
{
452
        Robot* r = &(robots[i]);
453
        if (r->id == -1)
454
                return;
455
        move_robot(r);
456
        update_rangefinders(r);
457
}
458