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

tecdiving_divecomputereu.c (16143B)


      1 /*
      2  * libdivecomputer
      3  *
      4  * Copyright (C) 2018 Jef Driesen
      5  *
      6  * This library is free software; you can redistribute it and/or
      7  * modify it under the terms of the GNU Lesser General Public
      8  * License as published by the Free Software Foundation; either
      9  * version 2.1 of the License, or (at your option) any later version.
     10  *
     11  * This library is distributed in the hope that it will be useful,
     12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
     13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
     14  * Lesser General Public License for more details.
     15  *
     16  * You should have received a copy of the GNU Lesser General Public
     17  * License along with this library; if not, write to the Free Software
     18  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
     19  * MA 02110-1301 USA
     20  */
     21 
     22 #include <string.h> // memcmp, memcpy
     23 #include <stdlib.h> // malloc, free
     24 
     25 #include "tecdiving_divecomputereu.h"
     26 #include "context-private.h"
     27 #include "device-private.h"
     28 #include "array.h"
     29 
     30 #define ISINSTANCE(device) dc_device_isinstance((device), &tecdiving_divecomputereu_device_vtable)
     31 
     32 #define MAXRETRIES  14
     33 
     34 #define STX         0x7E
     35 
     36 #define CMD_INIT    0x53
     37 #define CMD_LIST    0x57
     38 #define CMD_DIVE    0x58
     39 #define CMD_EXIT    0x59
     40 
     41 #define RSP_INIT    0x56
     42 #define RSP_LIST    CMD_LIST
     43 #define RSP_HEADER  0x51
     44 #define RSP_PROFILE 0x52
     45 
     46 #define SZ_MAXCMD   2
     47 #define SZ_SUMMARY  7
     48 #define SZ_SAMPLE   8
     49 #define SZ_INIT     56
     50 #define SZ_LIST     (2 + 0x10000 * SZ_SUMMARY)
     51 #define SZ_HEADER   100
     52 #define SZ_PROFILE  (1000 * SZ_SAMPLE)
     53 
     54 #define NSTEPS    1000
     55 #define STEP(i,n) (NSTEPS * (i) / (n))
     56 
     57 typedef struct tecdiving_divecomputereu_device_t {
     58 	dc_device_t base;
     59 	dc_iostream_t *iostream;
     60 	unsigned char fingerprint[SZ_SUMMARY];
     61 	unsigned char version[SZ_INIT];
     62 } tecdiving_divecomputereu_device_t;
     63 
     64 static dc_status_t tecdiving_divecomputereu_device_set_fingerprint (dc_device_t *abstract, const unsigned char data[], unsigned int size);
     65 static dc_status_t tecdiving_divecomputereu_device_foreach (dc_device_t *abstract, dc_dive_callback_t callback, void *userdata);
     66 static dc_status_t tecdiving_divecomputereu_device_close (dc_device_t *abstract);
     67 
     68 static const dc_device_vtable_t tecdiving_divecomputereu_device_vtable = {
     69 	sizeof(tecdiving_divecomputereu_device_t),
     70 	DC_FAMILY_TECDIVING_DIVECOMPUTEREU,
     71 	tecdiving_divecomputereu_device_set_fingerprint, /* set_fingerprint */
     72 	NULL, /* read */
     73 	NULL, /* write */
     74 	NULL, /* dump */
     75 	tecdiving_divecomputereu_device_foreach, /* foreach */
     76 	NULL, /* timesync */
     77 	tecdiving_divecomputereu_device_close, /* close */
     78 };
     79 
     80 static unsigned short
     81 checksum_crc (const unsigned char data[], unsigned int size, unsigned short init)
     82 {
     83 	unsigned short crc = init;
     84 	for (unsigned int i = 0; i < size; ++i) {
     85 		crc ^= data[i] << 8;
     86 		if (crc & 0x8000) {
     87 			crc <<= 1;
     88 			crc ^= 0x1021;
     89 		} else {
     90 			crc <<= 1;
     91 		}
     92 	}
     93 
     94 	return crc;
     95 }
     96 
     97 static dc_status_t
     98 tecdiving_divecomputereu_send (tecdiving_divecomputereu_device_t *device, unsigned char cmd, const unsigned char data[], size_t size)
     99 {
    100 	dc_status_t status = DC_STATUS_SUCCESS;
    101 	dc_device_t *abstract = (dc_device_t *) device;
    102 	unsigned short crc = 0;
    103 
    104 	if (device_is_cancelled (abstract))
    105 		return DC_STATUS_CANCELLED;
    106 
    107 	if (size > SZ_MAXCMD)
    108 		return DC_STATUS_INVALIDARGS;
    109 
    110 	// Setup the data packet
    111 	unsigned char packet[SZ_MAXCMD + 11] = {
    112 		STX,
    113 		0x00,
    114 		(size >>  0) & 0xFF,
    115 		(size >>  8) & 0xFF,
    116 		(size >> 16) & 0xFF,
    117 		(size >> 24) & 0xFF,
    118 		cmd,
    119 	};
    120 	if (size) {
    121 		memcpy(packet + 7, data, size);
    122 	}
    123 	crc = checksum_crc (packet + 1, size + 6, 0);
    124 	packet[size +  7] = (crc >> 8) & 0xFF;
    125 	packet[size +  8] = (crc     ) & 0xFF;
    126 	packet[size +  9] = 0x00;
    127 	packet[size + 10] = 0x00;
    128 
    129 	// Give the dive computer some extra time.
    130 	dc_iostream_sleep (device->iostream, 300);
    131 
    132 	// Send the data packet.
    133 	status = dc_iostream_write (device->iostream, packet, size + 11, NULL);
    134 	if (status != DC_STATUS_SUCCESS) {
    135 		ERROR (abstract->context, "Failed to send the command.");
    136 		return status;
    137 	}
    138 
    139 	return DC_STATUS_SUCCESS;
    140 }
    141 
    142 static dc_status_t
    143 tecdiving_divecomputereu_receive (tecdiving_divecomputereu_device_t *device, unsigned char rsp, unsigned char data[], size_t size, size_t *actual)
    144 {
    145 	dc_status_t status = DC_STATUS_SUCCESS;
    146 	dc_device_t *abstract = (dc_device_t *) device;
    147 	unsigned char header[7];
    148 	unsigned int nretries = 0;
    149 
    150 	// Read the packet start byte.
    151 	// Unfortunately it takes a relative long time, about 6-8 seconds,
    152 	// before the STX byte arrives. Hence the standard timeout of one
    153 	// second is not sufficient, and we need to retry a few times on
    154 	// timeout. The advantage over using a single read operation with a
    155 	// large timeout is that we can give the user a chance to cancel the
    156 	// operation.
    157 	while (1) {
    158 		status = dc_iostream_read (device->iostream, header + 0, 1, NULL);
    159 		if (status != DC_STATUS_SUCCESS) {
    160 			if (status != DC_STATUS_TIMEOUT) {
    161 				ERROR (abstract->context, "Failed to receive the packet start byte.");
    162 				return status;
    163 			}
    164 
    165 			// Abort if the maximum number of retries is reached.
    166 			if (nretries++ >= MAXRETRIES)
    167 				return status;
    168 
    169 			// Cancel if requested by the user.
    170 			if (device_is_cancelled (abstract))
    171 				return DC_STATUS_CANCELLED;
    172 
    173 			// Try again.
    174 			continue;
    175 		}
    176 
    177 		if (header[0] == STX)
    178 			break;
    179 
    180 		// Reset the retry counter.
    181 		nretries = 0;
    182 	}
    183 
    184 	// Read the packet header.
    185 	status = dc_iostream_read (device->iostream, header + 1, sizeof(header) - 1, NULL);
    186 	if (status != DC_STATUS_SUCCESS) {
    187 		ERROR (abstract->context, "Failed to receive the packet header.");
    188 		return status;
    189 	}
    190 
    191 	// Verify the type byte.
    192 	unsigned int type = header[1];
    193 	if (type != 0x00) {
    194 		ERROR (abstract->context, "Unexpected type byte (%02x).", type);
    195 		return DC_STATUS_PROTOCOL;
    196 	}
    197 
    198 	// Verify the length.
    199 	unsigned int length = array_uint32_le (header + 2);
    200 	if (length > size) {
    201 		ERROR (abstract->context, "Unexpected packet length (%u).", length);
    202 		return DC_STATUS_PROTOCOL;
    203 	}
    204 
    205 	// Get the command type.
    206 	unsigned int cmd = header[6];
    207 	if (cmd != rsp) {
    208 		ERROR (abstract->context, "Unexpected command byte (%02x).", cmd);
    209 		return DC_STATUS_PROTOCOL;
    210 	}
    211 
    212 	size_t nbytes = 0;
    213 	while (nbytes < length) {
    214 		// Set the maximum packet size.
    215 		size_t len = 1000;
    216 
    217 		// Limit the packet size to the total size.
    218 		if (nbytes + len > length)
    219 			len = length - nbytes;
    220 
    221 		// Read the packet payload.
    222 		status = dc_iostream_read (device->iostream, data + nbytes, len, NULL);
    223 		if (status != DC_STATUS_SUCCESS) {
    224 			ERROR (abstract->context, "Failed to receive the packet payload.");
    225 			return status;
    226 		}
    227 
    228 		nbytes += len;
    229 	}
    230 
    231 	// Read the packet checksum.
    232 	unsigned char checksum[4];
    233 	status = dc_iostream_read (device->iostream, checksum, sizeof(checksum), NULL);
    234 	if (status != DC_STATUS_SUCCESS) {
    235 		ERROR (abstract->context, "Failed to receive the packet checksum.");
    236 		return status;
    237 	}
    238 
    239 	// Verify the checksum.
    240 	unsigned short crc = array_uint16_be (checksum);
    241 	unsigned short ccrc = 0;
    242 	ccrc = checksum_crc (header + 1, sizeof(header) - 1, ccrc);
    243 	ccrc = checksum_crc (data, length, ccrc);
    244 	if (crc != ccrc || checksum[2] != 0x00 || checksum[3] != 0) {
    245 		ERROR (abstract->context, "Unexpected packet checksum.");
    246 		return DC_STATUS_PROTOCOL;
    247 	}
    248 
    249 	if (actual == NULL) {
    250 		// Verify the actual length.
    251 		if (length != size) {
    252 			ERROR (abstract->context, "Unexpected packet length (%u).", length);
    253 			return DC_STATUS_PROTOCOL;
    254 		}
    255 	} else {
    256 		// Return the actual length.
    257 		*actual = length;
    258 	}
    259 
    260 	return DC_STATUS_SUCCESS;
    261 }
    262 
    263 static dc_status_t
    264 tecdiving_divecomputereu_readdive (dc_device_t *abstract, dc_event_progress_t *progress, unsigned int idx, dc_buffer_t *buffer)
    265 {
    266 	dc_status_t status = DC_STATUS_SUCCESS;
    267 	tecdiving_divecomputereu_device_t *device = (tecdiving_divecomputereu_device_t *) abstract;
    268 
    269 	// Erase the buffer.
    270 	dc_buffer_clear (buffer);
    271 
    272 	// Encode the one based logbook ID.
    273 	unsigned int number = idx + 1;
    274 	unsigned char id[] = {
    275 		(number >> 8) & 0xFF,
    276 		(number     ) & 0xFF,
    277 	};
    278 
    279 	// Request the dive.
    280 	status = tecdiving_divecomputereu_send (device, CMD_DIVE, id, sizeof(id));
    281 	if (status != DC_STATUS_SUCCESS) {
    282 		ERROR (abstract->context, "Failed to send the dive command.");
    283 		return status;
    284 	}
    285 
    286 	// Read the dive header.
    287 	unsigned char header[SZ_HEADER];
    288 	status = tecdiving_divecomputereu_receive (device, RSP_HEADER, header, sizeof(header), NULL);
    289 	if (status != DC_STATUS_SUCCESS) {
    290 		ERROR (abstract->context, "Failed to receive the dive header.");
    291 		return status;
    292 	}
    293 
    294 	// Get the number of samples.
    295 	unsigned int nsamples = array_uint32_be (header + 36);
    296 
    297 	// Calculate the total size.
    298 	unsigned int size = sizeof(header) + nsamples * SZ_SAMPLE;
    299 
    300 	// Update and emit a progress event.
    301 	if (progress) {
    302 		progress->current = (idx + 1) * NSTEPS + STEP(sizeof(header), size);
    303 		device_event_emit (abstract, DC_EVENT_PROGRESS, progress);
    304 	}
    305 
    306 	// Allocate memory for the dive.
    307 	if (!dc_buffer_resize (buffer, size)) {
    308 		ERROR (abstract->context, "Insufficient buffer space available.");
    309 		return DC_STATUS_NOMEMORY;
    310 	}
    311 
    312 	// Cache the pointer.
    313 	unsigned char *data = dc_buffer_get_data(buffer);
    314 
    315 	// Append the header.
    316 	memcpy (data, header, sizeof(header));
    317 
    318 	unsigned int nbytes = sizeof(header);
    319 	while (nbytes < size) {
    320 		// Get the packet size. The maximum size for a single data
    321 		// packet is 1000 samples.
    322 		unsigned int len = size - nbytes;
    323 		if (len > SZ_PROFILE)
    324 			len = SZ_PROFILE;
    325 
    326 		// Read the dive samples.
    327 		status = tecdiving_divecomputereu_receive (device, RSP_PROFILE, data + nbytes, len, NULL);
    328 		if (status != DC_STATUS_SUCCESS) {
    329 			ERROR (abstract->context, "Failed to receive the dive samples.");
    330 			return status;
    331 		}
    332 
    333 		nbytes += len;
    334 
    335 		// Update and emit a progress event.
    336 		if (progress) {
    337 			progress->current = (idx + 1) * NSTEPS + STEP(nbytes, size);
    338 			device_event_emit (abstract, DC_EVENT_PROGRESS, progress);
    339 		}
    340 	}
    341 
    342 	return DC_STATUS_SUCCESS;
    343 }
    344 
    345 dc_status_t
    346 tecdiving_divecomputereu_device_open (dc_device_t **out, dc_context_t *context, dc_iostream_t *iostream)
    347 {
    348 	dc_status_t status = DC_STATUS_SUCCESS;
    349 	tecdiving_divecomputereu_device_t *device = NULL;
    350 
    351 	if (out == NULL)
    352 		return DC_STATUS_INVALIDARGS;
    353 
    354 	// Allocate memory.
    355 	device = (tecdiving_divecomputereu_device_t *) dc_device_allocate (context, &tecdiving_divecomputereu_device_vtable);
    356 	if (device == NULL) {
    357 		ERROR (context, "Failed to allocate memory.");
    358 		return DC_STATUS_NOMEMORY;
    359 	}
    360 
    361 	// Set the default values.
    362 	device->iostream = iostream;
    363 	memset (device->fingerprint, 0, sizeof (device->fingerprint));
    364 
    365 	// Set the serial communication protocol (115200 8N1).
    366 	status = dc_iostream_configure (device->iostream, 115200, 8, DC_PARITY_NONE, DC_STOPBITS_ONE, DC_FLOWCONTROL_NONE);
    367 	if (status != DC_STATUS_SUCCESS) {
    368 		ERROR (context, "Failed to set the terminal attributes.");
    369 		goto error_free;
    370 	}
    371 
    372 	// Set the timeout for receiving data (1000ms).
    373 	status = dc_iostream_set_timeout (device->iostream, 1000);
    374 	if (status != DC_STATUS_SUCCESS) {
    375 		ERROR (context, "Failed to set the timeout.");
    376 		goto error_free;
    377 	}
    378 
    379 	// Make sure everything is in a sane state.
    380 	dc_iostream_sleep (device->iostream, 100);
    381 	dc_iostream_purge (device->iostream, DC_DIRECTION_ALL);
    382 
    383 	// Send the init command.
    384 	status = tecdiving_divecomputereu_send (device, CMD_INIT, NULL, 0);
    385 	if (status != DC_STATUS_SUCCESS) {
    386 		ERROR (context, "Failed to send the init command.");
    387 		goto error_free;
    388 	}
    389 
    390 	// Read the device info.
    391 	status = tecdiving_divecomputereu_receive (device, RSP_INIT, device->version, sizeof(device->version), NULL);
    392 	if (status != DC_STATUS_SUCCESS) {
    393 		ERROR (context, "Failed to receive the device info.");
    394 		goto error_free;
    395 	}
    396 
    397 	HEXDUMP (context, DC_LOGLEVEL_DEBUG, "Version", device->version, sizeof(device->version));
    398 
    399 	*out = (dc_device_t *) device;
    400 
    401 	return DC_STATUS_SUCCESS;
    402 
    403 error_free:
    404 	dc_device_deallocate ((dc_device_t *) device);
    405 	return status;
    406 }
    407 
    408 static dc_status_t
    409 tecdiving_divecomputereu_device_close (dc_device_t *abstract)
    410 {
    411 	dc_status_t status = DC_STATUS_SUCCESS;
    412 	tecdiving_divecomputereu_device_t *device = (tecdiving_divecomputereu_device_t *) abstract;
    413 
    414 	status = tecdiving_divecomputereu_send (device, CMD_EXIT, NULL, 0);
    415 	if (status != DC_STATUS_SUCCESS) {
    416 		ERROR (abstract->context, "Failed to send the exit command.");
    417 		return status;
    418 	}
    419 
    420 	return DC_STATUS_SUCCESS;
    421 }
    422 
    423 static dc_status_t
    424 tecdiving_divecomputereu_device_set_fingerprint (dc_device_t *abstract, const unsigned char data[], unsigned int size)
    425 {
    426 	tecdiving_divecomputereu_device_t *device = (tecdiving_divecomputereu_device_t *) abstract;
    427 
    428 	if (size && size != sizeof (device->fingerprint))
    429 		return DC_STATUS_INVALIDARGS;
    430 
    431 	if (size)
    432 		memcpy (device->fingerprint, data, sizeof (device->fingerprint));
    433 	else
    434 		memset (device->fingerprint, 0, sizeof (device->fingerprint));
    435 
    436 	return DC_STATUS_SUCCESS;
    437 }
    438 
    439 static dc_status_t
    440 tecdiving_divecomputereu_device_foreach (dc_device_t *abstract, dc_dive_callback_t callback, void *userdata)
    441 {
    442 	dc_status_t status = DC_STATUS_SUCCESS;
    443 	tecdiving_divecomputereu_device_t *device = (tecdiving_divecomputereu_device_t *) abstract;
    444 
    445 	// Enable progress notifications.
    446 	dc_event_progress_t progress = EVENT_PROGRESS_INITIALIZER;
    447 	device_event_emit (abstract, DC_EVENT_PROGRESS, &progress);
    448 
    449 	// Emit a device info event.
    450 	dc_event_devinfo_t devinfo;
    451 	devinfo.model = 0;
    452 	devinfo.firmware = 0;
    453 	devinfo.serial = array_uint16_be (device->version + 0x22) << 16 | array_uint16_be (device->version + 0x26);
    454 	device_event_emit (abstract, DC_EVENT_DEVINFO, &devinfo);
    455 
    456 	// Emit a vendor event.
    457 	dc_event_vendor_t vendor;
    458 	vendor.data = device->version;
    459 	vendor.size = sizeof(device->version);
    460 	device_event_emit (abstract, DC_EVENT_VENDOR, &vendor);
    461 
    462 	// Allocate memory for the dive list.
    463 	size_t length = SZ_LIST;
    464 	unsigned char *logbook = (unsigned char *) malloc (length);
    465 	if (logbook == NULL) {
    466 		status = DC_STATUS_NOMEMORY;
    467 		goto error_exit;
    468 	}
    469 
    470 	// Request the dive list.
    471 	status = tecdiving_divecomputereu_send (device, CMD_LIST, NULL, 0);
    472 	if (status != DC_STATUS_SUCCESS) {
    473 		ERROR (abstract->context, "Failed to send the list command.");
    474 		goto error_logbook_free;
    475 	}
    476 
    477 	// Read the dive list.
    478 	status = tecdiving_divecomputereu_receive (device, RSP_LIST, logbook, length, &length);
    479 	if (status != DC_STATUS_SUCCESS) {
    480 		ERROR (abstract->context, "Failed to receive the logbook.");
    481 		goto error_logbook_free;
    482 	}
    483 
    484 	// Verify the minimum length.
    485 	if (length < 2) {
    486 		status = DC_STATUS_DATAFORMAT;
    487 		goto error_logbook_free;
    488 	}
    489 
    490 	// Get the number of logbook entries.
    491 	unsigned int nlogbooks = array_uint16_be (logbook);
    492 	if (length != 2 + nlogbooks * SZ_SUMMARY) {
    493 		status = DC_STATUS_DATAFORMAT;
    494 		goto error_logbook_free;
    495 	}
    496 
    497 	// Count the number of dives to download.
    498 	unsigned int ndives = 0;
    499 	for (unsigned int i = 0; i < nlogbooks; ++i) {
    500 		unsigned int offset = 2 + i * SZ_SUMMARY;
    501 
    502 		if (memcmp(logbook + offset, device->fingerprint, sizeof(device->fingerprint)) == 0)
    503 			break;
    504 
    505 		ndives++;
    506 	}
    507 
    508 	// Update and emit a progress event.
    509 	progress.current = 1 * NSTEPS;
    510 	progress.maximum = (ndives + 1) * NSTEPS;
    511 	device_event_emit (abstract, DC_EVENT_PROGRESS, &progress);
    512 
    513 	// Allocate a memory buffer for a single dive.
    514 	dc_buffer_t *buffer = dc_buffer_new(0);
    515 	if (buffer == NULL) {
    516 		status = DC_STATUS_NOMEMORY;
    517 		goto error_logbook_free;
    518 	}
    519 
    520 	for (unsigned int i = 0; i < ndives; ++i) {
    521 		unsigned int offset = 2 + i * SZ_SUMMARY;
    522 
    523 		// Read the dive.
    524 		status = tecdiving_divecomputereu_readdive (abstract, &progress, i, buffer);
    525 		if (status != DC_STATUS_SUCCESS) {
    526 			goto error_buffer_free;
    527 		}
    528 
    529 		// Cache the pointer.
    530 		unsigned char *data = dc_buffer_get_data(buffer);
    531 		unsigned int size = dc_buffer_get_size(buffer);
    532 
    533 		// Verify the logbook entry.
    534 		if (memcmp (data, logbook + offset, SZ_SUMMARY) != 0) {
    535 			ERROR (abstract->context, "Dive header doesn't match logbook entry.");
    536 			status = DC_STATUS_DATAFORMAT;
    537 			goto error_buffer_free;
    538 		}
    539 
    540 		if (callback && !callback (data, size, data, sizeof(device->fingerprint), userdata)) {
    541 			break;
    542 		}
    543 	}
    544 
    545 error_buffer_free:
    546 	dc_buffer_free (buffer);
    547 error_logbook_free:
    548 	free (logbook);
    549 error_exit:
    550 	return status;
    551 }