]> git.tdb.fi Git - ext/subsurface.git/blob - parse-xml.c
libdivecomputer does crazy gas mixes too
[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
337 #define MATCH(pattern, fn, dest) \
338         match(pattern, strlen(pattern), name, len, fn, buf, dest)
339
340 /* We're in samples - try to convert the random xml value to something useful */
341 static void try_to_fill_sample(struct sample *sample, const char *name, char *buf)
342 {
343         int len = strlen(name);
344
345         start_match("sample", name, buf);
346         if (MATCH(".sample.pressure", pressure, &sample->tankpressure))
347                 return;
348         if (MATCH(".sample.cylpress", pressure, &sample->tankpressure))
349                 return;
350         if (MATCH(".sample.depth", depth, &sample->depth))
351                 return;
352         if (MATCH(".sample.temperature", temperature, &sample->temperature))
353                 return;
354         if (MATCH(".sample.sampletime", sampletime, &sample->time))
355                 return;
356         if (MATCH(".sample.time", sampletime, &sample->time))
357                 return;
358
359         nonmatch("sample", name, buf);
360 }
361
362 /*
363  * Crazy suunto xml. Look at how those o2/he things match up.
364  */
365 static int suunto_dive_match(struct dive *dive, const char *name, int len, char *buf)
366 {
367         return  MATCH(".o2pct", percent, &dive->gasmix[0].o2) ||
368                 MATCH(".hepct_0", percent, &dive->gasmix[0].he) ||
369                 MATCH(".o2pct_2", percent, &dive->gasmix[1].o2) ||
370                 MATCH(".hepct_1", percent, &dive->gasmix[1].he) ||
371                 MATCH(".o2pct_3", percent, &dive->gasmix[2].o2) ||
372                 MATCH(".hepct_2", percent, &dive->gasmix[2].he) ||
373                 MATCH(".o2pct_4", percent, &dive->gasmix[3].o2) ||
374                 MATCH(".hepct_3", percent, &dive->gasmix[3].he);
375 }
376
377 /* We're in the top-level dive xml. Try to convert whatever value to a dive value */
378 static void try_to_fill_dive(struct dive *dive, const char *name, char *buf)
379 {
380         int len = strlen(name);
381
382         start_match("dive", name, buf);
383         if (MATCH(".date", divedate, &dive->when))
384                 return;
385         if (MATCH(".time", divetime, &dive->when))
386                 return;
387         if (MATCH(".datetime", divedatetime, &dive->when))
388                 return;
389         if (MATCH(".maxdepth", depth, &dive->maxdepth))
390                 return;
391         if (MATCH(".meandepth", depth, &dive->meandepth))
392                 return;
393         if (MATCH(".divetime", duration, &dive->duration))
394                 return;
395         if (MATCH(".divetimesec", duration, &dive->duration))
396                 return;
397         if (MATCH(".surfacetime", duration, &dive->surfacetime))
398                 return;
399         if (MATCH(".airtemp", temperature, &dive->airtemp))
400                 return;
401         if (MATCH(".watertemp", temperature, &dive->watertemp))
402                 return;
403         if (MATCH(".cylinderstartpressure", pressure, &dive->beginning_pressure))
404                 return;
405         if (MATCH(".cylinderendpressure", pressure, &dive->end_pressure))
406                 return;
407
408         if (MATCH(".o2", gasmix, &dive->gasmix[gasmix_index].o2))
409                 return;
410         if (MATCH(".n2", gasmix, &dive->gasmix[gasmix_index].n2))
411                 return;
412         if (MATCH(".he", gasmix, &dive->gasmix[gasmix_index].he))
413                 return;
414
415         /* Suunto XML files are some crazy sh*t. */
416         if (suunto && suunto_dive_match(dive, name, len, buf))
417                 return;
418
419         nonmatch("dive", name, buf);
420 }
421
422 static unsigned int dive_size(int samples)
423 {
424         return sizeof(struct dive) + samples*sizeof(struct sample);
425 }
426
427 /*
428  * File boundaries are dive boundaries. But sometimes there are
429  * multiple dives per file, so there can be other events too that
430  * trigger a "new dive" marker and you may get some nesting due
431  * to that. Just ignore nesting levels.
432  */
433 static void dive_start(void)
434 {
435         unsigned int size;
436
437         if (dive)
438                 return;
439
440         alloc_samples = 5;
441         size = dive_size(alloc_samples);
442         dive = malloc(size);
443         if (!dive)
444                 exit(1);
445         memset(dive, 0, size);
446         memset(&tm, 0, sizeof(tm));
447 }
448
449 static char *generate_name(struct dive *dive)
450 {
451         int len;
452         struct tm *tm;
453         char buffer[256], *p;
454
455         tm = gmtime(&dive->when);
456
457         len = snprintf(buffer, sizeof(buffer),
458                 "%04d-%02d-%02d "
459                 "%02d:%02d:%02d "
460                 "(%d ft, %d min)",
461                 tm->tm_year+1900, tm->tm_mon+1, tm->tm_mday,
462                 tm->tm_hour, tm->tm_min, tm->tm_sec,
463                 to_feet(dive->maxdepth), dive->duration.seconds / 60);
464         p = malloc(len+1);
465         if (!p)
466                 exit(1);
467         memcpy(p, buffer, len+1);
468         return p;
469 }
470
471 static void dive_end(void)
472 {
473         if (!dive)
474                 return;
475         if (!dive->name)
476                 dive->name = generate_name(dive);
477         record_dive(dive);
478         dive = NULL;
479         gasmix_index = 0;
480 }
481
482 static void suunto_start(void)
483 {
484         suunto++;
485 }
486
487 static void suunto_end(void)
488 {
489         suunto--;
490 }
491
492 static void event_start(void)
493 {
494 }
495
496 static void event_end(void)
497 {
498         event_index++;
499 }
500
501 static void gasmix_start(void)
502 {
503 }
504
505 static void gasmix_end(void)
506 {
507         gasmix_index++;
508 }
509
510 static void sample_start(void)
511 {
512         int nr;
513
514         if (!dive)
515                 return;
516         nr = dive->samples;
517         if (nr >= alloc_samples) {
518                 unsigned int size;
519
520                 alloc_samples = (alloc_samples * 3)/2 + 10;
521                 size = dive_size(alloc_samples);
522                 dive = realloc(dive, size);
523                 if (!dive)
524                         return;
525         }
526         sample = dive->sample + nr;
527         memset(sample, 0, sizeof(*sample));
528         event_index = 0;
529 }
530
531 static void sample_end(void)
532 {
533         if (!dive)
534                 return;
535
536         if (sample->time.seconds > dive->duration.seconds) {
537                 if (sample->depth.mm)
538                         dive->duration = sample->time;
539         }
540
541         if (sample->depth.mm > dive->maxdepth.mm)
542                 dive->maxdepth.mm = sample->depth.mm;
543
544         sample = NULL;
545         dive->samples++;
546 }
547
548 static void entry(const char *name, int size, const char *raw)
549 {
550         char *buf = malloc(size+1);
551
552         if (!buf)
553                 return;
554         memcpy(buf, raw, size);
555         buf[size] = 0;
556         if (sample) {
557                 try_to_fill_sample(sample, name, buf);
558                 return;
559         }
560         if (dive) {
561                 try_to_fill_dive(dive, name, buf);
562                 return;
563         }
564 }
565
566 static const char *nodename(xmlNode *node, char *buf, int len)
567 {
568         if (!node || !node->name)
569                 return "root";
570
571         buf += len;
572         *--buf = 0;
573         len--;
574
575         for(;;) {
576                 const char *name = node->name;
577                 int i = strlen(name);
578                 while (--i >= 0) {
579                         unsigned char c = name[i];
580                         *--buf = tolower(c);
581                         if (!--len)
582                                 return buf;
583                 }
584                 node = node->parent;
585                 if (!node || !node->name)
586                         return buf;
587                 *--buf = '.';
588                 if (!--len)
589                         return buf;
590         }
591 }
592
593 #define MAXNAME 64
594
595 static void visit_one_node(xmlNode *node)
596 {
597         int len;
598         const unsigned char *content;
599         char buffer[MAXNAME];
600         const char *name;
601
602         content = node->content;
603         if (!content)
604                 return;
605
606         /* Trim whitespace at beginning */
607         while (isspace(*content))
608                 content++;
609
610         /* Trim whitespace at end */
611         len = strlen(content);
612         while (len && isspace(content[len-1]))
613                 len--;
614
615         if (!len)
616                 return;
617
618         /* Don't print out the node name if it is "text" */
619         if (!strcmp(node->name, "text"))
620                 node = node->parent;
621
622         name = nodename(node, buffer, sizeof(buffer));
623
624         entry(name, len, content);
625 }
626
627 static void traverse(xmlNode *root);
628
629 static void traverse_properties(xmlNode *node)
630 {
631         xmlAttr *p;
632
633         for (p = node->properties; p; p = p->next)
634                 traverse(p->children);
635 }
636
637 static void visit(xmlNode *n)
638 {
639         visit_one_node(n);
640         traverse_properties(n);
641         traverse(n->children);
642 }
643
644 /*
645  * I'm sure this could be done as some fancy DTD rules.
646  * It's just not worth the headache.
647  */
648 static struct nesting {
649         const char *name;
650         void (*start)(void), (*end)(void);
651 } nesting[] = {
652         { "dive", dive_start, dive_end },
653         { "SUUNTO", suunto_start, suunto_end },
654         { "sample", sample_start, sample_end },
655         { "SAMPLE", sample_start, sample_end },
656         { "event", event_start, event_end },
657         { "gasmix", gasmix_start, gasmix_end },
658         { NULL, }
659 };
660
661 static void traverse(xmlNode *root)
662 {
663         xmlNode *n;
664
665         for (n = root; n; n = n->next) {
666                 struct nesting *rule = nesting;
667
668                 do {
669                         if (!strcmp(rule->name, n->name))
670                                 break;
671                         rule++;
672                 } while (rule->name);
673
674                 if (rule->start)
675                         rule->start();
676                 visit(n);
677                 if (rule->end)
678                         rule->end();
679         }
680 }
681
682 void parse_xml_file(const char *filename)
683 {
684         xmlDoc *doc;
685
686         doc = xmlReadFile(filename, NULL, 0);
687         if (!doc) {
688                 fprintf(stderr, "Failed to parse '%s'.\n", filename);
689                 return;
690         }
691
692         dive_start();
693         traverse(xmlDocGetRootElement(doc));
694         dive_end();
695         xmlFreeDoc(doc);
696         xmlCleanupParser();
697 }
698
699 void parse_xml_init(void)
700 {
701         LIBXML_TEST_VERSION
702 }