garcia-pilot.cc 15.5 KB
Newer Older
Timothy Stack's avatar
 
Timothy Stack committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
/*
 * EMULAB-COPYRIGHT
 * Copyright (c) 2005 University of Utah and the Flux Group.
 * All rights reserved.
 */

/**
 * @file garcia-pilot.cc
 *
 * The main body of the daemon that runs on the garcia robot.
 */

#include "config.h"

Timothy Stack's avatar
   
Timothy Stack committed
15
#include <errno.h>
Timothy Stack's avatar
 
Timothy Stack committed
16
#include <stdio.h>
Timothy Stack's avatar
   
Timothy Stack committed
17
#include <fcntl.h>
Timothy Stack's avatar
 
Timothy Stack committed
18
19
20
21
#include <assert.h>
#include <signal.h>
#include <string.h>
#include <unistd.h>
Timothy Stack's avatar
   
Timothy Stack committed
22
#include <fcntl.h>
Timothy Stack's avatar
 
Timothy Stack committed
23
24
#include <ucontext.h>

Timothy Stack's avatar
   
Timothy Stack committed
25
#include <sys/stat.h>
Timothy Stack's avatar
 
Timothy Stack committed
26
27
28
#include <sys/socket.h>
#include <arpa/inet.h>

Timothy Stack's avatar
   
Timothy Stack committed
29
30
31
#include <list>
#include <algorithm>

Timothy Stack's avatar
 
Timothy Stack committed
32
33
34
35
36
37
38
39
40
41
42
43
44
#include "acpGarcia.h"
#include "acpValue.h"

#include "pilotClient.hh"
#include "dashboard.hh"
#include "wheelManager.hh"
#include "pilotButtonCallback.hh"

/**
 * The default port to listen for client connections.
 */
#define PILOT_PORT 2531

Timothy Stack's avatar
   
Timothy Stack committed
45
46
static const char *DEFAULT_LOG_PATH = "/tmp/garcia-pilot.log";

Timothy Stack's avatar
 
Timothy Stack committed
47
48
49
50
51
/**
 * Default path to the battery log.
 */
static const char *BATTERY_LOG_PATH = "/var/log/battery.log";

52
53
54
55
56
57
58
59

/**
 * Default file to read in state data
 */
static const char *DEFAULT_SFILE = "sdata.txt";



Timothy Stack's avatar
 
Timothy Stack committed
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
/**
 * Determines whether or not to continue in the main loop.
 *
 * @see sigquit
 */
static volatile int looping = 1;

/**
 * Signal handler for SIGINT, SIGTERM, and SIGQUIT signals.  Sets looping to
 * zero and aborts() if it is called more than three times in case the program
 * is unable to return to the main loop.
 *
 * @param sig The actual signal number received.
 */
static void sigquit(int sig)
{
    static int quit_count = 3;
    
    if (quit_count == 0) {
79
80
81
        static char *msg = "error: wedged, aborting...\n";
        
        write(2, msg, strlen(msg));
Timothy Stack's avatar
 
Timothy Stack committed
82

83
        abort();
Timothy Stack's avatar
 
Timothy Stack committed
84
85
86
    }
    
    looping = 0;
Timothy Stack's avatar
   
Timothy Stack committed
87
88
89
90
91
92
93
94
95
96
97
    quit_count -= 1;
}

/**
 * Signal handler for SIGUSR1, just toggles the debugging level.
 *
 * @param sig The actual signal number received.
 */
static void sigdebug(int sig)
{
    if (debug == 3)
98
        debug = 1;
Timothy Stack's avatar
   
Timothy Stack committed
99
    else
100
        debug = 3;
Timothy Stack's avatar
 
Timothy Stack committed
101
102
103
104
105
106
}

/**
 * Signal handler for SIGSEGV and SIGBUS, just prints out the signal number and
 * aborts.
 */
Timothy Stack's avatar
   
Timothy Stack committed
107
static void sigpanic(int signum)
Timothy Stack's avatar
 
