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

shearwater_common.c (21677B)


      1 /*
      2  * libdivecomputer
      3  *
      4  * Copyright (C) 2013 Jef Driesen
      5  *
      6  * This library is free software; you can redistribute it and/or
      7  * modify it under the terms of the GNU Lesser General Public
      8  * License as published by the Free Software Foundation; either
      9  * version 2.1 of the License, or (at your option) any later version.
     10  *
     11  * This library is distributed in the hope that it will be useful,
     12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
     13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
     14  * Lesser General Public License for more details.
     15  *
     16  * You should have received a copy of the GNU Lesser General Public
     17  * License along with this library; if not, write to the Free Software
     18  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
     19  * MA 02110-1301 USA
     20  */
     21 
     22 #include <string.h> // memcmp, memcpy
     23 #include <stdlib.h> // malloc, free
     24 
     25 #include "shearwater_common.h"
     26 
     27 #include "context-private.h"
     28 #include "platform.h"
     29 #include "array.h"
     30 
     31 #define BLE_MTU_MIN  20
     32 #define BLE_MTU_MAX 514
     33 
     34 // Protocol variants.
     35 #define V1 1
     36 #define V2 2
     37 
     38 // Maximum packet payload size.
     39 // The V1 protocol uses an 8 bit length field, while the V2 protocol
     40 // uses a 16 bit length field. Theoretically the V2 maximum size is
     41 // 2^16-1 bytes, but the largest observed value is much smaller (0x0202
     42 // for the manifest and 0x0902 for the dive). Allow for an extra margin
     43 // for future expansions.
     44 #define SZ_PACKET_V1  254
     45 #define SZ_PACKET_V2  4096
     46 #define SZ_PACKET_MAX SZ_PACKET_V2
     47 
     48 // SLIP special character codes
     49 #define END       0xC0
     50 #define ESC       0xDB
     51 #define ESC_END   0xDC
     52 #define ESC_ESC   0xDD
     53 
     54 #define RDBI_REQUEST  0x22
     55 #define RDBI_RESPONSE 0x62
     56 
     57 #define WDBI_REQUEST  0x2E
     58 #define WDBI_RESPONSE 0x6E
     59 
     60 #define UPLOAD_INIT_REQUEST  0x35
     61 #define UPLOAD_INIT_RESPONSE 0x75
     62 
     63 #define UPLOAD_DATA_REQUEST  0x36
     64 #define UPLOAD_DATA_RESPONSE 0x76
     65 
     66 #define UPLOAD_EXIT_REQUEST  0x37
     67 #define UPLOAD_EXIT_RESPONSE 0x77
     68 
     69 #define NAK 0x7F
     70 
     71 dc_status_t
     72 shearwater_common_setup (shearwater_common_device_t *device, dc_context_t *context, dc_iostream_t *iostream, unsigned int model)
     73 {
     74 	dc_status_t status = DC_STATUS_SUCCESS;
     75 
     76 	device->iostream = iostream;
     77 
     78 	// Set the serial communication protocol (115200 8N1).
     79 	status = dc_iostream_configure (device->iostream, 115200, 8, DC_PARITY_NONE, DC_STOPBITS_ONE, DC_FLOWCONTROL_NONE);
     80 	if (status != DC_STATUS_SUCCESS) {
     81 		ERROR (context, "Failed to set the terminal attributes.");
     82 		return status;
     83 	}
     84 
     85 	// Set the timeout for receiving data (12s).
     86 	status = dc_iostream_set_timeout (device->iostream, 12 * 1000);
     87 	if (status != DC_STATUS_SUCCESS) {
     88 		ERROR (context, "Failed to set the timeout.");
     89 		return status;
     90 	}
     91 
     92 	// Make sure everything is in a sane state.
     93 	dc_iostream_sleep (device->iostream, 300);
     94 	dc_iostream_purge (device->iostream, DC_DIRECTION_ALL);
     95 
     96 	device->protocol = (model == PERDIX3) ? V2 : V1;
     97 
     98 	return DC_STATUS_SUCCESS;
     99 }
    100 
    101 
    102 static int
    103 shearwater_common_decompress_lre (unsigned char *data, unsigned int size, dc_buffer_t *buffer, unsigned int *isfinal)
    104 {
    105 	// The RLE decompression algorithm does interpret the binary data as a
    106 	// stream of 9 bit values. Therefore, the total number of bits needs to be
    107 	// a multiple of 9 bits.
    108 	unsigned int nbits = size * 8;
    109 	if (nbits % 9 != 0)
    110 		return -1;
    111 
    112 	unsigned int offset = 0;
    113 	while (offset + 9 <= nbits) {
    114 		// Extract the 9 bit value.
    115 		unsigned int byte = offset / 8;
    116 		unsigned int bit  = offset % 8;
    117 		unsigned int shift = 16 - (bit + 9);
    118 		unsigned int value = (array_uint16_be (data + byte) >> shift) & 0x1FF;
    119 
    120 		// The 9th bit indicates whether the remaining 8 bits represent
    121 		// a run of zero bytes or not. If the bit is set, the value is
    122 		// not a run and doesn't need expansion. If the bit is not set,
    123 		// the value contains the number of zero bytes in the run. A
    124 		// zero-length run indicates the end of the compressed stream.
    125 		if (value & 0x100) {
    126 			// Append the data byte directly.
    127 			unsigned char c = value & 0xFF;
    128 			if (!dc_buffer_append (buffer, &c, 1))
    129 				return -1;
    130 		} else if (value == 0) {
    131 			// Reached the end of the compressed stream.
    132 			if (isfinal)
    133 				*isfinal = 1;
    134 			break;
    135 		} else {
    136 			// Expand the run with zero bytes.
    137 			if (!dc_buffer_resize (buffer, dc_buffer_get_size (buffer) + value))
    138 				return -1;
    139 		}
    140 
    141 		offset += 9;
    142 	}
    143 
    144 	return 0;
    145 }
    146 
    147 
    148 static int
    149 shearwater_common_decompress_xor (unsigned char *data, unsigned int size)
    150 {
    151 	// Each block of 32 bytes is XOR'ed (in-place) with the previous block,
    152 	// except for the first block, which is passed through unchanged.
    153 	for (unsigned int i = 32; i < size; ++i) {
    154 		data[i] ^= data[i - 32];
    155 	}
    156 
    157 	return 0;
    158 }
    159 
    160 static dc_status_t
    161 shearwater_common_slip_write (shearwater_common_device_t *device, const unsigned char data[], unsigned int size)
    162 {
    163 	dc_status_t status = DC_STATUS_SUCCESS;
    164 	dc_transport_t transport = dc_iostream_get_transport(device->iostream);
    165 	const unsigned int header = transport == DC_TRANSPORT_BLE && device->protocol != V2;
    166 	unsigned char buffer[BLE_MTU_MIN];
    167 	unsigned int nbytes = 0;
    168 
    169 	if (header) {
    170 		// Calculate the total number of bytes.
    171 		unsigned int count = 1;
    172 		for (unsigned int i = 0; i < size; ++i) {
    173 			unsigned char c = data[i];
    174 			if (c == END || c == ESC) {
    175 				count += 2;
    176 			} else {
    177 				count++;
    178 			}
    179 		}
    180 
    181 		// Calculate the total number of frames.
    182 		unsigned int nframes = (count + sizeof(buffer) - 1) / sizeof(buffer);
    183 
    184 		buffer[0] = nframes;
    185 		buffer[1] = 0;
    186 		nbytes = 2;
    187 	}
    188 
    189 	for (unsigned int i = 0; i < size; ++i) {
    190 		unsigned char c = data[i];
    191 
    192 		if (c == END || c == ESC) {
    193 			// Append the escape character.
    194 			buffer[nbytes++] = ESC;
    195 
    196 			// Flush the buffer if necessary.
    197 			if (nbytes >= sizeof(buffer)) {
    198 				status = dc_iostream_write (device->iostream, buffer, nbytes, NULL);
    199 				if (status != DC_STATUS_SUCCESS) {
    200 					ERROR (device->base.context, "Failed to send the packet.");
    201 					return status;
    202 				}
    203 
    204 				if (header) {
    205 					buffer[1]++;
    206 					nbytes = 2;
    207 				} else {
    208 					nbytes = 0;
    209 				}
    210 			}
    211 
    212 			// Escape the character.
    213 			if (c == END) {
    214 				c = ESC_END;
    215 			} else {
    216 				c = ESC_ESC;
    217 			}
    218 		}
    219 
    220 		// Append the character.
    221 		buffer[nbytes++] = c;
    222 
    223 		// Flush the buffer if necessary.
    224 		if (nbytes >= sizeof(buffer)) {
    225 			status = dc_iostream_write (device->iostream, buffer, nbytes, NULL);
    226 			if (status != DC_STATUS_SUCCESS) {
    227 				ERROR (device->base.context, "Failed to send the packet.");
    228 				return status;
    229 			}
    230 
    231 			if (header) {
    232 				buffer[1]++;
    233 				nbytes = 2;
    234 			} else {
    235 				nbytes = 0;
    236 			}
    237 		}
    238 	}
    239 
    240 	// Append the END character to indicate the end of the packet.
    241 	buffer[nbytes++] = END;
    242 
    243 	// Flush the buffer.
    244 	status = dc_iostream_write (device->iostream, buffer, nbytes, NULL);
    245 	if (status != DC_STATUS_SUCCESS) {
    246 		ERROR (device->base.context, "Failed to send the packet.");
    247 		return status;
    248 	}
    249 
    250 	return DC_STATUS_SUCCESS;
    251 }
    252 
    253 
    254 static dc_status_t
    255 shearwater_common_slip_read (shearwater_common_device_t *device, unsigned char data[], unsigned int size, unsigned int *actual)
    256 {
    257 	dc_status_t status = DC_STATUS_SUCCESS;
    258 	dc_transport_t transport = dc_iostream_get_transport(device->iostream);
    259 	const unsigned int header = transport == DC_TRANSPORT_BLE && device->protocol != V2;
    260 	unsigned char buffer[BLE_MTU_MAX];
    261 	unsigned int escaped = 0;
    262 	unsigned int nbytes = 0;
    263 
    264 	// Get the packet size.
    265 	size_t packetsize = (transport == DC_TRANSPORT_BLE) ? sizeof(buffer) : 1;
    266 
    267 	// Read bytes until a complete packet has been received. If the
    268 	// buffer runs out of space, bytes are dropped. The caller can
    269 	// detect this condition because the return value will be larger
    270 	// than the supplied buffer size.
    271 	while (1) {
    272 		size_t transferred = 0;
    273 		status = dc_iostream_read (device->iostream, buffer, packetsize, &transferred);
    274 		if (status != DC_STATUS_SUCCESS) {
    275 			ERROR (device->base.context, "Failed to receive the packet.");
    276 			return status;
    277 		}
    278 
    279 		size_t offset = 0;
    280 		if (header) {
    281 			if (transferred < 2) {
    282 				ERROR (device->base.context, "Invalid packet length (" DC_PRINTF_SIZE ").", transferred);
    283 				return DC_STATUS_PROTOCOL;
    284 			}
    285 
    286 			offset = 2;
    287 		}
    288 
    289 		for (size_t i = offset; i < transferred; ++i) {
    290 			unsigned char c = buffer[i];
    291 
    292 			if (c == END || c == ESC) {
    293 				if (escaped) {
    294 					// If the END or ESC characters are escaped, then we
    295 					// have a protocol violation, and an error is reported.
    296 					ERROR (device->base.context, "SLIP frame escaped the special character %02x.", c);
    297 					return DC_STATUS_PROTOCOL;
    298 				}
    299 
    300 				if (c == END) {
    301 					// If it's an END character then we're done.
    302 					// As a minor optimization, empty packets are ignored. This
    303 					// is to avoid bothering the upper layers with all the empty
    304 					// packets generated by the duplicate END characters which
    305 					// are sent to try to detect line noise.
    306 					if (nbytes) {
    307 						goto done;
    308 					}
    309 				} else {
    310 					// If it's an ESC character, get another character and then
    311 					// figure out what to store in the packet based on that.
    312 					escaped = 1;
    313 				}
    314 
    315 				continue;
    316 			}
    317 
    318 			if (escaped) {
    319 				// If it's not one of the two escaped characters, then we
    320 				// have a protocol violation. The best bet seems to be to
    321 				// leave the byte alone and just stuff it into the packet.
    322 				switch (c) {
    323 				case ESC_END:
    324 					c = END;
    325 					break;
    326 				case ESC_ESC:
    327 					c = ESC;
    328 					break;
    329 				default:
    330 					break;
    331 				}
    332 
    333 				escaped = 0;
    334 			}
    335 
    336 			if (nbytes < size)
    337 				data[nbytes] = c;
    338 			nbytes++;
    339 		}
    340 	}
    341 
    342 done:
    343 
    344 	if (nbytes > size) {
    345 		ERROR (device->base.context, "Insufficient buffer space available.");
    346 		return DC_STATUS_PROTOCOL;
    347 	}
    348 
    349 	if (actual)
    350 		*actual = nbytes;
    351 
    352 	return status;
    353 }
    354 
    355 
    356 dc_status_t
    357 shearwater_common_transfer (shearwater_common_device_t *device, const unsigned char input[], unsigned int isize, unsigned char output[], unsigned int osize, unsigned int *actual)
    358 {
    359 	dc_status_t status = DC_STATUS_SUCCESS;
    360 	dc_device_t *abstract = (dc_device_t *) device;
    361 	const unsigned int maxpacket = (device->protocol == V2) ? SZ_PACKET_V2 : SZ_PACKET_V1;
    362 	const unsigned int headerlen = (device->protocol == V2) ? 5 : 4;
    363 	unsigned char packet[SZ_PACKET_MAX + 5];
    364 	unsigned int n = 0;
    365 
    366 	if (isize > maxpacket || osize > maxpacket)
    367 		return DC_STATUS_INVALIDARGS;
    368 
    369 	if (device_is_cancelled (abstract))
    370 		return DC_STATUS_CANCELLED;
    371 
    372 	// Setup the request packet.
    373 	packet[0] = 0xFF;
    374 	packet[1] = 0x01;
    375 	if (device->protocol == V2) {
    376 		// FF 01 00 [len_hi] [len_lo] <payload>
    377 		packet[2] = 0x00;
    378 		array_uint16_be_set (packet + 3, isize);
    379 	} else {
    380 		// FF 01 [len+1] 00 <payload>
    381 		packet[2] = isize + 1;
    382 		packet[3] = 0x00;
    383 	}
    384 	memcpy (packet + headerlen, input, isize);
    385 
    386 	// Send the request packet.
    387 	status = shearwater_common_slip_write (device, packet, isize + headerlen);
    388 	if (status != DC_STATUS_SUCCESS) {
    389 		ERROR (abstract->context, "Failed to send the request packet.");
    390 		return status;
    391 	}
    392 
    393 	// Return early if no response packet is requested.
    394 	if (osize == 0) {
    395 		if (actual)
    396 			*actual = 0;
    397 		return DC_STATUS_SUCCESS;
    398 	}
    399 
    400 	// Receive the response packet.
    401 	status = shearwater_common_slip_read (device, packet, sizeof (packet), &n);
    402 	if (status != DC_STATUS_SUCCESS) {
    403 		ERROR (abstract->context, "Failed to receive the response packet.");
    404 		return status;
    405 	}
    406 
    407 	// Validate the packet header.
    408 	unsigned int idx = (device->protocol == V2) ? 2 : 3;
    409 	if (n < headerlen || packet[0] != 0x01 || packet[1] != 0xFF || packet[idx] != 0x00) {
    410 		ERROR (abstract->context, "Invalid packet header.");
    411 		return DC_STATUS_PROTOCOL;
    412 	}
    413 
    414 	// Validate the packet length.
    415 	unsigned int length = 0;
    416 	if (device->protocol == V2) {
    417 		length = array_uint16_be (packet + 3);
    418 	} else {
    419 		length = packet[2];
    420 		if (length < 1) {
    421 			ERROR (abstract->context, "Invalid packet header.");
    422 			return DC_STATUS_PROTOCOL;
    423 		}
    424 
    425 		length -= 1;
    426 	}
    427 	if (length + headerlen != n || length > osize) {
    428 		ERROR (abstract->context, "Invalid packet header.");
    429 		return DC_STATUS_PROTOCOL;
    430 	}
    431 
    432 	memcpy (output, packet + headerlen, length);
    433 	if (actual)
    434 		*actual = length;
    435 
    436 	return DC_STATUS_SUCCESS;
    437 }
    438 
    439 
    440 dc_status_t
    441 shearwater_common_download (shearwater_common_device_t *device, dc_buffer_t *buffer, unsigned int address, unsigned int size, unsigned int compression, dc_event_progress_t *progress)
    442 {
    443 	dc_device_t *abstract = (dc_device_t *) device;
    444 	dc_status_t rc = DC_STATUS_SUCCESS;
    445 	const unsigned int maxpacket = (device->protocol == V2) ? SZ_PACKET_V2 : SZ_PACKET_V1;
    446 	unsigned char response[SZ_PACKET_MAX];
    447 	unsigned int n = 0;
    448 
    449 	unsigned char req_init[] = {
    450 		UPLOAD_INIT_REQUEST,
    451 		(compression ? 0x10 : 0x00),
    452 		0x34,
    453 		(address >> 24) & 0xFF,
    454 		(address >> 16) & 0xFF,
    455 		(address >>  8) & 0xFF,
    456 		(address      ) & 0xFF,
    457 		(size >> 16) & 0xFF,
    458 		(size >>  8) & 0xFF,
    459 		(size      ) & 0xFF};
    460 	unsigned char req_block[] = {UPLOAD_DATA_REQUEST, 0x00, 0x00};
    461 	unsigned char req_quit[] = {UPLOAD_EXIT_REQUEST};
    462 	unsigned int req_block_len = (device->protocol == V2) ?
    463 		sizeof(req_block) : sizeof(req_block) - 1;
    464 
    465 	// Erase the current contents of the buffer.
    466 	if (!dc_buffer_clear (buffer)) {
    467 		ERROR (abstract->context, "Insufficient buffer space available.");
    468 		return DC_STATUS_NOMEMORY;
    469 	}
    470 
    471 	// Enable progress notifications.
    472 	unsigned int initial = 0, current = 0, maximum = 3 + size + 1;
    473 	if (progress) {
    474 		initial = progress->current;
    475 		device_event_emit (abstract, DC_EVENT_PROGRESS, progress);
    476 	}
    477 
    478 	// Transfer the init request.
    479 	rc = shearwater_common_transfer (device, req_init, sizeof (req_init), response, maxpacket, &n);
    480 	if (rc != DC_STATUS_SUCCESS) {
    481 		return rc;
    482 	}
    483 
    484 	// Verify the init response.
    485 	if (n < 2 || response[0] != UPLOAD_INIT_RESPONSE) {
    486 		ERROR (abstract->context, "Unexpected response packet.");
    487 		return DC_STATUS_PROTOCOL;
    488 	}
    489 
    490 	// Verify the init response length.
    491 	unsigned int len = (response[1] & 0xF0) >> 4;
    492 	if (n < len + 2 || len > 4) {
    493 		ERROR (abstract->context, "Unexpected response packet.");
    494 		return DC_STATUS_PROTOCOL;
    495 	}
    496 
    497 	// Verify the maximum packet length.
    498 	unsigned int maxlength = array_uint_be (response + 2, len);
    499 	if (maxlength > maxpacket) {
    500 		ERROR (abstract->context, "Unexpected response packet.");
    501 		return DC_STATUS_PROTOCOL;
    502 	}
    503 
    504 	// Update and emit a progress event.
    505 	if (progress) {
    506 		current += 3;
    507 		progress->current = initial + STEP (current, maximum);
    508 		device_event_emit (abstract, DC_EVENT_PROGRESS, progress);
    509 	}
    510 
    511 	unsigned int done = 0;
    512 	unsigned char block = 1;
    513 	unsigned int nbytes = 0;
    514 	while (nbytes < size && !done) {
    515 		// Transfer the block request.
    516 		req_block[1] = block;
    517 		rc = shearwater_common_transfer (device, req_block, req_block_len, response, maxpacket, &n);
    518 		if (rc != DC_STATUS_SUCCESS) {
    519 			return rc;
    520 		}
    521 
    522 		// Verify the block header.
    523 		if (n < 2 || response[0] != UPLOAD_DATA_RESPONSE || response[1] != block) {
    524 			ERROR (abstract->context, "Unexpected response packet.");
    525 			return DC_STATUS_PROTOCOL;
    526 		}
    527 
    528 		// Verify the block length.
    529 		unsigned int length = n - 2;
    530 		if (nbytes + length > size) {
    531 			ERROR (abstract->context, "Unexpected packet size.");
    532 			return DC_STATUS_PROTOCOL;
    533 		}
    534 
    535 		// Update and emit a progress event.
    536 		if (progress) {
    537 			current += length;
    538 			progress->current = initial + STEP (current, maximum);
    539 			device_event_emit (abstract, DC_EVENT_PROGRESS, progress);
    540 		}
    541 
    542 		if (compression) {
    543 			if (shearwater_common_decompress_lre (response + 2, length, buffer, &done) != 0) {
    544 				ERROR (abstract->context, "Decompression error (LRE phase).");
    545 				return DC_STATUS_PROTOCOL;
    546 			}
    547 		} else {
    548 			if (!dc_buffer_append (buffer, response + 2, length)) {
    549 				ERROR (abstract->context, "Insufficient buffer space available.");
    550 				return DC_STATUS_PROTOCOL;
    551 			}
    552 		}
    553 
    554 		nbytes += length;
    555 		block++;
    556 	}
    557 
    558 	if (compression) {
    559 		if (shearwater_common_decompress_xor (dc_buffer_get_data (buffer), dc_buffer_get_size (buffer)) != 0) {
    560 			ERROR (abstract->context, "Decompression error (XOR phase).");
    561 			return DC_STATUS_PROTOCOL;
    562 		}
    563 	}
    564 
    565 	// Transfer the quit request.
    566 	rc = shearwater_common_transfer (device, req_quit, sizeof (req_quit), response, maxpacket, &n);
    567 	if (rc != DC_STATUS_SUCCESS) {
    568 		return rc;
    569 	}
    570 
    571 	// Verify the quit response.
    572 	if (n != 2 || response[0] != UPLOAD_EXIT_RESPONSE || response[1] != 0x00) {
    573 		ERROR (abstract->context, "Unexpected response packet.");
    574 		return DC_STATUS_PROTOCOL;
    575 	}
    576 
    577 	// Update and emit a progress event.
    578 	if (progress) {
    579 		current += 1;
    580 		progress->current = initial + STEP (current, maximum);
    581 		device_event_emit (abstract, DC_EVENT_PROGRESS, progress);
    582 	}
    583 
    584 	return DC_STATUS_SUCCESS;
    585 }
    586 
    587 
    588 dc_status_t
    589 shearwater_common_rdbi (shearwater_common_device_t *device, unsigned int id, unsigned char data[], unsigned int size, unsigned int *actual)
    590 {
    591 	dc_status_t status = DC_STATUS_SUCCESS;
    592 	dc_device_t *abstract = (dc_device_t *) device;
    593 	const unsigned int maxpacket = (device->protocol == V2) ? SZ_PACKET_V2 : SZ_PACKET_V1;
    594 	unsigned char response[SZ_PACKET_MAX];
    595 
    596 	// Transfer the request.
    597 	unsigned int n = 0;
    598 	unsigned char request[] = {
    599 		RDBI_REQUEST,
    600 		(id >> 8) & 0xFF,
    601 		(id     ) & 0xFF};
    602 	status = shearwater_common_transfer (device, request, sizeof (request), response, maxpacket, &n);
    603 	if (status != DC_STATUS_SUCCESS) {
    604 		return status;
    605 	}
    606 
    607 	// Verify the response.
    608 	if (n < 3 || response[0] != RDBI_RESPONSE || response[1] != request[1] || response[2] != request[2]) {
    609 		if (n == 3 && response[0] == NAK && response[1] == RDBI_REQUEST) {
    610 			ERROR (abstract->context, "Received NAK packet with error code 0x%02x.", response[2]);
    611 			return DC_STATUS_UNSUPPORTED;
    612 		}
    613 		ERROR (abstract->context, "Unexpected response packet.");
    614 		return DC_STATUS_PROTOCOL;
    615 	}
    616 
    617 	unsigned int length = n - 3;
    618 
    619 	if (length > size) {
    620 		ERROR (abstract->context, "Unexpected packet size (%u bytes).", length);
    621 		return DC_STATUS_PROTOCOL;
    622 	}
    623 
    624 	if (actual == NULL) {
    625 		// Verify the actual length.
    626 		if (length != size) {
    627 			ERROR (abstract->context, "Unexpected packet size (%u bytes).", length);
    628 			return DC_STATUS_PROTOCOL;
    629 		}
    630 	} else {
    631 		// Return the actual length.
    632 		*actual = length;
    633 	}
    634 
    635 	if (length) {
    636 		memcpy (data, response + 3, length);
    637 	}
    638 
    639 	return status;
    640 }
    641 
    642 dc_status_t
    643 shearwater_common_wdbi (shearwater_common_device_t *device, unsigned int id, const unsigned char data[], unsigned int size)
    644 {
    645 	dc_status_t status = DC_STATUS_SUCCESS;
    646 	dc_device_t *abstract = (dc_device_t *) device;
    647 	const unsigned int maxpacket = (device->protocol == V2) ? SZ_PACKET_V2 : SZ_PACKET_V1;
    648 	unsigned char response[SZ_PACKET_MAX];
    649 
    650 	if (size + 3 > maxpacket) {
    651 		return DC_STATUS_INVALIDARGS;
    652 	}
    653 
    654 	// Transfer the request.
    655 	unsigned int n = 0;
    656 	unsigned char request[SZ_PACKET_MAX] = {
    657 		WDBI_REQUEST,
    658 		(id >> 8) & 0xFF,
    659 		(id     ) & 0xFF};
    660 	if (size) {
    661 		memcpy (request + 3, data, size);
    662 	}
    663 	status = shearwater_common_transfer (device, request, size + 3, response, maxpacket, &n);
    664 	if (status != DC_STATUS_SUCCESS) {
    665 		return status;
    666 	}
    667 
    668 	// Verify the response.
    669 	if (n < 3 || response[0] != WDBI_RESPONSE || response[1] != request[1] || response[2] != request[2]) {
    670 		if (n == 3 && response[0] == NAK && response[1] == WDBI_REQUEST) {
    671 			ERROR (abstract->context, "Received NAK packet with error code 0x%02x.", response[2]);
    672 			return DC_STATUS_UNSUPPORTED;
    673 		}
    674 		ERROR (abstract->context, "Unexpected response packet.");
    675 		return DC_STATUS_PROTOCOL;
    676 	}
    677 
    678 	return status;
    679 }
    680 
    681 dc_status_t
    682 shearwater_common_timesync_local (shearwater_common_device_t *device, const dc_datetime_t *datetime)
    683 {
    684 	dc_status_t status = DC_STATUS_SUCCESS;
    685 	dc_device_t *abstract = (dc_device_t *) device;
    686 
    687 	// Convert to local time.
    688 	dc_datetime_t local = *datetime;
    689 	local.timezone = DC_TIMEZONE_NONE;
    690 
    691 	dc_ticks_t ticks = dc_datetime_mktime (&local);
    692 	if (ticks == -1) {
    693 		ERROR (abstract->context, "Invalid date/time value specified.");
    694 		return DC_STATUS_INVALIDARGS;
    695 	}
    696 
    697 	const unsigned char timestamp[] = {
    698 		(ticks >> 24) & 0xFF,
    699 		(ticks >> 16) & 0xFF,
    700 		(ticks >>  8) & 0xFF,
    701 		(ticks      ) & 0xFF,
    702 	};
    703 
    704 	status = shearwater_common_wdbi (device, ID_TIME_LOCAL, timestamp, sizeof(timestamp));
    705 	if (status != DC_STATUS_SUCCESS) {
    706 		ERROR (abstract->context, "Failed to write the dive computer local time.");
    707 		return status;
    708 	}
    709 
    710 	return status;
    711 }
    712 
    713 dc_status_t
    714 shearwater_common_timesync_utc (shearwater_common_device_t *device, const dc_datetime_t *datetime)
    715 {
    716 	dc_status_t status = DC_STATUS_SUCCESS;
    717 	dc_device_t *abstract = (dc_device_t *) device;
    718 
    719 	// Convert to UTC time.
    720 	dc_ticks_t ticks = dc_datetime_mktime (datetime);
    721 	if (ticks == -1) {
    722 		ERROR (abstract->context, "Invalid date/time value specified.");
    723 		return DC_STATUS_INVALIDARGS;
    724 	}
    725 
    726 	const unsigned char timestamp[] = {
    727 		(ticks >> 24) & 0xFF,
    728 		(ticks >> 16) & 0xFF,
    729 		(ticks >>  8) & 0xFF,
    730 		(ticks      ) & 0xFF,
    731 	};
    732 
    733 	status = shearwater_common_wdbi (device, ID_TIME_UTC, timestamp, sizeof(timestamp));
    734 	if (status != DC_STATUS_SUCCESS) {
    735 		ERROR (abstract->context, "Failed to write the dive computer UTC time.");
    736 		return status;
    737 	}
    738 
    739 	int timezone = datetime->timezone / 60;
    740 	const unsigned char offset[] = {
    741 		(timezone >> 24) & 0xFF,
    742 		(timezone >> 16) & 0xFF,
    743 		(timezone >>  8) & 0xFF,
    744 		(timezone      ) & 0xFF,
    745 	};
    746 
    747 	status = shearwater_common_wdbi (device, ID_TIME_OFFSET, offset, sizeof (offset));
    748 	if (status != DC_STATUS_SUCCESS) {
    749 		ERROR (abstract->context, "Failed to write the dive computer timezone offset.");
    750 		return status;
    751 	}
    752 
    753 	// We don't have a way to determine the daylight savings time setting,
    754 	// but the required offset is already factored into the timezone offset.
    755 	const unsigned char dst[] = {0, 0, 0, 0};
    756 
    757 	status = shearwater_common_wdbi (device, ID_TIME_DST, dst, sizeof (dst));
    758 	if (status != DC_STATUS_SUCCESS) {
    759 		ERROR (abstract->context, "Failed to write the dive computer DST setting.");
    760 		return status;
    761 	}
    762 
    763 	return status;
    764 }