subrascasse

Sub Rascasse: an iPhone dive log for Subsurface cloud storage, with a pure-Swift git client (GPL-2.0)
git clone https://git.schurger.org/subrascasse.git
Log | Files | Refs | README | LICENSE

mares_common.c (11342B)


      1 /*
      2  * libdivecomputer
      3  *
      4  * Copyright (C) 2009 Jef Driesen
      5  *
      6  * This library is free software; you can redistribute it and/or
      7  * modify it under the terms of the GNU Lesser General Public
      8  * License as published by the Free Software Foundation; either
      9  * version 2.1 of the License, or (at your option) any later version.
     10  *
     11  * This library is distributed in the hope that it will be useful,
     12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
     13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
     14  * Lesser General Public License for more details.
     15  *
     16  * You should have received a copy of the GNU Lesser General Public
     17  * License along with this library; if not, write to the Free Software
     18  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
     19  * MA 02110-1301 USA
     20  */
     21 
     22 #include <stdlib.h> // malloc
     23 #include <string.h> // memcpy, memcmp
     24 #include <assert.h> // assert
     25 
     26 #include "context-private.h"
     27 #include "mares_common.h"
     28 #include "checksum.h"
     29 #include "array.h"
     30 
     31 #define MAXRETRIES 4
     32 
     33 #define FP_OFFSET 8
     34 #define FP_SIZE   5
     35 
     36 #define NEMO        0
     37 #define NEMOWIDE    1
     38 #define NEMOAIR     4
     39 #define PUCK        7
     40 #define NEMOEXCEL   17
     41 #define NEMOAPNEIST 18
     42 #define PUCKAIR     19
     43 
     44 #define AIR      0
     45 #define NITROX   1
     46 #define FREEDIVE 2
     47 #define GAUGE    3
     48 
     49 void
     50 mares_common_device_init (mares_common_device_t *device, dc_iostream_t *iostream)
     51 {
     52 	assert (device != NULL);
     53 
     54 	// Set the default values.
     55 	device->iostream = iostream;
     56 	device->echo = 0;
     57 	device->delay = 0;
     58 }
     59 
     60 
     61 static void
     62 mares_common_make_ascii (const unsigned char raw[], unsigned int rsize, unsigned char ascii[], unsigned int asize)
     63 {
     64 	assert (asize == 2 * (rsize + 2));
     65 
     66 	// Header
     67 	ascii[0] = '<';
     68 
     69 	// Data
     70 	array_convert_bin2hex (raw, rsize, ascii + 1, 2 * rsize);
     71 
     72 	// Checksum
     73 	unsigned char checksum = checksum_add_uint8 (ascii + 1, 2 * rsize, 0x00);
     74 	array_convert_bin2hex (&checksum, 1, ascii + 1 + 2 * rsize, 2);
     75 
     76 	// Trailer
     77 	ascii[asize - 1] = '>';
     78 }
     79 
     80 
     81 static dc_status_t
     82 mares_common_packet (mares_common_device_t *device, const unsigned char command[], unsigned int csize, unsigned char answer[], unsigned int asize)
     83 {
     84 	dc_status_t status = DC_STATUS_SUCCESS;
     85 	dc_device_t *abstract = (dc_device_t *) device;
     86 
     87 	if (device_is_cancelled (abstract))
     88 		return DC_STATUS_CANCELLED;
     89 
     90 	if (device->delay) {
     91 		dc_iostream_sleep (device->iostream, device->delay);
     92 	}
     93 
     94 	// Send the command to the device.
     95 	status = dc_iostream_write (device->iostream, command, csize, NULL);
     96 	if (status != DC_STATUS_SUCCESS) {
     97 		ERROR (abstract->context, "Failed to send the command.");
     98 		return status;
     99 	}
    100 
    101 	if (device->echo) {
    102 		// Receive the echo of the command.
    103 		unsigned char echo[PACKETSIZE] = {0};
    104 		status = dc_iostream_read (device->iostream, echo, csize, NULL);
    105 		if (status != DC_STATUS_SUCCESS) {
    106 			ERROR (abstract->context, "Failed to receive the echo.");
    107 			return status;
    108 		}
    109 
    110 		// Verify the echo.
    111 		if (memcmp (echo, command, csize) != 0) {
    112 			WARNING (abstract->context, "Unexpected echo.");
    113 		}
    114 	}
    115 
    116 	// Receive the answer of the device.
    117 	status = dc_iostream_read (device->iostream, answer, asize, NULL);
    118 	if (status != DC_STATUS_SUCCESS) {
    119 		ERROR (abstract->context, "Failed to receive the answer.");
    120 		return status;
    121 	}
    122 
    123 	// Verify the header and trailer of the packet.
    124 	if (answer[0] != '<' || answer[asize - 1] != '>') {
    125 		ERROR (abstract->context, "Unexpected answer header/trailer byte.");
    126 		return DC_STATUS_PROTOCOL;
    127 	}
    128 
    129 	// Verify the checksum of the packet.
    130 	unsigned char crc = 0;
    131 	unsigned char ccrc = checksum_add_uint8 (answer + 1, asize - 4, 0x00);
    132 	array_convert_hex2bin (answer + asize - 3, 2, &crc, 1);
    133 	if (crc != ccrc) {
    134 		ERROR (abstract->context, "Unexpected answer checksum.");
    135 		return DC_STATUS_PROTOCOL;
    136 	}
    137 
    138 	return DC_STATUS_SUCCESS;
    139 }
    140 
    141 
    142 static dc_status_t
    143 mares_common_transfer (mares_common_device_t *device, const unsigned char command[], unsigned int csize, unsigned char answer[], unsigned int asize)
    144 {
    145 	unsigned int nretries = 0;
    146 	dc_status_t rc = DC_STATUS_SUCCESS;
    147 	while ((rc = mares_common_packet (device, command, csize, answer, asize)) != DC_STATUS_SUCCESS) {
    148 		// Automatically discard a corrupted packet,
    149 		// and request a new one.
    150 		if (rc != DC_STATUS_PROTOCOL && rc != DC_STATUS_TIMEOUT)
    151 			return rc;
    152 
    153 		// Abort if the maximum number of retries is reached.
    154 		if (nretries++ >= MAXRETRIES)
    155 			return rc;
    156 
    157 		// Discard any garbage bytes.
    158 		dc_iostream_sleep (device->iostream, 100);
    159 		dc_iostream_purge (device->iostream, DC_DIRECTION_INPUT);
    160 	}
    161 
    162 	return rc;
    163 }
    164 
    165 
    166 dc_status_t
    167 mares_common_device_read (dc_device_t *abstract, unsigned int address, unsigned char data[], unsigned int size)
    168 {
    169 	mares_common_device_t *device = (mares_common_device_t*) abstract;
    170 
    171 	unsigned int nbytes = 0;
    172 	while (nbytes < size) {
    173 		// Calculate the packet size.
    174 		unsigned int len = size - nbytes;
    175 		if (len > PACKETSIZE)
    176 			len = PACKETSIZE;
    177 
    178 		// Build the raw command.
    179 		unsigned char raw[] = {0x51,
    180 			(address     ) & 0xFF, // Low
    181 			(address >> 8) & 0xFF, // High
    182 			len}; // Count
    183 
    184 		// Build the ascii command.
    185 		unsigned char command[2 * (sizeof (raw) + 2)] = {0};
    186 		mares_common_make_ascii (raw, sizeof (raw), command, sizeof (command));
    187 
    188 		// Send the command and receive the answer.
    189 		unsigned char answer[2 * (PACKETSIZE + 2)] = {0};
    190 		dc_status_t rc = mares_common_transfer (device, command, sizeof (command), answer, 2 * (len + 2));
    191 		if (rc != DC_STATUS_SUCCESS)
    192 			return rc;
    193 
    194 		// Extract the raw data from the packet.
    195 		array_convert_hex2bin (answer + 1, 2 * len, data, len);
    196 
    197 		nbytes += len;
    198 		address += len;
    199 		data += len;
    200 	}
    201 
    202 	return DC_STATUS_SUCCESS;
    203 }
    204 
    205 
    206 dc_status_t
    207 mares_common_extract_dives (dc_context_t *context, const mares_common_layout_t *layout, const unsigned char fingerprint[], const unsigned char data[], dc_dive_callback_t callback, void *userdata)
    208 {
    209 	assert (layout != NULL);
    210 
    211 	// Get the freedive mode for this model.
    212 	unsigned int model = data[1];
    213 	unsigned int freedive = FREEDIVE;
    214 	if (model == NEMOWIDE || model == NEMOAIR || model == PUCK || model == PUCKAIR)
    215 		freedive = GAUGE;
    216 
    217 	// Get the end of the profile ring buffer.
    218 	unsigned int eop = array_uint16_le (data + 0x6B);
    219 	if (eop < layout->rb_profile_begin || eop >= layout->rb_profile_end) {
    220 		ERROR (context, "Ringbuffer pointer out of range (0x%04x).", eop);
    221 		return DC_STATUS_DATAFORMAT;
    222 	}
    223 
    224 	// Make the ringbuffer linear, to avoid having to deal
    225 	// with the wrap point. The buffer has extra space to
    226 	// store the profile data for the freedives.
    227 	unsigned char *buffer = (unsigned char *) malloc (
    228 		layout->rb_profile_end - layout->rb_profile_begin +
    229 		layout->rb_freedives_end - layout->rb_freedives_begin);
    230 	if (buffer == NULL) {
    231 		ERROR (context, "Failed to allocate memory.");
    232 		return DC_STATUS_NOMEMORY;
    233 	}
    234 
    235 	memcpy (buffer + 0, data + eop, layout->rb_profile_end - eop);
    236 	memcpy (buffer + layout->rb_profile_end - eop, data + layout->rb_profile_begin, eop - layout->rb_profile_begin);
    237 
    238 	// For a freedive session, the Mares Nemo stores all the freedives of
    239 	// that session in a single logbook entry, and each sample is actually
    240 	// a summary for each individual freedive in the session. The profile
    241 	// data is stored in a separate memory area. Since only the most recent
    242 	// recent freediving session can have profile data, we keep track of the
    243 	// number of freedives.
    244 	unsigned int nfreedives = 0;
    245 
    246 	unsigned int offset = layout->rb_profile_end - layout->rb_profile_begin;
    247 	while (offset >= 3) {
    248 		// Check for the presence of extra header bytes, which can be detected
    249 		// by means of a three byte marker sequence.
    250 		unsigned int extra = 0;
    251 		const unsigned char marker[3] = {0xAA, 0xBB, 0xCC};
    252 		if (memcmp (buffer + offset - 3, marker, sizeof (marker)) == 0) {
    253 			if (model == PUCKAIR)
    254 				extra = 7;
    255 			else
    256 				extra = 12;
    257 		}
    258 
    259 		// Check for overflows due to incomplete dives.
    260 		if (offset < extra + 3)
    261 			break;
    262 
    263 		// Check the dive mode of the logbook entry. Valid modes are
    264 		// 0 (air), 1 (EANx), 2 (freedive) or 3 (bottom timer).
    265 		// If the ringbuffer has never reached the wrap point before,
    266 		// there will be "empty" memory (filled with 0xFF) and
    267 		// processing should stop at this point.
    268 		unsigned int mode = buffer[offset - extra - 1];
    269 		if (mode == 0xFF)
    270 			break;
    271 
    272 		// The header and sample size are dependant on the dive mode. Only
    273 		// in freedive mode, the sizes are different from the other modes.
    274 		unsigned int header_size = 53;
    275 		unsigned int sample_size = 2;
    276 		if (extra) {
    277 			if (model == PUCKAIR)
    278 				sample_size = 3;
    279 			else
    280 				sample_size = 5;
    281 		}
    282 		if (mode == freedive) {
    283 			header_size = 28;
    284 			sample_size = 6;
    285 			nfreedives++;
    286 		}
    287 
    288 		// Get the number of samples in the profile data.
    289 		unsigned int nsamples = array_uint16_le (buffer + offset - extra - 3);
    290 
    291 		// Calculate the total number of bytes for this dive.
    292 		// If the buffer does not contain that much bytes, we reached the
    293 		// end of the ringbuffer. The current dive is incomplete (partially
    294 		// overwritten with newer data), and processing should stop.
    295 		unsigned int nbytes = 2 + nsamples * sample_size + header_size + extra;
    296 		if (offset < nbytes)
    297 			break;
    298 
    299 		// Move to the start of the dive.
    300 		offset -= nbytes;
    301 
    302 		// Verify that the length that is stored in the profile data
    303 		// equals the calculated length. If both values are different,
    304 		// something is wrong and an error is returned.
    305 		unsigned int length = array_uint16_le (buffer + offset);
    306 		if (length != nbytes) {
    307 			ERROR (context, "Calculated and stored size are not equal (%u %u).", length, nbytes);
    308 			free (buffer);
    309 			return DC_STATUS_DATAFORMAT;
    310 		}
    311 
    312 		// Process the profile data for the most recent freedive entry.
    313 		// Since we are processing the entries backwards (newest to oldest),
    314 		// this entry will always be the first one.
    315 		if (mode == freedive && nfreedives == 1) {
    316 			// Count the number of freedives in the profile data.
    317 			unsigned int count = 0;
    318 			unsigned int idx = layout->rb_freedives_begin;
    319 			while (idx + 2 <= layout->rb_freedives_end &&
    320 				count != nsamples)
    321 			{
    322 				// Each freedive in the session ends with a zero sample.
    323 				unsigned int sample = array_uint16_le (data + idx);
    324 				if (sample == 0)
    325 					count++;
    326 
    327 				// Move to the next sample.
    328 				idx += 2;
    329 			}
    330 
    331 			// Verify that the number of freedive entries in the session
    332 			// equals the number of freedives in the profile data. If
    333 			// both values are different, the profile data is incomplete.
    334 			if (count != nsamples) {
    335 				ERROR (context, "Unexpected number of freedive sessions (%u %u).", count, nsamples);
    336 				free (buffer);
    337 				return DC_STATUS_DATAFORMAT;
    338 			}
    339 
    340 			// Append the profile data to the main logbook entry. The
    341 			// buffer is guaranteed to have enough space, and the dives
    342 			// that will be overwritten have already been processed.
    343 			memcpy (buffer + offset + nbytes, data + layout->rb_freedives_begin, idx - layout->rb_freedives_begin);
    344 			nbytes += idx - layout->rb_freedives_begin;
    345 		}
    346 
    347 		unsigned int fp_offset = offset + length - extra - FP_OFFSET;
    348 		if (fingerprint && memcmp (buffer + fp_offset, fingerprint, FP_SIZE) == 0) {
    349 			free (buffer);
    350 			return DC_STATUS_SUCCESS;
    351 		}
    352 
    353 		if (callback && !callback (buffer + offset, nbytes, buffer + fp_offset, FP_SIZE, userdata)) {
    354 			free (buffer);
    355 			return DC_STATUS_SUCCESS;
    356 		}
    357 	}
    358 
    359 	free (buffer);
    360 
    361 	return DC_STATUS_SUCCESS;
    362 }