Timothy Stack committed
108
{
Timothy Stack's avatar
   
Timothy Stack committed
109
110
111
112
113
    char msg[128];
    
    snprintf(msg, sizeof(msg), "panic: %d; reexec'ing\n", signum);
    write(1, msg, strlen(msg));

Timothy Stack's avatar
   
Timothy Stack committed
114
#if 0
Timothy Stack's avatar
   
Timothy Stack committed
115
    execve(reexec_argv[0], reexec_argv, environ);
Timothy Stack's avatar
 
Timothy Stack committed
116

Timothy Stack's avatar
   
Timothy Stack committed
117
118
    snprintf(msg, sizeof(msg), "reexec failed %s\n", strerror(errno));
    write(1, msg, strlen(msg));
Timothy Stack's avatar
   
Timothy Stack committed
119
#endif
Timothy Stack's avatar
   
Timothy Stack committed
120

Timothy Stack's avatar
   
Timothy Stack committed
121
    abort();
Timothy Stack's avatar
 
Timothy Stack committed
122
123
124
125
126
127
128
129
}

/**
 * Prints the usage message for this daemon to stderr.
 */
static void usage(void)
{
    fprintf(stderr,
130
131
132
133
134
135
136
137
138
139
140
141
            "usage: garcia-pilot -hd [-l logfile] [-i pidfile] [-p port]\n"
            "  [-b battery-log]\n"
            "Options:\n"
            "  -h\t\tPrint this message\n"
            "  -d\t\tTurn on debugging messages and do not daemonize\n"
            "  -o\t\tOpen loop path demo\n"
            "  -l logfile\tSend log output to the given file\n"
            "  -i pidfile\tWrite the process ID to the given file\n"
            "  -p port\tListen on the given port for MTP messages\n"
            "  -b battery-log\tAppend battery log data to the given file\n"
            "    \t\t(Default: %s)\n",
            BATTERY_LOG_PATH);
Timothy Stack's avatar
 
Timothy Stack committed
142
143
144
145
}

