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

liquivision_lynx.c (22635B)


      1 /*
      2  * libdivecomputer
      3  *
      4  * Copyright (C) 2020 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>
     23 #include <string.h>
     24 #include <assert.h>
     25 
     26 #include <libdivecomputer/units.h>
     27 
     28 #include "liquivision_lynx.h"
     29 #include "context-private.h"
     30 #include "device-private.h"
     31 #include "ringbuffer.h"
     32 #include "rbstream.h"
     33 #include "checksum.h"
     34 #include "array.h"
     35 
     36 #define ISINSTANCE(device) dc_device_isinstance((device), &liquivision_lynx_device_vtable)
     37 
     38 #define XEN  0
     39 #define XEO  1
     40 #define LYNX 2
     41 #define KAON 3
     42 
     43 #define XEN_V1   0x83321485 // Not supported
     44 #define XEN_V2   0x83321502
     45 #define XEN_V3   0x83328401
     46 
     47 #define XEO_V1_A 0x17485623
     48 #define XEO_V1_B 0x27485623
     49 #define XEO_V2_A 0x17488401
     50 #define XEO_V2_B 0x27488401
     51 #define XEO_V3_A 0x17488402
     52 #define XEO_V3_B 0x27488402
     53 
     54 #define LYNX_V1  0x67488403
     55 #define LYNX_V2  0x67488404
     56 #define LYNX_V3  0x67488405
     57 
     58 #define KAON_V1  0x37488402
     59 #define KAON_V2  0x47488402
     60 
     61 #define MAXRETRIES 2
     62 #define MAXPACKET 12
     63 #define SEGMENTSIZE 0x400
     64 #define PAGESIZE    0x1000
     65 #define MEMSIZE     0x200000
     66 
     67 #define RB_LOGBOOK_BEGIN         (1 * PAGESIZE)
     68 #define RB_LOGBOOK_END           (25 * PAGESIZE)
     69 #define RB_LOGBOOK_SIZE          (RB_LOGBOOK_END - RB_LOGBOOK_BEGIN)
     70 #define RB_LOGBOOK_DISTANCE(a,b) ringbuffer_distance (a, b, DC_RINGBUFFER_FULL, RB_LOGBOOK_BEGIN, RB_LOGBOOK_END)
     71 
     72 #define RB_PROFILE_BEGIN         (25 * PAGESIZE)
     73 #define RB_PROFILE_END           (500 * PAGESIZE)
     74 #define RB_PROFILE_SIZE          (RB_PROFILE_END - RB_PROFILE_BEGIN)
     75 #define RB_PROFILE_DISTANCE(a,b) ringbuffer_distance (a, b, DC_RINGBUFFER_FULL, RB_PROFILE_BEGIN, RB_PROFILE_END)
     76 
     77 #define SZ_HEADER_XEN   80
     78 #define SZ_HEADER_OTHER 96
     79 #define SZ_HEADER_MAX   SZ_HEADER_OTHER
     80 
     81 typedef struct liquivision_lynx_device_t {
     82 	dc_device_t base;
     83 	dc_iostream_t *iostream;
     84 	unsigned char fingerprint[4];
     85 	unsigned char info[6];
     86 	unsigned char more[12];
     87 } liquivision_lynx_device_t;
     88 
     89 static dc_status_t liquivision_lynx_device_set_fingerprint (dc_device_t *abstract, const unsigned char data[], unsigned int size);
     90 static dc_status_t liquivision_lynx_device_read (dc_device_t *abstract, unsigned int address, unsigned char data[], unsigned int size);
     91 static dc_status_t liquivision_lynx_device_dump (dc_device_t *abstract, dc_buffer_t *buffer);
     92 static dc_status_t liquivision_lynx_device_foreach (dc_device_t *abstract, dc_dive_callback_t callback, void *userdata);
     93 static dc_status_t liquivision_lynx_device_close (dc_device_t *abstract);
     94 
     95 static const dc_device_vtable_t liquivision_lynx_device_vtable = {
     96 	sizeof(liquivision_lynx_device_t),
     97 	DC_FAMILY_LIQUIVISION_LYNX,
     98 	liquivision_lynx_device_set_fingerprint, /* set_fingerprint */
     99 	liquivision_lynx_device_read, /* read */
    100 	NULL, /* write */
    101 	liquivision_lynx_device_dump, /* dump */
    102 	liquivision_lynx_device_foreach, /* foreach */
    103 	NULL, /* timesync */
    104 	liquivision_lynx_device_close /* close */
    105 };
    106 
    107 static dc_status_t
    108 liquivision_lynx_send (liquivision_lynx_device_t *device, const unsigned char data[], unsigned int size)
    109 {
    110 	dc_status_t status = DC_STATUS_SUCCESS;
    111 	dc_device_t *abstract = (dc_device_t *) device;
    112 
    113 	if (size > MAXPACKET)
    114 		return DC_STATUS_INVALIDARGS;
    115 
    116 	// Build the packet.
    117 	unsigned char packet[2 + MAXPACKET + 2] = {0};
    118 	packet[0] = 0x00;
    119 	packet[1] = 0xB1;
    120 	if (size) {
    121 		memcpy (packet + 2, data, size);
    122 	}
    123 	packet[2 + size + 0] = 0x0B;
    124 	packet[2 + size + 1] = 0x0E;
    125 
    126 	// Send the packet to the device.
    127 	status = dc_iostream_write (device->iostream, packet, size + 4, NULL);
    128 	if (status != DC_STATUS_SUCCESS) {
    129 		ERROR (abstract->context, "Failed to send the packet.");
    130 		return status;
    131 	}
    132 
    133 	return DC_STATUS_SUCCESS;
    134 }
    135 
    136 static dc_status_t
    137 liquivision_lynx_recv (liquivision_lynx_device_t *device, unsigned char data[], unsigned int size)
    138 {
    139 	dc_status_t status = DC_STATUS_SUCCESS;
    140 	dc_device_t *abstract = (dc_device_t *) device;
    141 
    142 	if (size > SEGMENTSIZE)
    143 		return DC_STATUS_INVALIDARGS;
    144 
    145 	// Receive the packet from the device.
    146 	unsigned char packet[1 + SEGMENTSIZE + 2] = {0};
    147 	status = dc_iostream_read (device->iostream, packet, 1 + size + 2, NULL);
    148 	if (status != DC_STATUS_SUCCESS) {
    149 		ERROR (abstract->context, "Failed to receive the packet.");
    150 		return status;
    151 	}
    152 
    153 	// Verify the start byte.
    154 	if (packet[0] != 0xC5) {
    155 		ERROR (abstract->context, "Unexpected answer start byte (%02x).", packet[0]);
    156 		return DC_STATUS_PROTOCOL;
    157 	}
    158 
    159 	// Verify the checksum.
    160 	unsigned short crc = array_uint16_be (packet + 1 + size);
    161 	unsigned short ccrc = checksum_crc16_ccitt (packet + 1, size, 0xffff, 0x0000);
    162 	if (crc != ccrc) {
    163 		ERROR (abstract->context, "Unexpected answer checksum (%04x %04x).", crc, ccrc);
    164 		return DC_STATUS_PROTOCOL;
    165 	}
    166 
    167 	if (size) {
    168 		memcpy (data, packet + 1, size);
    169 	}
    170 
    171 	return DC_STATUS_SUCCESS;
    172 }
    173 
    174 static dc_status_t
    175 liquivision_lynx_packet (liquivision_lynx_device_t *device, const unsigned char command[], unsigned int csize, unsigned char answer[], unsigned int asize)
    176 {
    177 	dc_status_t status = DC_STATUS_SUCCESS;
    178 	dc_device_t *abstract = (dc_device_t *) device;
    179 
    180 	if (device_is_cancelled (abstract))
    181 		return DC_STATUS_CANCELLED;
    182 
    183 	status = liquivision_lynx_send (device, command, csize);
    184 	if (status != DC_STATUS_SUCCESS) {
    185 		ERROR (abstract->context, "Failed to send the command.");
    186 		return status;
    187 	}
    188 
    189 	if (asize) {
    190 		status = liquivision_lynx_recv (device, answer, asize);
    191 		if (status != DC_STATUS_SUCCESS) {
    192 			ERROR (abstract->context, "Failed to receive the answer.");
    193 			return status;
    194 		}
    195 	}
    196 
    197 	return DC_STATUS_SUCCESS;
    198 }
    199 
    200 static dc_status_t
    201 liquivision_lynx_transfer (liquivision_lynx_device_t *device, const unsigned char command[], unsigned int csize, unsigned char answer[], unsigned int asize)
    202 {
    203 	unsigned int nretries = 0;
    204 	dc_status_t rc = DC_STATUS_SUCCESS;
    205 	while ((rc = liquivision_lynx_packet (device, command, csize, answer, asize)) != DC_STATUS_SUCCESS) {
    206 		if (rc != DC_STATUS_TIMEOUT && rc != DC_STATUS_PROTOCOL)
    207 			return rc;
    208 
    209 		// Abort if the maximum number of retries is reached.
    210 		if (nretries++ >= MAXRETRIES)
    211 			return rc;
    212 
    213 		// Delay the next attempt.
    214 		dc_iostream_sleep (device->iostream, 100);
    215 		dc_iostream_purge (device->iostream, DC_DIRECTION_INPUT);
    216 	}
    217 
    218 	return DC_STATUS_SUCCESS;
    219 }
    220 
    221 dc_status_t
    222 liquivision_lynx_device_open (dc_device_t **out, dc_context_t *context, dc_iostream_t *iostream)
    223 {
    224 	dc_status_t status = DC_STATUS_SUCCESS;
    225 	liquivision_lynx_device_t *device = NULL;
    226 
    227 	if (out == NULL)
    228 		return DC_STATUS_INVALIDARGS;
    229 
    230 	// Allocate memory.
    231 	device = (liquivision_lynx_device_t *) dc_device_allocate (context, &liquivision_lynx_device_vtable);
    232 	if (device == NULL) {
    233 		ERROR (context, "Failed to allocate memory.");
    234 		return DC_STATUS_NOMEMORY;
    235 	}
    236 
    237 	// Set the default values.
    238 	device->iostream = iostream;
    239 	memset (device->fingerprint, 0, sizeof (device->fingerprint));
    240 
    241 	// Set the serial communication protocol (9600 8N1).
    242 	status = dc_iostream_configure (device->iostream, 9600, 8, DC_PARITY_NONE, DC_STOPBITS_ONE, DC_FLOWCONTROL_NONE);
    243 	if (status != DC_STATUS_SUCCESS) {
    244 		ERROR (context, "Failed to set the terminal attributes.");
    245 		goto error_free;
    246 	}
    247 
    248 	// Set the timeout for receiving data (3000 ms).
    249 	status = dc_iostream_set_timeout (device->iostream, 3000);
    250 	if (status != DC_STATUS_SUCCESS) {
    251 		ERROR (context, "Failed to set the timeout.");
    252 		goto error_free;
    253 	}
    254 
    255 	// Set the DTR line.
    256 	status = dc_iostream_set_dtr (device->iostream, 0);
    257 	if (status != DC_STATUS_SUCCESS) {
    258 		ERROR (context, "Failed to set the DTR line.");
    259 		goto error_free;
    260 	}
    261 
    262 	// Set the RTS line.
    263 	status = dc_iostream_set_rts (device->iostream, 0);
    264 	if (status != DC_STATUS_SUCCESS) {
    265 		ERROR (context, "Failed to set the RTS line.");
    266 		goto error_free;
    267 	}
    268 
    269 	// Make sure everything is in a sane state.
    270 	dc_iostream_sleep (device->iostream, 100);
    271 	dc_iostream_purge (device->iostream, DC_DIRECTION_ALL);
    272 
    273 	// Wakeup the device.
    274 	for (unsigned int i = 0; i < 6000; ++i) {
    275 		const unsigned char init[] = {0xAA};
    276 		dc_iostream_write (device->iostream, init, sizeof (init), NULL);
    277 	}
    278 
    279 	// Send the info command.
    280 	const unsigned char cmd_info[] = {0x49, 0x4E, 0x46, 0x4F, 0x49, 0x4E, 0x46, 0x4F, 0x49, 0x4E, 0x46, 0x4F};
    281 	status = liquivision_lynx_transfer (device, cmd_info, sizeof(cmd_info), device->info, sizeof(device->info));
    282 	if (status != DC_STATUS_SUCCESS) {
    283 		ERROR (context, "Failed to send the info command.");
    284 		goto error_free;
    285 	}
    286 
    287 	HEXDUMP (context, DC_LOGLEVEL_DEBUG, "Info", device->info, sizeof(device->info));
    288 
    289 	// Send the more info command.
    290 	const unsigned char cmd_more[] = {0x4D, 0x4F, 0x52, 0x45, 0x49, 0x4E, 0x46, 0x4F, 0x4D, 0x4F, 0x52, 0x45};
    291 	status = liquivision_lynx_transfer (device, cmd_more, sizeof(cmd_more), device->more, sizeof(device->more));
    292 	if (status != DC_STATUS_SUCCESS) {
    293 		ERROR (context, "Failed to send the more info command.");
    294 		goto error_free;
    295 	}
    296 
    297 	HEXDUMP (context, DC_LOGLEVEL_DEBUG, "More", device->more, sizeof(device->more));
    298 
    299 	*out = (dc_device_t *) device;
    300 
    301 	return DC_STATUS_SUCCESS;
    302 
    303 error_free:
    304 	dc_device_deallocate ((dc_device_t *) device);
    305 	return status;
    306 }
    307 
    308 
    309 static dc_status_t
    310 liquivision_lynx_device_set_fingerprint (dc_device_t *abstract, const unsigned char data[], unsigned int size)
    311 {
    312 	liquivision_lynx_device_t *device = (liquivision_lynx_device_t *) abstract;
    313 
    314 	if (size && size != sizeof (device->fingerprint))
    315 		return DC_STATUS_INVALIDARGS;
    316 
    317 	if (size)
    318 		memcpy (device->fingerprint, data, sizeof (device->fingerprint));
    319 	else
    320 		memset (device->fingerprint, 0, sizeof (device->fingerprint));
    321 
    322 	return DC_STATUS_SUCCESS;
    323 }
    324 
    325 static dc_status_t
    326 liquivision_lynx_device_read (dc_device_t *abstract, unsigned int address, unsigned char data[], unsigned int size)
    327 {
    328 	dc_status_t status = DC_STATUS_SUCCESS;
    329 	liquivision_lynx_device_t *device = (liquivision_lynx_device_t *) abstract;
    330 
    331 	if ((address % SEGMENTSIZE != 0) ||
    332 		(size    % SEGMENTSIZE != 0))
    333 		return DC_STATUS_INVALIDARGS;
    334 
    335 	// Get the page and segment number.
    336 	unsigned int page    = (address / PAGESIZE);
    337 	unsigned int segment = (address % PAGESIZE) / SEGMENTSIZE;
    338 
    339 	unsigned int nbytes = 0;
    340 	while (nbytes < size) {
    341 		const unsigned char command[] = {
    342 			0x50, 0x41, 0x47, 0x45,
    343 			'0' + ((page / 100) % 10),
    344 			'0' + ((page /  10) % 10),
    345 			'0' + ((page /   1) % 10),
    346 			'0' + ((page / 100) % 10),
    347 			'0' + ((page /  10) % 10),
    348 			'0' + ((page /   1) % 10),
    349 			'0' + segment,
    350 			'0' + segment
    351 		};
    352 
    353 		status = liquivision_lynx_transfer (device, command, sizeof(command), data + nbytes, SEGMENTSIZE);
    354 		if (status != DC_STATUS_SUCCESS) {
    355 			ERROR (abstract->context, "Failed to read page %u segment %u.", page, segment);
    356 			return status;
    357 		}
    358 
    359 		nbytes += SEGMENTSIZE;
    360 		segment++;
    361 		if (segment == (PAGESIZE / SEGMENTSIZE)) {
    362 			segment = 0;
    363 			page++;
    364 		}
    365 	}
    366 
    367 	return DC_STATUS_SUCCESS;
    368 }
    369 
    370 static dc_status_t
    371 liquivision_lynx_device_dump (dc_device_t *abstract, dc_buffer_t *buffer)
    372 {
    373 	liquivision_lynx_device_t *device = (liquivision_lynx_device_t *) abstract;
    374 
    375 	// Emit a device info event.
    376 	dc_event_devinfo_t devinfo;
    377 	devinfo.model = array_uint16_le (device->info + 0);
    378 	devinfo.firmware = 0;
    379 	devinfo.serial = array_uint32_le (device->more + 0);
    380 	device_event_emit (abstract, DC_EVENT_DEVINFO, &devinfo);
    381 
    382 	// Allocate the required amount of memory.
    383 	if (!dc_buffer_resize (buffer, MEMSIZE)) {
    384 		ERROR (abstract->context, "Insufficient buffer space available.");
    385 		return DC_STATUS_NOMEMORY;
    386 	}
    387 
    388 	// Download the memory dump.
    389 	return device_dump_read (abstract, 0, dc_buffer_get_data (buffer),
    390 		dc_buffer_get_size (buffer), SEGMENTSIZE);
    391 }
    392 
    393 static dc_status_t
    394 liquivision_lynx_device_foreach (dc_device_t *abstract, dc_dive_callback_t callback, void *userdata)
    395 {
    396 	dc_status_t status = DC_STATUS_SUCCESS;
    397 	liquivision_lynx_device_t *device = (liquivision_lynx_device_t *) abstract;
    398 
    399 	// Enable progress notifications.
    400 	dc_event_progress_t progress = EVENT_PROGRESS_INITIALIZER;
    401 	progress.maximum = SEGMENTSIZE + RB_LOGBOOK_SIZE + RB_PROFILE_SIZE;
    402 	device_event_emit (abstract, DC_EVENT_PROGRESS, &progress);
    403 
    404 	// Get the model and version.
    405 	unsigned int model = array_uint16_le (device->info + 0);
    406 	unsigned int version = array_uint32_le (device->info + 2);
    407 
    408 	// Emit a device info event.
    409 	dc_event_devinfo_t devinfo;
    410 	devinfo.model = model;
    411 	devinfo.firmware = 0;
    412 	devinfo.serial = array_uint32_le (device->more + 0);
    413 	device_event_emit (abstract, DC_EVENT_DEVINFO, &devinfo);
    414 
    415 	// Read the config segment.
    416 	unsigned char config[SEGMENTSIZE] = {0};
    417 	status = liquivision_lynx_device_read (abstract, 0, config, sizeof (config));
    418 	if (status != DC_STATUS_SUCCESS) {
    419 		ERROR (abstract->context, "Failed to read the memory.");
    420 		goto error_exit;
    421 	}
    422 
    423 	// Get the header size.
    424 	unsigned int headersize = (model == XEN) ? SZ_HEADER_XEN : SZ_HEADER_OTHER;
    425 
    426 	// Get the number of headers per page.
    427 	unsigned int npages = PAGESIZE / headersize;
    428 
    429 	// Get the logbook pointers.
    430 	unsigned int begin = array_uint16_le (config + 0x46);
    431 	unsigned int end   = array_uint16_le (config + 0x48);
    432 	unsigned int rb_logbook_begin = RB_LOGBOOK_BEGIN + (begin / npages) * PAGESIZE + (begin % npages) * headersize;
    433 	unsigned int rb_logbook_end   = RB_LOGBOOK_BEGIN + (end   / npages) * PAGESIZE + (end   % npages) * headersize;
    434 	if (rb_logbook_begin < RB_LOGBOOK_BEGIN || rb_logbook_begin > RB_LOGBOOK_END ||
    435 		rb_logbook_end   < RB_LOGBOOK_BEGIN || rb_logbook_end   > RB_LOGBOOK_END) {
    436 		ERROR (abstract->context, "Invalid logbook pointers (%04x, %04x).",
    437 			rb_logbook_begin, rb_logbook_end);
    438 		status = DC_STATUS_DATAFORMAT;
    439 		goto error_exit;
    440 	}
    441 
    442 	// Calculate the logbook size.
    443 #if 0
    444 	unsigned int rb_logbook_size = RB_LOGBOOK_DISTANCE (rb_logbook_begin, rb_logbook_end);
    445 #else
    446 	// The logbook begin pointer is explicitly ignored, because it only takes
    447 	// into account dives for which the profile is still available.
    448 	unsigned int rb_logbook_size = RB_LOGBOOK_SIZE;
    449 #endif
    450 
    451 	// Get the profile pointers.
    452 	unsigned int rb_profile_begin = array_uint32_le (config + 0x4A);
    453 	unsigned int rb_profile_end   = array_uint32_le (config + 0x4E);
    454 	if (rb_profile_begin < RB_PROFILE_BEGIN || rb_profile_begin > RB_PROFILE_END ||
    455 		rb_profile_end   < RB_PROFILE_BEGIN || rb_profile_end   > RB_PROFILE_END) {
    456 		ERROR (abstract->context, "Invalid profile pointers (%04x, %04x).",
    457 			rb_profile_begin, rb_profile_end);
    458 		status = DC_STATUS_DATAFORMAT;
    459 		goto error_exit;
    460 	}
    461 
    462 	// Update and emit a progress event.
    463 	progress.current += SEGMENTSIZE;
    464 	progress.maximum -= RB_LOGBOOK_SIZE - rb_logbook_size;
    465 	device_event_emit (abstract, DC_EVENT_PROGRESS, &progress);
    466 
    467 	// Allocate memory for the logbook entries.
    468 	unsigned char *logbook = (unsigned char *) malloc (rb_logbook_size);
    469 	if (logbook == NULL) {
    470 		status = DC_STATUS_NOMEMORY;
    471 		goto error_exit;
    472 	}
    473 
    474 	// Create the ringbuffer stream.
    475 	dc_rbstream_t *rblogbook = NULL;
    476 	status = dc_rbstream_new (&rblogbook, abstract, SEGMENTSIZE, SEGMENTSIZE, RB_LOGBOOK_BEGIN, RB_LOGBOOK_END, rb_logbook_end, DC_RBSTREAM_BACKWARD);
    477 	if (status != DC_STATUS_SUCCESS) {
    478 		ERROR (abstract->context, "Failed to create the ringbuffer stream.");
    479 		goto error_free_logbook;
    480 	}
    481 
    482 	// The logbook ringbuffer is read backwards to retrieve the most recent
    483 	// entries first. If an already downloaded entry is identified (by means
    484 	// of its fingerprint), the transfer is aborted immediately to reduce
    485 	// the transfer time.
    486 	unsigned int nbytes = 0;
    487 	unsigned int offset = rb_logbook_size;
    488 	unsigned int address = rb_logbook_end;
    489 	while (nbytes < rb_logbook_size) {
    490 		// Handle the ringbuffer wrap point.
    491 		if (address == RB_LOGBOOK_BEGIN)
    492 			address = RB_LOGBOOK_END;
    493 
    494 		// Skip the padding bytes.
    495 		if ((address % PAGESIZE) == 0) {
    496 			unsigned int padding = PAGESIZE % headersize;
    497 			unsigned char dummy[SZ_HEADER_MAX] = {0};
    498 			status = dc_rbstream_read (rblogbook, &progress, dummy, padding);
    499 			if (status != DC_STATUS_SUCCESS) {
    500 				ERROR (abstract->context, "Failed to read the memory.");
    501 				goto error_free_rblogbook;
    502 			}
    503 
    504 			address -= padding;
    505 			nbytes += padding;
    506 		}
    507 
    508 		// Move to the start of the current entry.
    509 		address -= headersize;
    510 		offset -= headersize;
    511 
    512 		// Read the logbook entry.
    513 		status = dc_rbstream_read (rblogbook, &progress, logbook + offset, headersize);
    514 		if (status != DC_STATUS_SUCCESS) {
    515 			ERROR (abstract->context, "Failed to read the memory.");
    516 			goto error_free_rblogbook;
    517 		}
    518 
    519 		nbytes += headersize;
    520 
    521 		if (array_isequal (logbook + offset, headersize, 0xFF)) {
    522 			offset += headersize;
    523 			break;
    524 		}
    525 
    526 		// Verify the checksum.
    527 		unsigned int unused = 2;
    528 		if (version == XEO_V1_A || version == XEO_V1_B) {
    529 			unused = 6;
    530 		}
    531 		unsigned char header[SZ_HEADER_MAX] = {0};
    532 		memcpy (header + 0, device->info + 2, 4);
    533 		memcpy (header + 4, logbook + offset + 4, headersize - 4);
    534 		unsigned int crc  = array_uint32_le (logbook + offset + 0);
    535 		unsigned int ccrc = checksum_crc32 (header, headersize - unused);
    536 		if (crc != ccrc) {
    537 			WARNING (abstract->context, "Invalid dive checksum (%08x %08x)", crc, ccrc);
    538 			status = DC_STATUS_DATAFORMAT;
    539 			goto error_free_rblogbook;
    540 		}
    541 
    542 		// Compare the fingerprint to identify previously downloaded entries.
    543 		if (memcmp (logbook + offset, device->fingerprint, sizeof(device->fingerprint)) == 0) {
    544 			offset += headersize;
    545 			break;
    546 		}
    547 	}
    548 
    549 	// Update and emit a progress event.
    550 	progress.maximum -= rb_logbook_size - nbytes;
    551 	device_event_emit (abstract, DC_EVENT_PROGRESS, &progress);
    552 
    553 	// Go through the logbook entries a first time, to calculate the total
    554 	// amount of bytes in the profile ringbuffer.
    555 	unsigned int rb_profile_size = 0;
    556 
    557 	// Traverse the logbook ringbuffer backwards to retrieve the most recent
    558 	// dives first. The logbook ringbuffer is linearized at this point, so
    559 	// we do not have to take into account any memory wrapping near the end
    560 	// of the memory buffer.
    561 	unsigned int remaining = RB_PROFILE_SIZE;
    562 	unsigned int previous = rb_profile_end;
    563 	unsigned int entry = rb_logbook_size;
    564 	while (entry != offset) {
    565 		// Move to the start of the current entry.
    566 		entry -= headersize;
    567 
    568 		// Get the profile pointer.
    569 		unsigned int current = array_uint32_le (logbook + entry + 16);
    570 		if (current < RB_PROFILE_BEGIN || current >= RB_PROFILE_END) {
    571 			ERROR (abstract->context, "Invalid profile ringbuffer pointer (%08x).", current);
    572 			status = DC_STATUS_DATAFORMAT;
    573 			goto error_free_rblogbook;
    574 		}
    575 
    576 		// Calculate the length.
    577 		unsigned int length = RB_PROFILE_DISTANCE (current, previous);
    578 
    579 		// Make sure the profile size is valid.
    580 		if (length > remaining) {
    581 			remaining = 0;
    582 			length = 0;
    583 		}
    584 
    585 		// Update the total profile size.
    586 		rb_profile_size += length;
    587 
    588 		// Move to the start of the current dive.
    589 		remaining -= length;
    590 		previous = current;
    591 	}
    592 
    593 	// At this point, we know the exact amount of data
    594 	// that needs to be transferred for the profiles.
    595 	progress.maximum -= RB_PROFILE_SIZE - rb_profile_size;
    596 	device_event_emit (abstract, DC_EVENT_PROGRESS, &progress);
    597 
    598 	// Allocate memory for the profile data.
    599 	unsigned char *profile = (unsigned char *) malloc (headersize + rb_profile_size);
    600 	if (profile == NULL) {
    601 		status = DC_STATUS_NOMEMORY;
    602 		goto error_free_rblogbook;
    603 	}
    604 
    605 	// Create the ringbuffer stream.
    606 	dc_rbstream_t *rbprofile = NULL;
    607 	status = dc_rbstream_new (&rbprofile, abstract, SEGMENTSIZE, SEGMENTSIZE, RB_PROFILE_BEGIN, RB_PROFILE_END, rb_profile_end, DC_RBSTREAM_BACKWARD);
    608 	if (status != DC_STATUS_SUCCESS) {
    609 		ERROR (abstract->context, "Failed to create the ringbuffer stream.");
    610 		goto error_free_profile;
    611 	}
    612 
    613 	// Traverse the logbook ringbuffer backwards to retrieve the most recent
    614 	// dives first. The logbook ringbuffer is linearized at this point, so
    615 	// we do not have to take into account any memory wrapping near the end
    616 	// of the memory buffer.
    617 	remaining = rb_profile_size;
    618 	previous = rb_profile_end;
    619 	entry = rb_logbook_size;
    620 	while (entry != offset) {
    621 		// Move to the start of the current entry.
    622 		entry -= headersize;
    623 
    624 		// Get the profile pointer.
    625 		unsigned int current = array_uint32_le (logbook + entry + 16);
    626 		if (current < RB_PROFILE_BEGIN || current >= RB_PROFILE_END) {
    627 			ERROR (abstract->context, "Invalid profile ringbuffer pointer (%08x).", current);
    628 			status = DC_STATUS_DATAFORMAT;
    629 			goto error_free_rbprofile;
    630 		}
    631 
    632 		// Calculate the length.
    633 		unsigned int length = RB_PROFILE_DISTANCE (current, previous);
    634 
    635 		// Make sure the profile size is valid.
    636 		if (length > remaining) {
    637 			remaining = 0;
    638 			length = 0;
    639 		}
    640 
    641 		// Move to the start of the current dive.
    642 		remaining -= length;
    643 		previous = current;
    644 
    645 		// Read the dive.
    646 		status = dc_rbstream_read (rbprofile, &progress, profile + remaining + headersize, length);
    647 		if (status != DC_STATUS_SUCCESS) {
    648 			ERROR (abstract->context, "Failed to read the dive.");
    649 			goto error_free_rbprofile;
    650 		}
    651 
    652 		// Prepend the logbook entry to the profile data. The memory buffer is
    653 		// large enough to store this entry. The checksum is replaced with the
    654 		// flash version number.
    655 		memcpy (profile + remaining + 0, device->info + 2, 4);
    656 		memcpy (profile + remaining + 4, logbook + entry + 4, headersize - 4);
    657 
    658 		if (callback && !callback (profile + remaining, headersize + length, logbook + entry, sizeof(device->fingerprint), userdata)) {
    659 			break;
    660 		}
    661 	}
    662 
    663 error_free_rbprofile:
    664 	dc_rbstream_free (rbprofile);
    665 error_free_profile:
    666 	free (profile);
    667 error_free_rblogbook:
    668 	dc_rbstream_free (rblogbook);
    669 error_free_logbook:
    670 	free (logbook);
    671 error_exit:
    672 	return status;
    673 }
    674 
    675 static dc_status_t
    676 liquivision_lynx_device_close (dc_device_t *abstract)
    677 {
    678 	dc_status_t status = DC_STATUS_SUCCESS;
    679 	liquivision_lynx_device_t *device = (liquivision_lynx_device_t*) abstract;
    680 	dc_status_t rc = DC_STATUS_SUCCESS;
    681 
    682 	// Send the finish command.
    683 	const unsigned char cmd_finish[] = {0x46, 0x49, 0x4E, 0x49, 0x53, 0x48, 0x46, 0x49, 0x4E, 0x49, 0x53, 0x48};
    684 	status = liquivision_lynx_transfer (device, cmd_finish, sizeof(cmd_finish), NULL, 0);
    685 	if (status != DC_STATUS_SUCCESS) {
    686 		ERROR (abstract->context, "Failed to send the finish command.");
    687 		dc_status_set_error(&status, rc);
    688 	}
    689 
    690 	return status;
    691 }