]> git.tdb.fi Git - ext/subsurface.git/blob - parse-xml.c
gasmix: stop tracking nitrogen percentages
[ext/subsurface.git] / parse-xml.c
1 #include <stdio.h>
2 #include <ctype.h>
3 #include <string.h>
4 #include <stdlib.h>
5 #include <errno.h>
6 #include <time.h>
7 #include <libxml/parser.h>
8 #include <libxml/tree.h>
9
10 #include "dive.h"
11
12 int verbose;
13
14 struct dive_table dive_table;
15
16 /*
17  * Add a dive into the dive_table array
18  */
19 static void record_dive(struct dive *dive)
20 {
21         int nr = dive_table.nr, allocated = dive_table.allocated;
22         struct dive **dives = dive_table.dives;
23
24         if (nr >= allocated) {
25                 allocated = (nr + 32) * 3 / 2;
26                 dives = realloc(dives, allocated * sizeof(struct dive *));
27                 if (!dives)
28                         exit(1);
29                 dive_table.dives = dives;
30                 dive_table.allocated = allocated;
31         }
32         dives[nr] = dive;
33         dive_table.nr = nr+1;
34 }
35
36 static void start_match(const char *type, const char *name, char *buffer)
37 {
38         if (verbose > 2)
39                 printf("Matching %s '%s' (%s)\n",
40                         type, name, buffer);
41 }
42
43 static void nonmatch(const char *type, const char *name, char *buffer)
44 {
45         if (verbose > 1)
46                 printf("Unable to match %s '%s' (%s)\n",
47                         type, name, buffer);
48         free(buffer);
49 }
50
51 typedef void (*matchfn_t)(char *buffer, void *);
52
53 static int match(const char *pattern, int plen,
54                  const char *name, int nlen,
55                  matchfn_t fn, char *buf, void *data)
56 {
57         if (plen > nlen)
58                 return 0;
59         if (memcmp(pattern, name + nlen - plen, plen))
60                 return 0;
61         fn(buf, data);
62         return 1;
63 }
64
65 /*
66  * Dive info as it is being built up..
67  */
68 static int alloc_samples;
69 static struct dive *dive;
70 static struct sample *sample;
71 static struct tm tm;
72 static int suunto;
73 static int event_index, gasmix_index;
74
75 static time_t utc_mktime(struct tm *tm)
76 {
77         static const int mdays[] = {
78             0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334
79         };
80         int year = tm->tm_year;
81         int month = tm->tm_mon;
82         int day = tm->tm_mday;
83
84         /* First normalize relative to 1900 */
85         if (year < 70)
86                 year += 100;
87         else if (year > 1900)
88                 year -= 1900;
89
90         /* Normalized to Jan 1, 1970: unix time */
91         year -= 70;
92
93         if (year < 0 || year > 129) /* algo only works for 1970-2099 */
94                 return -1;
95         if (month < 0 || month > 11) /* array bounds */
96                 return -1;
97         if (month < 2 || (year + 2) % 4)
98                 day--;
99         if (tm->tm_hour < 0 || tm->tm_min < 0 || tm->tm_sec < 0)
100                 return -1;
101         return (year * 365 + (year + 1) / 4 + mdays[month] + day) * 24*60*60UL +
102                 tm->tm_hour * 60*60 + tm->tm_min * 60 + tm->tm_sec;
103 }
104
105 static void divedate(char *buffer, void *_when)
106 {
107         int d,m,y;
108         time_t *when = _when;
109
110         if (sscanf(buffer, "%d.%d.%d", &d, &m, &y) == 3) {
111                 tm.tm_year = y;
112                 tm.tm_mon = m-1;
113                 tm.tm_mday = d;
114                 if (tm.tm_sec | tm.tm_min | tm.tm_hour)
115                         *when = utc_mktime(&tm);
116         }
117         free(buffer);
118 }
119
120 static void divetime(char *buffer, void *_when)
121 {
122         int h,m,s = 0;
123         time_t *when = _when;
124
125         if (sscanf(buffer, "%d:%d:%d", &h, &m, &s) >= 2) {
126                 tm.tm_hour = h;
127                 tm.tm_min = m;
128                 tm.tm_sec = s;
129                 if (tm.tm_year)
130                         *when = utc_mktime(&tm);
131         }
132         free(buffer);
133 }
134
135 /* Libdivecomputer: "2011-03-20 10:22:38" */
136 static void divedatetime(char *buffer, void *_when)
137 {
138         int y,m,d;
139         int hr,min,sec;
140         time_t *when = _when;
141
142         if (sscanf(buffer, "%d-%d-%d %d:%d:%d",
143                 &y, &m, &d, &hr, &min, &sec) == 6) {
144                 tm.tm_year = y;
145                 tm.tm_mon = m-1;
146                 tm.tm_mday = d;
147                 tm.tm_hour = hr;
148                 tm.tm_min = min;
149                 tm.tm_sec = sec;
150                 *when = utc_mktime(&tm);
151         }
152         free(buffer);
153 }
154
155 union int_or_float {
156         long i;
157         double fp;
158 };
159
160 enum number_type {
161         NEITHER,
162         INTEGER,
163         FLOAT
164 };
165
166 static enum number_type integer_or_float(char *buffer, union int_or_float *res)
167 {
168         char *end;
169         long val;
170         double fp;
171
172         /* Integer or floating point? */
173         val = strtol(buffer, &end, 10);
174         if (val < 0 || end == buffer)
175                 return NEITHER;
176
177         /* Looks like it might be floating point? */
178         if (*end == '.') {
179                 errno = 0;
180                 fp = strtod(buffer, &end);
181                 if (!errno) {
182                         res->fp = fp;
183                         return FLOAT;
184                 }
185         }
186
187         res->i = val;
188         return INTEGER;
189 }
190
191 static void pressure(char *buffer, void *_press)
192 {
193         pressure_t *pressure = _press;
194         union int_or_float val;
195
196         switch (integer_or_float(buffer, &val)) {
197         case FLOAT:
198                 /* Maybe it's in Bar? */
199                 if (val.fp < 500.0) {
200                         pressure->mbar = val.fp * 1000;
201                         break;
202                 }
203                 printf("Unknown fractional pressure reading %s\n", buffer);
204                 break;
205
206         case INTEGER:
207                 /*
208                  * Random integer? Maybe in PSI? Or millibar already?
209                  *
210                  * We assume that 5 bar is a ridiculous tank pressure,
211                  * so if it's smaller than 5000, it's in PSI..
212                  */
213                 if (val.i < 5000) {
214                         pressure->mbar = val.i * 68.95;
215                         break;
216                 }
217                 pressure->mbar = val.i;
218                 break;
219         default:
220                 printf("Strange pressure reading %s\n", buffer);
221         }
222         free(buffer);
223 }
224
225 static void depth(char *buffer, void *_depth)
226 {
227         depth_t *depth = _depth;
228         union int_or_float val;
229
230         switch (integer_or_float(buffer, &val)) {
231         /* All values are probably in meters */
232         case INTEGER:
233                 val.fp = val.i;
234                 /* fallthrough */
235         case FLOAT:
236                 depth->mm = val.fp * 1000;
237                 break;
238         default:
239                 printf("Strange depth reading %s\n", buffer);
240         }
241         free(buffer);
242 }
243
244 static void temperature(char *buffer, void *_temperature)
245 {
246         temperature_t *temperature = _temperature;
247         union int_or_float val;
248
249         switch (integer_or_float(buffer, &val)) {
250         /* C or F? Who knows? Let's default to Celsius */
251         case INTEGER:
252                 val.fp = val.i;
253                 /* Fallthrough */
254         case FLOAT:
255                 /* Ignore zero. It means "none" */
256                 if (!val.fp)
257                         break;
258                 /* Celsius */
259                 if (val.fp < 50.0) {
260                         temperature->mkelvin = (val.fp + 273.16) * 1000;
261                         break;
262                 }
263                 /* Fahrenheit */
264                 if (val.fp < 212.0) {
265                         temperature->mkelvin = (val.fp + 459.67) * 5000/9;
266                         break;
267                 }
268                 /* Kelvin or already millikelvin */
269                 if (val.fp < 1000.0)
270                         val.fp *= 1000;
271                 temperature->mkelvin = val.fp;
272                 break;
273         default:
274                 printf("Strange temperature reading %s\n", buffer);
275         }
276         free(buffer);
277 }
278
279 static void sampletime(char *buffer, void *_time)
280 {
281         int i;
282         int min, sec;
283         duration_t *time = _time;
284
285         i = sscanf(buffer, "%d:%d", &min, &sec);
286         switch (i) {
287         case 1:
288                 sec = min;
289                 min = 0;
290         /* fallthrough */
291         case 2:
292                 time->seconds = sec + min*60;
293                 break;
294         default:
295                 printf("Strange sample time reading %s\n", buffer);
296         }
297         free(buffer);
298 }
299
300 static void duration(char *buffer, void *_time)
301 {
302         sampletime(buffer, _time);
303 }
304
305 static void percent(char *buffer, void *_fraction)
306 {
307         fraction_t *fraction = _fraction;
308         union int_or_float val;
309
310         switch (integer_or_float(buffer, &val)) {
311         /* C or F? Who knows? Let's default to Celsius */
312         case INTEGER:
313                 val.fp = val.i;
314                 /* Fallthrough */
315         case FLOAT:
316                 if (val.fp <= 100.0)
317                         fraction->permille = val.fp * 10 + 0.5;
318                 break;
319
320         default:
321                 printf("Strange percentage reading %s\n", buffer);
322                 break;
323         }
324         free(buffer);
325 }
326
327 static void gasmix(char *buffer, void *_fraction)
328 {
329         /* libdivecomputer does negative percentages. */
330         if (*buffer == '-')
331                 return;
332         if (gasmix_index < MAX_MIXES)
333                 percent(buffer, _fraction);
334 }
335
336 static void gasmix_nitrogen(char *buffer, void *_gasmix)
337 {
338         /* Ignore n2 percentages. There's no value in them. */
339 }
340
341 #define MATCH(pattern, fn, dest) \
342         match(pattern, strlen(pattern), name, len, fn, buf, dest)
343
344 /* We're in samples - try to convert the random xml value to something useful */
345 static void try_to_fill_sample(struct sample *sample, const char *name, char *buf)
346 {
347         int len = strlen(name);
348
349         start_match("sample", name, buf);
350         if (MATCH(".sample.pressure", pressure, &sample->tankpressure))
351                 return;
352         if (MATCH(".sample.cylpress", pressure, &sample->tankpressure))
353                 return;
354         if (MATCH(".sample.depth", depth, &sample->depth))
355                 return;
356         if (MATCH(".sample.temperature", temperature, &sample->temperature))
357                 return;
358         if (MATCH(".sample.sampletime", sampletime, &sample->time))
359                 return;
360         if (MATCH(".sample.time", sampletime, &sample->time))
361                 return;
362
363         nonmatch("sample", name, buf);
364 }
365
366 /*
367  * Crazy suunto xml. Look at how those o2/he things match up.
368  */
369 static int suunto_dive_match(struct dive *dive, const char *name, int len, char *buf)
370 {
371         return  MATCH(".o2pct", percent, &dive->gasmix[0].o2) ||
372                 MATCH(".hepct_0", percent, &dive->gasmix[0].he) ||
373                 MATCH(".o2pct_2", percent, &dive->gasmix[1].o2) ||
374                 MATCH(".hepct_1", percent, &dive->gasmix[1].he) ||
375                 MATCH(".o2pct_3", percent, &dive->gasmix[2].o2) ||
376                 MATCH(".hepct_2", percent, &dive->gasmix[2].he) ||
377                 MATCH(".o2pct_4", percent, &dive->gasmix[3].o2) ||
378                 MATCH(".hepct_3", percent, &dive->gasmix[3].he);
379 }
380
381 /* We're in the top-level dive xml. Try to convert whatever value to a dive value */
382 static void try_to_fill_dive(struct dive *dive, const char *name, char *buf)
383 {
384         int len = strlen(name);
385
386         start_match("dive", name, buf);
387         if (MATCH(".date", divedate, &dive->when))
388                 return;
389         if (MATCH(".time", divetime, &dive->when))
390                 return;
391         if (MATCH(".datetime", divedatetime, &dive->when))
392                 return;
393         if (MATCH(".maxdepth", depth, &dive->maxdepth))
394                 return;
395         if (MATCH(".meandepth", depth, &dive->meandepth))
396                 return;
397         if (MATCH(".divetime", duration, &dive->duration))
398                 return;
399         if (MATCH(".divetimesec", duration, &dive->duration))
400                 return;
401         if (MATCH(".surfacetime", duration, &dive->surfacetime))
402                 return;
403         if (MATCH(".airtemp", temperature, &dive->airtemp))
404                 return;
405         if (MATCH(".watertemp", temperature, &dive->watertemp))
406                 return;
407         if (MATCH(".cylinderstartpressure", pressure, &dive->beginning_pressure))
408                 return;
409         if (MATCH(".cylinderendpressure", pressure, &dive->end_pressure))
410                 return;
411
412         if (MATCH(".o2", gasmix, &dive->gasmix[gasmix_index].o2))
413                 return;
414         if (MATCH(".n2", gasmix_nitrogen, &dive->gasmix[gasmix_index]))
415                 return;
416         if (MATCH(".he", gasmix, &dive->gasmix[gasmix_index].he))
417                 return;
418
419         /* Suunto XML files are some crazy sh*t. */
420         if (suunto && suunto_dive_match(dive, name, len, buf))
421                 return;
422
423         nonmatch("dive", name, buf);
424 }
425
426 static unsigned int dive_size(int samples)
427 {
428         return sizeof(struct dive) + samples*sizeof(struct sample);
429 }
430
431 /*
432  * File boundaries are dive boundaries. But sometimes there are
433  * multiple dives per file, so there can be other events too that
434  * trigger a "new dive" marker and you may get some nesting due
435  * to that. Just ignore nesting levels.
436  */
437 static void dive_start(void)
438 {
439         unsigned int size;
440
441         if (dive)
442                 return;
443
444         alloc_samples = 5;
445         size = dive_size(alloc_samples);
446         dive = malloc(size);
447         if (!dive)
448                 exit(1);
449         memset(dive, 0, size);
450         memset(&tm, 0, sizeof(tm));
451 }
452
453 static char *generate_name(struct dive *dive)
454 {
455         int len;
456         struct tm *tm;
457         char buffer[256], *p;
458
459         tm = gmtime(&dive->when);
460
461         len = snprintf(buffer, sizeof(buffer),
462                 "%04d-%02d-%02d "
463                 "%02d:%02d:%02d "
464                 "(%d ft, %d min)",
465                 tm->tm_year+1900, tm->tm_mon+1, tm->tm_mday,
466                 tm->tm_hour, tm->tm_min, tm->tm_sec,
467                 to_feet(dive->maxdepth), dive->duration.seconds / 60);
468         p = malloc(len+1);
469         if (!p)
470                 exit(1);
471         memcpy(p, buffer, len+1);
472         return p;
473 }
474
475 static void sanitize_gasmix(struct dive *dive)
476 {
477         int i;
478
479         for (i = 0; i < MAX_MIXES; i++) {
480                 gasmix_t *mix = dive->gasmix+i;
481                 unsigned int o2, he;
482
483                 o2 = mix->o2.permille;
484                 he = mix->he.permille;
485
486                 /* Regular air: leave empty */
487                 if (!he) {
488                         if (!o2)
489                                 continue;
490                         /* 20.9% or 21% O2 is just air */
491                         if (o2 >= 209 && o2 <= 210) {
492                                 mix->o2.permille = 0;
493                                 continue;
494                         }
495                 }
496
497                 /* Sane mix? */
498                 if (o2 <= 1000 && he <= 1000 && o2+he <= 1000)
499                         continue;
500                 fprintf(stderr, "Odd gasmix: %d O2 %d He\n", o2, he);
501                 memset(mix, 0, sizeof(*mix));
502         }
503 }
504
505 static void dive_end(void)
506 {
507         if (!dive)
508                 return;
509         if (!dive->name)
510                 dive->name = generate_name(dive);
511         sanitize_gasmix(dive);
512         record_dive(dive);
513         dive = NULL;
514         gasmix_index = 0;
515 }
516
517 static void suunto_start(void)
518 {
519         suunto++;
520 }
521
522 static void suunto_end(void)
523 {
524         suunto--;
525 }
526
527 static void event_start(void)
528 {
529 }
530
531 static void event_end(void)
532 {
533         event_index++;
534 }
535
536 static void gasmix_start(void)
537 {
538 }
539
540 static void gasmix_end(void)
541 {
542         gasmix_index++;
543 }
544
545 static void sample_start(void)
546 {
547         int nr;
548
549         if (!dive)
550                 return;
551         nr = dive->samples;
552         if (nr >= alloc_samples) {
553                 unsigned int size;
554
555                 alloc_samples = (alloc_samples * 3)/2 + 10;
556                 size = dive_size(alloc_samples);
557                 dive = realloc(dive, size);
558                 if (!dive)
559                         return;
560         }
561         sample = dive->sample + nr;
562         memset(sample, 0, sizeof(*sample));
563         event_index = 0;
564 }
565
566 static void sample_end(void)
567 {
568         if (!dive)
569                 return;
570
571         if (sample->time.seconds > dive->duration.seconds) {
572                 if (sample->depth.mm)
573                         dive->duration = sample->time;
574         }
575
576         if (sample->depth.mm > dive->maxdepth.mm)
577                 dive->maxdepth.mm = sample->depth.mm;
578
579         sample = NULL;
580         dive->samples++;
581 }
582
583 static void entry(const char *name, int size, const char *raw)
584 {
585         char *buf = malloc(size+1);
586
587         if (!buf)
588                 return;
589         memcpy(buf, raw, size);
590         buf[size] = 0;
591         if (sample) {
592                 try_to_fill_sample(sample, name, buf);
593                 return;
594         }
595         if (dive) {
596                 try_to_fill_dive(dive, name, buf);
597                 return;
598         }
599 }
600
601 static const char *nodename(xmlNode *node, char *buf, int len)
602 {
603         if (!node || !node->name)
604                 return "root";
605
606         buf += len;
607         *--buf = 0;
608         len--;
609
610         for(;;) {
611                 const char *name = node->name;
612                 int i = strlen(name);
613                 while (--i >= 0) {
614                         unsigned char c = name[i];
615                         *--buf = tolower(c);
616                         if (!--len)
617                                 return buf;
618                 }
619                 node = node->parent;
620                 if (!node || !node->name)
621                         return buf;
622                 *--buf = '.';
623                 if (!--len)
624                         return buf;
625         }
626 }
627
628 #define MAXNAME 64
629
630 static void visit_one_node(xmlNode *node)
631 {
632         int len;
633         const unsigned char *content;
634         char buffer[MAXNAME];
635         const char *name;
636
637         content = node->content;
638         if (!content)
639                 return;
640
641         /* Trim whitespace at beginning */
642         while (isspace(*content))
643                 content++;
644
645         /* Trim whitespace at end */
646         len = strlen(content);
647         while (len && isspace(content[len-1]))
648                 len--;
649
650         if (!len)
651                 return;
652
653         /* Don't print out the node name if it is "text" */
654         if (!strcmp(node->name, "text"))
655                 node = node->parent;
656
657         name = nodename(node, buffer, sizeof(buffer));
658
659         entry(name, len, content);
660 }
661
662 static void traverse(xmlNode *root);
663
664 static void traverse_properties(xmlNode *node)
665 {
666         xmlAttr *p;
667
668         for (p = node->properties; p; p = p->next)
669                 traverse(p->children);
670 }
671
672 static void visit(xmlNode *n)
673 {
674         visit_one_node(n);
675         traverse_properties(n);
676         traverse(n->children);
677 }
678
679 /*
680  * I'm sure this could be done as some fancy DTD rules.
681  * It's just not worth the headache.
682  */
683 static struct nesting {
684         const char *name;
685         void (*start)(void), (*end)(void);
686 } nesting[] = {
687         { "dive", dive_start, dive_end },
688         { "SUUNTO", suunto_start, suunto_end },
689         { "sample", sample_start, sample_end },
690         { "SAMPLE", sample_start, sample_end },
691         { "event", event_start, event_end },
692         { "gasmix", gasmix_start, gasmix_end },
693         { NULL, }
694 };
695
696 static void traverse(xmlNode *root)
697 {
698         xmlNode *n;
699
700         for (n = root; n; n = n->next) {
701                 struct nesting *rule = nesting;
702
703                 do {
704                         if (!strcmp(rule->name, n->name))
705                                 break;
706                         rule++;
707                 } while (rule->name);
708
709                 if (rule->start)
710                         rule->start();
711                 visit(n);
712                 if (rule->end)
713                         rule->end();
714         }
715 }
716
717 void parse_xml_file(const char *filename)
718 {
719         xmlDoc *doc;
720
721         doc = xmlReadFile(filename, NULL, 0);
722         if (!doc) {
723                 fprintf(stderr, "Failed to parse '%s'.\n", filename);
724                 return;
725         }
726
727         dive_start();
728         traverse(xmlDocGetRootElement(doc));
729         dive_end();
730         xmlFreeDoc(doc);
731         xmlCleanupParser();
732 }
733
734 void parse_xml_init(void)
735 {
736         LIBXML_TEST_VERSION
737 }