int main(int argc, char *argv[])
{
146
    int c, port = PILOT_PORT, serv_sock, on_off = 1, ol_demo = 0;
Timothy Stack's avatar
Timothy Stack committed
147
    const char *logfile = NULL, *pidfile = NULL;
Timothy Stack's avatar
 
Timothy Stack committed
148
    const char *batteryfile = BATTERY_LOG_PATH;
149
    const char *sfile = DEFAULT_SFILE;
Timothy Stack's avatar
 
Timothy Stack committed
150
151
152
    int retval = EXIT_SUCCESS;
    unsigned long now;
    FILE *batterylog;
153
    FILE *sdata_in;
Timothy Stack's avatar
 
Timothy Stack committed
154
155
156
    aIOLib ioRef;
    aErr err;

157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
    while ((c = getopt(argc, argv, "hdop:l:i:b:")) != -1) {
        switch (c) {
        case 'h':
            usage();
            exit(0);
            break;
        case 'd':
            debug += 1;
            break;
        case 'o':
            ol_demo = 1;
            break;
        case 'l':
            logfile = optarg;
            break;
        case 'i':
            pidfile = optarg;
            break;
        case 'p':
            if (sscanf(optarg, "%d", &port) != 1) {
                fprintf(stderr,
                        "error: -p option is not a number: %s\n",
                        optarg);
                usage();
                exit(1);
            }
            break;
        case 'b':
            batteryfile = optarg;
            break;
        }
Timothy Stack's avatar
 
Timothy Stack committed
188
189
    }

Timothy Stack's avatar
   
Timothy Stack committed
190
#if 0
Timothy Stack's avatar
 
Timothy Stack committed
191
    if (getuid() != 0) {
192
193
        fprintf(stderr, "error: must run as root!\n");
        exit(1);
Timothy Stack's avatar
 
Timothy Stack committed
194
    }
Timothy Stack's avatar
   
Timothy Stack committed
195
#endif
Timothy Stack's avatar
 
Timothy Stack committed
196
197

    if (!debug) {
198
199
        /* Become a daemon */
        daemon(1, 0);
Timothy Stack's avatar
   
Timothy Stack committed
200
    }
Timothy Stack's avatar
 
Timothy Stack committed
201

Timothy Stack's avatar
   
Timothy Stack committed
202
    if (logfile) {
203
204
205
206
207
208
209
210
        int logfd;
        
        if ((logfd = open(logfile, O_CREAT|O_WRONLY|O_APPEND, 0644)) != -1) {
            dup2(logfd, 1);
            dup2(logfd, 2);
            if (logfd > 2)
                close(logfd);
        }
Timothy Stack's avatar
 
Timothy Stack committed
211
    }
Timothy Stack's avatar
   
Timothy Stack committed
212
    
Timothy Stack's avatar
 
Timothy Stack committed
213
    if (pidfile) {
214
215
216
217
218
        FILE *fp;
        
        if ((fp = fopen(pidfile, "w")) != NULL) {
            (void) fclose(fp);
        }
Timothy Stack's avatar
 
Timothy Stack committed
219
220
221
    }

    if ((batterylog = fopen(batteryfile, "a")) == NULL) {
222
223
224
225
        fprintf(stderr,
                "error: cannot open battery log file - %s\n",
                batteryfile);
        exit(1);
Timothy Stack's avatar
   
Timothy Stack committed
226
227
    }

Timothy Stack's avatar
   
Timothy Stack committed
228
229
    acpGarcia garcia;
    
Timothy Stack's avatar
   
Timothy Stack committed
230
    signal(SIGHUP, sigdebug);
Timothy Stack's avatar
   
Timothy Stack committed
231

Timothy Stack's avatar
 
Timothy Stack committed
232
233
234
235
    signal(SIGQUIT, sigquit);
    signal(SIGTERM, sigquit);
    signal(SIGINT, sigquit);

Timothy Stack's avatar
   
Timothy Stack committed
236
237
    signal(SIGSEGV, sigpanic);
    signal(SIGBUS, sigpanic);
Timothy Stack's avatar
 
Timothy Stack committed
238
239
240
241
242
243
    
    signal(SIGPIPE, SIG_IGN);
    
    aIO_GetLibRef(&ioRef, &err);

    if (!wait_for_brainstem_link(ioRef, garcia)) {
244
245
246
247
        fprintf(stderr,
                "error: could not connect to robot %d\n",
                garcia.getNamedValue("status")->getIntVal());
        exit(1);
Timothy Stack's avatar
 
Timothy Stack committed
248
249
    }
    else {
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
        struct sockaddr_in saddr;
        acpValue av;

        if (debug) {
            fprintf(stderr, "debug: connected to brainstem\n");
        }

        /* Make sure the units used by the robot are what we expect. */
        av.set("radians");
        garcia.setNamedValue("angle-units-string", &av);

        av.set("meters");
        garcia.setNamedValue("distance-units-string", &av);

        /* turn off fall sensors */
        av.set(0);
        garcia.setNamedValue("down-ranger-enable", &av);
        
      
      
        if (1 == ol_demo) {
          /* open loop demonstration mode */
          
          float e_in = 0.0f, alpha_in = 0.0f, theta_in = 0.0f; /* states */
          float C_u, C_omega; /* controller outputs */
          
          /* controller parameters: */
          float K_gamma = 1.0f, K_h = 1.0f, K_k = 1.0f;
          
          float K_radius = 0.0889f;
          float vleft, vright;
          acpValue av_L;
          acpValue av_R;
          
          acpObject *nullb;  
          
          int lcount = 0;
          
          
          
          if ((sdata_in = fopen(sfile, "r")) == NULL) {
            fprintf(stderr,
            	    "FATAL: Error opening state input file:  %s\n",
                    sfile);
            exit(1);
          }
        
          nullb = garcia.createNamedBehavior("null", NULL);
          av.set(0.2f);
          nullb->setNamedValue("acceleration", &av);
          
          garcia.queueBehavior(nullb);
          

          /* read states (e,alpha,theta) in from file: */
          /* These states will come from the RMCD/EMCD in the future */
          while (3 == fscanf(sdata_in, "%f %f %f\n", &e_in, &alpha_in, &theta_in)) {
          
            lcount++;
            
            /* controller: */
            C_u = 0.8 * tanh(K_gamma * cos(alpha_in) * e_in);
            
            if (0 == alpha_in) {
              C_omega = 0.0f;
            }
            else {
              C_omega = K_k * alpha_in + K_gamma * ((cos(alpha_in)*sin(alpha_in)) / alpha_in) * (alpha_in + K_h * theta_in);
              
              if (C_omega > 26.25f) {
                C_omega = 26.25f;
              }
              if (C_omega < -26.25f) {
                C_omega = -26.25f;
              }
            }
            /* end controller */
            
            /* wheel velocity translator: */
            vleft = C_u - K_radius * C_omega;
            vright = C_u + K_radius * C_omega;
            /* end wheel velocity translator */
            
            
            av_L.set(vleft);
            av_R.set(vright);
            
            garcia.setNamedValue("damped-speed-left", &av_L);
            garcia.setNamedValue("damped-speed-right", &av_R);
            
            vleft = garcia.getNamedValue("damped-speed-left")->getFloatVal();
            vright = garcia.getNamedValue("damped-speed-right")->getFloatVal();
            
            if (debug) {
              fprintf(stderr, "L/R velocities: %f %f\n", vleft, vright);
            }
            
            
            /* wait 0.033 (1/30) seconds */
            garcia.handleCallbacks(33);
          
          }
          if (debug) {
            fprintf(stderr, "Done with file: read %d lines\n", lcount);
          }
          
          /* abort the null primitive: */
          av.set(aGARCIA_ERRFLAG_ABORT);
          garcia.setNamedValue("status", &av);
          
          
          if (sdata_in != NULL) {
              fclose(sdata_in);
              sdata_in = NULL;
          }
        
        
        
        }
        else {
          /* normal mode */
      
      
          memset(&saddr, 0, sizeof(saddr));
Timothy Stack's avatar
 
Timothy Stack committed
374
#if !defined(linux)
375
          saddr.sin_len = sizeof(saddr);
Timothy Stack's avatar
 
Timothy Stack committed
376
#endif
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
          saddr.sin_family = AF_INET;
          saddr.sin_port = htons(port);
          saddr.sin_addr.s_addr = INADDR_ANY;
        
          if ((serv_sock = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
            perror("socket");
          }
          else if (setsockopt(serv_sock,
                            SOL_SOCKET,
                            SO_REUSEADDR,
                            &on_off,
                            sizeof(on_off)) == -1) {
            perror("setsockopt");
          }
          else if (bind(serv_sock,
                      (struct sockaddr *)&saddr,
                      sizeof(saddr)) == -1) {
            perror("bind");
          }
          else if (listen(serv_sock, 5) == -1) {
            perror("listen");
          }
          else {
            int rmc_telemetry_timeout = 60;
            pilotClient::list clients;
            fd_set readfds, writefds;
            
            dashboard db(garcia, batterylog);
            wheelManager wm(garcia);
            pilotButtonCallback pbc(db, wm);
            
            FD_ZERO(&readfds);
            FD_ZERO(&writefds);
            FD_SET(serv_sock, &readfds);

            wm.setDashboard(&db);
            do {
                fd_set rreadyfds = readfds, wreadyfds = writefds;
                struct timeval tv_zero = { 0, 0 };
                int rc;

                /* Poll the file descriptors, don't block */
                rc = select(FD_SETSIZE,
                            &rreadyfds,
                            &wreadyfds,
                            NULL,
                            &tv_zero);
                if (rc > 0) {
                    bool do_telem = db.wasTelemetryUpdated();
                    pilotClient::iterator i, j;
                    struct mtp_packet tmp;
                    
                    if (FD_ISSET(serv_sock, &rreadyfds)) {
                        struct sockaddr_in peer_sin;
                        socklen_t slen;
                        int cfd;
                        
                        slen = sizeof(peer_sin);
                        if ((cfd = accept(serv_sock,
                                          (struct sockaddr *)&peer_sin,
                                          &slen)) == -1) {
                            perror("accept");
                        }
                        else {
                            pilotClient *pc = new pilotClient(cfd, wm, db);
                            
                            if (debug) {
                                fprintf(stderr,
                                        "debug: connect from %s:%d\n",
                                        inet_ntoa(peer_sin.sin_addr),
                                        ntohs(peer_sin.sin_port));
                            }
                            
                            pc->setFD(&readfds);
                            pc->setFD(&writefds);
                            clients.push_back(pc);
                        }
                    }
                    
                    if (do_telem) {
                        mtp_init_packet(&tmp,
                                        MA_Opcode, MTP_TELEMETRY,
                                        MA_Role, MTP_ROLE_RMC,
                                        MA_GarciaTelemetry, db.getTelemetry(),
                                        MA_TAG_DONE);

                        if (pilotClient::pc_rmc_client != NULL) {
                            rmc_telemetry_timeout -= 1;
                            if (rmc_telemetry_timeout <= 0) {
                                pilotClient *pc = pilotClient::pc_rmc_client;
                                
                                rmc_telemetry_timeout = 60;
                                if (mtp_send_packet(pc->getHandle(), &tmp) !=
                                    MTP_PP_SUCCESS) {
                                    fprintf(stderr,
                                            "error: cannot send telemetry to "
                                            "rmcd\n");
                                }
                            }
                        }
                    }

                    for (i = clients.begin(); i != clients.end(); ) {
                        bool bad_client = false;
                        pilotClient *pc = *i;
                        
                        j = i++;
                        if (pc->isFDSet(&rreadyfds)) {
                            do {
                                struct mtp_packet mp;
                                
                                if ((mtp_receive_packet(pc->getHandle(),
                                                        &mp) !=
                                     MTP_PP_SUCCESS) ||
                                    !pc->handlePacket(&mp, clients)) {
                                    bad_client = true;
                                }
                                
                                mtp_free_packet(&mp);
                            } while (pc && pc->getHandle()->mh_remaining);
                        }

                        if (!bad_client &&
                            (pc->getRole() == MTP_ROLE_EMULAB) &&
                            pc->isFDSet(&wreadyfds)) {
                            if (do_telem &&
                                mtp_send_packet(pc->getHandle(), &tmp) !=
                                MTP_PP_SUCCESS) {
                                fprintf(stderr,
                                        "error: cannot send telemetry to "
                                        "client\n");

                                bad_client = true;
                            }
                        }
                        
                        if (bad_client) {
                            clients.erase(j);
                            
                            pc->clearFD(&readfds);
                            pc->clearFD(&writefds);
                            
                            delete pc;
                            pc = NULL;
                        }
                    }
                }
                
                garcia.handleCallbacks(50);
                aIO_GetMSTicks(ioRef, &now, NULL);
            } while (looping && db.update(now));

            garcia.flushQueuedBehaviors();
            
            garcia.handleCallbacks(1000);
        }
      }
Timothy Stack's avatar
 
Timothy Stack committed
534
535
536
537
    }

    aIO_ReleaseLibRef(ioRef, &err);

Timothy Stack's avatar
   
Timothy Stack committed
538
    if (batterylog != NULL) {
539
540
        fclose(batterylog);
        batterylog = NULL;
Timothy Stack's avatar
   
Timothy Stack committed
541
    }
Timothy Stack's avatar
 
Timothy Stack committed
542
543
544
    
    return retval;
}