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

divesystem_idive.c (27783B)


      1 /*
      2  * libdivecomputer
      3  *
      4  * Copyright (C) 2014 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 #include <stdio.h>
     25 
     26 #include "divesystem_idive.h"
     27 #include "context-private.h"
     28 #include "device-private.h"
     29 #include "platform.h"
     30 #include "checksum.h"
     31 #include "array.h"
     32 #include "packet.h"
     33 
     34 #define ISINSTANCE(device) dc_device_isinstance((device), &divesystem_idive_device_vtable)
     35 
     36 #define ISIX3M(model) ((model) >= 0x21)
     37 
     38 #define MAXRETRIES 9
     39 
     40 #define MAXPACKET 0xFF
     41 #define START     0x55
     42 #define ACK       0x06
     43 #define WAIT      0x13
     44 #define NAK       0x15
     45 
     46 #define CMD_IDIVE_ID      0x10
     47 #define CMD_IDIVE_RANGE   0x98
     48 #define CMD_IDIVE_HEADER  0xA0
     49 #define CMD_IDIVE_SAMPLE  0xA8
     50 
     51 #define CMD_IX3M_ID       0x11
     52 #define CMD_IX3M_RANGE    0x78
     53 #define CMD_IX3M_HEADER   0x79
     54 #define CMD_IX3M_SAMPLE   0x7A
     55 #define CMD_IX3M_TIMESYNC 0x13
     56 #define CMD_IX3M_BOOTLOADER 0x0A
     57 
     58 #define BOOTLOADER_PROBE    0x78
     59 #define BOOTLOADER_UPLOAD_A 0x40
     60 #define BOOTLOADER_UPLOAD_B 0x23
     61 #define BOOTLOADER_ACK      0x46
     62 
     63 #define ERR_INVALID_CMD    0x10
     64 #define ERR_INVALID_LENGTH 0x20
     65 #define ERR_INVALID_DATA   0x30
     66 #define ERR_UNSUPPORTED    0x40
     67 #define ERR_UNAVAILABLE    0x58
     68 #define ERR_UNREADABLE     0x5F
     69 #define ERR_BUSY           0x60
     70 
     71 #define NSTEPS    1000
     72 #define STEP(i,n) (NSTEPS * (i) / (n))
     73 
     74 #define EPOCH 1199145600 /* 2008-01-01 00:00:00 */
     75 
     76 #define TZ_IDX_UNCHANGED 0xFF
     77 
     78 typedef struct divesystem_idive_command_t {
     79 	unsigned char cmd;
     80 	unsigned int size;
     81 } divesystem_idive_command_t;
     82 
     83 typedef struct divesystem_idive_commands_t {
     84 	divesystem_idive_command_t id;
     85 	divesystem_idive_command_t range;
     86 	divesystem_idive_command_t header;
     87 	divesystem_idive_command_t sample;
     88 	unsigned int nsamples;
     89 } divesystem_idive_commands_t;
     90 
     91 typedef struct divesystem_idive_signature_t {
     92 	const char *name;
     93 	unsigned int delay;
     94 } divesystem_idive_signature_t;
     95 
     96 typedef struct divesystem_idive_device_t {
     97 	dc_device_t base;
     98 	dc_iostream_t *iostream;
     99 	unsigned char fingerprint[4];
    100 	unsigned int model;
    101 } divesystem_idive_device_t;
    102 
    103 static dc_status_t divesystem_idive_device_set_fingerprint (dc_device_t *abstract, const unsigned char data[], unsigned int size);
    104 static dc_status_t divesystem_idive_device_foreach (dc_device_t *abstract, dc_dive_callback_t callback, void *userdata);
    105 static dc_status_t divesystem_idive_device_timesync (dc_device_t *abstract, const dc_datetime_t *datetime);
    106 static dc_status_t divesystem_idive_device_close (dc_device_t *abstract);
    107 
    108 static const dc_device_vtable_t divesystem_idive_device_vtable = {
    109 	sizeof(divesystem_idive_device_t),
    110 	DC_FAMILY_DIVESYSTEM_IDIVE,
    111 	divesystem_idive_device_set_fingerprint, /* set_fingerprint */
    112 	NULL, /* read */
    113 	NULL, /* write */
    114 	NULL, /* dump */
    115 	divesystem_idive_device_foreach, /* foreach */
    116 	divesystem_idive_device_timesync, /* timesync */
    117 	divesystem_idive_device_close /* close */
    118 };
    119 
    120 static const divesystem_idive_commands_t idive = {
    121 	{CMD_IDIVE_ID,     0x0A},
    122 	{CMD_IDIVE_RANGE,  0x04},
    123 	{CMD_IDIVE_HEADER, 0x32},
    124 	{CMD_IDIVE_SAMPLE, 0x2A},
    125 	1,
    126 };
    127 
    128 static const divesystem_idive_commands_t ix3m = {
    129 	{CMD_IX3M_ID,     0x1A},
    130 	{CMD_IX3M_RANGE,  0x04},
    131 	{CMD_IX3M_HEADER, 0x36},
    132 	{CMD_IX3M_SAMPLE, 0x36},
    133 	1,
    134 };
    135 
    136 static const divesystem_idive_commands_t ix3m_apos4 = {
    137 	{CMD_IX3M_ID,     0x1A},
    138 	{CMD_IX3M_RANGE,  0x04},
    139 	{CMD_IX3M_HEADER, 0x36},
    140 	{CMD_IX3M_SAMPLE, 0x40},
    141 	3,
    142 };
    143 
    144 static const divesystem_idive_signature_t signatures[] = {
    145 	{"dsh01", 50}, // IX3M GPS
    146 	{"dsh30", 50}, // IX3M Pro
    147 	{"dsh20",  5}, // iDive Sport
    148 	{"dsh23",  5}, // iDive Color
    149 	{"acx",    5}, // WPT
    150 };
    151 
    152 dc_status_t
    153 divesystem_idive_device_open (dc_device_t **out, dc_context_t *context, dc_iostream_t *iostream, unsigned int model)
    154 {
    155 	dc_status_t status = DC_STATUS_SUCCESS;
    156 	divesystem_idive_device_t *device = NULL;
    157 	dc_transport_t transport = dc_iostream_get_transport (iostream);
    158 
    159 	if (out == NULL)
    160 		return DC_STATUS_INVALIDARGS;
    161 
    162 	// Allocate memory.
    163 	device = (divesystem_idive_device_t *) dc_device_allocate (context, &divesystem_idive_device_vtable);
    164 	if (device == NULL) {
    165 		ERROR (context, "Failed to allocate memory.");
    166 		return DC_STATUS_NOMEMORY;
    167 	}
    168 
    169 	// Set the default values.
    170 	memset (device->fingerprint, 0, sizeof (device->fingerprint));
    171 	device->model = model;
    172 
    173 	// Create the packet stream.
    174 	if (transport == DC_TRANSPORT_BLE) {
    175 		status = dc_packet_open (&device->iostream, context, iostream, 244, 244);
    176 		if (status != DC_STATUS_SUCCESS) {
    177 			ERROR (context, "Failed to create the packet stream.");
    178 			goto error_free;
    179 		}
    180 	} else {
    181 		device->iostream = iostream;
    182 	}
    183 
    184 	// Set the serial communication protocol (115200 8N1).
    185 	status = dc_iostream_configure (device->iostream, 115200, 8, DC_PARITY_NONE, DC_STOPBITS_ONE, DC_FLOWCONTROL_NONE);
    186 	if (status != DC_STATUS_SUCCESS) {
    187 		ERROR (context, "Failed to set the terminal attributes.");
    188 		goto error_free_iostream;
    189 	}
    190 
    191 	// Set the timeout for receiving data (1000ms).
    192 	status = dc_iostream_set_timeout (device->iostream, 1000);
    193 	if (status != DC_STATUS_SUCCESS) {
    194 		ERROR (context, "Failed to set the timeout.");
    195 		goto error_free_iostream;
    196 	}
    197 
    198 	// Make sure everything is in a sane state.
    199 	dc_iostream_sleep (device->iostream, 300);
    200 	dc_iostream_purge (device->iostream, DC_DIRECTION_ALL);
    201 
    202 	*out = (dc_device_t *) device;
    203 
    204 	return DC_STATUS_SUCCESS;
    205 
    206 error_free_iostream:
    207 	if (transport == DC_TRANSPORT_BLE) {
    208 		dc_iostream_close (device->iostream);
    209 	}
    210 error_free:
    211 	dc_device_deallocate ((dc_device_t *) device);
    212 	return status;
    213 }
    214 
    215 static dc_status_t
    216 divesystem_idive_device_close (dc_device_t *abstract)
    217 {
    218 	divesystem_idive_device_t *device = (divesystem_idive_device_t *) abstract;
    219 
    220 	// Close the packet stream.
    221 	if (dc_iostream_get_transport (device->iostream) == DC_TRANSPORT_BLE) {
    222 		return dc_iostream_close (device->iostream);
    223 	}
    224 
    225 	return DC_STATUS_SUCCESS;
    226 }
    227 
    228 static dc_status_t
    229 divesystem_idive_device_set_fingerprint (dc_device_t *abstract, const unsigned char data[], unsigned int size)
    230 {
    231 	divesystem_idive_device_t *device = (divesystem_idive_device_t *) abstract;
    232 
    233 	if (size && size != sizeof (device->fingerprint))
    234 		return DC_STATUS_INVALIDARGS;
    235 
    236 	if (size)
    237 		memcpy (device->fingerprint, data, sizeof (device->fingerprint));
    238 	else
    239 		memset (device->fingerprint, 0, sizeof (device->fingerprint));
    240 
    241 	return DC_STATUS_SUCCESS;
    242 }
    243 
    244 
    245 static dc_status_t
    246 divesystem_idive_send (divesystem_idive_device_t *device, const unsigned char command[], unsigned int csize)
    247 {
    248 	dc_status_t status = DC_STATUS_SUCCESS;
    249 	dc_device_t *abstract = (dc_device_t *) device;
    250 	unsigned char packet[MAXPACKET + 4];
    251 	unsigned short crc = 0;
    252 
    253 	if (device_is_cancelled (abstract))
    254 		return DC_STATUS_CANCELLED;
    255 
    256 	if (csize < 1 || csize > MAXPACKET)
    257 		return DC_STATUS_INVALIDARGS;
    258 
    259 	// Setup the data packet
    260 	packet[0] = START;
    261 	packet[1] = csize;
    262 	memcpy(packet + 2, command, csize);
    263 	crc = checksum_crc16_ccitt (packet, csize + 2, 0xffff, 0x0000);
    264 	packet[csize + 2] = (crc >> 8) & 0xFF;
    265 	packet[csize + 3] = (crc     ) & 0xFF;
    266 
    267 	// Send the data packet.
    268 	status = dc_iostream_write (device->iostream, packet, csize + 4, NULL);
    269 	if (status != DC_STATUS_SUCCESS) {
    270 		ERROR (abstract->context, "Failed to send the command.");
    271 		return status;
    272 	}
    273 
    274 	return DC_STATUS_SUCCESS;
    275 }
    276 
    277 
    278 static dc_status_t
    279 divesystem_idive_receive (divesystem_idive_device_t *device, unsigned char answer[], unsigned int *asize)
    280 {
    281 	dc_status_t status = DC_STATUS_SUCCESS;
    282 	dc_device_t *abstract = (dc_device_t *) device;
    283 	unsigned char packet[MAXPACKET + 4];
    284 
    285 	if (asize == NULL || *asize < MAXPACKET) {
    286 		ERROR (abstract->context, "Invalid arguments.");
    287 		return DC_STATUS_INVALIDARGS;
    288 	}
    289 
    290 	// Read the packet start byte.
    291 	while (1) {
    292 		status = dc_iostream_read (device->iostream, packet + 0, 1, NULL);
    293 		if (status != DC_STATUS_SUCCESS) {
    294 			ERROR (abstract->context, "Failed to receive the packet start byte.");
    295 			return status;
    296 		}
    297 
    298 		if (packet[0] == START)
    299 			break;
    300 	}
    301 
    302 	// Read the packet length.
    303 	status = dc_iostream_read (device->iostream, packet + 1, 1, NULL);
    304 	if (status != DC_STATUS_SUCCESS) {
    305 		ERROR (abstract->context, "Failed to receive the packet length.");
    306 		return status;
    307 	}
    308 
    309 	unsigned int len = packet[1];
    310 	if (len < 2 || len > MAXPACKET) {
    311 		ERROR (abstract->context, "Invalid packet length.");
    312 		return DC_STATUS_PROTOCOL;
    313 	}
    314 
    315 	// Read the packet payload and checksum.
    316 	status = dc_iostream_read (device->iostream, packet + 2, len + 2, NULL);
    317 	if (status != DC_STATUS_SUCCESS) {
    318 		ERROR (abstract->context, "Failed to receive the packet payload and checksum.");
    319 		return status;
    320 	}
    321 
    322 	// Verify the checksum.
    323 	unsigned short crc = array_uint16_be (packet + len + 2);
    324 	unsigned short ccrc = checksum_crc16_ccitt (packet, len + 2, 0xffff, 0x0000);
    325 	if (crc != ccrc) {
    326 		ERROR (abstract->context, "Unexpected packet checksum.");
    327 		return DC_STATUS_PROTOCOL;
    328 	}
    329 
    330 	memcpy(answer, packet + 2, len);
    331 	*asize = len;
    332 
    333 	return DC_STATUS_SUCCESS;
    334 }
    335 
    336 
    337 static dc_status_t
    338 divesystem_idive_packet (divesystem_idive_device_t *device, const unsigned char command[], unsigned int csize, unsigned char answer[], unsigned int asize, unsigned int *errorcode)
    339 {
    340 	dc_status_t status = DC_STATUS_SUCCESS;
    341 	dc_device_t *abstract = (dc_device_t *) device;
    342 	unsigned char packet[MAXPACKET] = {0};
    343 	unsigned int length = sizeof(packet);
    344 	unsigned int errcode = 0;
    345 
    346 	// Send the command.
    347 	status = divesystem_idive_send (device, command, csize);
    348 	if (status != DC_STATUS_SUCCESS) {
    349 		goto error;
    350 	}
    351 
    352 	// Receive the answer.
    353 	status = divesystem_idive_receive (device, packet, &length);
    354 	if (status != DC_STATUS_SUCCESS) {
    355 		goto error;
    356 	}
    357 
    358 	// Verify the command byte.
    359 	if (packet[0] != command[0]) {
    360 		ERROR (abstract->context, "Unexpected packet header.");
    361 		status = DC_STATUS_PROTOCOL;
    362 		goto error;
    363 	}
    364 
    365 	// Verify the ACK/NAK byte.
    366 	unsigned int type = packet[length - 1];
    367 	if (type != ACK && type != NAK) {
    368 		ERROR (abstract->context, "Unexpected ACK/NAK byte.");
    369 		status = DC_STATUS_PROTOCOL;
    370 		goto error;
    371 	}
    372 
    373 	// Verify the length of the packet.
    374 	unsigned int expected = (type == ACK ? asize : 1) + 2;
    375 	if (length != expected) {
    376 		ERROR (abstract->context, "Unexpected packet length.");
    377 		status = DC_STATUS_PROTOCOL;
    378 		goto error;
    379 	}
    380 
    381 	// Get the error code from a NAK packet.
    382 	if (type == NAK) {
    383 		errcode = packet[1];
    384 		ERROR (abstract->context, "Received NAK packet with error code %02x.", errcode);
    385 		status = DC_STATUS_PROTOCOL;
    386 		goto error;
    387 	}
    388 
    389 	if (length > 2) {
    390 		memcpy (answer, packet + 1, length - 2);
    391 	}
    392 
    393 error:
    394 	if (errorcode) {
    395 		*errorcode = errcode;
    396 	}
    397 
    398 	return status;
    399 }
    400 
    401 
    402 static dc_status_t
    403 divesystem_idive_transfer (divesystem_idive_device_t *device, const unsigned char command[], unsigned int csize, unsigned char answer[], unsigned int asize, unsigned int *errorcode)
    404 {
    405 	dc_status_t status = DC_STATUS_SUCCESS;
    406 	unsigned int errcode = 0;
    407 
    408 	unsigned int nretries = 0;
    409 	while ((status = divesystem_idive_packet (device, command, csize, answer, asize, &errcode)) != DC_STATUS_SUCCESS) {
    410 		// Automatically discard a corrupted packet,
    411 		// and request a new one.
    412 		if (status != DC_STATUS_PROTOCOL && status != DC_STATUS_TIMEOUT)
    413 			break;
    414 
    415 		// Abort if the device reports a fatal error.
    416 		if (errcode && errcode != ERR_BUSY)
    417 			break;
    418 
    419 		// Abort if the maximum number of retries is reached.
    420 		if (nretries++ >= MAXRETRIES)
    421 			break;
    422 
    423 		// Delay the next attempt.
    424 		dc_iostream_sleep (device->iostream, 100);
    425 	}
    426 
    427 	if (errorcode) {
    428 		*errorcode = errcode;
    429 	}
    430 
    431 	return status;
    432 }
    433 
    434 static dc_status_t
    435 divesystem_idive_device_foreach (dc_device_t *abstract, dc_dive_callback_t callback, void *userdata)
    436 {
    437 	dc_status_t rc = DC_STATUS_SUCCESS;
    438 	divesystem_idive_device_t *device = (divesystem_idive_device_t *) abstract;
    439 	unsigned char packet[MAXPACKET - 2];
    440 	unsigned int errcode = 0;
    441 
    442 	const divesystem_idive_commands_t *commands = &idive;
    443 	if (ISIX3M(device->model)) {
    444 		commands = &ix3m;
    445 	}
    446 
    447 	// Enable progress notifications.
    448 	dc_event_progress_t progress = EVENT_PROGRESS_INITIALIZER;
    449 	device_event_emit (abstract, DC_EVENT_PROGRESS, &progress);
    450 
    451 	unsigned char cmd_id[] = {commands->id.cmd, 0xED};
    452 	rc = divesystem_idive_transfer (device, cmd_id, sizeof(cmd_id), packet, commands->id.size, &errcode);
    453 	if (rc != DC_STATUS_SUCCESS)
    454 		return rc;
    455 
    456 	HEXDUMP (abstract->context, DC_LOGLEVEL_DEBUG, "Version", packet, commands->id.size);
    457 
    458 	// Emit a device info event.
    459 	dc_event_devinfo_t devinfo;
    460 	devinfo.model = array_uint16_le (packet);
    461 	devinfo.firmware = array_uint32_le (packet + 2);
    462 	devinfo.serial = array_uint32_le (packet + 6);
    463 	device_event_emit (abstract, DC_EVENT_DEVINFO, &devinfo);
    464 
    465 	// Emit a vendor event.
    466 	dc_event_vendor_t vendor;
    467 	vendor.data = packet;
    468 	vendor.size = commands->id.size;
    469 	device_event_emit (abstract, DC_EVENT_VENDOR, &vendor);
    470 
    471 	if (ISIX3M(device->model)) {
    472 		// Detect the APOS4 firmware.
    473 		unsigned int apos4 = (devinfo.firmware / 10000000) >= 4;
    474 		if (apos4) {
    475 			commands = &ix3m_apos4;
    476 		}
    477 	}
    478 
    479 	unsigned char cmd_range[] = {commands->range.cmd, 0x8D};
    480 	rc = divesystem_idive_transfer (device, cmd_range, sizeof(cmd_range), packet, commands->range.size, &errcode);
    481 	if (rc != DC_STATUS_SUCCESS) {
    482 		if (errcode == ERR_UNAVAILABLE) {
    483 			return DC_STATUS_SUCCESS; // No dives found.
    484 		} else {
    485 			return rc;
    486 		}
    487 	}
    488 
    489 	// Get the range of the available dive numbers.
    490 	unsigned int first = array_uint16_le (packet + 0);
    491 	unsigned int last  = array_uint16_le (packet + 2);
    492 	if (first > last) {
    493 		ERROR(abstract->context, "Invalid dive numbers.");
    494 		return DC_STATUS_DATAFORMAT;
    495 	}
    496 
    497 	// Calculate the number of dives.
    498 	unsigned int ndives = last - first + 1;
    499 
    500 	// Update and emit a progress event.
    501 	progress.maximum = ndives * NSTEPS;
    502 	device_event_emit (abstract, DC_EVENT_PROGRESS, &progress);
    503 
    504 	dc_buffer_t *buffer = dc_buffer_new(0);
    505 	if (buffer == NULL) {
    506 		return DC_STATUS_NOMEMORY;
    507 	}
    508 
    509 	for (unsigned int i = 0; i < ndives; ++i) {
    510 		unsigned int number = last - i;
    511 		unsigned char cmd_header[] = {commands->header.cmd,
    512 			(number     ) & 0xFF,
    513 			(number >> 8) & 0xFF};
    514 		rc = divesystem_idive_transfer (device, cmd_header, sizeof(cmd_header), packet, commands->header.size, &errcode);
    515 		if (rc != DC_STATUS_SUCCESS) {
    516 			if (errcode == ERR_UNREADABLE) {
    517 				WARNING(abstract->context, "Skipped unreadable dive!");
    518 				continue;
    519 			} else {
    520 				dc_buffer_free(buffer);
    521 				return rc;
    522 			}
    523 		}
    524 
    525 		if (memcmp(packet + 7, device->fingerprint, sizeof(device->fingerprint)) == 0)
    526 			break;
    527 
    528 		unsigned int nsamples = array_uint16_le (packet + 1);
    529 
    530 		// Update and emit a progress event.
    531 		progress.current = i * NSTEPS + STEP(1, nsamples + 1);
    532 		device_event_emit (abstract, DC_EVENT_PROGRESS, &progress);
    533 
    534 		dc_buffer_clear(buffer);
    535 		dc_buffer_reserve(buffer, commands->header.size + commands->sample.size * nsamples);
    536 
    537 		if (!dc_buffer_append(buffer, packet, commands->header.size)) {
    538 			ERROR (abstract->context, "Insufficient buffer space available.");
    539 			dc_buffer_free(buffer);
    540 			return DC_STATUS_NOMEMORY;
    541 		}
    542 
    543 		for (unsigned int j = 0; j < nsamples; j += commands->nsamples) {
    544 			unsigned int idx = j + 1;
    545 			unsigned char cmd_sample[] = {commands->sample.cmd,
    546 				(idx     ) & 0xFF,
    547 				(idx >> 8) & 0xFF};
    548 			rc = divesystem_idive_transfer (device, cmd_sample, sizeof(cmd_sample), packet, commands->sample.size * commands->nsamples, &errcode);
    549 			if (rc != DC_STATUS_SUCCESS) {
    550 				dc_buffer_free(buffer);
    551 				return rc;
    552 			}
    553 
    554 			// If the number of samples is not an exact multiple of the
    555 			// number of samples per packet, then the last packet
    556 			// appears to contain garbage data. Ignore those samples.
    557 			unsigned int n = commands->nsamples;
    558 			if (j + n > nsamples) {
    559 				n = nsamples - j;
    560 			}
    561 
    562 			// Update and emit a progress event.
    563 			progress.current = i * NSTEPS + STEP(j + n + 1, nsamples + 1);
    564 			device_event_emit (abstract, DC_EVENT_PROGRESS, &progress);
    565 
    566 			if (!dc_buffer_append(buffer, packet, commands->sample.size * n)) {
    567 				ERROR (abstract->context, "Insufficient buffer space available.");
    568 				dc_buffer_free(buffer);
    569 				return DC_STATUS_NOMEMORY;
    570 			}
    571 		}
    572 
    573 		unsigned char *data = dc_buffer_get_data(buffer);
    574 		unsigned int   size = dc_buffer_get_size(buffer);
    575 		if (callback && !callback (data, size, data + 7, sizeof(device->fingerprint), userdata)) {
    576 			dc_buffer_free (buffer);
    577 			return DC_STATUS_SUCCESS;
    578 		}
    579 	}
    580 
    581 	dc_buffer_free(buffer);
    582 
    583 	return DC_STATUS_SUCCESS;
    584 }
    585 
    586 static dc_status_t
    587 divesystem_idive_device_timesync (dc_device_t *abstract, const dc_datetime_t *datetime)
    588 {
    589 	dc_status_t rc = DC_STATUS_SUCCESS;
    590 	divesystem_idive_device_t *device = (divesystem_idive_device_t *) abstract;
    591 	unsigned int errcode = 0;
    592 
    593 	static const signed char tz_array[] = {
    594 		-12,  0,    /* UTC-12    */
    595 		-11,  0,    /* UTC-11    */
    596 		-10,  0,    /* UTC-10    */
    597 		 -9, 30,    /* UTC-9:30  */
    598 		 -9,  0,    /* UTC-9     */
    599 		 -8,  0,    /* UTC-8     */
    600 		 -7,  0,    /* UTC-7     */
    601 		 -6,  0,    /* UTC-6     */
    602 		 -5,  0,    /* UTC-5     */
    603 		 -4, 30,    /* UTC-4:30  */
    604 		 -4,  0,    /* UTC-4     */
    605 		 -3, 30,    /* UTC-3:30  */
    606 		 -3,  0,    /* UTC-3     */
    607 		 -2,  0,    /* UTC-2     */
    608 		 -1,  0,    /* UTC-1     */
    609 		  0,  0,    /* UTC       */
    610 		  1,  0,    /* UTC+1     */
    611 		  2,  0,    /* UTC+2     */
    612 		  3,  0,    /* UTC+3     */
    613 		  3, 30,    /* UTC+3:30  */
    614 		  4,  0,    /* UTC+4     */
    615 		  4, 30,    /* UTC+4:30  */
    616 		  5,  0,    /* UTC+5     */
    617 		  5, 30,    /* UTC+5:30  */
    618 		  5, 45,    /* UTC+5:45  */
    619 		  6,  0,    /* UTC+6     */
    620 		  6, 30,    /* UTC+6:30  */
    621 		  7,  0,    /* UTC+7     */
    622 		  8,  0,    /* UTC+8     */
    623 		  8, 45,    /* UTC+8:45  */
    624 		  9,  0,    /* UTC+9     */
    625 		  9, 30,    /* UTC+9:30  */
    626 		  9, 45,    /* UTC+9:45  */
    627 		 10,  0,    /* UTC+10    */
    628 		 10, 30,    /* UTC+10:30 */
    629 		 11,  0,    /* UTC+11    */
    630 		 11, 30,    /* UTC+11:30 */
    631 		 12,  0,    /* UTC+12    */
    632 		 12, 45,    /* UTC+12:45 */
    633 		 13,  0,    /* UTC+13    */
    634 		 13, 45,    /* UTC+13:45 */
    635 		 14,  0     /* UTC+14    */
    636 	};
    637 
    638 	if (!ISIX3M(device->model)) {
    639 		return DC_STATUS_UNSUPPORTED;
    640 	}
    641 
    642 	// Get the UTC timestamp.
    643 	dc_ticks_t timestamp = dc_datetime_mktime(datetime);
    644 	if (timestamp == -1) {
    645 		ERROR (abstract->context, "Invalid date/time value specified.");
    646 		return DC_STATUS_INVALIDARGS;
    647 	}
    648 
    649 	// Adjust the epoch.
    650 	timestamp -= EPOCH;
    651 
    652 	// UTC offset.
    653 	int tz_offset = datetime->timezone != DC_TIMEZONE_NONE ?
    654 		datetime->timezone : 0;
    655 
    656 	// Find the timezone index.
    657 	size_t tz_idx = C_ARRAY_SIZE(tz_array);
    658 	for (size_t i = 0; i < C_ARRAY_SIZE(tz_array); i += 2) {
    659 		int timezone = tz_array[i] * 3600;
    660 		if (timezone < 0) {
    661 			timezone -= tz_array[i + 1] * 60;
    662 		} else {
    663 			timezone += tz_array[i + 1] * 60;
    664 		}
    665 
    666 		if (timezone == tz_offset) {
    667 			tz_idx = i;
    668 			break;
    669 		}
    670 	}
    671 	if (tz_idx >= C_ARRAY_SIZE(tz_array)) {
    672 		ERROR (abstract->context, "Invalid timezone value specified.");
    673 		return DC_STATUS_INVALIDARGS;
    674 	}
    675 
    676 	// Adjust the timezone index.
    677 	tz_idx /= 2;
    678 
    679 	// Send the command.
    680 	unsigned char command[] = {
    681 		CMD_IX3M_TIMESYNC,
    682 		(timestamp >>  0) & 0xFF,
    683 		(timestamp >>  8) & 0xFF,
    684 		(timestamp >> 16) & 0xFF,
    685 		(timestamp >> 24) & 0xFF,
    686 		tz_idx,            // Home timezone
    687 		TZ_IDX_UNCHANGED}; // Travel timezone
    688 	rc = divesystem_idive_transfer (device, command, sizeof(command), NULL, 0, &errcode);
    689 	if (rc != DC_STATUS_SUCCESS) {
    690 		if (errcode == ERR_INVALID_LENGTH || errcode == ERR_INVALID_DATA) {
    691 			// Fallback to the variant without the second timezone if the
    692 			// firmware doesn't support two timezones (ERR_INVALID_LENGTH) or
    693 			// leaving the timezone unchanged (ERR_INVALID_DATA).
    694 			rc = divesystem_idive_transfer (device, command, sizeof(command) - 1, NULL, 0, &errcode);
    695 			if (rc != DC_STATUS_SUCCESS) {
    696 				return rc;
    697 			}
    698 		} else {
    699 			return rc;
    700 		}
    701 	}
    702 
    703 	return DC_STATUS_SUCCESS;
    704 }
    705 
    706 static dc_status_t
    707 divesystem_idive_firmware_readfile (dc_buffer_t *buffer, dc_context_t *context, const char *filename)
    708 {
    709 	dc_status_t status = DC_STATUS_SUCCESS;
    710 	dc_buffer_t *tmp = NULL;
    711 	FILE *fp = NULL;
    712 
    713 	if (!dc_buffer_clear (buffer)) {
    714 		ERROR (context, "Invalid arguments.");
    715 		return DC_STATUS_INVALIDARGS;
    716 	}
    717 
    718 	// Allocate a temporary buffer.
    719 	tmp = dc_buffer_new (0x20000);
    720 	if (tmp == NULL) {
    721 		ERROR (context, "Failed to allocate memory.");
    722 		status = DC_STATUS_NOMEMORY;
    723 		goto error_exit;
    724 	}
    725 
    726 	// Open the file.
    727 	fp = fopen (filename, "rb");
    728 	if (fp == NULL) {
    729 		ERROR (context, "Failed to open the file.");
    730 		status = DC_STATUS_IO;
    731 		goto error_free;
    732 	}
    733 
    734 	// Read the entire file into the buffer.
    735 	size_t n = 0;
    736 	unsigned char block[4096] = {0};
    737 	while ((n = fread (block, 1, sizeof (block), fp)) > 0) {
    738 		if (!dc_buffer_append (tmp, block, n)) {
    739 			ERROR (context, "Insufficient buffer space available.");
    740 			status = DC_STATUS_NOMEMORY;
    741 			goto error_close;
    742 		}
    743 	}
    744 
    745 	// Resize the output buffer.
    746 	size_t nbytes = dc_buffer_get_size (tmp);
    747 	if (!dc_buffer_resize (buffer, nbytes / 2)) {
    748 		ERROR (context, "Insufficient buffer space available.");
    749 		status = DC_STATUS_NOMEMORY;
    750 		goto error_close;
    751 	}
    752 
    753 	// Convert to binary data.
    754 	int rc = array_convert_hex2bin (
    755 		dc_buffer_get_data (tmp), dc_buffer_get_size (tmp),
    756 		dc_buffer_get_data (buffer), dc_buffer_get_size (buffer));
    757 	if (rc != 0) {
    758 		ERROR (context, "Unexpected data format.");
    759 		status = DC_STATUS_DATAFORMAT;
    760 		goto error_close;
    761 	}
    762 
    763 error_close:
    764 	fclose (fp);
    765 error_free:
    766 	dc_buffer_free (tmp);
    767 error_exit:
    768 	return status;
    769 }
    770 
    771 static dc_status_t
    772 divesystem_idive_firmware_send (divesystem_idive_device_t *device, const divesystem_idive_signature_t *signature, const unsigned char data[], size_t size)
    773 {
    774 	dc_status_t status = DC_STATUS_SUCCESS;
    775 	dc_device_t *abstract = (dc_device_t *) device;
    776 
    777 	unsigned int nretries = 0;
    778 	while (1) {
    779 		// Send the frame.
    780 		status = dc_iostream_write (device->iostream, data, size, NULL);
    781 		if (status != DC_STATUS_SUCCESS) {
    782 			ERROR (abstract->context, "Failed to send the frame.");
    783 			return status;
    784 		}
    785 
    786 		// Read the response until an ACK or NAK byte is received.
    787 		unsigned int state = 0;
    788 		while (state == 0) {
    789 			// Receive the response.
    790 			unsigned char response = 0;
    791 			status = dc_iostream_read (device->iostream, &response, 1, NULL);
    792 			if (status != DC_STATUS_SUCCESS) {
    793 				ERROR (abstract->context, "Failed to receive the response.");
    794 				return status;
    795 			}
    796 
    797 			// Process the response.
    798 			switch (response) {
    799 			case ACK:
    800 			case NAK:
    801 				state = response;
    802 				break;
    803 			case WAIT:
    804 				dc_iostream_sleep (device->iostream, signature->delay);
    805 				break;
    806 			case 'A':
    807 			case 'B':
    808 			case 'C':
    809 			case 'D':
    810 			case 'E':
    811 			case 'F':
    812 			case 'G':
    813 			case 'H':
    814 			case 'K':
    815 			case 'X':
    816 				break;
    817 			default:
    818 				WARNING (abstract->context, "Unexpected response byte received (%02x)", response);
    819 				break;
    820 			}
    821 		}
    822 
    823 		// Exit if ACK received.
    824 		if (state == ACK)
    825 			break;
    826 
    827 		// Abort if the maximum number of retries is reached.
    828 		if (nretries++ >= MAXRETRIES) {
    829 			ERROR (abstract->context, "Maximum number of retries reached.");
    830 			return DC_STATUS_PROTOCOL;
    831 		}
    832 	}
    833 
    834 	return DC_STATUS_SUCCESS;
    835 }
    836 
    837 dc_status_t
    838 divesystem_idive_device_fwupdate (dc_device_t *abstract, const char *filename)
    839 {
    840 	dc_status_t status = DC_STATUS_SUCCESS;
    841 	divesystem_idive_device_t *device = (divesystem_idive_device_t *) abstract;
    842 	unsigned int errcode = 0;
    843 
    844 	// Allocate memory for the firmware data.
    845 	dc_buffer_t *buffer = dc_buffer_new (0);
    846 	if (buffer == NULL) {
    847 		ERROR (abstract->context, "Failed to allocate memory for the firmware data.");
    848 		status = DC_STATUS_NOMEMORY;
    849 		goto error_exit;
    850 	}
    851 
    852 	// Read the firmware file.
    853 	status = divesystem_idive_firmware_readfile (buffer, abstract->context, filename);
    854 	if (status != DC_STATUS_SUCCESS) {
    855 		ERROR (abstract->context, "Failed to read the firmware file.");
    856 		goto error_free;
    857 	}
    858 
    859 	// Cache the data and size.
    860 	const unsigned char *data = dc_buffer_get_data (buffer);
    861 	size_t size = dc_buffer_get_size (buffer);
    862 
    863 	// Enable progress notifications.
    864 	dc_event_progress_t progress = EVENT_PROGRESS_INITIALIZER;
    865 	progress.maximum = size;
    866 	device_event_emit (abstract, DC_EVENT_PROGRESS, &progress);
    867 
    868 	// Activate the bootloader.
    869 	const unsigned char bootloader[] = {CMD_IX3M_BOOTLOADER, 0xC9, 0x4B};
    870 	status = divesystem_idive_transfer (device, bootloader, sizeof (bootloader), NULL, 0, &errcode);
    871 	if (status != DC_STATUS_SUCCESS) {
    872 		ERROR (abstract->context, "Failed to activate the bootloader.");
    873 		goto error_free;
    874 	}
    875 
    876 	// Give the device some time to enter the bootloader.
    877 	dc_iostream_sleep (device->iostream, 2000);
    878 
    879 	// Wait for the bootloader.
    880 	const divesystem_idive_signature_t *signature = NULL;
    881 	while (signature == NULL) {
    882 		// Discard garbage data.
    883 		dc_iostream_purge (device->iostream, DC_DIRECTION_INPUT);
    884 
    885 		// Probe for the bootloader.
    886 		const unsigned char probe[] = {BOOTLOADER_PROBE};
    887 		status = dc_iostream_write (device->iostream, probe, sizeof (probe), NULL);
    888 		if (status != DC_STATUS_SUCCESS) {
    889 			ERROR (abstract->context, "Failed to activate the bootloader.");
    890 			goto error_free;
    891 		}
    892 
    893 		// Read the signature string.
    894 		size_t n = 0;
    895 		unsigned char name[5] = {0};
    896 		status = dc_iostream_read (device->iostream, name, sizeof (name), &n);
    897 		if (status != DC_STATUS_SUCCESS && status != DC_STATUS_TIMEOUT) {
    898 			ERROR (abstract->context, "Failed to read the signature string.");
    899 			goto error_free;
    900 		}
    901 
    902 		// Verify the signature string.
    903 		for (size_t i = 0; i < C_ARRAY_SIZE (signatures); ++i) {
    904 			if (n == strlen (signatures[i].name) && memcmp (name, signatures[i].name, n) == 0) {
    905 				signature = signatures + i;
    906 				break;
    907 			}
    908 		}
    909 	}
    910 
    911 	// Send the start upload command.
    912 	const unsigned char upload[] = {BOOTLOADER_UPLOAD_A, BOOTLOADER_UPLOAD_B};
    913 	status = dc_iostream_write (device->iostream, upload, sizeof(upload), NULL);
    914 	if (status != DC_STATUS_SUCCESS) {
    915 		ERROR (abstract->context, "Failed to send the start upload command.");
    916 		goto error_free;
    917 	}
    918 
    919 	// Receive the ack.
    920 	unsigned char ack[1] = {0};
    921 	status = dc_iostream_read (device->iostream, ack, sizeof(ack), NULL);
    922 	if (status != DC_STATUS_SUCCESS) {
    923 		ERROR (abstract->context, "Failed to receive the ack byte.");
    924 		goto error_free;
    925 	}
    926 
    927 	// Verify the ack.
    928 	if (ack[0] != BOOTLOADER_ACK) {
    929 		ERROR (abstract->context, "Invalid ack byte (%02x).", ack[0]);
    930 		status = DC_STATUS_PROTOCOL;
    931 		goto error_free;
    932 	}
    933 
    934 	// Wait before sending the firmware data.
    935 	dc_iostream_sleep (device->iostream, 100);
    936 
    937 	// Upload the firmware.
    938 	unsigned int offset = 0;
    939 	while (offset + 2 <= size) {
    940 		// Get the number of bytes in the current frame.
    941 		unsigned int len = array_uint16_be (data + offset) + 2;
    942 		if (offset + len > size) {
    943 			ERROR (abstract->context, "Invalid frame size (%u %u " DC_PRINTF_SIZE ")", offset, len, size);
    944 			status = DC_STATUS_DATAFORMAT;
    945 			goto error_free;
    946 		}
    947 
    948 		// Send the frame.
    949 		status = divesystem_idive_firmware_send (device, signature, data + offset, len);
    950 		if (status != DC_STATUS_SUCCESS) {
    951 			ERROR (abstract->context, "Failed to send the frame.");
    952 			goto error_free;
    953 		}
    954 
    955 		// Update and emit a progress event.
    956 		progress.current += len;
    957 		device_event_emit (abstract, DC_EVENT_PROGRESS, &progress);
    958 
    959 		offset += len;
    960 	}
    961 
    962 error_free:
    963 	dc_buffer_free (buffer);
    964 error_exit:
    965 	return status;
    966 }