]> git.tdb.fi Git - ext/subsurface.git/blob - parse-xml.c
Even more places with pressure and volume conversions
[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 #define __USE_XOPEN
7 #include <time.h>
8 #include <libxml/parser.h>
9 #include <libxml/tree.h>
10
11 #include "dive.h"
12 #include "uemis.h"
13
14 int verbose;
15
16 struct dive_table dive_table;
17
18 /*
19  * Add a dive into the dive_table array
20  */
21 void record_dive(struct dive *dive)
22 {
23         int nr = dive_table.nr, allocated = dive_table.allocated;
24         struct dive **dives = dive_table.dives;
25
26         if (nr >= allocated) {
27                 allocated = (nr + 32) * 3 / 2;
28                 dives = realloc(dives, allocated * sizeof(struct dive *));
29                 if (!dives)
30                         exit(1);
31                 dive_table.dives = dives;
32                 dive_table.allocated = allocated;
33         }
34         dives[nr] = fixup_dive(dive);
35         dive_table.nr = nr+1;
36 }
37
38 static void start_match(const char *type, const char *name, char *buffer)
39 {
40         if (verbose > 2)
41                 printf("Matching %s '%s' (%s)\n",
42                         type, name, buffer);
43 }
44
45 static void nonmatch(const char *type, const char *name, char *buffer)
46 {
47         if (verbose > 1)
48                 printf("Unable to match %s '%s' (%s)\n",
49                         type, name, buffer);
50         free(buffer);
51 }
52
53 typedef void (*matchfn_t)(char *buffer, void *);
54
55 static int match(const char *pattern, int plen,
56                  const char *name, int nlen,
57                  matchfn_t fn, char *buf, void *data)
58 {
59         if (plen > nlen)
60                 return 0;
61         if (memcmp(pattern, name + nlen - plen, plen))
62                 return 0;
63         fn(buf, data);
64         return 1;
65 }
66
67
68 struct units input_units;
69
70 /*
71  * We're going to default to SI units for input. Yes,
72  * technically the SI unit for pressure is Pascal, but
73  * we default to bar (10^5 pascal), which people
74  * actually use. Similarly, C instead of Kelvin.
75  */
76 const struct units SI_units = {
77         .length = METERS,
78         .volume = LITER,
79         .pressure = BAR,
80         .temperature = CELSIUS,
81         .weight = KG
82 };
83
84 const struct units IMPERIAL_units = {
85         .length = FEET,
86         .volume = CUFT,
87         .pressure = PSI,
88         .temperature = FAHRENHEIT,
89         .weight = LBS
90 };
91
92 /*
93  * Dive info as it is being built up..
94  */
95 static struct dive *dive;
96 static struct sample *sample;
97 static struct {
98         int active;
99         duration_t time;
100         int type, flags, value;
101         const char *name;
102 } event;
103 static struct tm tm;
104 static int cylinder_index;
105
106 static enum import_source {
107         UNKNOWN,
108         LIBDIVECOMPUTER,
109         SUUNTO,
110         UEMIS,
111         DIVINGLOG,
112         UDDF,
113 } import_source;
114
115 time_t utc_mktime(struct tm *tm)
116 {
117         static const int mdays[] = {
118             0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334
119         };
120         int year = tm->tm_year;
121         int month = tm->tm_mon;
122         int day = tm->tm_mday;
123
124         /* First normalize relative to 1900 */
125         if (year < 70)
126                 year += 100;
127         else if (year > 1900)
128                 year -= 1900;
129
130         /* Normalized to Jan 1, 1970: unix time */
131         year -= 70;
132
133         if (year < 0 || year > 129) /* algo only works for 1970-2099 */
134                 return -1;
135         if (month < 0 || month > 11) /* array bounds */
136                 return -1;
137         if (month < 2 || (year + 2) % 4)
138                 day--;
139         if (tm->tm_hour < 0 || tm->tm_min < 0 || tm->tm_sec < 0)
140                 return -1;
141         return (year * 365 + (year + 1) / 4 + mdays[month] + day) * 24*60*60UL +
142                 tm->tm_hour * 60*60 + tm->tm_min * 60 + tm->tm_sec;
143 }
144
145 static void divedate(char *buffer, void *_when)
146 {
147         int d,m,y;
148         time_t *when = _when;
149         int success = 0;
150
151         success = tm.tm_sec | tm.tm_min | tm.tm_hour;
152         if (sscanf(buffer, "%d.%d.%d", &d, &m, &y) == 3) {
153                 tm.tm_year = y;
154                 tm.tm_mon = m-1;
155                 tm.tm_mday = d;
156         } else if (sscanf(buffer, "%d-%d-%d", &y, &m, &d) == 3) {
157                 tm.tm_year = y;
158                 tm.tm_mon = m-1;
159                 tm.tm_mday = d;
160         } else {
161                 fprintf(stderr, "Unable to parse date '%s'\n", buffer);
162                 success = 0;
163         }
164
165         if (success)
166                 *when = utc_mktime(&tm);
167
168         free(buffer);
169 }
170
171 static void divetime(char *buffer, void *_when)
172 {
173         int h,m,s = 0;
174         time_t *when = _when;
175
176         if (sscanf(buffer, "%d:%d:%d", &h, &m, &s) >= 2) {
177                 tm.tm_hour = h;
178                 tm.tm_min = m;
179                 tm.tm_sec = s;
180                 if (tm.tm_year)
181                         *when = utc_mktime(&tm);
182         }
183         free(buffer);
184 }
185
186 /* Libdivecomputer: "2011-03-20 10:22:38" */
187 static void divedatetime(char *buffer, void *_when)
188 {
189         int y,m,d;
190         int hr,min,sec;
191         time_t *when = _when;
192
193         if (sscanf(buffer, "%d-%d-%d %d:%d:%d",
194                 &y, &m, &d, &hr, &min, &sec) == 6) {
195                 tm.tm_year = y;
196                 tm.tm_mon = m-1;
197                 tm.tm_mday = d;
198                 tm.tm_hour = hr;
199                 tm.tm_min = min;
200                 tm.tm_sec = sec;
201                 *when = utc_mktime(&tm);
202         }
203         free(buffer);
204 }
205
206 union int_or_float {
207         double fp;
208 };
209
210 enum number_type {
211         NEITHER,
212         FLOAT
213 };
214
215 static enum number_type integer_or_float(char *buffer, union int_or_float *res)
216 {
217         char *end;
218         long val;
219         double fp;
220
221         /* Integer or floating point? */
222         val = strtol(buffer, &end, 10);
223         if (val < 0 || end == buffer)
224                 return NEITHER;
225
226         /* Looks like it might be floating point? */
227         if (*end == '.') {
228                 errno = 0;
229                 fp = strtod(buffer, &end);
230                 if (!errno) {
231                         res->fp = fp;
232                         return FLOAT;
233                 }
234         }
235
236         res->fp = val;
237         return FLOAT;
238 }
239
240 static void pressure(char *buffer, void *_press)
241 {
242         double mbar;
243         pressure_t *pressure = _press;
244         union int_or_float val;
245
246         switch (integer_or_float(buffer, &val)) {
247         case FLOAT:
248                 /* Just ignore zero values */
249                 if (!val.fp)
250                         break;
251                 switch (input_units.pressure) {
252                 case PASCAL:
253                         mbar = val.fp / 100;
254                         break;
255                 case BAR:
256                         /* Assume mbar, but if it's really small, it's bar */
257                         mbar = val.fp;
258                         if (mbar < 5000)
259                                 mbar = mbar * 1000;
260                         break;
261                 case PSI:
262                         mbar = val.fp * 68.95;
263                         break;
264                 }
265                 if (mbar > 5 && mbar < 500000) {
266                         pressure->mbar = mbar + 0.5;
267                         break;
268                 }
269         /* fallthrough */
270         default:
271                 printf("Strange pressure reading %s\n", buffer);
272         }
273         free(buffer);
274 }
275
276 static void depth(char *buffer, void *_depth)
277 {
278         depth_t *depth = _depth;
279         union int_or_float val;
280
281         switch (integer_or_float(buffer, &val)) {
282         case FLOAT:
283                 switch (input_units.length) {
284                 case METERS:
285                         depth->mm = val.fp * 1000 + 0.5;
286                         break;
287                 case FEET:
288                         depth->mm = val.fp * 304.8 + 0.5;
289                         break;
290                 }
291                 break;
292         default:
293                 printf("Strange depth reading %s\n", buffer);
294         }
295         free(buffer);
296 }
297
298 static void temperature(char *buffer, void *_temperature)
299 {
300         temperature_t *temperature = _temperature;
301         union int_or_float val;
302
303         switch (integer_or_float(buffer, &val)) {
304         case FLOAT:
305                 /* Ignore zero. It means "none" */
306                 if (!val.fp)
307                         break;
308                 /* Celsius */
309                 switch (input_units.temperature) {
310                 case KELVIN:
311                         temperature->mkelvin = val.fp * 1000;
312                         break;
313                 case CELSIUS:
314                         temperature->mkelvin = (val.fp + 273.15) * 1000 + 0.5;
315                         break;
316                 case FAHRENHEIT:
317                         temperature->mkelvin = (val.fp + 459.67) * 5000/9;
318                         break;
319                 }
320                 break;
321         default:
322                 printf("Strange temperature reading %s\n", buffer);
323         }
324         free(buffer);
325 }
326
327 static void sampletime(char *buffer, void *_time)
328 {
329         int i;
330         int min, sec;
331         duration_t *time = _time;
332
333         i = sscanf(buffer, "%d:%d", &min, &sec);
334         switch (i) {
335         case 1:
336                 sec = min;
337                 min = 0;
338         /* fallthrough */
339         case 2:
340                 time->seconds = sec + min*60;
341                 break;
342         default:
343                 printf("Strange sample time reading %s\n", buffer);
344         }
345         free(buffer);
346 }
347
348 static void duration(char *buffer, void *_time)
349 {
350         sampletime(buffer, _time);
351 }
352
353 static void percent(char *buffer, void *_fraction)
354 {
355         fraction_t *fraction = _fraction;
356         union int_or_float val;
357
358         switch (integer_or_float(buffer, &val)) {
359         case FLOAT:
360                 if (val.fp <= 100.0)
361                         fraction->permille = val.fp * 10 + 0.5;
362                 break;
363
364         default:
365                 printf("Strange percentage reading %s\n", buffer);
366                 break;
367         }
368         free(buffer);
369 }
370
371 static void gasmix(char *buffer, void *_fraction)
372 {
373         /* libdivecomputer does negative percentages. */
374         if (*buffer == '-')
375                 return;
376         if (cylinder_index < MAX_CYLINDERS)
377                 percent(buffer, _fraction);
378 }
379
380 static void gasmix_nitrogen(char *buffer, void *_gasmix)
381 {
382         /* Ignore n2 percentages. There's no value in them. */
383 }
384
385 static void cylindersize(char *buffer, void *_volume)
386 {
387         volume_t *volume = _volume;
388         union int_or_float val;
389
390         switch (integer_or_float(buffer, &val)) {
391         case FLOAT:
392                 volume->mliter = val.fp * 1000 + 0.5;
393                 break;
394
395         default:
396                 printf("Strange volume reading %s\n", buffer);
397                 break;
398         }
399         free(buffer);
400 }
401
402 static void utf8_string(char *buffer, void *_res)
403 {
404         *(char **)_res = buffer;
405 }
406
407 /*
408  * Uemis water_pressure. In centibar. And when converting to
409  * depth, I'm just going to always use saltwater, because I
410  * think "true depth" is just stupid. From a diving standpoint,
411  * "true depth" is pretty much completely pointless, unless
412  * you're doing some kind of underwater surveying work.
413  *
414  * So I give water depths in "pressure depth", always assuming
415  * salt water. So one atmosphere per 10m.
416  */
417 static void water_pressure(char *buffer, void *_depth)
418 {
419         depth_t *depth = _depth;
420         union int_or_float val;
421         double atm, cm;
422
423         switch (integer_or_float(buffer, &val)) {
424         case FLOAT:
425                 if (!val.fp)
426                         break;
427                 /* cbar to atm */
428                 atm = bar_to_atm(val.fp * 10);
429                 /*
430                  * atm to cm. Why not mm? The precision just isn't
431                  * there.
432                  */
433                 cm = 100 * atm + 0.5;
434                 if (cm > 0) {
435                         depth->mm = 10 * (long)cm;
436                         break;
437                 }
438         default:
439                 fprintf(stderr, "Strange water pressure '%s'\n", buffer);
440         }
441         free(buffer);
442 }
443
444 #define MATCH(pattern, fn, dest) \
445         match(pattern, strlen(pattern), name, len, fn, buf, dest)
446
447 static void get_index(char *buffer, void *_i)
448 {
449         int *i = _i;
450         *i = atoi(buffer);
451         free(buffer);
452 }
453
454 static void centibar(char *buffer, void *_pressure)
455 {
456         pressure_t *pressure = _pressure;
457         union int_or_float val;
458
459         switch (integer_or_float(buffer, &val)) {
460         case FLOAT:
461                 pressure->mbar = val.fp * 10 + 0.5;
462                 break;
463         default:
464                 fprintf(stderr, "Strange centibar pressure '%s'\n", buffer);
465         }
466         free(buffer);
467 }
468
469 static void decicelsius(char *buffer, void *_temp)
470 {
471         temperature_t *temp = _temp;
472         union int_or_float val;
473
474         switch (integer_or_float(buffer, &val)) {
475         case FLOAT:
476                 temp->mkelvin = (val.fp/10 + 273.15) * 1000 + 0.5;
477                 break;
478         default:
479                 fprintf(stderr, "Strange julian date: %s", buffer);
480         }
481         free(buffer);
482 }
483
484 static int uemis_fill_sample(struct sample *sample, const char *name, int len, char *buf)
485 {
486         return  MATCH(".reading.dive_time", sampletime, &sample->time) ||
487                 MATCH(".reading.water_pressure", water_pressure, &sample->depth) ||
488                 MATCH(".reading.active_tank", get_index, &sample->cylinderindex) ||
489                 MATCH(".reading.tank_pressure", centibar, &sample->cylinderpressure) ||
490                 MATCH(".reading.dive_temperature", decicelsius, &sample->temperature) ||
491                 0;
492 }
493
494 /*
495  * Divinglog is crazy. The temperatures are in celsius. EXCEPT
496  * for the sample temperatures, that are in Fahrenheit.
497  * WTF?
498  *
499  * Oh, and I think Diving Log *internally* probably kept them
500  * in celsius, because I'm seeing entries like
501  *
502  *      <Temp>32.0</Temp>
503  *
504  * in there. Which is freezing, aka 0 degC. I bet the "0" is
505  * what Diving Log uses for "no temperature".
506  *
507  * So throw away crap like that.
508  */
509 static void fahrenheit(char *buffer, void *_temperature)
510 {
511         temperature_t *temperature = _temperature;
512         union int_or_float val;
513
514         switch (integer_or_float(buffer, &val)) {
515         case FLOAT:
516                 /* Floating point equality is evil, but works for small integers */
517                 if (val.fp == 32.0)
518                         break;
519                 temperature->mkelvin = (val.fp + 459.67) * 5000/9;
520                 break;
521         default:
522                 fprintf(stderr, "Crazy Diving Log temperature reading %s\n", buffer);
523         }
524         free(buffer);
525 }
526
527 /*
528  * Did I mention how bat-shit crazy divinglog is? The sample
529  * pressures are in PSI. But the tank working pressure is in
530  * bar. WTF^2?
531  *
532  * Crazy stuff like this is why subsurface has everything in
533  * these inconvenient typed structures, and you have to say
534  * "pressure->mbar" to get the actual value. Exactly so that
535  * you can never have unit confusion.
536  */
537 static void psi(char *buffer, void *_pressure)
538 {
539         pressure_t *pressure = _pressure;
540         union int_or_float val;
541
542         switch (integer_or_float(buffer, &val)) {
543         case FLOAT:
544                 pressure->mbar = val.fp * 68.95 + 0.5;
545                 break;
546         default:
547                 fprintf(stderr, "Crazy Diving Log PSI reading %s\n", buffer);
548         }
549         free(buffer);
550 }
551
552 static int divinglog_fill_sample(struct sample *sample, const char *name, int len, char *buf)
553 {
554         return  MATCH(".p.time", sampletime, &sample->time) ||
555                 MATCH(".p.depth", depth, &sample->depth) ||
556                 MATCH(".p.temp", fahrenheit, &sample->temperature) ||
557                 MATCH(".p.press1", psi, &sample->cylinderpressure) ||
558                 0;
559 }
560
561 static int uddf_fill_sample(struct sample *sample, const char *name, int len, char *buf)
562 {
563         return  MATCH(".divetime", sampletime, &sample->time) ||
564                 MATCH(".depth", depth, &sample->depth) ||
565                 MATCH(".temperature", temperature, &sample->temperature) ||
566                 0;
567 }
568
569 static void eventtime(char *buffer, void *_duration)
570 {
571         duration_t *duration = _duration;
572         sampletime(buffer, duration);
573         if (sample)
574                 duration->seconds += sample->time.seconds;
575 }
576
577 static void try_to_fill_event(const char *name, char *buf)
578 {
579         int len = strlen(name);
580
581         start_match("event", name, buf);
582         if (MATCH(".event", utf8_string, &event.name))
583                 return;
584         if (MATCH(".name", utf8_string, &event.name))
585                 return;
586         if (MATCH(".time", eventtime, &event.time))
587                 return;
588         if (MATCH(".type", get_index, &event.type))
589                 return;
590         if (MATCH(".flags", get_index, &event.flags))
591                 return;
592         if (MATCH(".value", get_index, &event.value))
593                 return;
594         nonmatch("event", name, buf);
595 }
596
597 /* We're in samples - try to convert the random xml value to something useful */
598 static void try_to_fill_sample(struct sample *sample, const char *name, char *buf)
599 {
600         int len = strlen(name);
601
602         start_match("sample", name, buf);
603         if (MATCH(".sample.pressure", pressure, &sample->cylinderpressure))
604                 return;
605         if (MATCH(".sample.cylpress", pressure, &sample->cylinderpressure))
606                 return;
607         if (MATCH(".sample.cylinderindex", get_index, &sample->cylinderindex))
608                 return;
609         if (MATCH(".sample.depth", depth, &sample->depth))
610                 return;
611         if (MATCH(".sample.temp", temperature, &sample->temperature))
612                 return;
613         if (MATCH(".sample.temperature", temperature, &sample->temperature))
614                 return;
615         if (MATCH(".sample.sampletime", sampletime, &sample->time))
616                 return;
617         if (MATCH(".sample.time", sampletime, &sample->time))
618                 return;
619
620         switch (import_source) {
621         case UEMIS:
622                 if (uemis_fill_sample(sample, name, len, buf))
623                         return;
624                 break;
625
626         case DIVINGLOG:
627                 if (divinglog_fill_sample(sample, name, len, buf))
628                         return;
629                 break;
630
631         case UDDF:
632                 if (uddf_fill_sample(sample, name, len, buf))
633                         return;
634                 break;
635
636         default:
637                 break;
638         }
639
640         nonmatch("sample", name, buf);
641 }
642
643 /*
644  * Crazy suunto xml. Look at how those o2/he things match up.
645  */
646 static int suunto_dive_match(struct dive **divep, const char *name, int len, char *buf)
647 {
648         struct dive *dive = *divep;
649
650         return  MATCH(".o2pct", percent, &dive->cylinder[0].gasmix.o2) ||
651                 MATCH(".hepct_0", percent, &dive->cylinder[0].gasmix.he) ||
652                 MATCH(".o2pct_2", percent, &dive->cylinder[1].gasmix.o2) ||
653                 MATCH(".hepct_1", percent, &dive->cylinder[1].gasmix.he) ||
654                 MATCH(".o2pct_3", percent, &dive->cylinder[2].gasmix.o2) ||
655                 MATCH(".hepct_2", percent, &dive->cylinder[2].gasmix.he) ||
656                 MATCH(".o2pct_4", percent, &dive->cylinder[3].gasmix.o2) ||
657                 MATCH(".hepct_3", percent, &dive->cylinder[3].gasmix.he) ||
658                 MATCH(".cylindersize", cylindersize, &dive->cylinder[0].type.size) ||
659                 MATCH(".cylinderworkpressure", pressure, &dive->cylinder[0].type.workingpressure) ||
660                 0;
661 }
662
663 static const char *country, *city;
664
665 static void divinglog_place(char *place, void *_location)
666 {
667         char **location = _location;
668         char buffer[256], *p;
669         int len;
670
671         len = snprintf(buffer, sizeof(buffer),
672                 "%s%s%s%s%s",
673                 place,
674                 city ? ", " : "",
675                 city ? city : "",
676                 country ? ", " : "",
677                 country ? country : "");
678
679         p = malloc(len+1);
680         memcpy(p, buffer, len+1);
681         *location = p;
682
683         city = NULL;
684         country = NULL;
685 }
686
687 static int divinglog_dive_match(struct dive **divep, const char *name, int len, char *buf)
688 {
689         struct dive *dive = *divep;
690
691         return  MATCH(".divedate", divedate, &dive->when) ||
692                 MATCH(".entrytime", divetime, &dive->when) ||
693                 MATCH(".depth", depth, &dive->maxdepth) ||
694                 MATCH(".tanksize", cylindersize, &dive->cylinder[0].type.size) ||
695                 MATCH(".presw", pressure, &dive->cylinder[0].type.workingpressure) ||
696                 MATCH(".comments", utf8_string, &dive->notes) ||
697                 MATCH(".buddy.names", utf8_string, &dive->buddy) ||
698                 MATCH(".country.name", utf8_string, &country) ||
699                 MATCH(".city.name", utf8_string, &city) ||
700                 MATCH(".place.name", divinglog_place, &dive->location) ||
701                 0;
702 }
703
704 static int buffer_value(char *buffer)
705 {
706         int val = atoi(buffer);
707         free(buffer);
708         return val;
709 }
710
711 static void uemis_length_unit(char *buffer, void *_unused)
712 {
713         input_units.length = buffer_value(buffer) ? FEET : METERS;
714 }
715
716 static void uemis_volume_unit(char *buffer, void *_unused)
717 {
718         input_units.volume = buffer_value(buffer) ? CUFT : LITER;
719 }
720
721 static void uemis_pressure_unit(char *buffer, void *_unused)
722 {
723 #if 0
724         input_units.pressure = buffer_value(buffer) ? PSI : BAR;
725 #endif
726 }
727
728 static void uemis_temperature_unit(char *buffer, void *_unused)
729 {
730         input_units.temperature = buffer_value(buffer) ? FAHRENHEIT : CELSIUS;
731 }
732
733 static void uemis_weight_unit(char *buffer, void *_unused)
734 {
735         input_units.weight = buffer_value(buffer) ? LBS : KG;
736 }
737
738 static void uemis_time_unit(char *buffer, void *_unused)
739 {
740 }
741
742 static void uemis_date_unit(char *buffer, void *_unused)
743 {
744 }
745
746 /* Modified julian day, yay! */
747 static void uemis_date_time(char *buffer, void *_when)
748 {
749         time_t *when = _when;
750         union int_or_float val;
751
752         switch (integer_or_float(buffer, &val)) {
753         case FLOAT:
754                 *when = (val.fp - 40587) * 86400;
755                 break;
756         default:
757                 fprintf(stderr, "Strange julian date: %s", buffer);
758         }
759         free(buffer);
760 }
761
762 /*
763  * Uemis doesn't know time zones. You need to do them as
764  * minutes, not hours.
765  *
766  * But that's ok, we don't track timezones yet either. We
767  * just turn everything into "localtime expressed as UTC".
768  */
769 static void uemis_time_zone(char *buffer, void *_when)
770 {
771 #if 0 /* seems like this is only used to display it correctly
772        * the stored time appears to be UTC */
773
774         time_t *when = _when;
775         signed char tz = atoi(buffer);
776
777         *when += tz * 3600;
778 #endif
779 }
780
781 static void uemis_ts(char *buffer, void *_when)
782 {
783         struct tm tm;
784         time_t *when = _when;
785
786         memset(&tm, 0, sizeof(tm));
787         sscanf(buffer,"%d-%d-%dT%d:%d:%d",
788                 &tm.tm_year, &tm.tm_mon, &tm.tm_mday,
789                 &tm.tm_hour, &tm.tm_min, &tm.tm_sec);
790         tm.tm_mon  -= 1;
791         tm.tm_year -= 1900;
792         *when = utc_mktime(&tm);
793
794 }
795
796 static void uemis_duration(char *buffer, void *_duration)
797 {
798         duration_t *duration = _duration;
799         duration->seconds = atof(buffer) * 60 + 0.5;
800 }
801
802 /* 0 - air ; 1 - nitrox1 ; 2 - nitrox2 ; 3 = nitrox3 */
803 static int uemis_gas_template;
804
805 /*
806  * Christ. Uemis tank data is a total mess.
807  *
808  * We're passed a "virtual cylinder" (0 - 6) for the different
809  * Uemis tank cases ("air", "nitrox_1", "nitrox_2.{bottom,deco}"
810  * and "nitrox_3.{bottom,deco,travel}". We need to turn that
811  * into the actual cylinder data depending on the gas template,
812  * and ignore the ones that are irrelevant for that template.
813  *
814  * So for "template 2" (nitrox_2), we ignore virtual tanks 0-1
815  * (which are "air" and "nitrox_1" respectively), and tanks 4-6
816  * (which are the three "nitrox_3" tanks), and we turn virtual
817  * tanks 2/3 into actual tanks 0/1.
818  *
819  * Confused yet?
820  */
821 static int uemis_cylinder_index(void *_cylinder)
822 {
823         cylinder_t *cylinder = _cylinder;
824         unsigned int index = cylinder - dive->cylinder;
825
826         if (index > 6) {
827                 fprintf(stderr, "Uemis cylinder pointer calculations broken\n");
828                 return -1;
829         }
830         switch(uemis_gas_template) {
831         case 1: /* Dive uses tank 1 */
832                 index -= 1;
833         /* Fallthrough */
834         case 0: /* Dive uses tank 0 */
835                 if (index)
836                         index = -1;
837                 break;
838         case 2: /* Dive uses tanks 2-3 */
839                 index -= 2;
840                 if (index > 1)
841                         index = -1;
842                 break;
843         case 3: /* Dive uses tanks 4-6 */
844                 index -= 4;
845                 if (index > 2)
846                         index = -1;
847                 break;
848         }
849         return index;
850 }
851
852 static void uemis_cylindersize(char *buffer, void *_cylinder)
853 {
854         int index = uemis_cylinder_index(_cylinder);
855         if (index >= 0)
856                 cylindersize(buffer, &dive->cylinder[index].type.size);
857 }
858
859 static void uemis_percent(char *buffer, void *_cylinder)
860 {
861         int index = uemis_cylinder_index(_cylinder);
862         if (index >= 0)
863                 percent(buffer, &dive->cylinder[index].gasmix.o2);
864 }
865
866 static int uemis_dive_match(struct dive **divep, const char *name, int len, char *buf)
867 {
868         struct dive *dive = *divep;
869
870         return  MATCH(".units.length", uemis_length_unit, &input_units) ||
871                 MATCH(".units.volume", uemis_volume_unit, &input_units) ||
872                 MATCH(".units.pressure", uemis_pressure_unit, &input_units) ||
873                 MATCH(".units.temperature", uemis_temperature_unit, &input_units) ||
874                 MATCH(".units.weight", uemis_weight_unit, &input_units) ||
875                 MATCH(".units.time", uemis_time_unit, &input_units) ||
876                 MATCH(".units.date", uemis_date_unit, &input_units) ||
877                 MATCH(".date_time", uemis_date_time, &dive->when) ||
878                 MATCH(".time_zone", uemis_time_zone, &dive->when) ||
879                 MATCH(".ambient.temperature", decicelsius, &dive->airtemp) ||
880                 MATCH(".gas.template", get_index, &uemis_gas_template) ||
881                 MATCH(".air.bottom_tank.size", uemis_cylindersize, dive->cylinder + 0) ||
882                 MATCH(".air.bottom_tank.oxygen", uemis_percent, dive->cylinder + 0) ||
883                 MATCH(".nitrox_1.bottom_tank.size", uemis_cylindersize, dive->cylinder + 1) ||
884                 MATCH(".nitrox_1.bottom_tank.oxygen", uemis_percent, dive->cylinder + 1) ||
885                 MATCH(".nitrox_2.bottom_tank.size", uemis_cylindersize, dive->cylinder + 2) ||
886                 MATCH(".nitrox_2.bottom_tank.oxygen", uemis_percent, dive->cylinder + 2) ||
887                 MATCH(".nitrox_2.deco_tank.size", uemis_cylindersize, dive->cylinder + 3) ||
888                 MATCH(".nitrox_2.deco_tank.oxygen", uemis_percent, dive->cylinder + 3) ||
889                 MATCH(".nitrox_3.bottom_tank.size", uemis_cylindersize, dive->cylinder + 4) ||
890                 MATCH(".nitrox_3.bottom_tank.oxygen", uemis_percent, dive->cylinder + 4) ||
891                 MATCH(".nitrox_3.deco_tank.size", uemis_cylindersize, dive->cylinder + 5) ||
892                 MATCH(".nitrox_3.deco_tank.oxygen", uemis_percent, dive->cylinder + 5) ||
893                 MATCH(".nitrox_3.travel_tank.size", uemis_cylindersize, dive->cylinder + 6) ||
894                 MATCH(".nitrox_3.travel_tank.oxygen", uemis_percent, dive->cylinder + 6) ||
895                 MATCH(".dive.val.float", uemis_duration, &dive->duration) ||
896                 MATCH(".dive.val.ts", uemis_ts, &dive->when) ||
897                 MATCH(".dive.val.bin", uemis_parse_divelog_binary, divep) ||
898                 0;
899 }
900
901 /*
902  * Uddf specifies ISO 8601 time format.
903  *
904  * There are many variations on that. This handles the useful cases.
905  */
906 static void uddf_datetime(char *buffer, void *_when)
907 {
908         char c;
909         int y,m,d,hh,mm,ss;
910         time_t *when = _when;
911         struct tm tm = { 0 };
912         int i;
913
914         i = sscanf(buffer, "%d-%d-%d%c%d:%d:%d", &y, &m, &d, &c, &hh, &mm, &ss);
915         if (i == 7)
916                 goto success;
917         ss = 0;
918         if (i == 6)
919                 goto success;
920
921         i = sscanf(buffer, "%04d%02d%02d%c%02d%02d%02d", &y, &m, &d, &c, &hh, &mm, &ss);
922         if (i == 7)
923                 goto success;
924         ss = 0;
925         if (i == 6)
926                 goto success;
927 bad_date:
928         printf("Bad date time %s\n", buffer);
929         free(buffer);
930         return;
931
932 success:
933         if (c != 'T' && c != ' ')
934                 goto bad_date;
935         tm.tm_year = y;
936         tm.tm_mon = m - 1;
937         tm.tm_mday = d;
938         tm.tm_hour = hh;
939         tm.tm_min = mm;
940         tm.tm_sec = ss;
941         *when = utc_mktime(&tm);
942         free(buffer);
943 }
944
945 static int uddf_dive_match(struct dive **divep, const char *name, int len, char *buf)
946 {
947         struct dive *dive = *divep;
948
949         return  MATCH(".datetime", uddf_datetime, &dive->when) ||
950                 MATCH(".diveduration", duration, &dive->duration) ||
951                 MATCH(".greatestdepth", depth, &dive->maxdepth) ||
952                 0;
953 }
954
955 static void gps_location(char *buffer, void *_dive)
956 {
957         int i;
958         struct dive *dive = _dive;
959         double latitude, longitude;
960
961         i = sscanf(buffer, "%lf %lf", &latitude, &longitude);
962         if (i == 2) {
963                 dive->latitude = latitude;
964                 dive->longitude = longitude;
965         }
966         free(buffer);
967 }
968
969 /* We're in the top-level dive xml. Try to convert whatever value to a dive value */
970 static void try_to_fill_dive(struct dive **divep, const char *name, char *buf)
971 {
972         int len = strlen(name);
973
974         start_match("dive", name, buf);
975
976         switch (import_source) {
977         case SUUNTO:
978                 if (suunto_dive_match(divep, name, len, buf))
979                         return;
980                 break;
981
982         case UEMIS:
983                 if (uemis_dive_match(divep, name, len, buf))
984                         return;
985                 break;
986
987         case DIVINGLOG:
988                 if (divinglog_dive_match(divep, name, len, buf))
989                         return;
990                 break;
991
992         case UDDF:
993                 if (uddf_dive_match(divep, name, len, buf))
994                         return;
995                 break;
996
997         default:
998                 break;
999         }
1000
1001         struct dive *dive = *divep;
1002
1003         if (MATCH(".number", get_index, &dive->number))
1004                 return;
1005         if (MATCH(".date", divedate, &dive->when))
1006                 return;
1007         if (MATCH(".time", divetime, &dive->when))
1008                 return;
1009         if (MATCH(".datetime", divedatetime, &dive->when))
1010                 return;
1011         if (MATCH(".maxdepth", depth, &dive->maxdepth))
1012                 return;
1013         if (MATCH(".meandepth", depth, &dive->meandepth))
1014                 return;
1015         if (MATCH(".depth.max", depth, &dive->maxdepth))
1016                 return;
1017         if (MATCH(".depth.mean", depth, &dive->meandepth))
1018                 return;
1019         if (MATCH(".duration", duration, &dive->duration))
1020                 return;
1021         if (MATCH(".divetime", duration, &dive->duration))
1022                 return;
1023         if (MATCH(".divetimesec", duration, &dive->duration))
1024                 return;
1025         if (MATCH(".surfacetime", duration, &dive->surfacetime))
1026                 return;
1027         if (MATCH(".airtemp", temperature, &dive->airtemp))
1028                 return;
1029         if (MATCH(".watertemp", temperature, &dive->watertemp))
1030                 return;
1031         if (MATCH(".temperature.air", temperature, &dive->airtemp))
1032                 return;
1033         if (MATCH(".temperature.water", temperature, &dive->watertemp))
1034                 return;
1035         if (MATCH(".cylinderstartpressure", pressure, &dive->cylinder[0].start))
1036                 return;
1037         if (MATCH(".cylinderendpressure", pressure, &dive->cylinder[0].end))
1038                 return;
1039         if (MATCH(".gps", gps_location, dive))
1040                 return;
1041         if (MATCH(".location", utf8_string, &dive->location))
1042                 return;
1043         if (MATCH(".notes", utf8_string, &dive->notes))
1044                 return;
1045         if (MATCH(".divemaster", utf8_string, &dive->divemaster))
1046                 return;
1047         if (MATCH(".buddy", utf8_string, &dive->buddy))
1048                 return;
1049
1050         if (MATCH(".cylinder.size", cylindersize, &dive->cylinder[cylinder_index].type.size))
1051                 return;
1052         if (MATCH(".cylinder.workpressure", pressure, &dive->cylinder[cylinder_index].type.workingpressure))
1053                 return;
1054         if (MATCH(".cylinder.description", utf8_string, &dive->cylinder[cylinder_index].type.description))
1055                 return;
1056         if (MATCH(".cylinder.start", pressure, &dive->cylinder[cylinder_index].start))
1057                 return;
1058         if (MATCH(".cylinder.end", pressure, &dive->cylinder[cylinder_index].end))
1059                 return;
1060
1061         if (MATCH(".o2", gasmix, &dive->cylinder[cylinder_index].gasmix.o2))
1062                 return;
1063         if (MATCH(".n2", gasmix_nitrogen, &dive->cylinder[cylinder_index].gasmix))
1064                 return;
1065         if (MATCH(".he", gasmix, &dive->cylinder[cylinder_index].gasmix.he))
1066                 return;
1067
1068         nonmatch("dive", name, buf);
1069 }
1070
1071 /*
1072  * File boundaries are dive boundaries. But sometimes there are
1073  * multiple dives per file, so there can be other events too that
1074  * trigger a "new dive" marker and you may get some nesting due
1075  * to that. Just ignore nesting levels.
1076  */
1077 static void dive_start(void)
1078 {
1079         if (dive)
1080                 return;
1081         dive = alloc_dive();
1082         memset(&tm, 0, sizeof(tm));
1083 }
1084
1085 static void sanitize_gasmix(struct gasmix *mix)
1086 {
1087         unsigned int o2, he;
1088
1089         o2 = mix->o2.permille;
1090         he = mix->he.permille;
1091
1092         /* Regular air: leave empty */
1093         if (!he) {
1094                 if (!o2)
1095                         return;
1096                 /* 20.9% or 21% O2 is just air */
1097                 if (o2 >= 209 && o2 <= 210) {
1098                         mix->o2.permille = 0;
1099                         return;
1100                 }
1101         }
1102
1103         /* Sane mix? */
1104         if (o2 <= 1000 && he <= 1000 && o2+he <= 1000)
1105                 return;
1106         fprintf(stderr, "Odd gasmix: %d O2 %d He\n", o2, he);
1107         memset(mix, 0, sizeof(*mix));
1108 }
1109
1110 /*
1111  * See if the size/workingpressure looks like some standard cylinder
1112  * size, eg "AL80".
1113  */
1114 static void match_standard_cylinder(cylinder_type_t *type)
1115 {
1116         double cuft;
1117         int psi, len;
1118         const char *fmt;
1119         char buffer[20], *p;
1120
1121         /* Do we already have a cylinder description? */
1122         if (type->description)
1123                 return;
1124
1125         cuft = ml_to_cuft(type->size.mliter);
1126         cuft *= to_ATM(type->workingpressure);
1127         psi = to_PSI(type->workingpressure);
1128
1129         switch (psi) {
1130         case 2300 ... 2500:     /* 2400 psi: LP tank */
1131                 fmt = "LP%d";
1132                 break;
1133         case 2600 ... 2700:     /* 2640 psi: LP+10% */
1134                 fmt = "LP%d";
1135                 break;
1136         case 2900 ... 3100:     /* 3000 psi: ALx tank */
1137                 fmt = "AL%d";
1138                 break;
1139         case 3400 ... 3500:     /* 3442 psi: HP tank */
1140                 fmt = "HP%d";
1141                 break;
1142         case 3700 ... 3850:     /* HP+10% */
1143                 fmt = "HP%d+";
1144                 break;
1145         default:
1146                 return;
1147         }
1148         len = snprintf(buffer, sizeof(buffer), fmt, (int) (cuft+0.5));
1149         p = malloc(len+1);
1150         if (!p)
1151                 return;
1152         memcpy(p, buffer, len+1);
1153         type->description = p;
1154 }
1155
1156
1157 /*
1158  * There are two ways to give cylinder size information:
1159  *  - total amount of gas in cuft (depends on working pressure and physical size)
1160  *  - physical size
1161  *
1162  * where "physical size" is the one that actually matters and is sane.
1163  *
1164  * We internally use physical size only. But we save the workingpressure
1165  * so that we can do the conversion if required.
1166  */
1167 static void sanitize_cylinder_type(cylinder_type_t *type)
1168 {
1169         double volume_of_air, atm, volume;
1170
1171         /* If we have no working pressure, it had *better* be just a physical size! */
1172         if (!type->workingpressure.mbar)
1173                 return;
1174
1175         /* No size either? Nothing to go on */
1176         if (!type->size.mliter)
1177                 return;
1178
1179         if (input_units.volume == CUFT || import_source == SUUNTO) {
1180                 /* confusing - we don't really start from ml but millicuft !*/
1181                 volume_of_air = cuft_to_l(type->size.mliter);
1182                 atm = to_ATM(type->workingpressure);            /* working pressure in atm */
1183                 volume = volume_of_air / atm;                   /* milliliters at 1 atm: "true size" */
1184                 type->size.mliter = volume + 0.5;
1185         }
1186
1187         /* Ok, we have both size and pressure: try to match a description */
1188         match_standard_cylinder(type);
1189 }
1190
1191 static void sanitize_cylinder_info(struct dive *dive)
1192 {
1193         int i;
1194
1195         for (i = 0; i < MAX_CYLINDERS; i++) {
1196                 sanitize_gasmix(&dive->cylinder[i].gasmix);
1197                 sanitize_cylinder_type(&dive->cylinder[i].type);
1198         }
1199 }
1200
1201 static void dive_end(void)
1202 {
1203         if (!dive)
1204                 return;
1205         sanitize_cylinder_info(dive);
1206         record_dive(dive);
1207         dive = NULL;
1208         cylinder_index = 0;
1209 }
1210
1211 static void event_start(void)
1212 {
1213         memset(&event, 0, sizeof(event));
1214         event.active = 1;
1215 }
1216
1217 static void event_end(void)
1218 {
1219         if (event.name && strcmp(event.name, "surface") != 0)
1220                 add_event(dive, event.time.seconds, event.type, event.flags, event.value, event.name);
1221         event.active = 0;
1222 }
1223
1224 static void cylinder_start(void)
1225 {
1226 }
1227
1228 static void cylinder_end(void)
1229 {
1230         cylinder_index++;
1231 }
1232
1233 static void sample_start(void)
1234 {
1235         sample = prepare_sample(&dive);
1236 }
1237
1238 static void sample_end(void)
1239 {
1240         if (!dive)
1241                 return;
1242
1243         finish_sample(dive, sample);
1244         sample = NULL;
1245 }
1246
1247 static void entry(const char *name, int size, const char *raw)
1248 {
1249         char *buf = malloc(size+1);
1250
1251         if (!buf)
1252                 return;
1253         memcpy(buf, raw, size);
1254         buf[size] = 0;
1255         if (event.active) {
1256                 try_to_fill_event(name, buf);
1257                 return;
1258         }
1259         if (sample) {
1260                 try_to_fill_sample(sample, name, buf);
1261                 return;
1262         }
1263         if (dive) {
1264                 try_to_fill_dive(&dive, name, buf);
1265                 return;
1266         }
1267 }
1268
1269 static const char *nodename(xmlNode *node, char *buf, int len)
1270 {
1271         if (!node || !node->name)
1272                 return "root";
1273
1274         buf += len;
1275         *--buf = 0;
1276         len--;
1277
1278         for(;;) {
1279                 const char *name = node->name;
1280                 int i = strlen(name);
1281                 while (--i >= 0) {
1282                         unsigned char c = name[i];
1283                         *--buf = tolower(c);
1284                         if (!--len)
1285                                 return buf;
1286                 }
1287                 node = node->parent;
1288                 if (!node || !node->name)
1289                         return buf;
1290                 *--buf = '.';
1291                 if (!--len)
1292                         return buf;
1293         }
1294 }
1295
1296 #define MAXNAME 64
1297
1298 static void visit_one_node(xmlNode *node)
1299 {
1300         int len;
1301         const unsigned char *content;
1302         char buffer[MAXNAME];
1303         const char *name;
1304
1305         content = node->content;
1306         if (!content)
1307                 return;
1308
1309         /* Trim whitespace at beginning */
1310         while (isspace(*content))
1311                 content++;
1312
1313         /* Trim whitespace at end */
1314         len = strlen(content);
1315         while (len && isspace(content[len-1]))
1316                 len--;
1317
1318         if (!len)
1319                 return;
1320
1321         /* Don't print out the node name if it is "text" */
1322         if (!strcmp(node->name, "text"))
1323                 node = node->parent;
1324
1325         name = nodename(node, buffer, sizeof(buffer));
1326
1327         entry(name, len, content);
1328 }
1329
1330 static void traverse(xmlNode *root);
1331
1332 static void traverse_properties(xmlNode *node)
1333 {
1334         xmlAttr *p;
1335
1336         for (p = node->properties; p; p = p->next)
1337                 traverse(p->children);
1338 }
1339
1340 static void visit(xmlNode *n)
1341 {
1342         visit_one_node(n);
1343         traverse_properties(n);
1344         traverse(n->children);
1345 }
1346
1347 static void suunto_importer(void)
1348 {
1349         import_source = SUUNTO;
1350         input_units = SI_units;
1351 }
1352
1353 static void uemis_importer(void)
1354 {
1355         import_source = UEMIS;
1356         input_units = SI_units;
1357 }
1358
1359 static void DivingLog_importer(void)
1360 {
1361         import_source = DIVINGLOG;
1362
1363         /*
1364          * Diving Log units are really strange.
1365          *
1366          * Temperatures are in C, except in samples,
1367          * when they are in Fahrenheit. Depths are in
1368          * meters, an dpressure is in PSI in the samples,
1369          * but in bar when it comes to working pressure.
1370          *
1371          * Crazy f*%^ morons.
1372          */
1373         input_units = SI_units;
1374 }
1375
1376 static void uddf_importer(void)
1377 {
1378         import_source = UDDF;
1379         input_units = SI_units;
1380         input_units.pressure = PASCAL;
1381         input_units.temperature = KELVIN;
1382 }
1383
1384 /*
1385  * I'm sure this could be done as some fancy DTD rules.
1386  * It's just not worth the headache.
1387  */
1388 static struct nesting {
1389         const char *name;
1390         void (*start)(void), (*end)(void);
1391 } nesting[] = {
1392         { "dive", dive_start, dive_end },
1393         { "Dive", dive_start, dive_end },
1394         { "sample", sample_start, sample_end },
1395         { "waypoint", sample_start, sample_end },
1396         { "SAMPLE", sample_start, sample_end },
1397         { "reading", sample_start, sample_end },
1398         { "event", event_start, event_end },
1399         { "gasmix", cylinder_start, cylinder_end },
1400         { "cylinder", cylinder_start, cylinder_end },
1401         { "P", sample_start, sample_end },
1402
1403         /* Import type recognition */
1404         { "SUUNTO", suunto_importer },
1405         { "Divinglog", DivingLog_importer },
1406         { "pre_dive", uemis_importer },
1407         { "dives", uemis_importer },
1408         { "uddf", uddf_importer },
1409
1410         { NULL, }
1411 };
1412
1413 static void traverse(xmlNode *root)
1414 {
1415         xmlNode *n;
1416
1417         for (n = root; n; n = n->next) {
1418                 struct nesting *rule = nesting;
1419
1420                 do {
1421                         if (!strcmp(rule->name, n->name))
1422                                 break;
1423                         rule++;
1424                 } while (rule->name);
1425
1426                 if (rule->start)
1427                         rule->start();
1428                 visit(n);
1429                 if (rule->end)
1430                         rule->end();
1431         }
1432 }
1433
1434 /* Per-file reset */
1435 static void reset_all(void)
1436 {
1437         /*
1438          * We reset the units for each file. You'd think it was
1439          * a per-dive property, but I'm not going to trust people
1440          * to do per-dive setup. If the xml does have per-dive
1441          * data within one file, we might have to reset it per
1442          * dive for that format.
1443          */
1444         input_units = SI_units;
1445         import_source = UNKNOWN;
1446 }
1447
1448 void parse_xml_file(const char *filename, GError **error)
1449 {
1450         xmlDoc *doc;
1451
1452         doc = xmlReadFile(filename, NULL, 0);
1453         if (!doc) {
1454                 fprintf(stderr, "Failed to parse '%s'.\n", filename);
1455                 if (error != NULL)
1456                 {
1457                         *error = g_error_new(g_quark_from_string("subsurface"),
1458                                              DIVE_ERROR_PARSE,
1459                                              "Failed to parse '%s'",
1460                                              filename);
1461                 }
1462                 return;
1463         }
1464         /* we assume that the last (or only) filename passed as argument is a 
1465          * great filename to use as default when saving the dives */ 
1466         set_filename(filename);
1467         reset_all();
1468         dive_start();
1469         traverse(xmlDocGetRootElement(doc));
1470         dive_end();
1471         xmlFreeDoc(doc);
1472         xmlCleanupParser();
1473 }
1474
1475 void parse_xml_init(void)
1476 {
1477         LIBXML_TEST_VERSION
1478 }