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

seac_screen.c (24011B)


      1 /*
      2  * libdivecomputer
      3  *
      4  * Copyright (C) 2022 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> // memcmp, memcpy
     23 #include <stdlib.h> // malloc, free
     24 
     25 #include "seac_screen.h"
     26 #include "seac_screen_common.h"
     27 #include "context-private.h"
     28 #include "device-private.h"
     29 #include "ringbuffer.h"
     30 #include "rbstream.h"
     31 #include "packet.h"
     32 #include "checksum.h"
     33 #include "array.h"
     34 
     35 #define ISINSTANCE(device) dc_device_isinstance((device), &seac_screen_device_vtable)
     36 
     37 #define MAXRETRIES 4
     38 
     39 #define START     0x55
     40 #define ACK       0x09
     41 #define NAK       0x30
     42 
     43 #define ERR_INVALID_CMD    0x02
     44 #define ERR_INVALID_LENGTH 0x03
     45 #define ERR_INVALID_DATA   0x04
     46 #define ERR_BATTERY_LOW    0x05
     47 #define ERR_BUSY           0x06
     48 
     49 #define SZ_MAXCMD   8
     50 #define SZ_MAXRSP   SZ_READ
     51 
     52 #define CMD_HWINFO  0x1833
     53 #define CMD_SWINFO  0x1834
     54 
     55 // Screen
     56 #define CMD_SCREEN_RANGE   0x1840
     57 #define CMD_SCREEN_ADDRESS 0x1841
     58 #define CMD_SCREEN_READ    0x1842
     59 
     60 // Tablet
     61 #define CMD_TABLET_RANGE   0x1850
     62 #define CMD_TABLET_ADDRESS 0x1851
     63 #define CMD_TABLET_READ    0x1852
     64 
     65 #define SZ_HWINFO  256
     66 #define SZ_SWINFO  256
     67 #define SZ_RANGE   8
     68 #define SZ_ADDRESS 4
     69 #define SZ_READ    2048
     70 
     71 #define FP_OFFSET   0
     72 #define FP_SIZE     4
     73 
     74 #define RB_PROFILE_DISTANCE(a,b,l) ringbuffer_distance (a, b, DC_RINGBUFFER_FULL, l->rb_profile_begin, l->rb_profile_end)
     75 #define RB_PROFILE_INCR(a,b,l)     ringbuffer_increment (a, b, l->rb_profile_begin, l->rb_profile_end)
     76 
     77 #define ACTION 0x01
     78 #define SCREEN 0x02
     79 #define TABLET 0x10
     80 
     81 typedef struct seac_screen_commands_t {
     82 	unsigned short range;
     83 	unsigned short address;
     84 	unsigned short read;
     85 } seac_screen_commands_t;
     86 
     87 typedef struct seac_screen_layout_t {
     88 	unsigned int rb_profile_begin;
     89 	unsigned int rb_profile_end;
     90 } seac_screen_layout_t;
     91 
     92 typedef struct seac_screen_device_t {
     93 	dc_device_t base;
     94 	dc_iostream_t *iostream;
     95 	const seac_screen_commands_t *cmds;
     96 	const seac_screen_layout_t *layout;
     97 	unsigned int fingerprint;
     98 	unsigned char info[SZ_HWINFO + SZ_SWINFO];
     99 } seac_screen_device_t;
    100 
    101 static dc_status_t seac_screen_device_set_fingerprint (dc_device_t *abstract, const unsigned char data[], unsigned int size);
    102 static dc_status_t seac_screen_device_read (dc_device_t *abstract, unsigned int address, unsigned char data[], unsigned int size);
    103 static dc_status_t seac_screen_device_dump (dc_device_t *abstract, dc_buffer_t *buffer);
    104 static dc_status_t seac_screen_device_foreach (dc_device_t *abstract, dc_dive_callback_t callback, void *userdata);
    105 static dc_status_t seac_screen_device_close (dc_device_t *abstract);
    106 
    107 static const dc_device_vtable_t seac_screen_device_vtable = {
    108 	sizeof(seac_screen_device_t),
    109 	DC_FAMILY_SEAC_SCREEN,
    110 	seac_screen_device_set_fingerprint, /* set_fingerprint */
    111 	seac_screen_device_read, /* read */
    112 	NULL, /* write */
    113 	seac_screen_device_dump, /* dump */
    114 	seac_screen_device_foreach, /* foreach */
    115 	NULL, /* timesync */
    116 	seac_screen_device_close, /* close */
    117 };
    118 
    119 static const seac_screen_commands_t cmds_screen = {
    120 	CMD_SCREEN_RANGE,
    121 	CMD_SCREEN_ADDRESS,
    122 	CMD_SCREEN_READ,
    123 };
    124 
    125 static const seac_screen_commands_t cmds_tablet = {
    126 	CMD_TABLET_RANGE,
    127 	CMD_TABLET_ADDRESS,
    128 	CMD_TABLET_READ,
    129 };
    130 
    131 static const seac_screen_layout_t layout_screen = {
    132 	0x010000, /* rb_profile_begin */
    133 	0x200000, /* rb_profile_end */
    134 };
    135 
    136 static const seac_screen_layout_t layout_tablet = {
    137 	0x0A0000, /* rb_profile_begin */
    138 	0x400000, /* rb_profile_end */
    139 };
    140 
    141 static dc_status_t
    142 seac_screen_send (seac_screen_device_t *device, unsigned short cmd, const unsigned char data[], size_t size)
    143 {
    144 	dc_status_t status = DC_STATUS_SUCCESS;
    145 	dc_device_t *abstract = (dc_device_t *) device;
    146 	unsigned short crc = 0;
    147 
    148 	if (device_is_cancelled (abstract))
    149 		return DC_STATUS_CANCELLED;
    150 
    151 	if (size > SZ_MAXCMD)
    152 		return DC_STATUS_INVALIDARGS;
    153 
    154 	// Setup the data packet
    155 	unsigned len = size + 6;
    156 	unsigned char packet[SZ_MAXCMD + 7] = {
    157 		START,
    158 		(len >> 8) & 0xFF,
    159 		(len     ) & 0xFF,
    160 		(cmd >> 8) & 0xFF,
    161 		(cmd     ) & 0xFF,
    162 	};
    163 	if (size) {
    164 		memcpy (packet + 5, data, size);
    165 	}
    166 	crc = checksum_crc16_ccitt (packet, size + 5, 0xFFFF, 0x0000);
    167 	packet[size +  5] = (crc >> 8) & 0xFF;
    168 	packet[size +  6] = (crc     ) & 0xFF;
    169 
    170 	// Send the data packet.
    171 	status = dc_iostream_write (device->iostream, packet, size + 7, NULL);
    172 	if (status != DC_STATUS_SUCCESS) {
    173 		ERROR (abstract->context, "Failed to send the command.");
    174 		return status;
    175 	}
    176 
    177 	return DC_STATUS_SUCCESS;
    178 }
    179 
    180 static dc_status_t
    181 seac_screen_receive (seac_screen_device_t *device, unsigned short cmd, unsigned char data[], size_t size)
    182 {
    183 	dc_status_t status = DC_STATUS_SUCCESS;
    184 	dc_device_t *abstract = (dc_device_t *) device;
    185 	unsigned char packet[SZ_MAXRSP + 8] = {0};
    186 
    187 	// Read the packet start byte.
    188 	while (1) {
    189 		status = dc_iostream_read (device->iostream, packet + 0, 1, NULL);
    190 		if (status != DC_STATUS_SUCCESS) {
    191 			ERROR (abstract->context, "Failed to receive the packet start byte.");
    192 			return status;
    193 		}
    194 
    195 		if (packet[0] == START)
    196 			break;
    197 
    198 		WARNING (abstract->context, "Unexpected packet header byte (%02x).", packet[0]);
    199 	}
    200 
    201 	// Read the packet length.
    202 	status = dc_iostream_read (device->iostream, packet + 1, 2, NULL);
    203 	if (status != DC_STATUS_SUCCESS) {
    204 		ERROR (abstract->context, "Failed to receive the packet length.");
    205 		return status;
    206 	}
    207 
    208 	// Verify the length.
    209 	unsigned int length = array_uint16_be (packet + 1);
    210 	if (length < 7 || length + 1 > sizeof(packet)) {
    211 		ERROR (abstract->context, "Unexpected packet length (%u).", length);
    212 		return DC_STATUS_PROTOCOL;
    213 	}
    214 
    215 	// Read the packet payload.
    216 	status = dc_iostream_read (device->iostream, packet + 3, length - 2, NULL);
    217 	if (status != DC_STATUS_SUCCESS) {
    218 		ERROR (abstract->context, "Failed to receive the packet payload.");
    219 		return status;
    220 	}
    221 
    222 	// Verify the checksum.
    223 	unsigned short crc = array_uint16_be (packet + 1 + length - 2);
    224 	unsigned short ccrc = checksum_crc16_ccitt (packet, 1 + length - 2, 0xFFFF, 0x0000);
    225 	if (crc != ccrc) {
    226 		ERROR (abstract->context, "Unexpected packet checksum (%04x %04x).", crc, ccrc);
    227 		return DC_STATUS_PROTOCOL;
    228 	}
    229 
    230 	// Verify the command response.
    231 	unsigned int rsp = array_uint16_be (packet + 3);
    232 	if (rsp != cmd) {
    233 		ERROR (abstract->context, "Unexpected command response (%04x).", rsp);
    234 		return DC_STATUS_PROTOCOL;
    235 	}
    236 
    237 	// Verify the ACK/NAK byte.
    238 	unsigned int type = packet[1 + length - 3];
    239 	if (type != ACK && type != NAK) {
    240 		ERROR (abstract->context, "Unexpected ACK/NAK byte (%02x).", type);
    241 		return DC_STATUS_PROTOCOL;
    242 	}
    243 
    244 	// Verify the length of the packet.
    245 	unsigned int expected = (type == ACK ? size : 1) + 7;
    246 	if (length != expected) {
    247 		ERROR (abstract->context, "Unexpected packet length (%u).", length);
    248 		return DC_STATUS_PROTOCOL;
    249 	}
    250 
    251 	// Get the error code from a NAK packet.
    252 	if (type == NAK) {
    253 		unsigned int errcode = packet[5];
    254 		ERROR (abstract->context, "Received NAK packet with error code %02x.", errcode);
    255 		return DC_STATUS_PROTOCOL;
    256 	}
    257 
    258 	memcpy (data, packet + 5, length - 7);
    259 
    260 	return DC_STATUS_SUCCESS;
    261 }
    262 
    263 static dc_status_t
    264 seac_screen_packet (seac_screen_device_t *device, unsigned int cmd, const unsigned char data[], unsigned int size, unsigned char answer[], unsigned int asize)
    265 {
    266 	dc_status_t status = DC_STATUS_SUCCESS;
    267 	dc_device_t *abstract = (dc_device_t *) device;
    268 
    269 	status = seac_screen_send (device, cmd, data, size);
    270 	if (status != DC_STATUS_SUCCESS) {
    271 		ERROR (abstract->context, "Failed to send the command.");
    272 		return status;
    273 	}
    274 
    275 	status = seac_screen_receive (device, cmd, answer, asize);
    276 	if (status != DC_STATUS_SUCCESS) {
    277 		ERROR (abstract->context, "Failed to receive the response.");
    278 		return status;
    279 	}
    280 
    281 	return status;
    282 }
    283 
    284 static dc_status_t
    285 seac_screen_transfer (seac_screen_device_t *device, unsigned int cmd, const unsigned char data[], unsigned int size, unsigned char answer[], unsigned int asize)
    286 {
    287 	unsigned int nretries = 0;
    288 	dc_status_t rc = DC_STATUS_SUCCESS;
    289 	while ((rc = seac_screen_packet (device, cmd, data, size, answer, asize)) != DC_STATUS_SUCCESS) {
    290 		// Automatically discard a corrupted packet,
    291 		// and request a new one.
    292 		if (rc != DC_STATUS_PROTOCOL && rc != DC_STATUS_TIMEOUT)
    293 			return rc;
    294 
    295 		// Abort if the maximum number of retries is reached.
    296 		if (nretries++ >= MAXRETRIES)
    297 			return rc;
    298 
    299 		// Discard any garbage bytes.
    300 		dc_iostream_sleep (device->iostream, 100);
    301 		dc_iostream_purge (device->iostream, DC_DIRECTION_INPUT);
    302 	}
    303 
    304 	return DC_STATUS_SUCCESS;
    305 }
    306 
    307 dc_status_t
    308 seac_screen_device_open (dc_device_t **out, dc_context_t *context, dc_iostream_t *iostream)
    309 {
    310 	dc_status_t status = DC_STATUS_SUCCESS;
    311 	seac_screen_device_t *device = NULL;
    312 	dc_transport_t transport = dc_iostream_get_transport (iostream);
    313 
    314 	if (out == NULL)
    315 		return DC_STATUS_INVALIDARGS;
    316 
    317 	// Allocate memory.
    318 	device = (seac_screen_device_t *) dc_device_allocate (context, &seac_screen_device_vtable);
    319 	if (device == NULL) {
    320 		ERROR (context, "Failed to allocate memory.");
    321 		return DC_STATUS_NOMEMORY;
    322 	}
    323 
    324 	// Set the default values.
    325 	device->cmds = NULL;
    326 	device->layout = NULL;
    327 	device->fingerprint = 0;
    328 	memset (device->info, 0, sizeof (device->info));
    329 
    330 	// Create the packet stream.
    331 	if (transport == DC_TRANSPORT_BLE) {
    332 		status = dc_packet_open (&device->iostream, context, iostream, 244, 244);
    333 		if (status != DC_STATUS_SUCCESS) {
    334 			ERROR (context, "Failed to create the packet stream.");
    335 			goto error_free;
    336 		}
    337 	} else {
    338 		device->iostream = iostream;
    339 	}
    340 
    341 	// Set the serial communication protocol (115200 8N1).
    342 	status = dc_iostream_configure (device->iostream, 115200, 8, DC_PARITY_NONE, DC_STOPBITS_ONE, DC_FLOWCONTROL_NONE);
    343 	if (status != DC_STATUS_SUCCESS) {
    344 		ERROR (context, "Failed to set the terminal attributes.");
    345 		goto error_free_iostream;
    346 	}
    347 
    348 	// Set the timeout for receiving data.
    349 	int timeout = transport == DC_TRANSPORT_BLE ? 6000 : 1000;
    350 	status = dc_iostream_set_timeout (device->iostream, timeout);
    351 	if (status != DC_STATUS_SUCCESS) {
    352 		ERROR (context, "Failed to set the timeout.");
    353 		goto error_free_iostream;
    354 	}
    355 
    356 	// Make sure everything is in a sane state.
    357 	dc_iostream_sleep (device->iostream, 100);
    358 	dc_iostream_purge (device->iostream, DC_DIRECTION_ALL);
    359 
    360 	// Wakeup the device.
    361 	const unsigned char init[] = {0x61};
    362 	dc_iostream_write (device->iostream, init, sizeof (init), NULL);
    363 
    364 	// Read the hardware info.
    365 	status = seac_screen_transfer (device, CMD_HWINFO, NULL, 0, device->info, SZ_HWINFO);
    366 	if (status != DC_STATUS_SUCCESS) {
    367 		ERROR (context, "Failed to read the hardware info.");
    368 		goto error_free_iostream;
    369 	}
    370 
    371 	HEXDUMP (context, DC_LOGLEVEL_DEBUG, "Hardware", device->info, SZ_HWINFO);
    372 
    373 	// Read the software info.
    374 	status = seac_screen_transfer (device, CMD_SWINFO, NULL, 0, device->info + SZ_HWINFO, SZ_SWINFO);
    375 	if (status != DC_STATUS_SUCCESS) {
    376 		ERROR (context, "Failed to read the software info.");
    377 		goto error_free_iostream;
    378 	}
    379 
    380 	HEXDUMP (context, DC_LOGLEVEL_DEBUG, "Software", device->info + SZ_HWINFO, SZ_SWINFO);
    381 
    382 	unsigned int model = array_uint32_le (device->info + 4);
    383 	if (model == TABLET) {
    384 		device->cmds = &cmds_tablet;
    385 		device->layout = &layout_tablet;
    386 	} else {
    387 		device->cmds = &cmds_screen;
    388 		device->layout = &layout_screen;
    389 	}
    390 
    391 	*out = (dc_device_t *) device;
    392 
    393 	return DC_STATUS_SUCCESS;
    394 
    395 error_free_iostream:
    396 	if (transport == DC_TRANSPORT_BLE) {
    397 		dc_iostream_close (device->iostream);
    398 	}
    399 error_free:
    400 	dc_device_deallocate ((dc_device_t *) device);
    401 	return status;
    402 }
    403 
    404 static dc_status_t
    405 seac_screen_device_close (dc_device_t *abstract)
    406 {
    407 	seac_screen_device_t *device = (seac_screen_device_t *) abstract;
    408 	dc_transport_t transport = dc_iostream_get_transport (device->iostream);
    409 
    410 	// Close the packet stream.
    411 	if (transport == DC_TRANSPORT_BLE) {
    412 		return dc_iostream_close (device->iostream);
    413 	}
    414 
    415 	return DC_STATUS_SUCCESS;
    416 }
    417 
    418 static dc_status_t
    419 seac_screen_device_set_fingerprint (dc_device_t *abstract, const unsigned char data[], unsigned int size)
    420 {
    421 	seac_screen_device_t *device = (seac_screen_device_t *) abstract;
    422 
    423 	if (size && size != FP_SIZE)
    424 		return DC_STATUS_INVALIDARGS;
    425 
    426 	if (size) {
    427 		device->fingerprint = array_uint32_le (data);
    428 	} else {
    429 		device->fingerprint = 0;
    430 	}
    431 
    432 	return DC_STATUS_SUCCESS;
    433 }
    434 
    435 static dc_status_t
    436 seac_screen_device_read (dc_device_t *abstract, unsigned int address, unsigned char data[], unsigned int size)
    437 {
    438 	dc_status_t status = DC_STATUS_SUCCESS;
    439 	seac_screen_device_t *device = (seac_screen_device_t *) abstract;
    440 
    441 	unsigned int nbytes = 0;
    442 	while (nbytes < size) {
    443 		// Maximum payload size.
    444 		unsigned int len = size - nbytes;
    445 		if (len > SZ_READ)
    446 			len = SZ_READ;
    447 
    448 		// Read the data packet.
    449 		// Regardless of the requested payload size, the packet size is always
    450 		// the maximum size. The remainder of the packet is padded with zeros.
    451 		const unsigned char params[] = {
    452 			(address >> 24) & 0xFF,
    453 			(address >> 16) & 0xFF,
    454 			(address >>  8) & 0xFF,
    455 			(address      ) & 0xFF,
    456 			(len >> 24) & 0xFF,
    457 			(len >> 16) & 0xFF,
    458 			(len >>  8) & 0xFF,
    459 			(len      ) & 0xFF,
    460 		};
    461 		unsigned char packet[SZ_READ] = {0};
    462 		const unsigned int packetsize = device->cmds->read == CMD_TABLET_READ ? len : sizeof(packet);
    463 		status = seac_screen_transfer (device, device->cmds->read, params, sizeof(params), packet, packetsize);
    464 		if (status != DC_STATUS_SUCCESS) {
    465 			ERROR (abstract->context, "Failed to send the read command.");
    466 			return status;
    467 		}
    468 
    469 		// Copy only the payload bytes.
    470 		memcpy (data, packet, len);
    471 
    472 		nbytes += len;
    473 		address += len;
    474 		data += len;
    475 	}
    476 
    477 	return status;
    478 }
    479 
    480 static dc_status_t
    481 seac_screen_device_dump (dc_device_t *abstract, dc_buffer_t *buffer)
    482 {
    483 	seac_screen_device_t *device = (seac_screen_device_t *) abstract;
    484 	const seac_screen_layout_t *layout = device->layout;
    485 
    486 	// Emit a device info event.
    487 	dc_event_devinfo_t devinfo;
    488 	devinfo.model = array_uint32_le (device->info + 4);
    489 	if (devinfo.model == TABLET) {
    490 		devinfo.firmware = array_uint32_le (device->info + 0x114);
    491 	} else {
    492 		devinfo.firmware = array_uint32_le (device->info + 0x11C);
    493 	}
    494 	devinfo.serial = array_uint32_le (device->info + 0x10);
    495 	device_event_emit (abstract, DC_EVENT_DEVINFO, &devinfo);
    496 
    497 	// Emit a vendor event.
    498 	dc_event_vendor_t vendor;
    499 	vendor.data = device->info;
    500 	vendor.size = sizeof(device->info);
    501 	device_event_emit (abstract, DC_EVENT_VENDOR, &vendor);
    502 
    503 	// Allocate the required amount of memory.
    504 	if (!dc_buffer_resize (buffer, layout->rb_profile_end - layout->rb_profile_begin)) {
    505 		ERROR (abstract->context, "Insufficient buffer space available.");
    506 		return DC_STATUS_NOMEMORY;
    507 	}
    508 
    509 	return device_dump_read (abstract, layout->rb_profile_begin, dc_buffer_get_data (buffer),
    510 		dc_buffer_get_size (buffer), SZ_READ);
    511 }
    512 
    513 static dc_status_t
    514 seac_screen_device_foreach (dc_device_t *abstract, dc_dive_callback_t callback, void *userdata)
    515 {
    516 	dc_status_t status = DC_STATUS_SUCCESS;
    517 	seac_screen_device_t *device = (seac_screen_device_t *) abstract;
    518 	const seac_screen_layout_t *layout = device->layout;
    519 
    520 	// Enable progress notifications.
    521 	dc_event_progress_t progress = EVENT_PROGRESS_INITIALIZER;
    522 	progress.maximum = layout->rb_profile_end - layout->rb_profile_begin;
    523 	device_event_emit (abstract, DC_EVENT_PROGRESS, &progress);
    524 
    525 	// Emit a device info event.
    526 	dc_event_devinfo_t devinfo;
    527 	devinfo.model = array_uint32_le (device->info + 4);
    528 	if (devinfo.model == TABLET) {
    529 		devinfo.firmware = array_uint32_le (device->info + 0x114);
    530 	} else {
    531 		devinfo.firmware = array_uint32_le (device->info + 0x11C);
    532 	}
    533 	devinfo.serial = array_uint32_le (device->info + 0x010);
    534 	device_event_emit (abstract, DC_EVENT_DEVINFO, &devinfo);
    535 
    536 	// Emit a vendor event.
    537 	dc_event_vendor_t vendor;
    538 	vendor.data = device->info;
    539 	vendor.size = sizeof(device->info);
    540 	device_event_emit (abstract, DC_EVENT_VENDOR, &vendor);
    541 
    542 	// Read the range of the available dive numbers.
    543 	unsigned char range[SZ_RANGE] = {0};
    544 	status = seac_screen_transfer (device, device->cmds->range, NULL, 0, range, sizeof(range));
    545 	if (status != DC_STATUS_SUCCESS) {
    546 		ERROR (abstract->context, "Failed to send the range command.");
    547 		goto error_exit;
    548 	}
    549 
    550 	// Extract the first and last dive number.
    551 	unsigned int first = array_uint32_be (range + 0);
    552 	unsigned int last  = array_uint32_be (range + 4);
    553 	if (first > last) {
    554 		ERROR (abstract->context, "Invalid dive numbers (%u %u).", first, last);
    555 		status = DC_STATUS_DATAFORMAT;
    556 		goto error_exit;
    557 	}
    558 
    559 	// Calculate the number of dives.
    560 	unsigned int ndives = last - first + 1;
    561 
    562 	// Check the fingerprint.
    563 	if (device->fingerprint >= last) {
    564 		ndives = 0;
    565 	} else if (device->fingerprint >= first) {
    566 		first = device->fingerprint + 1;
    567 		ndives = last - first + 1;
    568 	}
    569 
    570 	// Update and emit a progress event.
    571 	progress.current += SZ_RANGE;
    572 	progress.maximum += SZ_RANGE + ndives * SZ_ADDRESS;
    573 	device_event_emit (abstract, DC_EVENT_PROGRESS, &progress);
    574 
    575 	// Exit if no dives to download.
    576 	if (ndives == 0) {
    577 		goto error_exit;
    578 	}
    579 
    580 	// Allocate memory for the dive addresses.
    581 	unsigned int *address = (unsigned int *) malloc (ndives * sizeof (unsigned int));
    582 	if (address == NULL) {
    583 		status = DC_STATUS_NOMEMORY;
    584 		goto error_exit;
    585 	}
    586 
    587 	// Read the address of each dive in reverse order (most recent first).
    588 	unsigned int eop = 0;
    589 	unsigned int previous = 0;
    590 	unsigned int begin = 0;
    591 	unsigned int count = 0;
    592 	unsigned int skip = 0;
    593 	unsigned int rb_profile_size = 0;
    594 	unsigned int remaining = layout->rb_profile_end - layout->rb_profile_begin;
    595 	for (unsigned int i = 0; i < ndives; ++i) {
    596 		unsigned int number = last - i;
    597 
    598 		// Read the dive address.
    599 		const unsigned char cmd_address[] = {
    600 			(number >> 24) & 0xFF,
    601 			(number >> 16) & 0xFF,
    602 			(number >>  8) & 0xFF,
    603 			(number      ) & 0xFF,
    604 		};
    605 		unsigned char rsp_address[SZ_ADDRESS] = {0};
    606 		status = seac_screen_transfer (device, device->cmds->address, cmd_address, sizeof(cmd_address), rsp_address, sizeof(rsp_address));
    607 		if (status != DC_STATUS_SUCCESS) {
    608 			ERROR (abstract->context, "Failed to read the dive address.");
    609 			goto error_free_logbook;
    610 		}
    611 
    612 		// Update and emit a progress event.
    613 		progress.current += SZ_ADDRESS;
    614 		device_event_emit (abstract, DC_EVENT_PROGRESS, &progress);
    615 
    616 		// Get the dive address.
    617 		address[i] = array_uint32_be (rsp_address);
    618 		if (address[i] < layout->rb_profile_begin || address[i] >= layout->rb_profile_end) {
    619 			ERROR (abstract->context, "Invalid ringbuffer pointer (0x%08x).", address[i]);
    620 			status = DC_STATUS_DATAFORMAT;
    621 			goto error_free_logbook;
    622 		}
    623 
    624 		// Get the end-of-profile pointer.
    625 		if (eop == 0) {
    626 			// Read the dive header.
    627 			unsigned char header[SZ_HEADER] = {0};
    628 			status = seac_screen_device_read (abstract, address[i], header, sizeof(header));
    629 			if (status != DC_STATUS_SUCCESS) {
    630 				ERROR (abstract->context, "Failed to read the dive header.");
    631 				goto error_free_logbook;
    632 			}
    633 
    634 			// Update and emit a progress event.
    635 			progress.current += sizeof(header);
    636 			progress.maximum += sizeof(header);
    637 			device_event_emit (abstract, DC_EVENT_PROGRESS, &progress);
    638 
    639 			// Check the header records.
    640 			unsigned int isvalid = 1;
    641 			for (unsigned int j = 0; j < 2; ++j) {
    642 				unsigned int type = j == 0 ? HEADER1 : HEADER2;
    643 				if (!seac_screen_record_isvalid (abstract->context,
    644 					header + j * SZ_HEADER / 2, SZ_HEADER / 2,
    645 					type, number)) {
    646 					WARNING (abstract->context, "Invalid header record %u.", j);
    647 					isvalid = 0;
    648 				}
    649 			}
    650 
    651 			// For dives with an invalid header, the number of samples in the
    652 			// header is not guaranteed to be valid. Discard the entire dive
    653 			// instead and take its start address as the end of the profile.
    654 			if (!isvalid) {
    655 				WARNING (abstract->context, "Unable to locate the end of the profile.");
    656 				eop = previous = address[i];
    657 				begin = 1;
    658 				skip++;
    659 				continue;
    660 			}
    661 
    662 			// Get the number of samples.
    663 			unsigned int nsamples = array_uint32_le (header + 0x44);
    664 			unsigned int nbytes = SZ_HEADER + nsamples * SZ_SAMPLE;
    665 
    666 			// Calculate the end of the profile.
    667 			eop = previous = RB_PROFILE_INCR (address[i], nbytes, layout);
    668 		}
    669 
    670 		// Calculate the length.
    671 		unsigned int length = RB_PROFILE_DISTANCE (address[i], previous, layout);
    672 
    673 		// Check for the end of the ringbuffer.
    674 		if (length > remaining) {
    675 			WARNING (abstract->context, "Reached the end of the ringbuffer.");
    676 			skip++;
    677 			break;
    678 		}
    679 
    680 		// Update the total profile size.
    681 		rb_profile_size += length;
    682 
    683 		// Move to the start of the current dive.
    684 		remaining -= length;
    685 		previous = address[i];
    686 		count++;
    687 	}
    688 
    689 	// Update and emit a progress event.
    690 	progress.maximum -= (ndives - count - skip) * SZ_ADDRESS +
    691 		((layout->rb_profile_end - layout->rb_profile_begin) - rb_profile_size);
    692 	device_event_emit (abstract, DC_EVENT_PROGRESS, &progress);
    693 
    694 	// Exit if no dives to download.
    695 	if (count == 0) {
    696 		goto error_free_logbook;
    697 	}
    698 
    699 	// Allocate memory for the profile data.
    700 	unsigned char *profile = (unsigned char *) malloc (rb_profile_size);
    701 	if (profile == NULL) {
    702 		status = DC_STATUS_NOMEMORY;
    703 		goto error_free_logbook;
    704 	}
    705 
    706 	// Create the ringbuffer stream.
    707 	dc_rbstream_t *rbstream = NULL;
    708 	status = dc_rbstream_new (&rbstream, abstract, SZ_READ, SZ_READ, layout->rb_profile_begin, layout->rb_profile_end, eop, DC_RBSTREAM_BACKWARD);
    709 	if (status != DC_STATUS_SUCCESS) {
    710 		ERROR (abstract->context, "Failed to create the ringbuffer stream.");
    711 		goto error_free_profile;
    712 	}
    713 
    714 	previous = eop;
    715 	unsigned int offset = rb_profile_size;
    716 	for (unsigned int i = 0; i < count; ++i) {
    717 		unsigned int idx = begin + i;
    718 		unsigned int number = last - idx;
    719 
    720 		// Calculate the length.
    721 		unsigned int length = RB_PROFILE_DISTANCE (address[idx], previous, layout);
    722 
    723 		// Move to the start of the current dive.
    724 		offset -= length;
    725 		previous = address[idx];
    726 
    727 		// Read the dive.
    728 		status = dc_rbstream_read (rbstream, &progress, profile + offset, length);
    729 		if (status != DC_STATUS_SUCCESS) {
    730 			ERROR (abstract->context, "Failed to read the dive.");
    731 			goto error_free_rbstream;
    732 		}
    733 
    734 		// Check the minimum header length.
    735 		if (length < SZ_HEADER) {
    736 			ERROR (abstract->context, "Unexpected dive length (%u).", length);
    737 			status = DC_STATUS_DATAFORMAT;
    738 			goto error_free_rbstream;
    739 		}
    740 
    741 		// Check the header records.
    742 		unsigned int isvalid = 1;
    743 		for (unsigned int j = 0; j < 2; ++j) {
    744 			unsigned int type = j == 0 ? HEADER1 : HEADER2;
    745 			if (!seac_screen_record_isvalid (abstract->context,
    746 				profile + offset + j * SZ_HEADER / 2, SZ_HEADER / 2,
    747 				type, number)) {
    748 				WARNING (abstract->context, "Invalid header record %u.", j);
    749 				isvalid = 0;
    750 			}
    751 		}
    752 
    753 		// Get the number of samples.
    754 		// The actual size of the dive, based on the number of samples, can
    755 		// sometimes be smaller than the maximum length. In that case, the
    756 		// remainder of the data is padded with 0xFF bytes.
    757 		unsigned int nsamples = 0;
    758 		unsigned int nbytes = 0;
    759 		if (isvalid) {
    760 			nsamples = array_uint32_le (profile + offset + 0x44);
    761 			nbytes = SZ_HEADER + nsamples * SZ_SAMPLE;
    762 		} else {
    763 			WARNING (abstract->context, "Unable to locate the padding bytes.");
    764 			nbytes = length;
    765 		}
    766 
    767 		if (nbytes > length) {
    768 			ERROR (abstract->context, "Unexpected dive length (%u %u).", nbytes, length);
    769 			status = DC_STATUS_DATAFORMAT;
    770 			goto error_free_rbstream;
    771 		}
    772 
    773 		if (callback && !callback (profile + offset, nbytes, profile + offset + FP_OFFSET, FP_SIZE, userdata)) {
    774 			break;
    775 		}
    776 	}
    777 
    778 error_free_rbstream:
    779 	dc_rbstream_free (rbstream);
    780 error_free_profile:
    781 	free (profile);
    782 error_free_logbook:
    783 	free (address);
    784 error_exit:
    785 	return status;
    786 }