Ticket #30: wmdemo-argv.diff

File wmdemo-argv.diff, 1.7 kB (added by pere@…, 5 years ago)

patch to add argument parsing

  • wmdemo/wmdemo.c

     
    11#include <stdarg.h> 
    22#include <stdio.h> 
    33#include <stdlib.h> 
     4#include <unistd.h> 
    45 
    56#include <cwiid.h> 
    67 
     8/* GetOpt */ 
     9#define OPTSTRING       "h" 
     10extern char *optarg; 
     11extern int optind, opterr, optopt; 
     12 
     13#define USAGE "usage:%s [-h] [bdaddr]\n" 
     14 
    715/* This is a sample program written to demonstrate basic CWiid libwiimote 
    816 * usage, until _actual_ documentation can be written.  It's quick and dirty 
    917 * has a horrible interface, but it's sparce enough to pick out the important 
     
    4856        unsigned char rpt_mode = 0; 
    4957        unsigned char rumble = 0; 
    5058        int exit = 0; 
     59        char *str_addr; 
     60        int c; 
    5161 
    5262        cwiid_set_err(err); 
    5363 
    54         /* Connect to any wiimote */ 
    55         bdaddr = *BDADDR_ANY; 
     64        /* Parse Options */ 
     65        while ((c = getopt(argc, argv, OPTSTRING)) != -1) { 
     66                switch (c) { 
     67                case 'h': 
     68                        printf(USAGE, argv[0]); 
     69                        return 0; 
     70                        break; 
     71                case '?': 
     72                default: 
     73                        return -1; 
     74                        break; 
     75                } 
     76        } 
     77 
     78        /* Connect to any wiimote unless told otherwise */ 
     79        if (optind < argc) { 
     80                if (str2ba(argv[optind], &bdaddr)) { 
     81                        fprintf(stderr, "invalid bdaddr\n"); 
     82                        bdaddr = *BDADDR_ANY; 
     83                } 
     84                optind++; 
     85                if (optind < argc) { 
     86                        fprintf(stderr, "invalid command-line\n"); 
     87                        printf(USAGE, argv[0]); 
     88                        return -1; 
     89                } 
     90        } 
     91        else if ((str_addr = getenv(CWIID_BDADDR)) != NULL) { 
     92                if (str2ba(str_addr, &bdaddr)) { 
     93                        fprintf(stderr, "invalid address in %s\n", 
     94                                CWIID_BDADDR); 
     95                        bdaddr = *BDADDR_ANY; 
     96                } 
     97        } 
     98        else { 
     99                bdaddr = *BDADDR_ANY; 
     100        } 
     101 
    56102        /* Connect to address in string CWIID_BDADDR */ 
    57103        /* str2ba(CWIID_BDADDR, &bdaddr); */ 
    58104