Project

General

Profile

Statistics
| Revision:

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

History | View | Annotate | Download (8.53 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,i;
317

    
318
  pthread_mutex_lock(&all_finished_mutex);
319

    
320

    
321
  for(i=0; i<num_robots; i++) {
322

    
323
    ret = waitpid(robots[i].pid, &stat, WUNTRACED | WNOHANG);
324
  
325
    if(ret==-1)
326
      err(errno,"error waiting on robot");
327

    
328
    if(WIFSTOPPED(stat))
329
      finished++;
330
  }
331

    
332
  if (finished >= num_robots)
333
  {
334
    pthread_cond_signal(&all_finished_cond);
335
  }
336
  pthread_mutex_unlock(&all_finished_mutex);
337
}
338

    
339
void* robot_event_loop(void* arg)
340
{
341
        int i;
342
        int ret;
343

    
344
        //TODO: not exit if there is an error?
345

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

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

    
371
                if(ret)
372
                  fprintf(stderr, "hmmm, error unlocking. errno: %d", errno);
373

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

    
390
                if (timeStep % 5 == 0)
391
                        gui_refresh();
392
        }
393
}
394

    
395
void* logger_step_loop(void* arg)
396
{
397
        printf("going into logger\n");
398
        int timeStep;
399
        int index;
400

    
401
        int prevStep = -1;
402

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

    
408
            return (void*)-1;
409
        }
410

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

    
421
            //Update the robot
422
                        if(timeStep == CREATE_STEP)
423
                        {
424
                            robot_create(NULL);
425
                        }
426

    
427

    
428
                        if(getLog(&robots[index]) < 0)
429
                        {
430
                                robot_destroy_all();
431
                                 return (void*) -1;
432
                        }
433

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

    
441
                   if (prevStep < 0)
442
                                   prevStep = timeStep;
443
                   }while(timeStep == prevStep || timeStep == CREATE_STEP);
444

    
445

    
446
                gui_refresh();
447

    
448
                usleep(100);
449
        }
450

    
451
}
452

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