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

cressi_leonardo.c (16783B)


      1 /*
      2  * libdivecomputer
      3  *
      4  * Copyright (C) 2013 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 <string.h> // memcpy, memcmp
     23 #include <stdlib.h> // malloc, free
     24 #include <assert.h> // assert
     25 
     26 #include "cressi_leonardo.h"
     27 #include "context-private.h"
     28 #include "device-private.h"
     29 #include "checksum.h"
     30 #include "array.h"
     31 #include "ringbuffer.h"
     32 
     33 #define ISINSTANCE(device) dc_device_isinstance((device), &cressi_leonardo_device_vtable)
     34 
     35 #define SZ_MEMORY 32000
     36 
     37 #define RB_LOGBOOK_BEGIN 0x0100
     38 #define RB_LOGBOOK_END   0x1438
     39 #define RB_LOGBOOK_SIZE  0x52
     40 #define RB_LOGBOOK_COUNT ((RB_LOGBOOK_END - RB_LOGBOOK_BEGIN) / RB_LOGBOOK_SIZE)
     41 
     42 #define RB_PROFILE_BEGIN 0x1438
     43 #define RB_PROFILE_END   SZ_MEMORY
     44 #define RB_PROFILE_DISTANCE(a,b) ringbuffer_distance (a, b, DC_RINGBUFFER_EMPTY, RB_PROFILE_BEGIN, RB_PROFILE_END)
     45 
     46 #define MAXRETRIES 4
     47 #define PACKETSIZE 32
     48 
     49 typedef struct cressi_leonardo_device_t {
     50 	dc_device_t base;
     51 	dc_iostream_t *iostream;
     52 	unsigned char fingerprint[5];
     53 } cressi_leonardo_device_t;
     54 
     55 static dc_status_t cressi_leonardo_device_set_fingerprint (dc_device_t *abstract, const unsigned char data[], unsigned int size);
     56 static dc_status_t cressi_leonardo_device_read (dc_device_t *abstract, unsigned int address, unsigned char data[], unsigned int size);
     57 static dc_status_t cressi_leonardo_device_dump (dc_device_t *abstract, dc_buffer_t *buffer);
     58 static dc_status_t cressi_leonardo_device_foreach (dc_device_t *abstract, dc_dive_callback_t callback, void *userdata);
     59 
     60 static const dc_device_vtable_t cressi_leonardo_device_vtable = {
     61 	sizeof(cressi_leonardo_device_t),
     62 	DC_FAMILY_CRESSI_LEONARDO,
     63 	cressi_leonardo_device_set_fingerprint, /* set_fingerprint */
     64 	cressi_leonardo_device_read, /* read */
     65 	NULL, /* write */
     66 	cressi_leonardo_device_dump, /* dump */
     67 	cressi_leonardo_device_foreach, /* foreach */
     68 	NULL, /* timesync */
     69 	NULL /* close */
     70 };
     71 
     72 static dc_status_t
     73 cressi_leonardo_extract_dives (dc_device_t *abstract, const unsigned char data[], unsigned int size, dc_dive_callback_t callback, void *userdata);
     74 
     75 static void
     76 cressi_leonardo_make_ascii (const unsigned char raw[], unsigned int rsize, unsigned char ascii[], unsigned int asize)
     77 {
     78 	assert (asize == 2 * (rsize + 3));
     79 
     80 	// Header
     81 	ascii[0] = '{';
     82 
     83 	// Data
     84 	array_convert_bin2hex (raw, rsize, ascii + 1, 2 * rsize);
     85 
     86 	// Checksum
     87 	unsigned short crc = checksum_crc16_ccitt (ascii + 1, 2 * rsize, 0xffff, 0x0000);
     88 	unsigned char checksum[] = {
     89 			(crc >> 8) & 0xFF,  // High
     90 			(crc     ) & 0xFF}; // Low
     91 	array_convert_bin2hex (checksum, sizeof(checksum), ascii + 1 + 2 * rsize, 4);
     92 
     93 	// Trailer
     94 	ascii[asize - 1] = '}';
     95 }
     96 
     97 static dc_status_t
     98 cressi_leonardo_packet (cressi_leonardo_device_t *device, const unsigned char command[], unsigned int csize, unsigned char answer[], unsigned int asize)
     99 {
    100 	dc_status_t status = DC_STATUS_SUCCESS;
    101 	dc_device_t *abstract = (dc_device_t *) device;
    102 
    103 	if (device_is_cancelled (abstract))
    104 		return DC_STATUS_CANCELLED;
    105 
    106 	// Send the command to the device.
    107 	status = dc_iostream_write (device->iostream, command, csize, NULL);
    108 	if (status != DC_STATUS_SUCCESS) {
    109 		ERROR (abstract->context, "Failed to send the command.");
    110 		return status;
    111 	}
    112 
    113 	// Receive the answer of the device.
    114 	status = dc_iostream_read (device->iostream, answer, asize, NULL);
    115 	if (status != DC_STATUS_SUCCESS) {
    116 		ERROR (abstract->context, "Failed to receive the answer.");
    117 		return status;
    118 	}
    119 
    120 	// Verify the header and trailer of the packet.
    121 	if (answer[0] != '{' || answer[asize - 1] != '}') {
    122 		ERROR (abstract->context, "Unexpected answer header/trailer byte.");
    123 		return DC_STATUS_PROTOCOL;
    124 	}
    125 
    126 	// Convert the checksum of the packet.
    127 	unsigned char checksum[2] = {0};
    128 	array_convert_hex2bin (answer + asize - 5, 4, checksum, sizeof(checksum));
    129 
    130 	// Verify the checksum of the packet.
    131 	unsigned short crc = array_uint16_be (checksum);
    132 	unsigned short ccrc = checksum_crc16_ccitt (answer + 1, asize - 6, 0xffff, 0x0000);
    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 static dc_status_t
    142 cressi_leonardo_transfer (cressi_leonardo_device_t *device, const unsigned char command[], unsigned int csize, unsigned char answer[], unsigned int asize)
    143 {
    144 	unsigned int nretries = 0;
    145 	dc_status_t rc = DC_STATUS_SUCCESS;
    146 	while ((rc = cressi_leonardo_packet (device, command, csize, answer, asize)) != DC_STATUS_SUCCESS) {
    147 		// Automatically discard a corrupted packet,
    148 		// and request a new one.
    149 		if (rc != DC_STATUS_PROTOCOL && rc != DC_STATUS_TIMEOUT)
    150 			return rc;
    151 
    152 		// Abort if the maximum number of retries is reached.
    153 		if (nretries++ >= MAXRETRIES)
    154 			return rc;
    155 
    156 		// Discard any garbage bytes.
    157 		dc_iostream_sleep (device->iostream, 100);
    158 		dc_iostream_purge (device->iostream, DC_DIRECTION_INPUT);
    159 	}
    160 
    161 	return rc;
    162 }
    163 
    164 dc_status_t
    165 cressi_leonardo_device_open (dc_device_t **out, dc_context_t *context, dc_iostream_t *iostream)
    166 {
    167 	dc_status_t status = DC_STATUS_SUCCESS;
    168 	cressi_leonardo_device_t *device = NULL;
    169 
    170 	if (out == NULL)
    171 		return DC_STATUS_INVALIDARGS;
    172 
    173 	// Allocate memory.
    174 	device = (cressi_leonardo_device_t *) dc_device_allocate (context, &cressi_leonardo_device_vtable);
    175 	if (device == NULL) {
    176 		ERROR (context, "Failed to allocate memory.");
    177 		return DC_STATUS_NOMEMORY;
    178 	}
    179 
    180 	// Set the default values.
    181 	device->iostream = iostream;
    182 	memset (device->fingerprint, 0, sizeof (device->fingerprint));
    183 
    184 	// Set the serial communication protocol (115200 8N1).
    185 	status = dc_iostream_configure (device->iostream, 115200, 8, DC_PARITY_NONE, DC_STOPBITS_ONE, DC_FLOWCONTROL_NONE);
    186 	if (status != DC_STATUS_SUCCESS) {
    187 		ERROR (context, "Failed to set the terminal attributes.");
    188 		goto error_free;
    189 	}
    190 
    191 	// Set the timeout for receiving data (1000 ms).
    192 	status = dc_iostream_set_timeout (device->iostream, 1000);
    193 	if (status != DC_STATUS_SUCCESS) {
    194 		ERROR (context, "Failed to set the timeout.");
    195 		goto error_free;
    196 	}
    197 
    198 	// Set the RTS line.
    199 	status = dc_iostream_set_rts (device->iostream, 1);
    200 	if (status != DC_STATUS_SUCCESS) {
    201 		ERROR (context, "Failed to set the RTS line.");
    202 		goto error_free;
    203 	}
    204 
    205 	// Set the DTR line.
    206 	status = dc_iostream_set_dtr (device->iostream, 1);
    207 	if (status != DC_STATUS_SUCCESS) {
    208 		ERROR (context, "Failed to set the DTR line.");
    209 		goto error_free;
    210 	}
    211 
    212 	dc_iostream_sleep (device->iostream, 200);
    213 
    214 	// Clear the DTR line.
    215 	status = dc_iostream_set_dtr (device->iostream, 0);
    216 	if (status != DC_STATUS_SUCCESS) {
    217 		ERROR (context, "Failed to clear the DTR line.");
    218 		goto error_free;
    219 	}
    220 
    221 	dc_iostream_sleep (device->iostream, 100);
    222 	dc_iostream_purge (device->iostream, DC_DIRECTION_ALL);
    223 
    224 	*out = (dc_device_t *) device;
    225 
    226 	return DC_STATUS_SUCCESS;
    227 
    228 error_free:
    229 	dc_device_deallocate ((dc_device_t *) device);
    230 	return status;
    231 }
    232 
    233 static dc_status_t
    234 cressi_leonardo_device_set_fingerprint (dc_device_t *abstract, const unsigned char data[], unsigned int size)
    235 {
    236 	cressi_leonardo_device_t *device = (cressi_leonardo_device_t *) abstract;
    237 
    238 	if (size && size != sizeof (device->fingerprint))
    239 		return DC_STATUS_INVALIDARGS;
    240 
    241 	if (size)
    242 		memcpy (device->fingerprint, data, sizeof (device->fingerprint));
    243 	else
    244 		memset (device->fingerprint, 0, sizeof (device->fingerprint));
    245 
    246 	return DC_STATUS_SUCCESS;
    247 }
    248 
    249 static dc_status_t
    250 cressi_leonardo_device_read (dc_device_t *abstract, unsigned int address, unsigned char data[], unsigned int size)
    251 {
    252 	dc_status_t rc = DC_STATUS_SUCCESS;
    253 	cressi_leonardo_device_t *device = (cressi_leonardo_device_t *) abstract;
    254 
    255 	unsigned int nbytes = 0;
    256 	while (nbytes < size) {
    257 		// Calculate the packet size.
    258 		unsigned int len = size - nbytes;
    259 		if (len > PACKETSIZE)
    260 			len = PACKETSIZE;
    261 
    262 		// Build the raw command.
    263 		unsigned char raw[] = {
    264 			(address >> 8) & 0xFF, // High
    265 			(address     ) & 0xFF, // Low
    266 			(len >> 8) & 0xFF, // High
    267 			(len     ) & 0xFF}; // Low
    268 
    269 		// Build the ascii command.
    270 		unsigned char command[2 * (sizeof (raw) + 3)] = {0};
    271 		cressi_leonardo_make_ascii (raw, sizeof (raw), command, sizeof (command));
    272 
    273 		// Send the command and receive the answer.
    274 		unsigned char answer[2 * (PACKETSIZE + 3)] = {0};
    275 		rc = cressi_leonardo_transfer (device, command, sizeof (command), answer, 2 * (len + 3));
    276 		if (rc != DC_STATUS_SUCCESS)
    277 			return rc;
    278 
    279 		// Extract the raw data from the packet.
    280 		array_convert_hex2bin (answer + 1, 2 * len, data, len);
    281 
    282 		nbytes += len;
    283 		address += len;
    284 		data += len;
    285 	}
    286 
    287 	return rc;
    288 }
    289 
    290 static dc_status_t
    291 cressi_leonardo_device_dump (dc_device_t *abstract, dc_buffer_t *buffer)
    292 {
    293 	dc_status_t status = DC_STATUS_SUCCESS;
    294 	cressi_leonardo_device_t *device = (cressi_leonardo_device_t *) abstract;
    295 
    296 	// Allocate the required amount of memory.
    297 	if (!dc_buffer_resize (buffer, SZ_MEMORY)) {
    298 		ERROR (abstract->context, "Insufficient buffer space available.");
    299 		return DC_STATUS_NOMEMORY;
    300 	}
    301 
    302 	// Enable progress notifications.
    303 	dc_event_progress_t progress = EVENT_PROGRESS_INITIALIZER;
    304 	progress.maximum = SZ_MEMORY;
    305 	device_event_emit (abstract, DC_EVENT_PROGRESS, &progress);
    306 
    307 	// Send the command header to the dive computer.
    308 	const unsigned char command[] = {0x7B, 0x31, 0x32, 0x33, 0x44, 0x42, 0x41, 0x7d};
    309 	status = dc_iostream_write (device->iostream, command, sizeof (command), NULL);
    310 	if (status != DC_STATUS_SUCCESS) {
    311 		ERROR (abstract->context, "Failed to send the command.");
    312 		return status;
    313 	}
    314 
    315 	// Receive the header packet.
    316 	unsigned char header[7] = {0};
    317 	status = dc_iostream_read (device->iostream, header, sizeof (header), NULL);
    318 	if (status != DC_STATUS_SUCCESS) {
    319 		ERROR (abstract->context, "Failed to receive the answer.");
    320 		return status;
    321 	}
    322 
    323 	// Verify the header packet.
    324 	const unsigned char expected[] = {0x7B, 0x21, 0x44, 0x35, 0x42, 0x33, 0x7d};
    325 	if (memcmp (header, expected, sizeof (expected)) != 0) {
    326 		ERROR (abstract->context, "Unexpected answer byte.");
    327 		return DC_STATUS_PROTOCOL;
    328 	}
    329 
    330 	unsigned char *data = dc_buffer_get_data (buffer);
    331 
    332 	unsigned int nbytes = 0;
    333 	while (nbytes < SZ_MEMORY) {
    334 		// Set the minimum packet size.
    335 		unsigned int len = 1024;
    336 
    337 		// Increase the packet size if more data is immediately available.
    338 		size_t available = 0;
    339 		status = dc_iostream_get_available (device->iostream, &available);
    340 		if (status == DC_STATUS_SUCCESS && available > len)
    341 			len = available;
    342 
    343 		// Limit the packet size to the total size.
    344 		if (nbytes + len > SZ_MEMORY)
    345 			len = SZ_MEMORY - nbytes;
    346 
    347 		// Read the packet.
    348 		status = dc_iostream_read (device->iostream, data + nbytes, len, NULL);
    349 		if (status != DC_STATUS_SUCCESS) {
    350 			ERROR (abstract->context, "Failed to receive the answer.");
    351 			return status;
    352 		}
    353 
    354 		// Update and emit a progress event.
    355 		progress.current += len;
    356 		device_event_emit (abstract, DC_EVENT_PROGRESS, &progress);
    357 
    358 		nbytes += len;
    359 	}
    360 
    361 	// Receive the trailer packet.
    362 	unsigned char trailer[4] = {0};
    363 	status = dc_iostream_read (device->iostream, trailer, sizeof (trailer), NULL);
    364 	if (status != DC_STATUS_SUCCESS) {
    365 		ERROR (abstract->context, "Failed to receive the answer.");
    366 		return status;
    367 	}
    368 
    369 	// Convert to a binary checksum.
    370 	unsigned char checksum[2] = {0};
    371 	array_convert_hex2bin (trailer, sizeof (trailer), checksum, sizeof (checksum));
    372 
    373 	// Verify the checksum.
    374 	unsigned int csum1 = array_uint16_be (checksum);
    375 	unsigned int csum2 = checksum_crc16_ccitt (data, SZ_MEMORY, 0xffff, 0x0000);
    376 	if (csum1 != csum2) {
    377 		ERROR (abstract->context, "Unexpected answer bytes.");
    378 		return DC_STATUS_PROTOCOL;
    379 	}
    380 
    381 	// Emit a device info event.
    382 	dc_event_devinfo_t devinfo;
    383 	devinfo.model = data[0];
    384 	devinfo.firmware = 0;
    385 	devinfo.serial = array_uint24_le (data + 1);
    386 	device_event_emit (abstract, DC_EVENT_DEVINFO, &devinfo);
    387 
    388 	return DC_STATUS_SUCCESS;
    389 }
    390 
    391 static dc_status_t
    392 cressi_leonardo_device_foreach (dc_device_t *abstract, dc_dive_callback_t callback, void *userdata)
    393 {
    394 	dc_buffer_t *buffer = dc_buffer_new (SZ_MEMORY);
    395 	if (buffer == NULL)
    396 		return DC_STATUS_NOMEMORY;
    397 
    398 	dc_status_t rc = cressi_leonardo_device_dump (abstract, buffer);
    399 	if (rc != DC_STATUS_SUCCESS) {
    400 		dc_buffer_free (buffer);
    401 		return rc;
    402 	}
    403 
    404 	rc = cressi_leonardo_extract_dives (abstract, dc_buffer_get_data (buffer),
    405 		dc_buffer_get_size (buffer), callback, userdata);
    406 
    407 	dc_buffer_free (buffer);
    408 
    409 	return rc;
    410 }
    411 
    412 static dc_status_t
    413 cressi_leonardo_extract_dives (dc_device_t *abstract, const unsigned char data[], unsigned int size, dc_dive_callback_t callback, void *userdata)
    414 {
    415 	cressi_leonardo_device_t *device = (cressi_leonardo_device_t *) abstract;
    416 	dc_context_t *context = (abstract ? abstract->context : NULL);
    417 
    418 	if (abstract && !ISINSTANCE (abstract))
    419 		return DC_STATUS_INVALIDARGS;
    420 
    421 	if (size < SZ_MEMORY)
    422 		return DC_STATUS_DATAFORMAT;
    423 
    424 	// Get the number of dives.
    425 	//unsigned int ndives = array_uint16_le(data + 0x62);
    426 
    427 	// Get the logbook pointer.
    428 	unsigned int last = array_uint16_le(data + 0x64);
    429 	if (last < RB_LOGBOOK_BEGIN || last > RB_LOGBOOK_END ||
    430 		((last - RB_LOGBOOK_BEGIN) % RB_LOGBOOK_SIZE) != 0) {
    431 		ERROR (context, "Invalid logbook pointer (0x%04x).", last);
    432 		return DC_STATUS_DATAFORMAT;
    433 	}
    434 
    435 	// Convert to an index.
    436 	unsigned int latest = (last - RB_LOGBOOK_BEGIN) / RB_LOGBOOK_SIZE;
    437 
    438 	// Get the profile pointer.
    439 	unsigned int eop = array_uint16_le(data + 0x66);
    440 	if (eop < RB_PROFILE_BEGIN || last > RB_PROFILE_END) {
    441 		ERROR (context, "Invalid profile pointer (0x%04x).", eop);
    442 		return DC_STATUS_DATAFORMAT;
    443 	}
    444 
    445 	unsigned char *buffer = (unsigned char *) malloc (RB_LOGBOOK_SIZE + RB_PROFILE_END - RB_PROFILE_BEGIN);
    446 	if (buffer == NULL) {
    447 		ERROR (context, "Failed to allocate memory.");
    448 		return DC_STATUS_NOMEMORY;
    449 	}
    450 
    451 	unsigned int previous = eop;
    452 	unsigned int remaining = RB_PROFILE_END - RB_PROFILE_BEGIN;
    453 	for (unsigned int i = 0; i < RB_LOGBOOK_COUNT; ++i) {
    454 		unsigned int idx = (latest + RB_LOGBOOK_COUNT - i) % RB_LOGBOOK_COUNT;
    455 		unsigned int offset = RB_LOGBOOK_BEGIN + idx * RB_LOGBOOK_SIZE;
    456 
    457 		// Ignore uninitialized header entries.
    458 		if (array_isequal (data + offset, RB_LOGBOOK_SIZE, 0xFF))
    459 			break;
    460 
    461 		// Get the ringbuffer pointers.
    462 		unsigned int header = array_uint16_le (data + offset + 2);
    463 		unsigned int footer = array_uint16_le (data + offset + 4);
    464 		if (header < RB_PROFILE_BEGIN || header + 2 > RB_PROFILE_END ||
    465 			footer < RB_PROFILE_BEGIN || footer + 2 > RB_PROFILE_END)
    466 		{
    467 			ERROR (context, "Invalid ringbuffer pointer detected (0x%04x 0x%04x).", header, footer);
    468 			free (buffer);
    469 			return DC_STATUS_DATAFORMAT;
    470 		}
    471 
    472 		if (previous && previous != footer + 2) {
    473 			ERROR (context, "Profiles are not continuous (0x%04x 0x%04x 0x%04x).", header, footer, previous);
    474 			free (buffer);
    475 			return DC_STATUS_DATAFORMAT;
    476 		}
    477 
    478 		// Check the fingerprint data.
    479 		if (device && memcmp (data + offset + 8, device->fingerprint, sizeof (device->fingerprint)) == 0)
    480 			break;
    481 
    482 		// Copy the logbook entry.
    483 		memcpy (buffer, data + offset, RB_LOGBOOK_SIZE);
    484 
    485 		// Calculate the profile address and length.
    486 		unsigned int address = header + 2;
    487 		unsigned int length = RB_PROFILE_DISTANCE (header, footer) - 2;
    488 
    489 		if (remaining && remaining >= length + 4) {
    490 			// Get the same pointers from the profile.
    491 			unsigned int header2 = array_uint16_le (data + footer);
    492 			unsigned int footer2 = array_uint16_le (data + header);
    493 			if (header2 != header || footer2 != footer) {
    494 				ERROR (context, "Invalid ringbuffer pointer detected (0x%04x 0x%04x).", header2, footer2);
    495 				free (buffer);
    496 				return DC_STATUS_DATAFORMAT;
    497 			}
    498 
    499 			// Copy the profile data.
    500 			if (address + length > RB_PROFILE_END) {
    501 				unsigned int len_a = RB_PROFILE_END - address;
    502 				unsigned int len_b = length - len_a;
    503 				memcpy (buffer + RB_LOGBOOK_SIZE, data + address, len_a);
    504 				memcpy (buffer + RB_LOGBOOK_SIZE + len_a, data + RB_PROFILE_BEGIN, len_b);
    505 			} else {
    506 				memcpy (buffer + RB_LOGBOOK_SIZE, data + address, length);
    507 			}
    508 
    509 			remaining -= length + 4;
    510 		} else {
    511 			// No more profile data available!
    512 			remaining = 0;
    513 			length = 0;
    514 		}
    515 
    516 		if (callback && !callback (buffer, RB_LOGBOOK_SIZE + length, buffer + 8, sizeof (device->fingerprint), userdata)) {
    517 			break;
    518 		}
    519 
    520 		previous = header;
    521 	}
    522 
    523 	free (buffer);
    524 
    525 	return DC_STATUS_SUCCESS;
    526 }