subrascasse

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

mares_iconhd.c (37352B)


      1 /*
      2  * libdivecomputer
      3  *
      4  * Copyright (C) 2010 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 
     25 #include "mares_iconhd.h"
     26 #include "context-private.h"
     27 #include "device-private.h"
     28 #include "array.h"
     29 #include "rbstream.h"
     30 #include "platform.h"
     31 #include "packet.h"
     32 #include "mares_iconhd_freedive.h"
     33 
     34 #define ISINSTANCE(device) dc_device_isinstance((device), &mares_iconhd_device_vtable)
     35 
     36 #define NSTEPS    1000
     37 #define STEP(i,n) (NSTEPS * (i) / (n))
     38 
     39 #define MATRIX    0x0F
     40 #define SMART      0x000010
     41 #define SMARTAPNEA 0x010010
     42 #define ICONHD    0x14
     43 #define ICONHDNET 0x15
     44 #define PUCKPRO   0x18
     45 #define NEMOWIDE2 0x19
     46 #define GENIUS    0x1C
     47 #define PUCK2     0x1F
     48 #define QUADAIR   0x23
     49 #define SMARTAIR  0x24
     50 #define QUAD      0x29
     51 #define HORIZON   0x2C
     52 #define PUCKAIR2  0x2D
     53 #define QUADCI    0x31
     54 #define QUAD2     0x32
     55 #define SIRIUS_L  0x33
     56 #define PUCK4     0x35
     57 
     58 #define ISSMART(model) ( \
     59 	(model) == SMART || \
     60 	(model) == SMARTAPNEA || \
     61 	(model) == SMARTAIR)
     62 
     63 #define ISGENIUS(model) ( \
     64 	(model) == GENIUS || \
     65 	(model) == HORIZON || \
     66 	(model) == PUCKAIR2 || \
     67 	(model) == SIRIUS || \
     68 	(model) == QUADCI || \
     69 	(model) == QUAD2 || \
     70 	(model) == SIRIUS_L || \
     71 	(model) == PUCK4)
     72 
     73 #define ISSIRIUS(model) ( \
     74 	(model) == PUCKAIR2 || \
     75 	(model) == SIRIUS || \
     76 	(model) == QUADCI || \
     77 	(model) == QUAD2 || \
     78 	(model) == SIRIUS_L || \
     79 	(model) == PUCK4)
     80 
     81 #define MAXRETRIES 4
     82 
     83 #define MAXPACKET 244
     84 
     85 #define FIXED    0
     86 #define VARIABLE 1
     87 
     88 #define ACK 0xAA
     89 #define END 0xEA
     90 #define XOR 0xA5
     91 
     92 #define CMD_VERSION   0xC2
     93 #define CMD_FLASHSIZE 0xB3
     94 #define CMD_READ      0xE7
     95 #define CMD_OBJ_INIT  0xBF
     96 #define CMD_OBJ_EVEN  0xAC
     97 #define CMD_OBJ_ODD   0xFE
     98 #define CMD_SET_TIME  0xB0
     99 
    100 #define OBJ_DEVICE        0x2000
    101 #define OBJ_DEVICE_MODEL  0x02
    102 #define OBJ_DEVICE_SERIAL 0x04
    103 #define OBJ_LOGBOOK       0x2008
    104 #define OBJ_LOGBOOK_COUNT 0x01
    105 #define OBJ_DIVE_HEADER   0x02
    106 
    107 #define AIR       0
    108 #define GAUGE     1
    109 #define NITROX    2
    110 #define FREEDIVE  3
    111 
    112 typedef struct mares_iconhd_layout_t {
    113 	unsigned int memsize;
    114 	unsigned int rb_profile_begin;
    115 	unsigned int rb_profile_end;
    116 } mares_iconhd_layout_t;
    117 
    118 typedef struct mares_iconhd_model_t {
    119 	unsigned char name[16 + 1];
    120 	unsigned int id;
    121 } mares_iconhd_model_t;
    122 
    123 typedef struct mares_iconhd_device_t {
    124 	dc_device_t base;
    125 	dc_iostream_t *iostream;
    126 	const mares_iconhd_layout_t *layout;
    127 	unsigned char fingerprint[10];
    128 	unsigned int fingerprint_size;
    129 	unsigned char version[140];
    130 	unsigned int model;
    131 	unsigned int packetsize;
    132 	unsigned int ble;
    133 } mares_iconhd_device_t;
    134 
    135 static dc_status_t mares_iconhd_device_set_fingerprint (dc_device_t *abstract, const unsigned char data[], unsigned int size);
    136 static dc_status_t mares_iconhd_device_read (dc_device_t *abstract, unsigned int address, unsigned char data[], unsigned int size);
    137 static dc_status_t mares_iconhd_device_dump (dc_device_t *abstract, dc_buffer_t *buffer);
    138 static dc_status_t mares_iconhd_device_foreach (dc_device_t *abstract, dc_dive_callback_t callback, void *userdata);
    139 static dc_status_t mares_iconhd_device_timesync (dc_device_t *abstract, const dc_datetime_t *datetime);
    140 static dc_status_t mares_iconhd_device_close (dc_device_t *abstract);
    141 
    142 static const dc_device_vtable_t mares_iconhd_device_vtable = {
    143 	sizeof(mares_iconhd_device_t),
    144 	DC_FAMILY_MARES_ICONHD,
    145 	mares_iconhd_device_set_fingerprint, /* set_fingerprint */
    146 	mares_iconhd_device_read, /* read */
    147 	NULL, /* write */
    148 	mares_iconhd_device_dump, /* dump */
    149 	mares_iconhd_device_foreach, /* foreach */
    150 	mares_iconhd_device_timesync, /* timesync */
    151 	mares_iconhd_device_close /* close */
    152 };
    153 
    154 static const mares_iconhd_layout_t mares_iconhd_layout = {
    155 	0x100000, /* memsize */
    156 	0x00A000, /* rb_profile_begin */
    157 	0x100000, /* rb_profile_end */
    158 };
    159 
    160 static const mares_iconhd_layout_t mares_iconhdnet_layout = {
    161 	0x100000, /* memsize */
    162 	0x00E000, /* rb_profile_begin */
    163 	0x100000, /* rb_profile_end */
    164 };
    165 
    166 static const mares_iconhd_layout_t mares_genius_layout = {
    167 	0x1000000, /* memsize */
    168 	0x0100000, /* rb_profile_begin */
    169 	0x1000000, /* rb_profile_end */
    170 };
    171 
    172 static const mares_iconhd_layout_t mares_matrix_layout = {
    173 	0x40000, /* memsize */
    174 	0x0A000, /* rb_profile_begin */
    175 	0x3E000, /* rb_profile_end */
    176 };
    177 
    178 static const mares_iconhd_layout_t mares_nemowide2_layout = {
    179 	0x40000, /* memsize */
    180 	0x0A000, /* rb_profile_begin */
    181 	0x40000, /* rb_profile_end */
    182 };
    183 
    184 static unsigned int
    185 mares_iconhd_get_model (mares_iconhd_device_t *device)
    186 {
    187 	const mares_iconhd_model_t models[] = {
    188 		{"Matrix",      MATRIX},
    189 		{"Smart",       SMART},
    190 		{"Smart Apnea", SMARTAPNEA},
    191 		{"Icon HD",     ICONHD},
    192 		{"Icon AIR",    ICONHDNET},
    193 		{"Puck Pro U",  PUCK4},
    194 		{"Puck Pro",    PUCKPRO},
    195 		{"Nemo Wide 2", NEMOWIDE2},
    196 		{"Genius",      GENIUS},
    197 		{"Puck 2",      PUCK2},
    198 		{"Quad Air",    QUADAIR},
    199 		{"Smart Air",   SMARTAIR},
    200 		{"Quad",        QUAD},
    201 		{"Horizon",     HORIZON},
    202 		{"Puck Air 2",  PUCKAIR2},
    203 		{"Sirius",      SIRIUS},
    204 		{"Sirius L",    SIRIUS_L},
    205 		{"Quad Ci",     QUADCI},
    206 		{"Quad2",       QUAD2},
    207 		{"Puck4",       PUCK4},
    208 		{"Puck Lite",   PUCK4},
    209 		{"Puck",        PUCK4},
    210 	};
    211 
    212 	// Check the product name in the version packet against the list
    213 	// with valid names, and return the corresponding model number.
    214 	unsigned int model = 0;
    215 	for (unsigned int i = 0; i < C_ARRAY_SIZE(models); ++i) {
    216 		if (memcmp (device->version + 0x46, models[i].name, sizeof (models[i].name) - 1) == 0) {
    217 			model = models[i].id;
    218 			break;
    219 		}
    220 	}
    221 
    222 	return model;
    223 }
    224 
    225 static void
    226 mares_iconhd_fill_product_name (const mares_iconhd_device_t *device, dc_event_devinfo_t *devinfo)
    227 {
    228 	/* Copy at most DC_DEVINFO_PRODUCT_NAME_SIZE-1 bytes from the version packet
    229 	 * product-name field (offset 0x46, up to 16 bytes) and NUL-terminate.
    230 	 * The buffer is already zeroed by the caller initialising devinfo to {0}. */
    231 	const unsigned char *src = device->version + 0x46;
    232 	unsigned int n = sizeof (devinfo->product_name) - 1;
    233 	unsigned int i;
    234 	for (i = 0; i < n; i++) {
    235 		if (src[i] == '\0')
    236 			break;
    237 		devinfo->product_name[i] = (char) src[i];
    238 	}
    239 	devinfo->product_name[i] = '\0';
    240 }
    241 
    242 static dc_status_t
    243 mares_iconhd_packet_fixed (mares_iconhd_device_t *device,
    244 	unsigned char cmd,
    245 	const unsigned char data[], unsigned int size,
    246 	unsigned char answer[], unsigned int asize,
    247 	unsigned int *actual)
    248 {
    249 	dc_status_t status = DC_STATUS_SUCCESS;
    250 	dc_device_t *abstract = (dc_device_t *) device;
    251 	dc_transport_t transport = dc_iostream_get_transport (device->iostream);
    252 
    253 	if (device_is_cancelled (abstract))
    254 		return DC_STATUS_CANCELLED;
    255 
    256 	// Send the command header to the dive computer.
    257 	const unsigned char command[2] = {
    258 		cmd, cmd ^ XOR,
    259 	};
    260 	status = dc_iostream_write (device->iostream, command, sizeof(command), NULL);
    261 	if (status != DC_STATUS_SUCCESS) {
    262 		ERROR (abstract->context, "Failed to send the command header.");
    263 		return status;
    264 	}
    265 
    266 	// Send the command payload to the dive computer.
    267 	if (size && transport == DC_TRANSPORT_BLE) {
    268 		status = dc_iostream_write (device->iostream, data, size, NULL);
    269 		if (status != DC_STATUS_SUCCESS) {
    270 			ERROR (abstract->context, "Failed to send the command data.");
    271 			return status;
    272 		}
    273 	}
    274 
    275 	// Receive the header byte.
    276 	while (1) {
    277 		unsigned char header[1] = {0};
    278 		status = dc_iostream_read (device->iostream, header, sizeof (header), NULL);
    279 		if (status != DC_STATUS_SUCCESS) {
    280 			ERROR (abstract->context, "Failed to receive the packet header.");
    281 			return status;
    282 		}
    283 
    284 		if (header[0] == ACK)
    285 			break;
    286 
    287 		WARNING (abstract->context, "Unexpected packet header byte (%02x).", header[0]);
    288 	}
    289 
    290 	// Send the command payload to the dive computer.
    291 	if (size && transport != DC_TRANSPORT_BLE) {
    292 		status = dc_iostream_write (device->iostream, data, size, NULL);
    293 		if (status != DC_STATUS_SUCCESS) {
    294 			ERROR (abstract->context, "Failed to send the command data.");
    295 			return status;
    296 		}
    297 	}
    298 
    299 	// Read the packet.
    300 	status = dc_iostream_read (device->iostream, answer, asize, NULL);
    301 	if (status != DC_STATUS_SUCCESS) {
    302 		ERROR (abstract->context, "Failed to receive the packet data.");
    303 		return status;
    304 	}
    305 
    306 	// Receive the trailer byte.
    307 	unsigned char trailer[1] = {0};
    308 	status = dc_iostream_read (device->iostream, trailer, sizeof (trailer), NULL);
    309 	if (status != DC_STATUS_SUCCESS) {
    310 		ERROR (abstract->context, "Failed to receive the packet trailer.");
    311 		return status;
    312 	}
    313 
    314 	// Verify the trailer byte.
    315 	if (trailer[0] != END) {
    316 		ERROR (abstract->context, "Unexpected packet trailer byte (%02x).", trailer[0]);
    317 		return DC_STATUS_PROTOCOL;
    318 	}
    319 
    320 	if (actual) {
    321 		*actual = asize;
    322 	}
    323 
    324 	return DC_STATUS_SUCCESS;
    325 }
    326 
    327 static dc_status_t
    328 mares_iconhd_packet_variable (mares_iconhd_device_t *device,
    329 	unsigned char cmd,
    330 	const unsigned char data[], unsigned int size,
    331 	unsigned char answer[], unsigned int asize,
    332 	unsigned int *actual)
    333 {
    334 	dc_status_t status = DC_STATUS_SUCCESS;
    335 	dc_device_t *abstract = (dc_device_t *) device;
    336 	unsigned char packet[MAXPACKET] = {0};
    337 	size_t length = 0;
    338 
    339 	if (device_is_cancelled (abstract))
    340 		return DC_STATUS_CANCELLED;
    341 
    342 	// Send the command header to the dive computer.
    343 	const unsigned char command[2] = {
    344 		cmd, cmd ^ XOR,
    345 	};
    346 	status = dc_iostream_write (device->iostream, command, sizeof(command), NULL);
    347 	if (status != DC_STATUS_SUCCESS) {
    348 		ERROR (abstract->context, "Failed to send the command header.");
    349 		return status;
    350 	}
    351 
    352 	// Read either the entire data packet (if there is no command data to send),
    353 	// or only the header byte (if there is also command data to send).
    354 	status = dc_iostream_read (device->iostream, packet, sizeof (packet), &length);
    355 	if (status != DC_STATUS_SUCCESS) {
    356 		ERROR (abstract->context, "Failed to receive the packet header.");
    357 		return status;
    358 	}
    359 
    360 	if (size) {
    361 		// Send the command payload to the dive computer.
    362 		status = dc_iostream_write (device->iostream, data, size, NULL);
    363 		if (status != DC_STATUS_SUCCESS) {
    364 			ERROR (abstract->context, "Failed to send the command data.");
    365 			return status;
    366 		}
    367 
    368 		// Read the data packet.
    369 		size_t len = 0;
    370 		status = dc_iostream_read (device->iostream, packet + length, sizeof (packet) - length, &len);
    371 		if (status != DC_STATUS_SUCCESS) {
    372 			ERROR (abstract->context, "Failed to receive the packet data.");
    373 			return status;
    374 		}
    375 
    376 		length += len;
    377 	}
    378 
    379 	if (length < 2 || length - 2 > asize) {
    380 		ERROR (abstract->context, "Unexpected packet length (" DC_PRINTF_SIZE ").", length);
    381 		return DC_STATUS_PROTOCOL;
    382 	}
    383 
    384 	// Verify the header byte.
    385 	if (packet[0] != ACK) {
    386 		ERROR (abstract->context, "Unexpected packet header byte (%02x).", packet[0]);
    387 		return DC_STATUS_PROTOCOL;
    388 	}
    389 
    390 	// Verify the trailer byte.
    391 	if (packet[length - 1] != END) {
    392 		ERROR (abstract->context, "Unexpected packet trailer byte (%02x).", packet[length - 1]);
    393 		return DC_STATUS_PROTOCOL;
    394 	}
    395 
    396 	if (actual == NULL) {
    397 		// Verify the actual length.
    398 		if (length - 2 != asize) {
    399 			ERROR (abstract->context, "Unexpected packet length (" DC_PRINTF_SIZE ").", length - 2);
    400 			return DC_STATUS_PROTOCOL;
    401 		}
    402 	} else {
    403 		// Return the actual length.
    404 		*actual = length - 2;
    405 	}
    406 
    407 	memcpy (answer, packet + 1, length - 2);
    408 
    409 	return DC_STATUS_SUCCESS;
    410 }
    411 
    412 static dc_status_t
    413 mares_iconhd_packet (mares_iconhd_device_t *device,
    414 	unsigned char cmd,
    415 	const unsigned char data[], unsigned int size,
    416 	unsigned char answer[], unsigned int asize,
    417 	unsigned int *actual)
    418 {
    419 	dc_transport_t transport = dc_iostream_get_transport (device->iostream);
    420 
    421 	if (transport == DC_TRANSPORT_BLE && device->ble == VARIABLE) {
    422 		return mares_iconhd_packet_variable (device, cmd, data, size, answer, asize, actual);
    423 	} else {
    424 		return mares_iconhd_packet_fixed (device, cmd, data, size, answer, asize, actual);
    425 	}
    426 }
    427 
    428 static dc_status_t
    429 mares_iconhd_transfer (mares_iconhd_device_t *device, unsigned char cmd, const unsigned char data[], unsigned int size, unsigned char answer[], unsigned int asize, unsigned int *actual)
    430 {
    431 	unsigned int nretries = 0;
    432 	dc_status_t rc = DC_STATUS_SUCCESS;
    433 	while ((rc = mares_iconhd_packet (device, cmd, data, size, answer, asize, actual)) != DC_STATUS_SUCCESS) {
    434 		// Automatically discard a corrupted packet,
    435 		// and request a new one.
    436 		if (rc != DC_STATUS_PROTOCOL && rc != DC_STATUS_TIMEOUT)
    437 			return rc;
    438 
    439 		// Abort if the maximum number of retries is reached.
    440 		if (nretries++ >= MAXRETRIES)
    441 			return rc;
    442 
    443 		// Discard any garbage bytes.
    444 		dc_iostream_sleep (device->iostream, 1000);
    445 		dc_iostream_purge (device->iostream, DC_DIRECTION_INPUT);
    446 	}
    447 
    448 	return DC_STATUS_SUCCESS;
    449 }
    450 
    451 static dc_status_t
    452 mares_iconhd_read_object(mares_iconhd_device_t *device, dc_event_progress_t *progress, dc_buffer_t *buffer, unsigned int index, unsigned int subindex)
    453 {
    454 	dc_status_t status = DC_STATUS_SUCCESS;
    455 	dc_device_t *abstract = (dc_device_t *) device;
    456 	dc_transport_t transport = dc_iostream_get_transport (device->iostream);
    457 	const unsigned int maxpacket = (transport == DC_TRANSPORT_BLE) ?
    458 		(device->ble == VARIABLE ? MAXPACKET - 3 : 124) :
    459 		504;
    460 
    461 	// Update and emit a progress event.
    462 	unsigned int initial = 0;
    463 	if (progress) {
    464 		initial = progress->current;
    465 		device_event_emit (abstract, DC_EVENT_PROGRESS, progress);
    466 	}
    467 
    468 	// Transfer the init packet.
    469 	unsigned char rsp_init[16];
    470 	unsigned char cmd_init[16] = {
    471 		0x40,
    472 		(index >> 0) & 0xFF,
    473 		(index >> 8) & 0xFF,
    474 		subindex & 0xFF
    475 	};
    476 	memset (cmd_init + 6, 0x00, sizeof(cmd_init) - 6);
    477 	status = mares_iconhd_transfer (device, CMD_OBJ_INIT, cmd_init, sizeof (cmd_init), rsp_init, sizeof (rsp_init), NULL);
    478 	if (status != DC_STATUS_SUCCESS) {
    479 		ERROR (abstract->context, "Failed to transfer the init packet.");
    480 		return status;
    481 	}
    482 
    483 	// Verify the packet header.
    484 	if (memcmp (cmd_init + 1, rsp_init + 1, 3) != 0) {
    485 		ERROR (abstract->context, "Unexpected packet header.");
    486 		return DC_STATUS_PROTOCOL;
    487 	}
    488 
    489 	unsigned int nbytes = 0, size = 0;
    490 	if (rsp_init[0] == 0x41) {
    491 		// A large (and variable size) payload is split into multiple
    492 		// data packets. The first packet contains only the total size
    493 		// of the payload.
    494 		size = array_uint32_le (rsp_init + 4);
    495 	} else if (rsp_init[0] == 0x42) {
    496 		// A short (and fixed size) payload is embedded into the first
    497 		// data packet.
    498 		size = sizeof(rsp_init) - 4;
    499 
    500 		// Append the payload to the output buffer.
    501 		if (!dc_buffer_append (buffer, rsp_init + 4, sizeof(rsp_init) - 4)) {
    502 			ERROR (abstract->context, "Insufficient buffer space available.");
    503 			return DC_STATUS_NOMEMORY;
    504 		}
    505 
    506 		nbytes += sizeof(rsp_init) - 4;
    507 	} else {
    508 		ERROR (abstract->context, "Unexpected packet type (%02x).", rsp_init[0]);
    509 		return DC_STATUS_PROTOCOL;
    510 	}
    511 
    512 	// Update and emit a progress event.
    513 	if (progress) {
    514 		progress->current = initial + STEP (nbytes, size);
    515 		device_event_emit (abstract, DC_EVENT_PROGRESS, progress);
    516 	}
    517 
    518 	unsigned int npackets = 0;
    519 	while (nbytes < size) {
    520 		// Get the command byte.
    521 		unsigned char toggle = npackets % 2;
    522 		unsigned char cmd = toggle == 0 ? CMD_OBJ_EVEN : CMD_OBJ_ODD;
    523 
    524 		// Get the packet size.
    525 		unsigned int len = size - nbytes;
    526 		if (len > maxpacket) {
    527 			len = maxpacket;
    528 		}
    529 
    530 		// Transfer the segment packet.
    531 		unsigned int length = 0;
    532 		unsigned char rsp_segment[1 + 504];
    533 		status = mares_iconhd_transfer (device, cmd, NULL, 0, rsp_segment, len + 1, &length);
    534 		if (status != DC_STATUS_SUCCESS) {
    535 			ERROR (abstract->context, "Failed to transfer the segment packet.");
    536 			return status;
    537 		}
    538 
    539 		if (length < 1) {
    540 			ERROR (abstract->context, "Unexpected packet length (%u).", length);
    541 			return DC_STATUS_PROTOCOL;
    542 		}
    543 
    544 		// Verify the packet header.
    545 		if ((rsp_segment[0] & 0xF0) >> 4 != toggle) {
    546 			if (npackets == 0 && mares_iconhd_freedive_unavailable (device->model,
    547 					dc_buffer_get_data (buffer), dc_buffer_get_size (buffer), index, subindex, rsp_segment, length))
    548 				return DC_STATUS_UNSUPPORTED;
    549 			ERROR (abstract->context, "Unexpected packet header (%02x).", rsp_segment[0]);
    550 			return DC_STATUS_PROTOCOL;
    551 		}
    552 
    553 		length--;
    554 
    555 		// Append the payload to the output buffer.
    556 		if (!dc_buffer_append (buffer, rsp_segment + 1, length)) {
    557 			ERROR (abstract->context, "Insufficient buffer space available.");
    558 			return DC_STATUS_NOMEMORY;
    559 		}
    560 
    561 		nbytes += length;
    562 		npackets++;
    563 
    564 		// Update and emit the progress events.
    565 		if (progress) {
    566 			progress->current = initial + STEP (nbytes, size);
    567 			device_event_emit (abstract, DC_EVENT_PROGRESS, progress);
    568 		}
    569 	}
    570 
    571 	return status;
    572 }
    573 
    574 dc_status_t
    575 mares_iconhd_device_open (dc_device_t **out, dc_context_t *context, dc_iostream_t *iostream, unsigned int model)
    576 {
    577 	dc_status_t status = DC_STATUS_SUCCESS;
    578 	mares_iconhd_device_t *device = NULL;
    579 	dc_transport_t transport = dc_iostream_get_transport (iostream);
    580 
    581 	if (out == NULL)
    582 		return DC_STATUS_INVALIDARGS;
    583 
    584 	// Allocate memory.
    585 	device = (mares_iconhd_device_t *) dc_device_allocate (context, &mares_iconhd_device_vtable);
    586 	if (device == NULL) {
    587 		ERROR (context, "Failed to allocate memory.");
    588 		return DC_STATUS_NOMEMORY;
    589 	}
    590 
    591 	// Set the default values.
    592 	device->layout = NULL;
    593 	memset (device->fingerprint, 0, sizeof (device->fingerprint));
    594 	device->fingerprint_size = sizeof (device->fingerprint);
    595 	memset (device->version, 0, sizeof (device->version));
    596 	device->model = 0;
    597 	device->packetsize = 0;
    598 	device->ble = ISSIRIUS(model) ? VARIABLE : FIXED;
    599 
    600 	// Create the packet stream.
    601 	if (transport == DC_TRANSPORT_BLE && device->ble == FIXED) {
    602 		status = dc_packet_open (&device->iostream, context, iostream, 244, 20);
    603 		if (status != DC_STATUS_SUCCESS) {
    604 			ERROR (context, "Failed to create the packet stream.");
    605 			goto error_free;
    606 		}
    607 	} else {
    608 		device->iostream = iostream;
    609 	}
    610 
    611 	// Set the serial communication protocol (115200 8E1).
    612 	status = dc_iostream_configure (device->iostream, 115200, 8, DC_PARITY_EVEN, DC_STOPBITS_ONE, DC_FLOWCONTROL_NONE);
    613 	if (status != DC_STATUS_SUCCESS) {
    614 		ERROR (context, "Failed to set the terminal attributes.");
    615 		goto error_free_iostream;
    616 	}
    617 
    618 	// Set the timeout for receiving data (3000 ms).
    619 	status = dc_iostream_set_timeout (device->iostream, 3000);
    620 	if (status != DC_STATUS_SUCCESS) {
    621 		ERROR (context, "Failed to set the timeout.");
    622 		goto error_free_iostream;
    623 	}
    624 
    625 	// Clear the DTR line.
    626 	status = dc_iostream_set_dtr (device->iostream, 0);
    627 	if (status != DC_STATUS_SUCCESS) {
    628 		ERROR (context, "Failed to clear the DTR line.");
    629 		goto error_free_iostream;
    630 	}
    631 
    632 	// Clear the RTS line.
    633 	status = dc_iostream_set_rts (device->iostream, 0);
    634 	if (status != DC_STATUS_SUCCESS) {
    635 		ERROR (context, "Failed to clear the RTS line.");
    636 		goto error_free_iostream;
    637 	}
    638 
    639 	// Make sure everything is in a sane state.
    640 	dc_iostream_purge (device->iostream, DC_DIRECTION_ALL);
    641 
    642 	// Send the version command.
    643 	status = mares_iconhd_transfer (device, CMD_VERSION, NULL, 0,
    644 		device->version, sizeof (device->version), NULL);
    645 	if (status != DC_STATUS_SUCCESS) {
    646 		goto error_free_iostream;
    647 	}
    648 
    649 	HEXDUMP (context, DC_LOGLEVEL_DEBUG, "Version", device->version, sizeof (device->version));
    650 
    651 	// Autodetect the model using the version packet.
    652 	device->model = mares_iconhd_get_model (device);
    653 
    654 	// Read the size of the flash memory.
    655 	unsigned int memsize = 0;
    656 	if (device->model == QUAD) {
    657 		unsigned char rsp_flash[4] = {0};
    658 		status = mares_iconhd_transfer (device, CMD_FLASHSIZE, NULL, 0, rsp_flash, sizeof (rsp_flash), NULL);
    659 		if (status != DC_STATUS_SUCCESS) {
    660 			WARNING (context, "Failed to read the flash memory size.");
    661 		} else {
    662 			memsize = array_uint32_le (rsp_flash);
    663 			DEBUG (context, "Flash memory size is %u bytes.", memsize);
    664 		}
    665 	}
    666 
    667 	// Load the correct memory layout.
    668 	switch (device->model) {
    669 	case MATRIX:
    670 		device->layout = &mares_matrix_layout;
    671 		device->packetsize = 256;
    672 		break;
    673 	case PUCKPRO:
    674 	case PUCK2:
    675 	case NEMOWIDE2:
    676 	case SMART:
    677 	case SMARTAPNEA:
    678 		device->layout = &mares_nemowide2_layout;
    679 		device->packetsize = 256;
    680 		break;
    681 	case QUAD:
    682 		if (memsize > 0x40000) {
    683 			device->layout = &mares_iconhd_layout;
    684 		} else {
    685 			device->layout = &mares_nemowide2_layout;
    686 		}
    687 		device->packetsize = 256;
    688 		break;
    689 	case QUADAIR:
    690 	case SMARTAIR:
    691 		device->layout = &mares_iconhdnet_layout;
    692 		device->packetsize = 256;
    693 		break;
    694 	case GENIUS:
    695 	case HORIZON:
    696 	case PUCKAIR2:
    697 	case SIRIUS:
    698 	case QUADCI:
    699 	case QUAD2:
    700 	case SIRIUS_L:
    701 	case PUCK4:
    702 		device->layout = &mares_genius_layout;
    703 		device->packetsize = 4096;
    704 		device->fingerprint_size = 4;
    705 		break;
    706 	case ICONHDNET:
    707 		device->layout = &mares_iconhdnet_layout;
    708 		device->packetsize = 4096;
    709 		break;
    710 	case ICONHD:
    711 	default:
    712 		device->layout = &mares_iconhd_layout;
    713 		device->packetsize = 4096;
    714 		break;
    715 	}
    716 
    717 	if (dc_iostream_get_transport(device->iostream) == DC_TRANSPORT_BLE) {
    718 		/*
    719 		 * Don't ask for larger amounts of data with the BLE
    720 		 * transport - it will fail.  I suspect there is a buffer
    721 		 * overflow in the BlueLink Pro dongle when bluetooth is
    722 		 * slower than the serial protocol that the dongle talks to
    723 		 * the dive computer.
    724 		 */
    725 		if (device->packetsize > 128)
    726 			device->packetsize = 128;
    727 	}
    728 
    729 	*out = (dc_device_t *) device;
    730 
    731 	return DC_STATUS_SUCCESS;
    732 
    733 
    734 error_free_iostream:
    735 	if (transport == DC_TRANSPORT_BLE && device->ble == FIXED) {
    736 		dc_iostream_close (device->iostream);
    737 	}
    738 error_free:
    739 	dc_device_deallocate ((dc_device_t *) device);
    740 	return status;
    741 }
    742 
    743 
    744 static dc_status_t
    745 mares_iconhd_device_close (dc_device_t *abstract)
    746 {
    747 	mares_iconhd_device_t *device = (mares_iconhd_device_t *) abstract;
    748 	dc_transport_t transport = dc_iostream_get_transport (device->iostream);
    749 
    750 	// Close the packet stream.
    751 	if (transport == DC_TRANSPORT_BLE && device->ble == FIXED) {
    752 		return dc_iostream_close (device->iostream);
    753 	}
    754 
    755 	return DC_STATUS_SUCCESS;
    756 }
    757 
    758 
    759 static dc_status_t
    760 mares_iconhd_device_set_fingerprint (dc_device_t *abstract, const unsigned char data[], unsigned int size)
    761 {
    762 	mares_iconhd_device_t *device = (mares_iconhd_device_t *) abstract;
    763 
    764 	if (size && size != device->fingerprint_size)
    765 		return DC_STATUS_INVALIDARGS;
    766 
    767 	if (size)
    768 		memcpy (device->fingerprint, data, device->fingerprint_size);
    769 	else
    770 		memset (device->fingerprint, 0, device->fingerprint_size);
    771 
    772 	return DC_STATUS_SUCCESS;
    773 }
    774 
    775 
    776 static dc_status_t
    777 mares_iconhd_device_read (dc_device_t *abstract, unsigned int address, unsigned char data[], unsigned int size)
    778 {
    779 	dc_status_t rc = DC_STATUS_SUCCESS;
    780 	mares_iconhd_device_t *device = (mares_iconhd_device_t *) abstract;
    781 
    782 	unsigned int nbytes = 0;
    783 	while (nbytes < size) {
    784 		// Calculate the packet size.
    785 		unsigned int len = size - nbytes;
    786 		if (len > device->packetsize)
    787 			len = device->packetsize;
    788 
    789 		// Read the packet.
    790 		unsigned char command[] = {
    791 			(address      ) & 0xFF,
    792 			(address >>  8) & 0xFF,
    793 			(address >> 16) & 0xFF,
    794 			(address >> 24) & 0xFF,
    795 			(len      ) & 0xFF,
    796 			(len >>  8) & 0xFF,
    797 			(len >> 16) & 0xFF,
    798 			(len >> 24) & 0xFF};
    799 		rc = mares_iconhd_transfer (device, CMD_READ, command, sizeof (command), data, len, NULL);
    800 		if (rc != DC_STATUS_SUCCESS)
    801 			return rc;
    802 
    803 		nbytes += len;
    804 		address += len;
    805 		data += len;
    806 	}
    807 
    808 	return rc;
    809 }
    810 
    811 
    812 static dc_status_t
    813 mares_iconhd_device_dump (dc_device_t *abstract, dc_buffer_t *buffer)
    814 {
    815 	dc_status_t status = DC_STATUS_SUCCESS;
    816 	mares_iconhd_device_t *device = (mares_iconhd_device_t *) abstract;
    817 
    818 	// Allocate the required amount of memory.
    819 	if (!dc_buffer_resize (buffer, device->layout->memsize)) {
    820 		ERROR (abstract->context, "Insufficient buffer space available.");
    821 		return DC_STATUS_NOMEMORY;
    822 	}
    823 
    824 	// Emit a vendor event.
    825 	dc_event_vendor_t vendor;
    826 	vendor.data = device->version;
    827 	vendor.size = sizeof (device->version);
    828 	device_event_emit (abstract, DC_EVENT_VENDOR, &vendor);
    829 
    830 	// Download the memory dump.
    831 	status = device_dump_read (abstract, 0, dc_buffer_get_data (buffer),
    832 		dc_buffer_get_size (buffer), device->packetsize);
    833 	if (status != DC_STATUS_SUCCESS) {
    834 		return status;
    835 	}
    836 
    837 	// Emit a device info event.
    838 	unsigned char *data = dc_buffer_get_data (buffer);
    839 	dc_event_devinfo_t devinfo = {0};
    840 	devinfo.model = device->model;
    841 	devinfo.firmware = 0;
    842 	devinfo.serial = array_uint32_le (data + 0x0C);
    843 	mares_iconhd_fill_product_name (device, &devinfo);
    844 	device_event_emit (abstract, DC_EVENT_DEVINFO, &devinfo);
    845 
    846 	return status;
    847 }
    848 
    849 static dc_status_t
    850 mares_iconhd_device_foreach_raw (dc_device_t *abstract, dc_dive_callback_t callback, void *userdata)
    851 {
    852 	dc_status_t rc = DC_STATUS_SUCCESS;
    853 	mares_iconhd_device_t *device = (mares_iconhd_device_t *) abstract;
    854 
    855 	const mares_iconhd_layout_t *layout = device->layout;
    856 
    857 	// Read the serial number.
    858 	unsigned char serial[4] = {0};
    859 	rc = mares_iconhd_device_read (abstract, 0x0C, serial, sizeof (serial));
    860 	if (rc != DC_STATUS_SUCCESS) {
    861 		ERROR (abstract->context, "Failed to read the memory.");
    862 		return rc;
    863 	}
    864 
    865 	// Emit a device info event.
    866 	dc_event_devinfo_t devinfo = {0};
    867 	devinfo.model = device->model;
    868 	devinfo.firmware = 0;
    869 	devinfo.serial = array_uint32_le (serial);
    870 	mares_iconhd_fill_product_name (device, &devinfo);
    871 	device_event_emit (abstract, DC_EVENT_DEVINFO, &devinfo);
    872 
    873 	// Enable progress notifications.
    874 	dc_event_progress_t progress = EVENT_PROGRESS_INITIALIZER;
    875 	progress.maximum = layout->rb_profile_end - layout->rb_profile_begin;
    876 	device_event_emit (abstract, DC_EVENT_PROGRESS, &progress);
    877 
    878 	// Get the model code.
    879 	unsigned int model = device->model;
    880 
    881 	// Get the corresponding dive header size.
    882 	unsigned int header = 0x5C;
    883 	if (model == ICONHDNET)
    884 		header = 0x80;
    885 	else if (model == QUADAIR)
    886 		header = 0x84;
    887 	else if (model == SMART || model == SMARTAIR)
    888 		header = 4; // Type and number of samples only!
    889 	else if (model == SMARTAPNEA)
    890 		header = 6; // Type and number of samples only!
    891 
    892 	// Get the end of the profile ring buffer.
    893 	unsigned int eop = 0;
    894 	const unsigned int config[] = {0x2001, 0x3001};
    895 	for (unsigned int i = 0; i < sizeof (config) / sizeof (*config); ++i) {
    896 		// Read the pointer.
    897 		unsigned char pointer[4] = {0};
    898 		rc = mares_iconhd_device_read (abstract, config[i], pointer, sizeof (pointer));
    899 		if (rc != DC_STATUS_SUCCESS) {
    900 			ERROR (abstract->context, "Failed to read the memory.");
    901 			return rc;
    902 		}
    903 
    904 		// Update and emit a progress event.
    905 		progress.maximum += sizeof (pointer);
    906 		progress.current += sizeof (pointer);
    907 		device_event_emit (abstract, DC_EVENT_PROGRESS, &progress);
    908 
    909 		eop = array_uint32_le (pointer);
    910 		if (eop >= layout->rb_profile_begin && eop < layout->rb_profile_end)
    911 			break;
    912 	}
    913 	if (eop < layout->rb_profile_begin || eop >= layout->rb_profile_end) {
    914 		if (eop == 0xFFFFFFFF)
    915 			return DC_STATUS_SUCCESS; // No dives available.
    916 		ERROR (abstract->context, "Ringbuffer pointer out of range (0x%08x).", eop);
    917 		return DC_STATUS_DATAFORMAT;
    918 	}
    919 
    920 	// Create the ringbuffer stream.
    921 	dc_rbstream_t *rbstream = NULL;
    922 	rc = dc_rbstream_new (&rbstream, abstract, 1, device->packetsize, layout->rb_profile_begin, layout->rb_profile_end, eop, DC_RBSTREAM_BACKWARD);
    923 	if (rc != DC_STATUS_SUCCESS) {
    924 		ERROR (abstract->context, "Failed to create the ringbuffer stream.");
    925 		return rc;
    926 	}
    927 
    928 	// Allocate memory for the dives.
    929 	unsigned char *buffer = (unsigned char *) malloc (layout->rb_profile_end - layout->rb_profile_begin);
    930 	if (buffer == NULL) {
    931 		ERROR (abstract->context, "Failed to allocate memory.");
    932 		dc_rbstream_free (rbstream);
    933 		return DC_STATUS_NOMEMORY;
    934 	}
    935 
    936 	unsigned int offset = layout->rb_profile_end - layout->rb_profile_begin;
    937 	while (offset >= header + 4) {
    938 		// Read the first part of the dive header.
    939 		rc = dc_rbstream_read (rbstream, &progress, buffer + offset - header, header);
    940 		if (rc != DC_STATUS_SUCCESS) {
    941 			ERROR (abstract->context, "Failed to read the dive.");
    942 			dc_rbstream_free (rbstream);
    943 			free (buffer);
    944 			return rc;
    945 		}
    946 
    947 		// Get the number of samples in the profile data.
    948 		unsigned int type = 0, nsamples = 0;
    949 		if (ISSMART(model)) {
    950 			type     = array_uint16_le (buffer + offset - header + 2);
    951 			nsamples = array_uint16_le (buffer + offset - header + 0);
    952 		} else {
    953 			type     = array_uint16_le (buffer + offset - header + 0);
    954 			nsamples = array_uint16_le (buffer + offset - header + 2);
    955 		}
    956 		if (nsamples == 0xFFFF || type == 0xFFFF)
    957 			break;
    958 
    959 		// Get the dive mode.
    960 		unsigned int mode = type & 0x03;
    961 
    962 		// Get the header/sample size and fingerprint offset.
    963 		unsigned int headersize = 0x5C;
    964 		unsigned int samplesize = 8;
    965 		unsigned int fingerprint = 6;
    966 		if (model == ICONHDNET) {
    967 			headersize = 0x80;
    968 			samplesize = 12;
    969 		} else if (model == QUADAIR) {
    970 			headersize = 0x84;
    971 			samplesize = 12;
    972 		} else if (model == SMART) {
    973 			if (mode == FREEDIVE) {
    974 				headersize = 0x2E;
    975 				samplesize = 6;
    976 				fingerprint = 0x20;
    977 			} else {
    978 				headersize = 0x5C;
    979 				samplesize = 8;
    980 				fingerprint = 2;
    981 			}
    982 		} else if (model == SMARTAPNEA) {
    983 			headersize = 0x50;
    984 			samplesize = 14;
    985 			fingerprint = 0x40;
    986 		} else if (model == SMARTAIR) {
    987 			if (mode == FREEDIVE) {
    988 				headersize = 0x30;
    989 				samplesize = 6;
    990 				fingerprint = 0x22;
    991 			} else {
    992 				headersize = 0x84;
    993 				samplesize = 12;
    994 				fingerprint = 2;
    995 			}
    996 		}
    997 		if (offset < headersize)
    998 			break;
    999 
   1000 		// Read the second part of the dive header.
   1001 		rc = dc_rbstream_read (rbstream, &progress, buffer + offset - headersize, headersize - header);
   1002 		if (rc != DC_STATUS_SUCCESS) {
   1003 			ERROR (abstract->context, "Failed to read the dive.");
   1004 			dc_rbstream_free (rbstream);
   1005 			free (buffer);
   1006 			return rc;
   1007 		}
   1008 
   1009 		// Calculate the total number of bytes for this dive.
   1010 		// If the buffer does not contain that much bytes, we reached the
   1011 		// end of the ringbuffer. The current dive is incomplete (partially
   1012 		// overwritten with newer data), and processing should stop.
   1013 		unsigned int nbytes = 4 + headersize + nsamples * samplesize;
   1014 		if (model == ICONHDNET || model == QUADAIR || (model == SMARTAIR && mode != FREEDIVE)) {
   1015 			nbytes += (nsamples / 4) * 8;
   1016 		} else if (model == SMARTAPNEA) {
   1017 			unsigned int settings = array_uint16_le (buffer + offset - headersize + 0x1C);
   1018 			unsigned int divetime = array_uint32_le (buffer + offset - headersize + 0x24);
   1019 			unsigned int samplerate = 1 << ((settings >> 9) & 0x03);
   1020 
   1021 			nbytes += divetime * samplerate * 2;
   1022 		}
   1023 		if (offset < nbytes)
   1024 			break;
   1025 
   1026 		// Read the remainder of the dive.
   1027 		rc = dc_rbstream_read (rbstream, &progress, buffer + offset - nbytes, nbytes - headersize);
   1028 		if (rc != DC_STATUS_SUCCESS) {
   1029 			ERROR (abstract->context, "Failed to read the dive.");
   1030 			dc_rbstream_free (rbstream);
   1031 			free (buffer);
   1032 			return rc;
   1033 		}
   1034 
   1035 		// Move to the start of the dive.
   1036 		offset -= nbytes;
   1037 
   1038 		// Verify that the length that is stored in the profile data
   1039 		// equals the calculated length. If both values are different,
   1040 		// we assume we reached the last dive.
   1041 		unsigned int length = array_uint32_le (buffer + offset);
   1042 		if (length != nbytes)
   1043 			break;
   1044 
   1045 		unsigned char *fp = buffer + offset + length - headersize + fingerprint;
   1046 		if (memcmp (fp, device->fingerprint, sizeof (device->fingerprint)) == 0) {
   1047 			break;
   1048 		}
   1049 
   1050 		if (callback && !callback (buffer + offset, length, fp, sizeof (device->fingerprint), userdata)) {
   1051 			break;
   1052 		}
   1053 	}
   1054 
   1055 	dc_rbstream_free (rbstream);
   1056 	free (buffer);
   1057 
   1058 	return rc;
   1059 }
   1060 
   1061 static dc_status_t
   1062 mares_iconhd_device_foreach_object (dc_device_t *abstract, dc_dive_callback_t callback, void *userdata)
   1063 {
   1064 	dc_status_t rc = DC_STATUS_SUCCESS;
   1065 	mares_iconhd_device_t *device = (mares_iconhd_device_t *) abstract;
   1066 
   1067 	// Enable progress notifications.
   1068 	dc_event_progress_t progress = EVENT_PROGRESS_INITIALIZER;
   1069 	device_event_emit (abstract, DC_EVENT_PROGRESS, &progress);
   1070 
   1071 	// Allocate memory for the dives.
   1072 	dc_buffer_t *buffer = dc_buffer_new (4096);
   1073 	if (buffer == NULL) {
   1074 		ERROR (abstract->context, "Failed to allocate memory.");
   1075 		return DC_STATUS_NOMEMORY;
   1076 	}
   1077 
   1078 	// Read the model number.
   1079 	rc = mares_iconhd_read_object (device, NULL, buffer, OBJ_DEVICE, OBJ_DEVICE_MODEL);
   1080 	if (rc != DC_STATUS_SUCCESS) {
   1081 		ERROR (abstract->context, "Failed to read the model number.");
   1082 		dc_buffer_free (buffer);
   1083 		return rc;
   1084 	}
   1085 
   1086 	HEXDUMP (abstract->context, DC_LOGLEVEL_DEBUG, "Model", dc_buffer_get_data (buffer), dc_buffer_get_size (buffer));
   1087 
   1088 	if (dc_buffer_get_size (buffer) < 4) {
   1089 		ERROR (abstract->context, "Unexpected number of bytes received (" DC_PRINTF_SIZE ").",
   1090 			dc_buffer_get_size (buffer));
   1091 		dc_buffer_free (buffer);
   1092 		return DC_STATUS_PROTOCOL;
   1093 	}
   1094 
   1095 	unsigned int DC_ATTR_UNUSED model = array_uint32_le (dc_buffer_get_data (buffer));
   1096 
   1097 	// Erase the buffer.
   1098 	dc_buffer_clear (buffer);
   1099 
   1100 	// Read the serial number.
   1101 	rc = mares_iconhd_read_object (device, NULL, buffer, OBJ_DEVICE, OBJ_DEVICE_SERIAL);
   1102 	if (rc != DC_STATUS_SUCCESS) {
   1103 		ERROR (abstract->context, "Failed to read the serial number.");
   1104 		dc_buffer_free (buffer);
   1105 		return rc;
   1106 	}
   1107 
   1108 	HEXDUMP (abstract->context, DC_LOGLEVEL_DEBUG, "Serial", dc_buffer_get_data (buffer), dc_buffer_get_size (buffer));
   1109 
   1110 	if (dc_buffer_get_size (buffer) < 16) {
   1111 		ERROR (abstract->context, "Unexpected number of bytes received (" DC_PRINTF_SIZE ").",
   1112 			dc_buffer_get_size (buffer));
   1113 		dc_buffer_free (buffer);
   1114 		return DC_STATUS_PROTOCOL;
   1115 	}
   1116 
   1117 	unsigned int serial = array_convert_str2num (dc_buffer_get_data (buffer) + 10, 6);
   1118 
   1119 	// Emit a device info event.
   1120 	dc_event_devinfo_t devinfo = {0};
   1121 	devinfo.model = device->model;
   1122 	devinfo.firmware = 0;
   1123 	devinfo.serial = serial;
   1124 	mares_iconhd_fill_product_name (device, &devinfo);
   1125 	device_event_emit (abstract, DC_EVENT_DEVINFO, &devinfo);
   1126 
   1127 	// Erase the buffer.
   1128 	dc_buffer_clear (buffer);
   1129 
   1130 	// Read the number of dives.
   1131 	rc = mares_iconhd_read_object (device, NULL, buffer, OBJ_LOGBOOK, OBJ_LOGBOOK_COUNT);
   1132 	if (rc != DC_STATUS_SUCCESS) {
   1133 		ERROR (abstract->context, "Failed to read the number of dives.");
   1134 		dc_buffer_free (buffer);
   1135 		return rc;
   1136 	}
   1137 
   1138 	if (dc_buffer_get_size (buffer) < 2) {
   1139 		ERROR (abstract->context, "Unexpected number of bytes received (" DC_PRINTF_SIZE ").",
   1140 			dc_buffer_get_size (buffer));
   1141 		dc_buffer_free (buffer);
   1142 		return DC_STATUS_PROTOCOL;
   1143 	}
   1144 
   1145 	// Get the number of dives.
   1146 	unsigned int ndives = array_uint16_le (dc_buffer_get_data(buffer));
   1147 
   1148 	// Update and emit a progress event.
   1149 	progress.current = 1 * NSTEPS;
   1150 	progress.maximum = (1 + ndives * 2) * NSTEPS;
   1151 	device_event_emit (abstract, DC_EVENT_PROGRESS, &progress);
   1152 
   1153 	// Download the dives.
   1154 	for (unsigned int i = 0; i < ndives; ++i) {
   1155 		// Erase the buffer.
   1156 		dc_buffer_clear (buffer);
   1157 
   1158 		// Read the dive header.
   1159 		rc = mares_iconhd_read_object (device, &progress, buffer, OBJ_DIVE + i, OBJ_DIVE_HEADER);
   1160 		if (rc != DC_STATUS_SUCCESS) {
   1161 			ERROR (abstract->context, "Failed to read the dive header.");
   1162 			break;
   1163 		}
   1164 
   1165 		// Check the fingerprint data.
   1166 		if (memcmp (dc_buffer_get_data (buffer) + 0x08, device->fingerprint, device->fingerprint_size) == 0) {
   1167 			INFO (abstract->context, "Stopping due to detecting a matching fingerprint");
   1168 			break;
   1169 		}
   1170 
   1171 		// Read the dive data.
   1172 		rc = mares_iconhd_read_object (device, &progress, buffer, OBJ_DIVE + i, OBJ_DIVE_DATA);
   1173 		if (rc == DC_STATUS_UNSUPPORTED) {
   1174 			INFO (abstract->context, "Skipping Sirius freedive without downloadable data (%u).", i);
   1175 			progress.current += NSTEPS;
   1176 			device_event_emit (abstract, DC_EVENT_PROGRESS, &progress);
   1177 			rc = DC_STATUS_SUCCESS;
   1178 			continue;
   1179 		}
   1180 		if (rc != DC_STATUS_SUCCESS) {
   1181 			ERROR (abstract->context, "Failed to read the dive data.");
   1182 			break;
   1183 		}
   1184 
   1185 		const unsigned char *data = dc_buffer_get_data (buffer);
   1186 		if (callback && !callback (data, dc_buffer_get_size (buffer), data + 0x08, device->fingerprint_size, userdata)) {
   1187 			break;
   1188 		}
   1189 	}
   1190 
   1191 	dc_buffer_free(buffer);
   1192 
   1193 	return rc;
   1194 }
   1195 
   1196 static dc_status_t
   1197 mares_iconhd_device_foreach (dc_device_t *abstract, dc_dive_callback_t callback, void *userdata)
   1198 {
   1199 	mares_iconhd_device_t *device = (mares_iconhd_device_t *) abstract;
   1200 
   1201 	// Emit a vendor event.
   1202 	dc_event_vendor_t vendor;
   1203 	vendor.data = device->version;
   1204 	vendor.size = sizeof (device->version);
   1205 	device_event_emit (abstract, DC_EVENT_VENDOR, &vendor);
   1206 
   1207 	if (ISGENIUS(device->model)) {
   1208 		return mares_iconhd_device_foreach_object (abstract, callback, userdata);
   1209 	} else {
   1210 		return mares_iconhd_device_foreach_raw (abstract, callback, userdata);
   1211 	}
   1212 }
   1213 
   1214 
   1215 static dc_status_t
   1216 mares_iconhd_device_timesync (dc_device_t *abstract, const dc_datetime_t *datetime)
   1217 {
   1218 	dc_status_t status = DC_STATUS_SUCCESS;
   1219 	mares_iconhd_device_t *device = (mares_iconhd_device_t *) abstract;
   1220 
   1221 	// Convert to local time.
   1222 	dc_datetime_t local = *datetime;
   1223 	local.timezone = DC_TIMEZONE_NONE;
   1224 
   1225 	dc_ticks_t ticks = dc_datetime_mktime (&local);
   1226 	if (ticks == -1) {
   1227 		ERROR (abstract->context, "Invalid date/time value specified.");
   1228 		return DC_STATUS_INVALIDARGS;
   1229 	}
   1230 
   1231 	const unsigned char timestamp[] = {
   1232 		(ticks      ) & 0xFF,
   1233 		(ticks >>  8) & 0xFF,
   1234 		(ticks >> 16) & 0xFF,
   1235 		(ticks >> 24) & 0xFF,
   1236 	};
   1237 
   1238 	status = mares_iconhd_transfer (device, CMD_SET_TIME, timestamp, sizeof (timestamp), NULL, 0, NULL);
   1239 	if (status != DC_STATUS_SUCCESS) {
   1240 		ERROR (abstract->context, "Failed to set the local time.");
   1241 		return status;
   1242 	}
   1243 
   1244 	return status;
   1245 }