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_goa.c (23214B)


      1 /*
      2  * libdivecomputer
      3  *
      4  * Copyright (C) 2018 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 <libdivecomputer/ble.h>
     27 
     28 #include "cressi_goa.h"
     29 #include "context-private.h"
     30 #include "device-private.h"
     31 #include "checksum.h"
     32 #include "array.h"
     33 #include "platform.h"
     34 
     35 #define ISINSTANCE(device) dc_device_isinstance((device), &cressi_goa_device_vtable)
     36 
     37 #define CMD_VERSION        0x00
     38 #define CMD_SET_TIME       0x13
     39 #define CMD_EXIT_PCLINK    0x1D
     40 #define CMD_LOGBOOK        0x21
     41 #define CMD_DIVE           0x22
     42 #define CMD_LOGBOOK_V4     0x23
     43 
     44 #define CMD_LOGBOOK_BLE 0x02
     45 #define CMD_DIVE_BLE    0x03
     46 
     47 #define HEADER  0xAA
     48 #define TRAILER 0x55
     49 #define END     0x04
     50 #define ACK     0x06
     51 
     52 #define SZ_DATA   512
     53 #define SZ_PACKET 12
     54 
     55 #define FP_SIZE   6
     56 
     57 #define NSTEPS    1000
     58 #define STEP(i,n) (NSTEPS * (i) / (n))
     59 
     60 typedef struct cressi_goa_device_t {
     61 	dc_device_t base;
     62 	dc_iostream_t *iostream;
     63 	unsigned char fingerprint[FP_SIZE];
     64 } cressi_goa_device_t;
     65 
     66 typedef struct cressi_goa_conf_t {
     67 	unsigned int logbook_cmd;
     68 	unsigned int logbook_len;
     69 	unsigned int logbook_fp_offset;
     70 	unsigned int dive_fp_offset;
     71 } cressi_goa_conf_t;
     72 
     73 static dc_status_t cressi_goa_device_set_fingerprint (dc_device_t *abstract, const unsigned char data[], unsigned int size);
     74 static dc_status_t cressi_goa_device_foreach (dc_device_t *abstract, dc_dive_callback_t callback, void *userdata);
     75 static dc_status_t cressi_goa_device_timesync (dc_device_t *abstract, const dc_datetime_t *datetime);
     76 static dc_status_t cressi_goa_device_close (dc_device_t *abstract);
     77 
     78 static const dc_device_vtable_t cressi_goa_device_vtable = {
     79 	sizeof(cressi_goa_device_t),
     80 	DC_FAMILY_CRESSI_GOA,
     81 	cressi_goa_device_set_fingerprint, /* set_fingerprint */
     82 	NULL, /* read */
     83 	NULL, /* write */
     84 	NULL, /* dump */
     85 	cressi_goa_device_foreach, /* foreach */
     86 	cressi_goa_device_timesync, /* timesync */
     87 	cressi_goa_device_close /* close */
     88 };
     89 
     90 static const cressi_goa_conf_t version_conf[] = {
     91 	{ CMD_LOGBOOK,    23, 17, 12 },
     92 	{ CMD_LOGBOOK_V4, 15,  3,  4 },
     93 };
     94 
     95 static dc_status_t
     96 cressi_goa_device_send (cressi_goa_device_t *device, unsigned char cmd, const unsigned char data[], unsigned int size)
     97 {
     98 	dc_status_t status = DC_STATUS_SUCCESS;
     99 	dc_device_t *abstract = (dc_device_t *) device;
    100 	dc_transport_t transport = dc_iostream_get_transport (device->iostream);
    101 
    102 	if (size > SZ_PACKET) {
    103 		ERROR (abstract->context, "Unexpected payload size (%u).", size);
    104 		return DC_STATUS_INVALIDARGS;
    105 	}
    106 
    107 	// Setup the data packet.
    108 	unsigned short crc = 0;
    109 	unsigned char packet[SZ_PACKET + 8] = {
    110 		HEADER, HEADER, HEADER,
    111 		size,
    112 		cmd
    113 	};
    114 	if (size) {
    115 		memcpy (packet + 5, data, size);
    116 	}
    117 	crc = checksum_crc16_ccitt (packet + 3, size + 2, 0x000, 0x0000);
    118 	packet[5 + size + 0] = (crc     ) & 0xFF; // Low
    119 	packet[5 + size + 1] = (crc >> 8) & 0xFF; // High
    120 	packet[5 + size + 2] = TRAILER;
    121 
    122 	// Wait a small amount of time before sending the command. Without
    123 	// this delay, the transfer will fail most of the time.
    124 	unsigned int delay = transport == DC_TRANSPORT_BLE ? 2000 : 100;
    125 	dc_iostream_sleep (device->iostream, delay);
    126 
    127 	// Send the command to the device.
    128 	if (transport == DC_TRANSPORT_BLE) {
    129 		status = dc_iostream_write (device->iostream, packet + 4, size + 1, NULL);
    130 	} else {
    131 		status = dc_iostream_write (device->iostream, packet, size + 8, NULL);
    132 	}
    133 	if (status != DC_STATUS_SUCCESS) {
    134 		ERROR (abstract->context, "Failed to send the command.");
    135 		return status;
    136 	}
    137 
    138 	return status;
    139 }
    140 
    141 static dc_status_t
    142 cressi_goa_device_receive (cressi_goa_device_t *device, dc_buffer_t *output)
    143 {
    144 	dc_status_t status = DC_STATUS_SUCCESS;
    145 	dc_device_t *abstract = (dc_device_t *) device;
    146 	dc_transport_t transport = dc_iostream_get_transport (device->iostream);
    147 
    148 	unsigned char packet[SZ_PACKET + 8];
    149 
    150 	if (transport == DC_TRANSPORT_BLE) {
    151 		if (output) {
    152 			return DC_STATUS_INVALIDARGS;
    153 		} else {
    154 			return DC_STATUS_SUCCESS;
    155 		}
    156 	}
    157 
    158 	// Clear the output buffer.
    159 	dc_buffer_clear (output);
    160 
    161 	// Read the header of the data packet.
    162 	status = dc_iostream_read (device->iostream, packet, 4, NULL);
    163 	if (status != DC_STATUS_SUCCESS) {
    164 		ERROR (abstract->context, "Failed to receive the answer.");
    165 		return status;
    166 	}
    167 
    168 	// Verify the header of the packet.
    169 	if (packet[0] != HEADER || packet[1] != HEADER || packet[2] != HEADER) {
    170 		ERROR (abstract->context, "Unexpected answer header byte.");
    171 		return DC_STATUS_PROTOCOL;
    172 	}
    173 
    174 	// Get the payload length.
    175 	unsigned int length = packet[3];
    176 	if (length > SZ_PACKET) {
    177 		ERROR (abstract->context, "Unexpected payload size (%u).", length);
    178 		return DC_STATUS_PROTOCOL;
    179 	}
    180 
    181 	// Read the remainder of the data packet.
    182 	status = dc_iostream_read (device->iostream, packet + 4, length + 4, NULL);
    183 	if (status != DC_STATUS_SUCCESS) {
    184 		ERROR (abstract->context, "Failed to receive the answer.");
    185 		return status;
    186 	}
    187 
    188 	// Verify the trailer of the packet.
    189 	if (packet[length + 7] != TRAILER) {
    190 		ERROR (abstract->context, "Unexpected answer trailer byte.");
    191 		return DC_STATUS_PROTOCOL;
    192 	}
    193 
    194 	// Verify the checksum of the packet.
    195 	unsigned short crc = array_uint16_le (packet + length + 5);
    196 	unsigned short ccrc = checksum_crc16_ccitt (packet + 3, length + 2, 0x0000, 0x0000);
    197 	if (crc != ccrc) {
    198 		ERROR (abstract->context, "Unexpected answer checksum.");
    199 		return DC_STATUS_PROTOCOL;
    200 	}
    201 
    202 	if (length && output) {
    203 		if (!dc_buffer_append (output, packet + 5, length)) {
    204 			ERROR (abstract->context, "Could not append received data.");
    205 			return DC_STATUS_NOMEMORY;
    206 		}
    207 	}
    208 
    209 	return status;
    210 }
    211 
    212 static dc_status_t
    213 cressi_goa_device_download (cressi_goa_device_t *device, dc_buffer_t *buffer, dc_event_progress_t *progress)
    214 {
    215 	dc_status_t status = DC_STATUS_SUCCESS;
    216 	dc_device_t *abstract = (dc_device_t *) device;
    217 	dc_transport_t transport = dc_iostream_get_transport (device->iostream);
    218 
    219 	const unsigned char ack[] = {ACK};
    220 	const unsigned int initial = progress ? progress->current : 0;
    221 
    222 	// Erase the contents of the buffer.
    223 	if (!dc_buffer_clear (buffer)) {
    224 		ERROR (abstract->context, "Insufficient buffer space available.");
    225 		return DC_STATUS_NOMEMORY;
    226 	}
    227 
    228 	unsigned int skip = 2;
    229 	unsigned int size = 2;
    230 	unsigned int nbytes = 0;
    231 	while (nbytes < size) {
    232 		unsigned char packet[3 + SZ_DATA + 2];
    233 
    234 		if (transport == DC_TRANSPORT_BLE) {
    235 			// Read the data packet.
    236 			unsigned int packetsize = 0;
    237 			while (packetsize < SZ_DATA) {
    238 				size_t len = 0;
    239 				status = dc_iostream_read (device->iostream, packet + 3 + packetsize, SZ_DATA - packetsize, &len);
    240 				if (status != DC_STATUS_SUCCESS) {
    241 					ERROR (abstract->context, "Failed to receive the answer.");
    242 					return status;
    243 				}
    244 
    245 				packetsize += len;
    246 			}
    247 		} else {
    248 			// Read the data packet.
    249 			status = dc_iostream_read (device->iostream, packet, sizeof(packet), NULL);
    250 			if (status != DC_STATUS_SUCCESS) {
    251 				ERROR (abstract->context, "Failed to receive the answer.");
    252 				return status;
    253 			}
    254 
    255 			// Verify the checksum of the packet.
    256 			unsigned short crc = array_uint16_le (packet + sizeof(packet) - 2);
    257 			unsigned short ccrc = checksum_crc16_ccitt (packet + 3, sizeof(packet) - 5, 0x0000, 0x0000);
    258 			if (crc != ccrc) {
    259 				ERROR (abstract->context, "Unexpected answer checksum.");
    260 				return DC_STATUS_PROTOCOL;
    261 			}
    262 
    263 			// Send the ack byte to the device.
    264 			status = dc_iostream_write (device->iostream, ack, sizeof(ack), NULL);
    265 			if (status != DC_STATUS_SUCCESS) {
    266 				ERROR (abstract->context, "Failed to send the ack byte.");
    267 				return status;
    268 			}
    269 		}
    270 
    271 		// Get the total size from the first data packet.
    272 		if (nbytes == 0) {
    273 			size += array_uint16_le (packet + 3);
    274 		}
    275 
    276 		// Calculate the payload size of the packet.
    277 		unsigned int length = size - nbytes;
    278 		if (length > SZ_DATA) {
    279 			length = SZ_DATA;
    280 		}
    281 
    282 		// Append the payload to the output buffer.
    283 		if (!dc_buffer_append (buffer, packet + 3 + skip, length - skip)) {
    284 			ERROR (abstract->context, "Insufficient buffer space available.");
    285 			return DC_STATUS_NOMEMORY;
    286 		}
    287 
    288 		nbytes += length;
    289 		skip = 0;
    290 
    291 		// Update and emit a progress event.
    292 		if (progress) {
    293 			progress->current = initial + STEP(nbytes, size);
    294 			device_event_emit (abstract, DC_EVENT_PROGRESS, progress);
    295 		}
    296 	}
    297 
    298 	if (transport == DC_TRANSPORT_BLE) {
    299 		// Read the end bytes.
    300 		unsigned char end[16] = {0};
    301 		size_t len = 0;
    302 		status = dc_iostream_read (device->iostream, end, sizeof(end), &len);
    303 		if (status != DC_STATUS_SUCCESS) {
    304 			ERROR (abstract->context, "Failed to receive the end bytes.");
    305 			return status;
    306 		}
    307 
    308 		// Verify the end bytes ("EOT xmodem").
    309 		const unsigned char validate[16] = {
    310 			0x45, 0x4F, 0x54, 0x20, 0x78, 0x6D, 0x6F, 0x64,
    311 			0x65, 0x6D, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
    312 		if (memcmp (end, validate, sizeof(validate)) != 0) {
    313 			ERROR (abstract->context, "Unexpected end bytes.");
    314 			return DC_STATUS_PROTOCOL;
    315 		}
    316 	} else {
    317 		// Read the end byte.
    318 		unsigned char end = 0;
    319 		status = dc_iostream_read (device->iostream, &end, 1, NULL);
    320 		if (status != DC_STATUS_SUCCESS) {
    321 			ERROR (abstract->context, "Failed to receive the end byte.");
    322 			return status;
    323 		}
    324 
    325 		// Verify the end byte.
    326 		if (end != END) {
    327 			ERROR (abstract->context, "Unexpected end byte (%02x).", end);
    328 			return DC_STATUS_PROTOCOL;
    329 		}
    330 
    331 		// Send the ack byte to the device.
    332 		status = dc_iostream_write (device->iostream, ack, sizeof(ack), NULL);
    333 		if (status != DC_STATUS_SUCCESS) {
    334 			ERROR (abstract->context, "Failed to send the ack byte.");
    335 			return status;
    336 		}
    337 	}
    338 
    339 	return status;
    340 }
    341 
    342 static dc_status_t
    343 cressi_goa_device_transfer (cressi_goa_device_t *device,
    344                             unsigned char cmd,
    345                             const unsigned char input[], unsigned int isize,
    346                             dc_buffer_t *output,
    347                             dc_buffer_t *buffer,
    348                             dc_event_progress_t *progress)
    349 {
    350 	dc_status_t status = DC_STATUS_SUCCESS;
    351 
    352 	// Send the command to the dive computer.
    353 	status = cressi_goa_device_send (device, cmd, input, isize);
    354 	if (status != DC_STATUS_SUCCESS) {
    355 		return status;
    356 	}
    357 
    358 	// Receive the answer from the dive computer.
    359 	status = cressi_goa_device_receive (device, output);
    360 	if (status != DC_STATUS_SUCCESS) {
    361 		return status;
    362 	}
    363 
    364 	// Download the optional and variable sized payload.
    365 	if (buffer) {
    366 		status = cressi_goa_device_download (device, buffer, progress);
    367 		if (status != DC_STATUS_SUCCESS) {
    368 			return status;
    369 		}
    370 	}
    371 
    372 	return status;
    373 }
    374 
    375 
    376 dc_status_t
    377 cressi_goa_device_open (dc_device_t **out, dc_context_t *context, dc_iostream_t *iostream)
    378 {
    379 	dc_status_t status = DC_STATUS_SUCCESS;
    380 	cressi_goa_device_t *device = NULL;
    381 
    382 	if (out == NULL)
    383 		return DC_STATUS_INVALIDARGS;
    384 
    385 	// Allocate memory.
    386 	device = (cressi_goa_device_t *) dc_device_allocate (context, &cressi_goa_device_vtable);
    387 	if (device == NULL) {
    388 		ERROR (context, "Failed to allocate memory.");
    389 		return DC_STATUS_NOMEMORY;
    390 	}
    391 
    392 	// Set the default values.
    393 	device->iostream = iostream;
    394 	memset (device->fingerprint, 0, sizeof (device->fingerprint));
    395 
    396 	// Set the serial communication protocol (115200 8N1).
    397 	status = dc_iostream_configure (device->iostream, 115200, 8, DC_PARITY_NONE, DC_STOPBITS_ONE, DC_FLOWCONTROL_NONE);
    398 	if (status != DC_STATUS_SUCCESS) {
    399 		ERROR (context, "Failed to set the terminal attributes.");
    400 		goto error_free;
    401 	}
    402 
    403 	// Set the timeout for receiving data (3000 - 5000 ms).
    404 	dc_transport_t transport = dc_iostream_get_transport (device->iostream);
    405 	int timeout = transport == DC_TRANSPORT_BLE ? 5000 : 3000;
    406 	status = dc_iostream_set_timeout (device->iostream, timeout);
    407 	if (status != DC_STATUS_SUCCESS) {
    408 		ERROR (context, "Failed to set the timeout.");
    409 		goto error_free;
    410 	}
    411 
    412 	// Clear the RTS line.
    413 	status = dc_iostream_set_rts (device->iostream, 0);
    414 	if (status != DC_STATUS_SUCCESS) {
    415 		ERROR (context, "Failed to clear the RTS line.");
    416 		goto error_free;
    417 	}
    418 
    419 	// Clear the DTR line.
    420 	status = dc_iostream_set_dtr (device->iostream, 0);
    421 	if (status != DC_STATUS_SUCCESS) {
    422 		ERROR (context, "Failed to clear the DTR line.");
    423 		goto error_free;
    424 	}
    425 
    426 	dc_iostream_sleep (device->iostream, 100);
    427 	dc_iostream_purge (device->iostream, DC_DIRECTION_ALL);
    428 
    429 	*out = (dc_device_t *) device;
    430 
    431 	return DC_STATUS_SUCCESS;
    432 
    433 error_free:
    434 	dc_device_deallocate ((dc_device_t *) device);
    435 	return status;
    436 }
    437 
    438 static dc_status_t
    439 cressi_goa_device_set_fingerprint (dc_device_t *abstract, const unsigned char data[], unsigned int size)
    440 {
    441 	cressi_goa_device_t *device = (cressi_goa_device_t *) abstract;
    442 
    443 	if (size && size != sizeof (device->fingerprint))
    444 		return DC_STATUS_INVALIDARGS;
    445 
    446 	if (size)
    447 		memcpy (device->fingerprint, data, sizeof (device->fingerprint));
    448 	else
    449 		memset (device->fingerprint, 0, sizeof (device->fingerprint));
    450 
    451 	return DC_STATUS_SUCCESS;
    452 }
    453 
    454 static dc_status_t
    455 cressi_goa_device_foreach (dc_device_t *abstract, dc_dive_callback_t callback, void *userdata)
    456 {
    457 	dc_status_t status = DC_STATUS_SUCCESS;
    458 	cressi_goa_device_t *device = (cressi_goa_device_t *) abstract;
    459 	dc_transport_t transport = dc_iostream_get_transport (device->iostream);
    460 	dc_buffer_t *logbook = NULL;
    461 	dc_buffer_t *dive = NULL;
    462 
    463 	// Enable progress notifications.
    464 	dc_event_progress_t progress = EVENT_PROGRESS_INITIALIZER;
    465 	device_event_emit (abstract, DC_EVENT_PROGRESS, &progress);
    466 
    467 	dc_buffer_t *id = dc_buffer_new(11);
    468 	if (id == NULL) {
    469 		ERROR (abstract->context, "Failed to allocate memory for the ID.");
    470 		status = DC_STATUS_NOMEMORY;
    471 		goto error_exit;
    472 	}
    473 
    474 	// Read the version information.
    475 	if (transport == DC_TRANSPORT_BLE) {
    476 		/*
    477 		 * With the BLE communication, there is no variant of the CMD_VERSION
    478 		 * command available. The corresponding information must be obtained by
    479 		 * reading some secondary characteristics instead:
    480 		 *     6E400003-B5A3-F393-E0A9-E50E24DC10B8 - 5 bytes
    481 		 *     6E400004-B5A3-F393-E0A9-E50E24DC10B8 - 2 bytes
    482 		 *     6E400005-B5A3-F393-E0A9-E50E24DC10B8 - 2 bytes
    483 		 */
    484 		const dc_ble_uuid_t characteristics[] = {
    485 			{0x6E, 0x40, 0x00, 0x03, 0xB5, 0xA3, 0xF3, 0x93, 0xE0, 0xA9, 0xE5, 0x0E, 0x24, 0xDC, 0x10, 0xB8},
    486 			{0x6E, 0x40, 0x00, 0x04, 0xB5, 0xA3, 0xF3, 0x93, 0xE0, 0xA9, 0xE5, 0x0E, 0x24, 0xDC, 0x10, 0xB8},
    487 			{0x6E, 0x40, 0x00, 0x05, 0xB5, 0xA3, 0xF3, 0x93, 0xE0, 0xA9, 0xE5, 0x0E, 0x24, 0xDC, 0x10, 0xB8},
    488 		};
    489 		const size_t sizes[] = {5, 2, 2};
    490 
    491 		for (size_t i = 0; i < C_ARRAY_SIZE(characteristics); ++i) {
    492 			unsigned char request[sizeof(dc_ble_uuid_t) + 5] = {0};
    493 
    494 			// Setup the request.
    495 			memcpy (request, characteristics[i], sizeof(dc_ble_uuid_t));
    496 			memset (request + sizeof(dc_ble_uuid_t), 0, sizes[i]);
    497 
    498 			// Read the characteristic.
    499 			status = dc_iostream_ioctl (device->iostream, DC_IOCTL_BLE_CHARACTERISTIC_READ, request, sizeof(dc_ble_uuid_t) + sizes[i]);
    500 			if (status != DC_STATUS_SUCCESS) {
    501 				char uuidstr[DC_BLE_UUID_SIZE] = {0};
    502 				ERROR (abstract->context, "Failed to read the characteristic '%s'.",
    503 					dc_ble_uuid2str(characteristics[i], uuidstr, sizeof(uuidstr)));
    504 				goto error_free_id;
    505 			}
    506 
    507 			// Copy the payload data.
    508 			if (!dc_buffer_append(id, request + sizeof(dc_ble_uuid_t), sizes[i])) {
    509 				ERROR (abstract->context, "Insufficient buffer space available.");
    510 				status = DC_STATUS_NOMEMORY;
    511 				goto error_free_id;
    512 			}
    513 		}
    514 	} else {
    515 		status = cressi_goa_device_transfer (device, CMD_VERSION, NULL, 0, id, NULL, NULL);
    516 		if (status != DC_STATUS_SUCCESS) {
    517 			ERROR (abstract->context, "Failed to read the version information.");
    518 			goto error_free_id;
    519 		}
    520 	}
    521 
    522 	const unsigned char *id_data = dc_buffer_get_data(id);
    523 	size_t id_size = dc_buffer_get_size(id);
    524 
    525 	HEXDUMP (abstract->context, DC_LOGLEVEL_DEBUG, "Version", id_data, id_size);
    526 
    527 	if (id_size < 9) {
    528 		ERROR (abstract->context, "Unexpected version length (" DC_PRINTF_SIZE ").", id_size);
    529 		status = DC_STATUS_DATAFORMAT;
    530 		goto error_free_id;
    531 	}
    532 
    533 	// Get the device info.
    534 	unsigned int model = id_data[4];
    535 	unsigned int firmware = array_uint16_le (id_data + 5);
    536 	unsigned int serial = array_uint32_le (id_data + 0);
    537 
    538 	// Get the data format version.
    539 	unsigned int version = 0;
    540 	if (id_size == 11) {
    541 		version = array_uint16_le (id_data + 9);
    542 	} else {
    543 		if (firmware >= 161 && firmware <= 165) {
    544 			version = 0;
    545 		} else if (firmware >= 166 && firmware <= 169) {
    546 			version = 1;
    547 		} else if (firmware >= 170 && firmware <= 179) {
    548 			version = 2;
    549 		} else if (firmware >= 100 && firmware <= 110) {
    550 			version = 3;
    551 		} else if (firmware >= 200 && firmware <= 299) {
    552 			version = 4;
    553 		} else if (firmware >= 300) {
    554 			version = 5;
    555 		} else {
    556 			ERROR (abstract->context, "Unknown firmware version (%u).", firmware);
    557 			status = DC_STATUS_DATAFORMAT;
    558 			goto error_free_id;
    559 		}
    560 	}
    561 
    562 	const cressi_goa_conf_t *conf = &version_conf[version >= 4];
    563 
    564 	// Emit a vendor event.
    565 	dc_event_vendor_t vendor;
    566 	vendor.data = id_data;
    567 	vendor.size = id_size;
    568 	device_event_emit (abstract, DC_EVENT_VENDOR, &vendor);
    569 
    570 	// Emit a device info event.
    571 	dc_event_devinfo_t devinfo;
    572 	devinfo.model = model;
    573 	devinfo.firmware = firmware;
    574 	devinfo.serial = serial;
    575 	device_event_emit (abstract, DC_EVENT_DEVINFO, &devinfo);
    576 
    577 	// Allocate memory for the logbook data.
    578 	logbook = dc_buffer_new(4096);
    579 	if (logbook == NULL) {
    580 		ERROR (abstract->context, "Failed to allocate memory for the logbook.");
    581 		status = DC_STATUS_NOMEMORY;
    582 		goto error_free_id;
    583 	}
    584 
    585 	// Read the logbook data.
    586 	if (transport == DC_TRANSPORT_BLE) {
    587 		unsigned char args[] = {0x00};
    588 		status = cressi_goa_device_transfer (device, CMD_LOGBOOK_BLE, args, sizeof(args), NULL, logbook, &progress);
    589 	} else {
    590 		status = cressi_goa_device_transfer (device, conf->logbook_cmd, NULL, 0, NULL, logbook, &progress);
    591 	}
    592 	if (status != DC_STATUS_SUCCESS) {
    593 		ERROR (abstract->context, "Failed to read the logbook data.");
    594 		goto error_free_logbook;
    595 	}
    596 
    597 	const unsigned char *logbook_data = dc_buffer_get_data(logbook);
    598 	size_t logbook_size = dc_buffer_get_size(logbook);
    599 
    600 	// Count the number of dives.
    601 	unsigned int count = 0;
    602 	unsigned int offset = logbook_size;
    603 	while (offset >= conf->logbook_len) {
    604 		// Move to the start of the logbook entry.
    605 		offset -= conf->logbook_len;
    606 
    607 		// Get the dive number.
    608 		unsigned int number= array_uint16_le (logbook_data + offset);
    609 		if (number == 0)
    610 			break;
    611 
    612 		// Compare the fingerprint to identify previously downloaded entries.
    613 		if (memcmp (logbook_data + offset + conf->logbook_fp_offset, device->fingerprint, sizeof(device->fingerprint)) == 0) {
    614 			break;
    615 		}
    616 
    617 		count++;
    618 	}
    619 
    620 	// Update and emit a progress event.
    621 	progress.maximum = (count + 1) * NSTEPS;
    622 	device_event_emit (abstract, DC_EVENT_PROGRESS, &progress);
    623 
    624 	// Allocate memory for the dive data.
    625 	dive = dc_buffer_new(4096);
    626 	if (dive == NULL) {
    627 		ERROR (abstract->context, "Failed to allocate memory for the dive.");
    628 		status = DC_STATUS_NOMEMORY;
    629 		goto error_free_logbook;
    630 	}
    631 
    632 	// Download the dives.
    633 	offset = logbook_size;
    634 	for (unsigned int i = 0; i < count; ++i) {
    635 		// Move to the start of the logbook entry.
    636 		offset -= conf->logbook_len;
    637 
    638 		// Read the dive data.
    639 		if (transport == DC_TRANSPORT_BLE) {
    640 			unsigned char number[2] = {
    641 				logbook_data[offset + 1],
    642 				logbook_data[offset + 0]};
    643 			status = cressi_goa_device_transfer (device, CMD_DIVE_BLE, number, 2, NULL, dive, &progress);
    644 		} else {
    645 			status = cressi_goa_device_transfer (device, CMD_DIVE, logbook_data + offset, 2, NULL, dive, &progress);
    646 		}
    647 		if (status != DC_STATUS_SUCCESS) {
    648 			ERROR (abstract->context, "Failed to read the dive data.");
    649 			goto error_free_dive;
    650 		}
    651 
    652 		const unsigned char *dive_data = dc_buffer_get_data (dive);
    653 		size_t dive_size = dc_buffer_get_size (dive);
    654 
    655 		// Verify the dive number and the fingerprint in the logbook and dive
    656 		// data are identical.
    657 		if (dive_size < conf->dive_fp_offset + FP_SIZE ||
    658 			memcmp (dive_data, logbook_data + offset, 2) != 0 ||
    659 			memcmp (dive_data + conf->dive_fp_offset, logbook_data + offset + conf->logbook_fp_offset, FP_SIZE) != 0) {
    660 			ERROR (abstract->context, "Unexpected dive header.");
    661 			status = DC_STATUS_DATAFORMAT;
    662 			goto error_free_dive;
    663 		}
    664 
    665 		// The dive computer id data and the logbook entry contain important
    666 		// information that is required for parsing the dive data, but is
    667 		// not present in the dive data itself. Therefore, both pieces of data
    668 		// are prepended to the dive data, along with a small header containing
    669 		// their size.
    670 		const unsigned char header[] = {
    671 			id_size,
    672 			conf->logbook_len,
    673 		};
    674 		unsigned int headersize = sizeof(header) + id_size + conf->logbook_len;
    675 		if (!dc_buffer_prepend(dive, logbook_data + offset, conf->logbook_len) ||
    676 			!dc_buffer_prepend(dive, id_data, id_size) ||
    677 			!dc_buffer_prepend(dive, header, sizeof(header))) {
    678 			ERROR (abstract->context, "Out of memory.");
    679 			status = DC_STATUS_NOMEMORY;
    680 			goto error_free_dive;
    681 		}
    682 
    683 		dive_data = dc_buffer_get_data (dive);
    684 		dive_size = dc_buffer_get_size (dive);
    685 
    686 		if (callback && !callback(dive_data, dive_size, dive_data + headersize + conf->dive_fp_offset, sizeof(device->fingerprint), userdata))
    687 			break;
    688 	}
    689 
    690 error_free_dive:
    691 	dc_buffer_free(dive);
    692 error_free_logbook:
    693 	dc_buffer_free(logbook);
    694 error_free_id:
    695 	dc_buffer_free(id);
    696 error_exit:
    697 	return status;
    698 }
    699 
    700 static dc_status_t
    701 cressi_goa_device_timesync (dc_device_t *abstract, const dc_datetime_t *datetime)
    702 {
    703 	dc_status_t status = DC_STATUS_SUCCESS;
    704 	cressi_goa_device_t *device = (cressi_goa_device_t *) abstract;
    705 	dc_transport_t transport = dc_iostream_get_transport (device->iostream);
    706 
    707 	if (transport == DC_TRANSPORT_BLE) {
    708 		return DC_STATUS_UNSUPPORTED;
    709 	}
    710 
    711 	unsigned char new_time[7];
    712 	array_uint16_le_set(new_time, datetime->year);
    713 	new_time[2] = datetime->month;
    714 	new_time[3] = datetime->day;
    715 	new_time[4] = datetime->hour;
    716 	new_time[5] = datetime->minute;
    717 	new_time[6] = datetime->second;
    718 	status = cressi_goa_device_transfer (device, CMD_SET_TIME, new_time, sizeof(new_time), NULL, NULL, NULL);
    719 	if (status != DC_STATUS_SUCCESS) {
    720 		ERROR (abstract->context, "Failed to set the new time.");
    721 		return status;
    722 	}
    723 
    724 	return status;
    725 }
    726 
    727 static dc_status_t
    728 cressi_goa_device_close (dc_device_t *abstract)
    729 {
    730 	dc_status_t status = DC_STATUS_SUCCESS;
    731 	cressi_goa_device_t *device = (cressi_goa_device_t *) abstract;
    732 	dc_transport_t transport = dc_iostream_get_transport (device->iostream);
    733 
    734 	if (transport == DC_TRANSPORT_BLE) {
    735 		return DC_STATUS_SUCCESS;
    736 	}
    737 
    738 	status = cressi_goa_device_transfer (device, CMD_EXIT_PCLINK, NULL, 0, NULL, NULL, NULL);
    739 	if (status != DC_STATUS_SUCCESS) {
    740 		ERROR (abstract->context, "Failed to exit PC Link.");
    741 		return status;
    742 	}
    743 
    744 	return status;
    745 }