]> git.tdb.fi Git - ext/subsurface.git/blob - uemis.c
Integrate loading of uemis SDA files into the regular xml parsing
[ext/subsurface.git] / uemis.c
1 /*
2  * uemis.c
3  *
4  * UEMIS SDA file importer
5  * AUTHOR:  Dirk Hohndel - Copyright 2011
6  *
7  * Licensed under the MIT license.
8  */
9
10 #include <unistd.h>
11 #include <stdio.h>
12 #include <string.h>
13 #include <stdint.h>
14 #include <stdlib.h>
15 #define __USE_XOPEN
16 #include <time.h>
17 #include <regex.h>
18
19 #include "dive.h"
20 #include "uemis.h"
21
22 /*
23  * following code is based on code found in at base64.sourceforge.net/b64.c
24  * AUTHOR:         Bob Trower 08/04/01
25  * COPYRIGHT:      Copyright (c) Trantor Standard Systems Inc., 2001
26  * NOTE:           This source code may be used as you wish, subject to
27  *                 the MIT license.
28  */
29 /*
30  * Translation Table to decode (created by Bob Trower)
31  */
32 static const char cd64[]="|$$$}rstuvwxyz{$$$$$$$>?@ABCDEFGHIJKLMNOPQRSTUVW$$$$$$XYZ[\\]^_`abcdefghijklmnopq";
33
34 /*
35  * decodeblock -- decode 4 '6-bit' characters into 3 8-bit binary bytes
36  */
37 static void decodeblock( unsigned char in[4], unsigned char out[3] ) {
38         out[ 0 ] = (unsigned char ) (in[0] << 2 | in[1] >> 4);
39         out[ 1 ] = (unsigned char ) (in[1] << 4 | in[2] >> 2);
40         out[ 2 ] = (unsigned char ) (((in[2] << 6) & 0xc0) | in[3]);
41 }
42
43 /*
44  * decode a base64 encoded stream discarding padding, line breaks and noise
45  */
46 static void decode( uint8_t *inbuf, uint8_t *outbuf, int inbuf_len ) {
47         uint8_t in[4], out[3], v;
48         int i,len,indx_in=0,indx_out=0;
49
50         while (indx_in < inbuf_len) {
51                 for (len = 0, i = 0; i < 4 && (indx_in < inbuf_len); i++ ) {
52                         v = 0;
53                         while ((indx_in < inbuf_len) && v == 0) {
54                                 v = inbuf[indx_in++];
55                                 v = ((v < 43 || v > 122) ? 0 : cd64[ v - 43 ]);
56                                 if (v)
57                                         v = ((v == '$') ? 0 : v - 61);
58                         }
59                         if (indx_in < inbuf_len) {
60                                 len++;
61                                 if (v)
62                                         in[i] = (v - 1);
63                         }
64                         else
65                                 in[i] = 0;
66                 }
67                 if( len ) {
68                         decodeblock( in, out );
69                         for( i = 0; i < len - 1; i++ )
70                                 outbuf[indx_out++] = out[i];
71                 }
72         }
73 }
74 /* end code from Bob Trower */
75
76 /* small helper functions */
77 /* simpleregex allocates (and reallocates) the found buffer
78  * don't forget to free it when you are done
79  */
80 static int simpleregex(char *buffer, char *regex, char **found) {
81         int status;
82         regex_t re;
83         regmatch_t match[5];
84
85         if (regcomp(&re, regex, 0) !=0) {
86                 fprintf(stderr,"internal error, regex failed!\n");
87                 exit(1);
88         }
89         status = regexec(&re,buffer,5,match,0);
90         if(status == 0) {
91                 *found = realloc(*found,match[1].rm_eo-match[1].rm_so + 1);
92                 strncpy(*found,buffer+match[1].rm_so,match[1].rm_eo-match[1].rm_so);
93                 (*found)[match[1].rm_eo-match[1].rm_so] = '\0';
94         }
95         return(status == 0);
96 }
97
98 /* read in line of arbitrary length (important for SDA files that can
99  * have lines that are tens of kB long
100  * don't forget to free it when you are done
101  */
102 #define MYGETL_INCR 1024
103 static char * mygetline(FILE * f) {
104         size_t size = 0;
105         size_t len  = 0;
106         char * buf  = NULL;
107
108         do {
109                 size += MYGETL_INCR;
110                 if ((buf = realloc(buf,size)) == NULL)
111                         break;
112                 fgets(buf+len,MYGETL_INCR,f);
113                 len = strlen(buf);
114         } while (!feof(f) && buf[len-1]!='\n');
115         return buf;
116 }
117
118 /* text matching, used to build very poor man's XML parser */
119 int matchit(FILE *infd, char *regex, char *typeregex, char **found) {
120         char *buffer;
121
122         while (!feof(infd)) {
123                 buffer = mygetline(infd);
124                 if (buffer && simpleregex(buffer,regex,found)) {
125                         buffer = mygetline(infd);
126                         if (buffer && simpleregex(buffer,typeregex,found)) {
127                                 return 1;
128                         }
129                 }
130         }
131         return 0;
132 }
133
134 /*
135  * pressure_to_depth: In centibar. And when converting to
136  * depth, I'm just going to always use saltwater, because I
137  * think "true depth" is just stupid. From a diving standpoint,
138  * "true depth" is pretty much completely pointless, unless
139  * you're doing some kind of underwater surveying work.
140  *
141  * So I give water depths in "pressure depth", always assuming
142  * salt water. So one atmosphere per 10m.
143  */
144 static int pressure_to_depth(uint16_t value)
145 {
146         double atm, cm;
147
148         atm = (value / 100.0) / 1.01325;
149         cm = 100 * atm + 0.5;
150         return( (cm > 0) ? 10 * (long)cm : 0);
151 }
152
153 /*
154  * convert the base64 data blog
155  */
156 int uemis_convert_base64(char *base64, uint8_t **data) {
157         int len,datalen;
158
159         len = strlen(base64);
160         datalen = (len/4 + 1)*3;
161         if (datalen < 0x123+0x25) {
162                 /* less than header + 1 sample??? */
163                 fprintf(stderr,"suspiciously short data block\n");
164         }
165         *data = malloc(datalen);
166         if (! *data) {
167                 datalen = 0;
168                 fprintf(stderr,"Out of memory\n");
169                 goto bail;
170         }
171         decode(base64, *data, len);
172
173         if (memcmp(*data,"Dive\01\00\00",7))
174                 fprintf(stderr,"Missing Dive100 header\n");
175
176 bail:
177         return datalen;
178 }
179
180 /*
181  * parse uemis base64 data blob into struct dive
182  */
183 void uemis_parse_divelog_binary(char *base64, void *datap) {
184         int datalen;
185         int i;
186         uint8_t *data;
187         struct sample *sample;
188         struct dive **divep = datap;
189         struct dive *dive = *divep;
190         int template, gasoffset;
191
192         datalen = uemis_convert_base64(base64, &data);
193
194         /* dive template in use:
195            0 = air
196            1 = nitrox (B)
197            2 = nitrox (B+D)
198            3 = nitrox (B+T+D)
199            uemis cylinder data is insane - it stores seven tank settings in a block
200            and the template tells us which of the four groups of tanks we need to look at
201          */
202         gasoffset = template = *(uint8_t *)(data+115);
203         if (template == 3)
204                 gasoffset = 4;
205         for (i = 0; i < template; i++) {
206                 float volume = *(float *)(data+116+25*(gasoffset + i)) * 1000.0;
207                 /* uemis always assumes a working pressure of 3000psi / 206bar - even though that's wrong */
208                 /* I also think that the unit that it stores (cuft for me) might change with SDA settings */
209                 // dive->cylinder[i].type.size.mliter = volume * 206.84 / 28.317;
210                 dive->cylinder[i].type.size.mliter = volume * 200 / 28.317;
211                 dive->cylinder[i].gasmix.o2.permille = *(uint8_t *)(data+120+25*(gasoffset + i)) * 10 + 0.5;
212                 dive->cylinder[i].gasmix.he.permille = 0;
213         }
214         /* first byte of divelog data is at offset 0x123 */
215         i = 0x123;
216         while ((i < datalen) && (*(uint16_t *)(data+i))) {
217                 /* it seems that a dive_time of 0 indicates the end of the valid readings */
218                 /* the SDA usually records more samples after the end of the dive --
219                  * we want to discard those, but not cut the dive short; sadly the dive
220                  * duration in the header is a) in minutes and b) up to 3 minutes short */
221                 if (*(uint16_t *)(data+i) > dive->duration.seconds + 180)
222                         break;
223                 sample = prepare_sample(divep);
224                 dive = *divep; /* prepare_sample might realloc the dive */
225                 sample->time.seconds = *(uint16_t *)(data+i);
226                 sample->depth.mm = pressure_to_depth(*(uint16_t *)(data+i+2));
227                 sample->temperature.mkelvin = (*(uint16_t *)(data+i+4) * 100) + 273150;
228                 sample->cylinderpressure.mbar= *(uint16_t *)(data+i+23) * 10;
229                 sample->cylinderindex = *(uint8_t *)(data+i+22);
230                 finish_sample(dive, sample);
231                 i += 0x25;
232         }
233         dive->duration.seconds = sample->time.seconds - 1;
234         return;
235 }
236
237 /* parse a single file
238  * TODO: we don't report any errors when the parse fails - we simply don't add them to the list
239  */
240 void
241 parse_uemis_file(char *divelogfilename) {
242         char *found=NULL;
243         struct tm tm;
244         struct dive *dive;
245
246         FILE *divelogfile = fopen(divelogfilename,"r");
247
248         dive = alloc_dive();
249
250         if (! matchit(divelogfile,"val key=\"date\"","<ts>\\([^<]*\\)</ts>",&found)) {
251                 /* some error handling */
252                 goto bail;
253         }
254         strptime(found, "%Y-%m-%dT%H:%M:%S", &tm);
255         dive->when = utc_mktime(&tm);
256         if (! matchit(divelogfile,"<val key=\"duration\">",
257                         "<float>\\([0-9.]*\\)</float>", &found)) {
258                 /* some error handling */
259                 goto bail;
260         }
261         dive->duration.seconds = 60.0 * atof(found);
262
263         if (! matchit(divelogfile,"<val key=\"depth\">",
264                         "<int>\\([0-9.]*\\)</int>", &found)) {
265                 /* some error handling */
266                 goto bail;
267         }
268         dive->maxdepth.mm = pressure_to_depth(atoi(found));
269
270         if (! matchit(divelogfile,"<val key=\"file_content\">",
271                         ">\\([a-zA-Z0-9+/=]*\\)<", &found)) {
272                 /* some error handling */
273                 goto bail;
274         }
275         uemis_parse_divelog_binary(found,&dive);
276         record_dive(dive);
277 bail:
278         if (found)
279                 free(found);
280 }
281
282 /*
283  * parse the two files extracted from the SDA
284  */
285 void
286 uemis_import() {
287         if (open_import_file_dialog("*.SDA","uemis Zurich SDA files",
288                                         &parse_uemis_file))
289                 report_dives();
290 }