source: BAORadio/libindi/libindi/tools/getINDIproperty.c @ 642

Last change on this file since 642 was 642, checked in by frichard, 12 years ago

-Alignement des antennes
-Version 0.0.9 de libindi

File size: 16.2 KB
Line 
1/* connect to an INDI server and show all desired device.property.element
2 *   with possible wild card * in any category.
3 * All types but BLOBs are handled from their defXXX messages. Receipt of a
4 *   defBLOB sends enableBLOB then uses setBLOBVector for the value. BLOBs
5 *   are stored in a file dev.nam.elem.format. only .z compression is handled.
6 * exit status: 0 at least some found, 1 some not found, 2 real trouble.
7 */
8
9#include <stdio.h>
10#include <stdlib.h>
11#include <math.h>
12#include <string.h>
13#include <errno.h>
14#include <signal.h>
15#include <time.h>
16#include <unistd.h>
17#include <sys/types.h>
18#include <sys/socket.h>
19#include <netinet/in.h>
20#include <netdb.h>
21
22#include "indiapi.h"
23#include "lilxml.h"
24#include "base64.h"
25#include "zlib.h"
26
27
28/* table of INDI definition elements, plus setBLOB.
29 * we also look for set* if -m
30 */
31typedef struct {
32    char *vec;          /* vector name */
33    char *one;          /* one element name */
34} INDIDef;
35static INDIDef defs[] = {
36    {"defTextVector",   "defText"},
37    {"defNumberVector", "defNumber"},
38    {"defSwitchVector", "defSwitch"},
39    {"defLightVector",  "defLight"},
40    {"defBLOBVector",   "defBLOB"},
41    {"setBLOBVector",   "oneBLOB"},
42    {"setTextVector",   "oneText"},
43    {"setNumberVector", "oneNumber"},
44    {"setSwitchVector", "oneSwitch"},
45    {"setLightVector",  "oneLight"},
46};
47static int ndefs = 6;                   /* or 10 if -m */
48
49/* table of keyword to use in query vs name of INDI defXXX attribute */
50typedef struct {
51    char *keyword;
52    char *indiattr;
53} INDIkwattr;
54static INDIkwattr kwattr[] = {
55    {"_LABEL", "label"},
56    {"_GROUP", "group"},
57    {"_STATE", "state"},
58    {"_PERM", "perm"},
59    {"_TO", "timeout"},
60    {"_TS", "timestamp"},
61};
62#define NKWA   (sizeof(kwattr)/sizeof(kwattr[0]))
63
64typedef struct {
65    char *d;                            /* device to seek */
66    char *p;                            /* property to seek */
67    char *e;                            /* element to seek */
68    int wc : 1;                         /* whether pattern uses wild cards */
69    int ok : 1;                         /* something matched this query */
70} SearchDef;
71static SearchDef *srchs;                /* properties to look for */
72static int nsrchs;
73
74static void usage (void);
75static void crackDPE (char *spec);
76static void addSearchDef (char *dev, char *prop, char *ele);
77static void openINDIServer(void);
78static void getprops(void);
79static void listenINDI(void);
80static int finished (void);
81static void onAlarm (int dummy);
82static int readServerChar(void);
83static void findDPE (XMLEle *root);
84static void findEle (XMLEle *root, char *dev, char *nam, char *defone,
85    SearchDef *sp);
86static void enableBLOBs(char *dev, char *nam);
87static void oneBLOB (XMLEle *root, char *dev, char *nam, char *enam, char *p,
88    int plen);
89
90static char *me;                        /* our name for usage() message */
91static char host_def[] = "localhost";   /* default host name */
92static char *host = host_def;           /* working host name */
93#define INDIPORT        7624            /* default port */
94static int port = INDIPORT;             /* working port number */
95#define TIMEOUT         2               /* default timeout, secs */
96static int timeout = TIMEOUT;           /* working timeout, secs */
97static int verbose;                     /* report extra info */
98static LilXML *lillp;                   /* XML parser context */
99#define WILDCARD        '*'             /* show all in this category */
100static int onematch;                    /* only one possible match */
101static int justvalue;                   /* if just one match show only value */
102static int monitor;                     /* keep watching even after seen def */
103static int directfd = -1;               /* direct filedes to server, if >= 0 */
104static FILE *svrwfp;                    /* FILE * to talk to server */
105static FILE *svrrfp;                    /* FILE * to read from server */
106static int wflag;                       /* show wo properties too */
107
108int
109main (int ac, char *av[])
110{
111        /* save our name */
112        me = av[0];
113
114        /* crack args */
115        while (--ac && **++av == '-') {
116            char *s = *av;
117            while (*++s) {
118                switch (*s) {
119                case '1':       /* just value */
120                    justvalue++;
121                    break;
122                case 'd':
123                    if (ac < 2) {
124                        fprintf (stderr, "-d requires open fileno\n");
125                        usage();
126                    }
127                    directfd = atoi(*++av);
128                    ac--;
129                    break;
130                case 'h':
131                    if (directfd >= 0) {
132                        fprintf (stderr, "Can not combine -d and -h\n");
133                        usage();
134                    }
135                    if (ac < 2) {
136                        fprintf (stderr, "-h requires host name\n");
137                        usage();
138                    }
139                    host = *++av;
140                    ac--;
141                    break;
142                case 'm':
143                    monitor++;
144                    ndefs = 10;                 /* include set*Vectors too */
145                    break;
146                case 'p':
147                    if (directfd >= 0) {
148                        fprintf (stderr, "Can not combine -d and -p\n");
149                        usage();
150                    }
151                    if (ac < 2) {
152                        fprintf (stderr, "-p requires tcp port number\n");
153                        usage();
154                    }
155                    port = atoi(*++av);
156                    ac--;
157                    break;
158                case 't':
159                    if (ac < 2) {
160                        fprintf (stderr, "-t requires timeout\n");
161                        usage();
162                    }
163                    timeout = atoi(*++av);
164                    ac--;
165                    break;
166                case 'v':       /* verbose */
167                    verbose++;
168                    break;
169                case 'w':
170                    wflag++;
171                    break;
172                default:
173                    fprintf (stderr, "Unknown flag: %c\n", *s);
174                    usage();
175                }
176            }
177        }
178
179        /* now ac args starting with av[0] */
180        if (ac == 0)
181            av[ac++] = "*.*.*";         /* default is get everything */
182
183        /* crack each d.p.e */
184        while (ac--)
185            crackDPE (*av++);
186        onematch = nsrchs == 1 && !srchs[0].wc;
187
188        /* open connection */
189        if (directfd >= 0) {
190            svrwfp = fdopen (directfd, "w");
191            svrrfp = fdopen (directfd, "r");
192            setbuf (svrrfp, NULL);      /* don't absorb next guy's stuff */
193            if (!svrwfp || !svrrfp) {
194                fprintf (stderr, "Direct fd %d: %s\n",directfd,strerror(errno));
195                exit(1);
196            }
197            if (verbose)
198                fprintf (stderr, "Using direct fd %d\n", directfd);
199        } else {
200            openINDIServer();
201            if (verbose)
202                fprintf (stderr, "Connected to %s on port %d\n", host, port);
203        }
204
205        /* build a parser context for cracking XML responses */
206        lillp = newLilXML();
207
208        /* issue getProperties */
209        getprops();
210
211        /* listen for responses, looking for d.p.e or timeout */
212        listenINDI();
213
214        return (0);
215}
216
217static void
218usage()
219{
220        int i;
221
222        fprintf(stderr, "Purpose: retrieve readable properties from an INDI server\n");
223        fprintf(stderr, "%s\n", "$Revision: 1.11 $");
224        fprintf(stderr, "Usage: %s [options] [device.property.element ...]\n",me);
225        fprintf(stderr, "  Any component may be \"*\" to match all (beware shell metacharacters).\n");
226        fprintf(stderr, "  Reports all properties if none specified.\n");
227        fprintf(stderr, "  BLOBs are saved in file named device.property.element.format\n");
228        fprintf(stderr, "  In perl try: %s\n", "%props = split (/[=\\n]/, `getINDI`);");
229        fprintf(stderr, "  Set element to one of following to return property attribute:\n");
230        for (i = 0; i < NKWA; i++)
231            fprintf (stderr, "    %10s to report %s\n", kwattr[i].keyword,
232                                                        kwattr[i].indiattr);
233        fprintf(stderr, "Output format: output is fully qualified name=value one per line\n");
234        fprintf(stderr, "  or just value if -1 and exactly one query without wildcards.\n");
235        fprintf(stderr, "Options:\n");
236        fprintf(stderr, "  -1    : print just value if expecting exactly one response\n");
237        fprintf(stderr, "  -d f  : use file descriptor f already open to server\n");
238        fprintf(stderr, "  -h h  : alternate host, default is %s\n", host_def);
239        fprintf(stderr, "  -m    : keep monitoring for more updates\n");
240        fprintf(stderr, "  -p p  : alternate port, default is %d\n", INDIPORT);
241        fprintf(stderr, "  -t t  : max time to wait, default is %d secs\n",TIMEOUT);
242        fprintf(stderr, "  -v    : verbose (cumulative)\n");
243        fprintf(stderr, "  -w    : show write-only properties too\n");
244        fprintf(stderr, "Exit status:\n");
245        fprintf(stderr, "  0: found at least one match for each query\n");
246        fprintf(stderr, "  1: at least one query returned nothing\n");
247        fprintf(stderr, "  2: real trouble, try repeating with -v\n");
248
249        exit (2);
250}
251
252/* crack spec and add to srchs[], else exit */
253static void
254crackDPE (char *spec)
255{
256        char d[1024], p[1024], e[1024];
257
258        if (verbose)
259            fprintf (stderr, "looking for %s\n", spec);
260        if (sscanf (spec, "%[^.].%[^.].%[^.]", d, p, e) != 3) {
261            fprintf (stderr, "Unknown format for property spec: %s\n", spec);
262            usage();
263        }
264
265        addSearchDef (d, p, e);
266}
267
268/* grow srchs[] with the new search */
269static void
270addSearchDef (char *dev, char *prop, char *ele)
271{
272        if (!srchs)
273            srchs = (SearchDef *) malloc (1);           /* realloc seed */
274        srchs = (SearchDef *) realloc (srchs, (nsrchs+1)*sizeof(SearchDef));
275        srchs[nsrchs].d = strcpy (malloc(strlen(dev)+1), dev);
276        srchs[nsrchs].p = strcpy (malloc(strlen(prop)+1), prop);
277        srchs[nsrchs].e = strcpy (malloc(strlen(ele)+1), ele);
278        srchs[nsrchs].wc = *dev==WILDCARD || *prop==WILDCARD || *ele==WILDCARD;
279        srchs[nsrchs].ok = 0;
280        nsrchs++;
281}
282
283/* open a connection to the given host and port.
284 * set svrwfp and svrrfp or die.
285 */
286static void
287openINDIServer (void)
288{
289        struct sockaddr_in serv_addr;
290        struct hostent *hp;
291        int sockfd;
292
293        /* lookup host address */
294        hp = gethostbyname (host);
295        if (!hp) {
296            herror ("gethostbyname");
297            exit (2);
298        }
299
300        /* create a socket to the INDI server */
301        (void) memset ((char *)&serv_addr, 0, sizeof(serv_addr));
302        serv_addr.sin_family = AF_INET;
303        serv_addr.sin_addr.s_addr =
304                            ((struct in_addr *)(hp->h_addr_list[0]))->s_addr;
305        serv_addr.sin_port = htons(port);
306        if ((sockfd = socket (AF_INET, SOCK_STREAM, 0)) < 0) {
307            perror ("socket");
308            exit(2);
309        }
310
311        /* connect */
312        if (connect (sockfd,(struct sockaddr *)&serv_addr,sizeof(serv_addr))<0){
313            perror ("connect");
314            exit(2);
315        }
316
317        /* prepare for line-oriented i/o with client */
318        svrwfp = fdopen (sockfd, "w");
319        svrrfp = fdopen (sockfd, "r");
320}
321
322/* issue getProperties to svrwfp, possibly constrained to one device */
323static void
324getprops()
325{
326        char *onedev = NULL;
327        int i;
328
329        /* find if only need one device */
330        for (i = 0; i < nsrchs; i++) {
331            char *d = srchs[i].d;
332            if (*d == WILDCARD || (onedev && strcmp(d,onedev))) {
333                onedev = NULL;
334                break;
335            } else
336                onedev = d;
337        }
338
339        if (onedev)
340            fprintf(svrwfp, "<getProperties version='%g' device='%s'/>\n",
341                                                                INDIV, onedev);
342        else
343            fprintf(svrwfp, "<getProperties version='%g'/>\n", INDIV);
344        fflush (svrwfp);
345
346        if (verbose)
347            fprintf (stderr, "Queried properties from %s\n", onedev?onedev:"*");
348}
349
350/* listen for INDI traffic on svrrfp.
351 * print matching srchs[] and return when see all.
352 * timeout and exit if any trouble.
353 */
354static void
355listenINDI ()
356{
357        char msg[1024];
358
359        /* arrange to call onAlarm() if not seeing any more defXXX */
360        signal (SIGALRM, onAlarm);
361        alarm (timeout);
362
363        /* read from server, exit if find all requested properties */
364        while (1) {
365            XMLEle *root = readXMLEle (lillp, readServerChar(), msg);
366            if (root) {
367                /* found a complete XML element */
368                if (verbose > 1)
369                    prXMLEle (stderr, root, 0);
370                findDPE (root);
371                if (finished() == 0)
372                    exit (0);           /* found all we want */
373                delXMLEle (root);       /* not yet, delete and continue */
374            } else if (msg[0]) {
375                fprintf (stderr, "Bad XML from %s/%d: %s\n", host, port, msg);
376                exit(2);
377            }
378        }
379}
380
381/* return 0 if we are sure we have everything we are looking for, else -1 */
382static int
383finished ()
384{
385        int i;
386
387        if (monitor)
388            return(-1);
389
390        for (i = 0; i < nsrchs; i++)
391            if (srchs[i].wc || !srchs[i].ok)
392                return (-1);
393        return (0);
394}
395
396/* called after timeout seconds either because we are matching wild cards or
397 * there is something still not found
398 */
399static void
400onAlarm (int dummy)
401{
402        int trouble = 0;
403        int i;
404
405        for (i = 0; i < nsrchs; i++) {
406            if (!srchs[i].ok) {
407                trouble = 1;
408                fprintf (stderr, "No %s.%s.%s from %s:%d\n", srchs[i].d,
409                                        srchs[i].p, srchs[i].e, host, port);
410            }
411        }
412
413        exit (trouble ? 1 : 0);
414}
415
416/* read one char from svrrfp */
417static int
418readServerChar ()
419{
420        int c = fgetc (svrrfp);
421
422        if (c == EOF) {
423            if (ferror(svrrfp))
424                perror ("read");
425            else
426                fprintf (stderr,"INDI server %s/%d disconnected\n", host, port);
427            exit (2);
428        }
429
430        if (verbose > 2)
431            fprintf (stderr, "Read %c\n", c);
432
433        return (c);
434}
435
436/* print value if root is any srchs[] we are looking for*/
437static void
438findDPE (XMLEle *root)
439{
440        int i, j;
441
442        for (i = 0; i < nsrchs; i++) {
443            /* for each property we are looking for */
444            for (j = 0; j < ndefs; j++) {
445                /* for each possible type */
446                if (strcmp (tagXMLEle (root), defs[j].vec) == 0) {
447                    /* legal defXXXVector, check device */
448                    char *dev = (char *) findXMLAttValu (root, "device");
449                    char *idev = srchs[i].d;
450                    if (idev[0] == WILDCARD || !strcmp (dev,idev)) {
451                        /* found device, check name */
452                        char *nam = (char *) findXMLAttValu (root, "name");
453                        char *iprop = srchs[i].p;
454                        if (iprop[0] == WILDCARD || !strcmp (nam,iprop)) {
455                            /* found device and name, check perm */
456                            char *perm = (char *) findXMLAttValu (root, "perm");
457                            if (!wflag && perm[0] && !strchr (perm, 'r')) {
458                                if (verbose)
459                                    fprintf (stderr, "%s.%s is write-only\n",
460                                                                    dev, nam);
461                            } else {
462                                /* check elements or attr keywords */
463                                if (!strcmp (defs[j].vec, "defBLOBVector"))
464                                    enableBLOBs (dev,nam);
465                                else
466                                    findEle(root,dev,nam,defs[j].one,&srchs[i]);
467                                if (onematch)
468                                    return;             /* only one can match */
469                                if (!strncmp (defs[j].vec, "def", 3))
470                                    alarm (timeout);    /* reset timer if def */
471                            }
472                        }
473                    }
474                }
475            }
476        }
477}
478
479/* print elements in root speced in sp (known to be of type defone).
480 * print just value if onematch and justvalue else fully qualified name.
481 */
482static void
483findEle (XMLEle *root, char *dev, char *nam, char *defone, SearchDef *sp)
484{
485        char *iele = sp->e;
486        XMLEle *ep;
487        int i;
488
489        /* check for attr keyword */
490        for (i = 0; i < NKWA; i++) {
491            if (strcmp (iele, kwattr[i].keyword) == 0) {
492                /* just print the property state, not the element values */
493                char *s = (char *) findXMLAttValu (root, kwattr[i].indiattr);
494                sp->ok = 1;                     /* progress */
495                if (onematch && justvalue)
496                    printf ("%s\n", s);
497                else
498                    printf ("%s.%s.%s=%s\n", dev, nam, kwattr[i].keyword, s);
499                return;
500            }
501        }
502
503        /* no special attr, look for specific element name */
504        for (ep = nextXMLEle(root,1); ep; ep = nextXMLEle(root,0)) {
505            if (!strcmp (tagXMLEle (ep), defone)) {
506                /* legal defXXX, check deeper */
507                char *enam = (char *) findXMLAttValu (ep, "name");
508                if (iele[0]==WILDCARD || !strcmp(enam,iele)) {
509                    /* found it! */
510                    char *p = pcdataXMLEle(ep);
511                    sp->ok = 1;                 /* progress */
512                    if (!strcmp (defone, "oneBLOB"))
513                        oneBLOB (ep, dev, nam, enam, p, pcdatalenXMLEle(ep));
514                    else if (onematch && justvalue)
515                        printf ("%s\n", p);
516                    else
517                        printf ("%s.%s.%s=%s\n",  dev, nam, enam, p);
518                    if (onematch)
519                        return;         /* only one can match*/
520                }
521            }
522        }
523}
524
525/* send server command to svrwfp that enables blobs for the given dev nam
526 */
527static void
528enableBLOBs(char *dev, char *nam)
529{
530        if (verbose)
531            fprintf (stderr, "sending enableBLOB %s.%s\n", dev, nam);
532        fprintf (svrwfp,"<enableBLOB device='%s' name='%s'>Also</enableBLOB>\n",
533                                                                    dev, nam);
534        fflush (svrwfp);
535}
536
537/* given a oneBLOB, save
538 */
539static void
540oneBLOB (XMLEle *root, char *dev, char *nam, char *enam, char *p, int plen)
541{
542        char *format;
543        FILE *fp;
544        int bloblen;
545        unsigned char *blob;
546        int ucs;
547        int isz;
548        char fn[128];
549        int i;
550
551        /* get uncompressed size */
552        ucs = atoi(findXMLAttValu (root, "size"));
553        if (verbose)
554            fprintf (stderr, "%s.%s.%s reports uncompressed size as %d\n",
555                                                        dev, nam, enam, ucs);
556
557        /* get format and length */
558        format = (char *) findXMLAttValu (root, "format");
559        isz = !strcmp (&format[strlen(format)-2], ".z");
560
561        /* decode blob from base64 in p */
562        blob = malloc (3*plen/4);
563        bloblen = from64tobits ((char *)blob, p);
564        if (bloblen < 0) {
565            fprintf (stderr, "%s.%s.%s bad base64\n", dev, nam, enam);
566            exit(2);
567        }
568
569        /* uncompress effectively in place if z */
570        if (isz) {
571            uLong nuncomp = ucs;
572            unsigned char *uncomp = malloc (ucs);
573            int ok = uncompress (uncomp, &nuncomp, blob, bloblen);
574            if (ok != Z_OK) {
575                fprintf (stderr, "%s.%s.%s uncompress error %d\n", dev, nam,
576                                                                    enam, ok);
577                exit(2);
578            }
579            free (blob);
580            blob = uncomp;
581            bloblen = nuncomp;
582        }
583
584        /* rig up a file name from property name */
585        i = sprintf (fn, "%s.%s.%s%s", dev, nam, enam, format);
586        if (isz)
587            fn[i-2] = '\0';     /* chop off .z */
588
589        /* save */
590        fp = fopen (fn, "w");
591        if (fp) {
592            if (verbose)
593                fprintf (stderr, "Wrote %s\n", fn);
594            fwrite (blob, bloblen, 1, fp);
595            fclose (fp);
596        } else {
597            fprintf (stderr, "%s: %s\n", fn, strerror(errno));
598        }
599
600        /* clean up */
601        free (blob);
602}
603
604/* For RCS Only -- Do Not Edit */
605static char *rcsid[2] = {(char *)rcsid, "@(#) $RCSfile: getINDI.c,v $ $Date: 2007/10/11 20:11:23 $ $Revision: 1.11 $ $Name:  $"};
Note: See TracBrowser for help on using the repository browser.