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

cochran_commander.c (33790B)


      1 /*
      2  * libdivecomputer
      3  *
      4  * Copyright (C) 2014 John Van Ostrand
      5  *
      6  * This library is free software; you can redistribute it and/or
      7  * modify it under the terms of the GNU Lesser General Public
      8  * License as published by the Free Software Foundation; either
      9  * version 2.1 of the License, or (at your option) any later version.
     10  *
     11  * This library is distributed in the hope that it will be useful,
     12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
     13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
     14  * Lesser General Public License for more details.
     15  *
     16  * You should have received a copy of the GNU Lesser General Public
     17  * License along with this library; if not, write to the Free Software
     18  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
     19  * MA 02110-1301 USA
     20  */
     21 
     22 #include <string.h> // memcpy, memcmp
     23 #include <stdlib.h> // malloc, free
     24 #include <assert.h> // assert
     25 
     26 #include "cochran_commander.h"
     27 #include "context-private.h"
     28 #include "device-private.h"
     29 #include "array.h"
     30 #include "ringbuffer.h"
     31 #include "rbstream.h"
     32 
     33 #define MAXRETRIES 2
     34 
     35 #define COCHRAN_MODEL_COMMANDER_TM 0
     36 #define COCHRAN_MODEL_COMMANDER_PRE21000 1
     37 #define COCHRAN_MODEL_COMMANDER_AIR_NITROX 2
     38 #define COCHRAN_MODEL_EMC_14 3
     39 #define COCHRAN_MODEL_EMC_16 4
     40 #define COCHRAN_MODEL_EMC_20 5
     41 
     42 #define UNDEFINED 0xFFFFFFFF
     43 
     44 typedef enum cochran_endian_t {
     45 	ENDIAN_LE,
     46 	ENDIAN_BE,
     47 	ENDIAN_WORD_BE,
     48 } cochran_endian_t;
     49 
     50 typedef struct cochran_commander_model_t {
     51 	unsigned char id[3 + 1];
     52 	unsigned int model;
     53 } cochran_commander_model_t;
     54 
     55 typedef struct cochran_data_t {
     56 	unsigned char config[1024];
     57 	unsigned char *logbook;
     58 
     59 	unsigned short int dive_count;
     60 	unsigned int fp_dive_num;
     61 	unsigned int invalid_profile_dive_num;
     62 
     63 	unsigned int logbook_size;
     64 } cochran_data_t;
     65 
     66 typedef struct cochran_device_layout_t {
     67 	unsigned int model;
     68 	unsigned int address_bits;
     69 	cochran_endian_t endian;
     70 	unsigned int baudrate;
     71 	unsigned int rbstream_size;
     72 	// Config data.
     73 	unsigned int cf_dive_count;
     74 	unsigned int cf_last_log;
     75 	unsigned int cf_last_interdive;
     76 	unsigned int cf_serial_number;
     77 	// Logbook ringbuffer.
     78 	unsigned int rb_logbook_begin;
     79 	unsigned int rb_logbook_end;
     80 	unsigned int rb_logbook_entry_size;
     81 	unsigned int rb_logbook_entry_count;
     82 	// Profile ringbuffer.
     83 	unsigned int rb_profile_begin;
     84 	unsigned int rb_profile_end;
     85 	// pointers.
     86 	unsigned int pt_fingerprint;
     87 	unsigned int fingerprint_size;
     88 	unsigned int pt_profile_pre;
     89 	unsigned int pt_profile_begin;
     90 	unsigned int pt_profile_end;
     91 	unsigned int pt_dive_number;
     92 } cochran_device_layout_t;
     93 
     94 typedef struct cochran_commander_device_t {
     95 	dc_device_t base;
     96 	dc_iostream_t *iostream;
     97 	const cochran_device_layout_t *layout;
     98 	unsigned char id[67];
     99 	unsigned char fingerprint[6];
    100 } cochran_commander_device_t;
    101 
    102 static dc_status_t cochran_commander_device_set_fingerprint (dc_device_t *device, const unsigned char data[], unsigned int size);
    103 static dc_status_t cochran_commander_device_read (dc_device_t *device, unsigned int address, unsigned char data[], unsigned int size);
    104 static dc_status_t cochran_commander_device_dump (dc_device_t *device, dc_buffer_t *data);
    105 static dc_status_t cochran_commander_device_foreach (dc_device_t *device, dc_dive_callback_t callback, void *userdata);
    106 
    107 static const dc_device_vtable_t cochran_commander_device_vtable = {
    108 	sizeof (cochran_commander_device_t),
    109 	DC_FAMILY_COCHRAN_COMMANDER,
    110 	cochran_commander_device_set_fingerprint,/* set_fingerprint */
    111 	cochran_commander_device_read, /* read */
    112 	NULL, /* write */
    113 	cochran_commander_device_dump, /* dump */
    114 	cochran_commander_device_foreach, /* foreach */
    115 	NULL, /* timesync */
    116 	NULL /* close */
    117 };
    118 
    119 // Cochran Commander TM, pre-dates pre-21000 s/n
    120 static const cochran_device_layout_t cochran_cmdr_tm_device_layout = {
    121 	COCHRAN_MODEL_COMMANDER_TM, // model
    122 	24,         // address_bits
    123 	ENDIAN_WORD_BE,	// endian
    124 	9600,       // baudrate
    125 	4096,       // rbstream_size
    126 	0x146,      // cf_dive_count
    127 	0x158,      // cf_last_log
    128 	0xffffff,   // cf_last_interdive
    129 	0x15c,      // cf_serial_number
    130 	0x010000,   // rb_logbook_begin
    131 	0x01232b,   // rb_logbook_end
    132 	90,         // rb_logbook_entry_size
    133 	100,        // rb_logbook_entry_count
    134 	0x01232b,   // rb_profile_begin
    135 	0x018000,   // rb_profile_end
    136 	15,         // pt_fingerprint
    137 	4,          // fingerprint_size
    138 	0,          // pt_profile_pre
    139 	0,          // pt_profile_begin
    140 	90,         // pt_profile_end (Next begin pointer is the end)
    141 	20,         // pt_dive_number
    142 };
    143 
    144 // Cochran Commander pre-21000 s/n
    145 static const cochran_device_layout_t cochran_cmdr_1_device_layout = {
    146 	COCHRAN_MODEL_COMMANDER_PRE21000, // model
    147 	24,         // address_bits
    148 	ENDIAN_WORD_BE,  // endian
    149 	115200,     // baudrate
    150 	32768,      // rbstream_size
    151 	0x046,      // cf_dive_count
    152 	0x6c,       // cf_last_log
    153 	0x70,       // cf_last_interdive
    154 	0x0AA,      // cf_serial_number
    155 	0x00000000, // rb_logbook_begin
    156 	0x00020000, // rb_logbook_end
    157 	256,        // rb_logbook_entry_size
    158 	512,        // rb_logbook_entry_count
    159 	0x00020000, // rb_profile_begin
    160 	0x00100000, // rb_profile_end
    161 	12,         // pt_fingerprint
    162 	4,          // fingerprint_size
    163 	28,         // pt_profile_pre
    164 	0,          // pt_profile_begin
    165 	128,        // pt_profile_end
    166 	68,         // pt_dive_number
    167 };
    168 
    169 
    170 // Cochran Commander Nitrox
    171 static const cochran_device_layout_t cochran_cmdr_device_layout = {
    172 	COCHRAN_MODEL_COMMANDER_AIR_NITROX, // model
    173 	24,         // address_bits
    174 	ENDIAN_WORD_BE,  // endian
    175 	115200,     // baudrate
    176 	32768,      // rbstream_size
    177 	0x046,      // cf_dive_count
    178 	0x06C,      // cf_last_log
    179 	0x070,      // cf_last_interdive
    180 	0x0AA,      // cf_serial_number
    181 	0x00000000, // rb_logbook_begin
    182 	0x00020000, // rb_logbook_end
    183 	256,        // rb_logbook_entry_size
    184 	512,        // rb_logbook_entry_count
    185 	0x00020000, // rb_profile_begin
    186 	0x00100000, // rb_profile_end
    187 	0,          // pt_fingerprint
    188 	6,          // fingerprint_size
    189 	30,         // pt_profile_pre
    190 	6,          // pt_profile_begin
    191 	128,        // pt_profile_end
    192 	70,         // pt_dive_number
    193 };
    194 
    195 // Cochran EMC-14
    196 static const cochran_device_layout_t cochran_emc14_device_layout = {
    197 	COCHRAN_MODEL_EMC_14, // model
    198 	32,         // address_bits
    199 	ENDIAN_LE,  // endian
    200 	850000,     // baudrate
    201 	32768,      // rbstream_size
    202 	0x0D2,      // cf_dive_count
    203 	0x13E,      // cf_last_log
    204 	0x142,      // cf_last_interdive
    205 	0x1E6,      // cf_serial_number
    206 	0x00000000, // rb_logbook_begin
    207 	0x00020000, // rb_logbook_end
    208 	512,        // rb_logbook_entry_size
    209 	256,        // rb_logbook_entry_count
    210 	0x00022000, // rb_profile_begin
    211 	0x00200000, // rb_profile_end
    212 	0,          // pt_fingerprint
    213 	6,          // fingerprint_size
    214 	30,         // pt_profile_pre
    215 	6,          // pt_profile_begin
    216 	256,        // pt_profile_end
    217 	86,         // pt_dive_number
    218 };
    219 
    220 // Cochran EMC-16
    221 static const cochran_device_layout_t cochran_emc16_device_layout = {
    222 	COCHRAN_MODEL_EMC_16, // model
    223 	32,         // address_bits
    224 	ENDIAN_LE,  // endian
    225 	850000,     // baudrate
    226 	32768,      // rbstream_size
    227 	0x0D2,      // cf_dive_count
    228 	0x13E,      // cf_last_log
    229 	0x142,      // cf_last_interdive
    230 	0x1E6,      // cf_serial_number
    231 	0x00000000, // rb_logbook_begin
    232 	0x00080000, // rb_logbook_end
    233 	512,        // rb_logbook_entry_size
    234 	1024,       // rb_logbook_entry_count
    235 	0x00094000, // rb_profile_begin
    236 	0x00800000, // rb_profile_end
    237 	0,          // pt_fingerprint
    238 	6,          // fingerprint_size
    239 	30,         // pt_profile_pre
    240 	6,          // pt_profile_begin
    241 	256,        // pt_profile_end
    242 	86,         // pt_dive_number
    243 };
    244 
    245 // Cochran EMC-20
    246 static const cochran_device_layout_t cochran_emc20_device_layout = {
    247 	COCHRAN_MODEL_EMC_20, // model
    248 	32,         // address_bits
    249 	ENDIAN_LE,  // endian
    250 	850000,     // baudrate
    251 	32768,      // rbstream_size
    252 	0x0D2,      // cf_dive_count
    253 	0x13E,      // cf_last_log
    254 	0x142,      // cf_last_interdive
    255 	0x1E6,      // cf_serial_number
    256 	0x00000000, // rb_logbook_begin
    257 	0x00080000, // rb_logbook_end
    258 	512,        // rb_logbook_entry_size
    259 	1024,       // rb_logbook_entry_count
    260 	0x00094000, // rb_profile_begin
    261 	0x01000000, // rb_profile_end
    262 	0,          // pt_fingerprint
    263 	6,          // fingerprint_size
    264 	30,         // pt_profile_pre
    265 	6,          // pt_profile_begin
    266 	256,        // pt_profile_end
    267 	86,         // pt_dive_number
    268 };
    269 
    270 
    271 // Determine model descriptor number from model string
    272 static unsigned int
    273 cochran_commander_get_model (cochran_commander_device_t *device)
    274 {
    275 	const cochran_commander_model_t models[] = {
    276 		{"\x0a""12", COCHRAN_MODEL_COMMANDER_TM},
    277 		{"\x11""21", COCHRAN_MODEL_COMMANDER_PRE21000},
    278 		{"\x11""22", COCHRAN_MODEL_COMMANDER_AIR_NITROX},
    279 		{"730",      COCHRAN_MODEL_EMC_14},
    280 		{"731",      COCHRAN_MODEL_EMC_14},
    281 		{"A30",      COCHRAN_MODEL_EMC_16},
    282 		{"A31",      COCHRAN_MODEL_EMC_16},
    283 		{"230",      COCHRAN_MODEL_EMC_20},
    284 		{"231",      COCHRAN_MODEL_EMC_20},
    285 		{"\x40""30", COCHRAN_MODEL_EMC_20},
    286 	};
    287 
    288 	unsigned int model = 0xFFFFFFFF;
    289 	for (unsigned int i = 0; i < C_ARRAY_SIZE(models); ++i) {
    290 		if (memcmp (device->id + 0x3D, models[i].id, sizeof(models[i].id) - 1) == 0) {
    291 			model = models[i].model;
    292 			break;
    293 		}
    294 	}
    295 
    296 	return model;
    297 }
    298 
    299 
    300 static dc_status_t
    301 cochran_commander_serial_setup (cochran_commander_device_t *device)
    302 {
    303 	dc_status_t status = DC_STATUS_SUCCESS;
    304 
    305 	// Set the serial communication protocol (9600 8N2, no FC).
    306 	status = dc_iostream_configure (device->iostream, 9600, 8, DC_PARITY_NONE, DC_STOPBITS_TWO, DC_FLOWCONTROL_NONE);
    307 	if (status != DC_STATUS_SUCCESS) {
    308 		ERROR (device->base.context, "Failed to set the terminal attributes.");
    309 		return status;
    310 	}
    311 
    312 	// Set the timeout for receiving data (5000 ms).
    313 	status = dc_iostream_set_timeout (device->iostream, 5000);
    314 	if (status != DC_STATUS_SUCCESS) {
    315 		ERROR (device->base.context, "Failed to set the timeout.");
    316 		return status;
    317 	}
    318 
    319 	// Wake up DC and trigger heartbeat
    320 	dc_iostream_set_break(device->iostream, 1);
    321 	dc_iostream_sleep(device->iostream, 16);
    322 	dc_iostream_set_break(device->iostream, 0);
    323 
    324 	// Clear old heartbeats
    325 	dc_iostream_purge (device->iostream, DC_DIRECTION_ALL);
    326 
    327 	// Wait for heartbeat byte before send
    328 	unsigned char answer = 0;
    329 	status = dc_iostream_read(device->iostream, &answer, 1, NULL);
    330 	if (status != DC_STATUS_SUCCESS) {
    331 		ERROR (device->base.context, "Failed to receive device heartbeat.");
    332 		return status;
    333 	}
    334 
    335 	if (answer != 0xAA) {
    336 		ERROR (device->base.context, "Received bad hearbeat byte (%02x).", answer);
    337 		return DC_STATUS_PROTOCOL;
    338 	}
    339 
    340 	return DC_STATUS_SUCCESS;
    341 }
    342 
    343 
    344 static dc_status_t
    345 cochran_commander_packet (cochran_commander_device_t *device, dc_event_progress_t *progress,
    346 	const unsigned char command[], unsigned int csize,
    347 	unsigned char answer[], unsigned int asize, int high_speed)
    348 {
    349 	dc_device_t *abstract = (dc_device_t *) device;
    350 	dc_status_t status = DC_STATUS_SUCCESS;
    351 
    352 	if (device_is_cancelled (abstract))
    353 		return DC_STATUS_CANCELLED;
    354 
    355 	// Send the command to the device, one byte at a time
    356 	// If sent all at once the command is ignored. It's like the DC
    357 	// has no buffering.
    358 	for (unsigned int i = 0; i < csize; i++) {
    359 		// Give the DC time to read the character.
    360 		if (i) dc_iostream_sleep(device->iostream, 16); // 16 ms
    361 
    362 		status = dc_iostream_write(device->iostream, command + i, 1, NULL);
    363 		if (status != DC_STATUS_SUCCESS) {
    364 			ERROR (abstract->context, "Failed to send the command.");
    365 			return status;
    366 		}
    367 	}
    368 
    369 	if (high_speed && device->layout->baudrate != 9600) {
    370 		// Give the DC time to process the command.
    371 		dc_iostream_sleep(device->iostream, 45);
    372 
    373 		// Rates are odd, like 850400 for the EMC, 115200 for commander
    374 		status = dc_iostream_configure(device->iostream, device->layout->baudrate, 8, DC_PARITY_NONE, DC_STOPBITS_TWO, DC_FLOWCONTROL_NONE);
    375 		if (status != DC_STATUS_SUCCESS) {
    376 			ERROR (abstract->context, "Failed to set the high baud rate.");
    377 			return status;
    378 		}
    379 	}
    380 
    381 	// Receive the answer from the device.
    382 	// Use 1024 byte "packets" so we can display progress.
    383 	unsigned int nbytes = 0;
    384 	while (nbytes < asize) {
    385 		unsigned int len = asize - nbytes;
    386 		if (len > 1024)
    387 			len = 1024;
    388 
    389 		status = dc_iostream_read (device->iostream, answer + nbytes, len, NULL);
    390 		if (status != DC_STATUS_SUCCESS) {
    391 			ERROR (abstract->context, "Failed to receive data.");
    392 			return status;
    393 		}
    394 
    395 		nbytes += len;
    396 
    397 		if (progress) {
    398 			progress->current += len;
    399 			device_event_emit (abstract, DC_EVENT_PROGRESS, progress);
    400 		}
    401 	}
    402 
    403 	return DC_STATUS_SUCCESS;
    404 }
    405 
    406 
    407 static dc_status_t
    408 cochran_commander_read_id (cochran_commander_device_t *device, unsigned char id[], unsigned int size)
    409 {
    410 	dc_status_t rc = DC_STATUS_SUCCESS;
    411 
    412 	unsigned char command[6] = {0x05, 0x9D, 0xFF, 0x00, 0x43, 0x00};
    413 
    414 	rc = cochran_commander_packet(device, NULL, command, sizeof(command), id, size, 0);
    415 	if (rc != DC_STATUS_SUCCESS)
    416 		return rc;
    417 
    418 	if (memcmp(id, "(C)", 3) != 0) {
    419 		// It's a Commander, read a different location
    420 		command[1] = 0xBD;
    421 		command[2] = 0x7F;
    422 
    423 		rc = cochran_commander_packet(device, NULL, command, sizeof(command), id, size, 0);
    424 		if (rc != DC_STATUS_SUCCESS)
    425 			return rc;
    426 	}
    427 
    428 	return DC_STATUS_SUCCESS;
    429 }
    430 
    431 
    432 static dc_status_t
    433 cochran_commander_read_config (cochran_commander_device_t *device, dc_event_progress_t *progress, unsigned char data[], unsigned int size)
    434 {
    435 	dc_device_t *abstract = (dc_device_t *) device;
    436 	dc_status_t rc = DC_STATUS_SUCCESS;
    437 
    438 	if ((size % 512) != 0)
    439 		return DC_STATUS_INVALIDARGS;
    440 
    441 	// Read two 512 byte blocks into one 1024 byte buffer
    442 	unsigned int pages = size / 512;
    443 	for (unsigned int i = 0; i < pages; i++) {
    444 		unsigned char command[2] = {0x96, i};
    445 		unsigned int command_size = sizeof(command);
    446 		if (device->layout->model == COCHRAN_MODEL_COMMANDER_TM)
    447 			command_size = 1;
    448 
    449 		rc = cochran_commander_packet(device, progress, command, command_size, data + i * 512, 512, 0);
    450 		if (rc != DC_STATUS_SUCCESS)
    451 			return rc;
    452 
    453 		dc_event_vendor_t vendor;
    454 		vendor.data = data + i * 512;
    455 		vendor.size = 512;
    456 		device_event_emit (abstract, DC_EVENT_VENDOR, &vendor);
    457 	}
    458 
    459 	return DC_STATUS_SUCCESS;
    460 }
    461 
    462 
    463 static dc_status_t
    464 cochran_commander_read (cochran_commander_device_t *device, dc_event_progress_t *progress, unsigned int address, unsigned char data[], unsigned int size)
    465 {
    466 	dc_status_t rc = DC_STATUS_SUCCESS;
    467 
    468 	// Build the command
    469 	unsigned char command[10];
    470 	unsigned char command_size;
    471 
    472 	switch (device->layout->address_bits) {
    473 	case 32:
    474 		// EMC uses 32 bit addressing
    475 		command[0] = 0x15;
    476 		command[1] = (address      ) & 0xff;
    477 		command[2] = (address >>  8) & 0xff;
    478 		command[3] = (address >> 16) & 0xff;
    479 		command[4] = (address >> 24) & 0xff;
    480 		command[5] = (size         ) & 0xff;
    481 		command[6] = (size >>  8   ) & 0xff;
    482 		command[7] = (size >> 16   ) & 0xff;
    483 		command[8] = (size >> 24   ) & 0xff;
    484 		command[9] = 0x05;
    485 		command_size = 10;
    486 		break;
    487 	case 24:
    488 		// Commander uses 24 byte addressing
    489 		if (device->layout->baudrate == 9600) {
    490 			// This read command will return 32K bytes if asked to read
    491 			// 0 bytes. So we can allow a size of up to 0x10000 but if
    492 			// the user asks for 0 bytes we should just return success
    493 			// otherwise we'll end end up running past the buffer.
    494 			if (size > 0x10000)
    495 				return DC_STATUS_INVALIDARGS;
    496 			if (size == 0)
    497 				return DC_STATUS_SUCCESS;
    498 
    499 			// Older commander, use low-speed read command
    500 			command[0] = 0x05;
    501 			command[1] = (address      ) & 0xff;
    502 			command[2] = (address >>  8) & 0xff;
    503 			command[3] = (address >> 16) & 0xff;
    504 			command[4] = (size         ) & 0xff;
    505 			command[5] = (size >> 8    ) & 0xff;
    506 			command_size = 6;
    507 		} else {
    508 			// Newer commander with high-speed read command
    509 			command[0] = 0x15;
    510 			command[1] = (address      ) & 0xff;
    511 			command[2] = (address >>  8) & 0xff;
    512 			command[3] = (address >> 16) & 0xff;
    513 			command[4] = (size         ) & 0xff;
    514 			command[5] = (size >>  8   ) & 0xff;
    515 			command[6] = (size >> 16   ) & 0xff;
    516 			command[7] = 0x04;
    517 			command_size = 8;
    518 		}
    519 		break;
    520 	default:
    521 		return DC_STATUS_UNSUPPORTED;
    522 	}
    523 
    524 	dc_iostream_sleep(device->iostream, 550);
    525 
    526 	// set back to 9600 baud
    527 	rc = cochran_commander_serial_setup(device);
    528 	if (rc != DC_STATUS_SUCCESS)
    529 		return rc;
    530 
    531 	// Read data at high speed
    532 	rc = cochran_commander_packet (device, progress, command, command_size, data, size, 1);
    533 	if (rc != DC_STATUS_SUCCESS)
    534 		return rc;
    535 
    536 	return DC_STATUS_SUCCESS;
    537 }
    538 
    539 
    540 static dc_status_t
    541 cochran_commander_read_retry (cochran_commander_device_t *device, dc_event_progress_t *progress, unsigned int address, unsigned char data[], unsigned int size)
    542 {
    543 	// Save the state of the progress events.
    544 	unsigned int saved = 0;
    545 	if (progress) {
    546 		saved = progress->current;
    547 	}
    548 
    549 	unsigned int nretries = 0;
    550 	dc_status_t rc = DC_STATUS_SUCCESS;
    551 	while ((rc = cochran_commander_read (device, progress, address, data, size)) != DC_STATUS_SUCCESS) {
    552 		// Automatically discard a corrupted packet,
    553 		// and request a new one.
    554 		if (rc != DC_STATUS_PROTOCOL && rc != DC_STATUS_TIMEOUT)
    555 			return rc;
    556 
    557 		// Abort if the maximum number of retries is reached.
    558 		if (nretries++ >= MAXRETRIES)
    559 			return rc;
    560 
    561 		// Restore the state of the progress events.
    562 		if (progress) {
    563 			progress->current = saved;
    564 		}
    565 	}
    566 
    567 	return rc;
    568 }
    569 
    570 
    571 /*
    572  *  For corrupt dives the end-of-samples pointer is 0xFFFFFFFF
    573  *  search for a reasonable size, e.g. using next dive start sample
    574  *  or end-of-samples to limit searching for recoverable samples
    575  */
    576 static unsigned int
    577 cochran_commander_guess_sample_end_address(cochran_commander_device_t *device, cochran_data_t *data, unsigned int log_num)
    578 {
    579 	const unsigned char *log_entry = data->logbook + device->layout->rb_logbook_entry_size * log_num;
    580 
    581 	if (log_num == data->dive_count)
    582 		// Return next usable address from config page
    583 		return array_uint32_le(data->config + device->layout->rb_profile_end);
    584 
    585 	// Next log's start address
    586 	return array_uint32_le(log_entry + device->layout->rb_logbook_entry_size + device->layout->pt_profile_begin);
    587 }
    588 
    589 
    590 static unsigned int
    591 cochran_commander_profile_size(cochran_commander_device_t *device, cochran_data_t *data, int dive_num, unsigned int sample_start_address, unsigned int sample_end_address)
    592 {
    593 	// Validate addresses
    594 	if (sample_start_address < device->layout->rb_profile_begin ||
    595 		sample_start_address > device->layout->rb_profile_end ||
    596 		sample_end_address < device->layout->rb_profile_begin ||
    597 		(sample_end_address > device->layout->rb_profile_end &&
    598 		sample_end_address != 0xFFFFFFFF)) {
    599 		return 0;
    600 	}
    601 
    602 	if (sample_end_address == 0xFFFFFFFF)
    603 		// Corrupt dive, guess the end address
    604 		sample_end_address = cochran_commander_guess_sample_end_address(device, data, dive_num);
    605 
    606 	return ringbuffer_distance(sample_start_address, sample_end_address, DC_RINGBUFFER_EMPTY, device->layout->rb_profile_begin, device->layout->rb_profile_end);
    607 }
    608 
    609 
    610 /*
    611  * Do several things. Find the log that matches the fingerprint,
    612  * calculate the total read size for progress indicator,
    613  * Determine the most recent dive without profile data.
    614  */
    615 
    616 static unsigned int
    617 cochran_commander_find_fingerprint(cochran_commander_device_t *device, cochran_data_t *data)
    618 {
    619 	unsigned int base = device->layout->rb_logbook_begin;
    620 
    621 	// We track profile ringbuffer usage to determine which dives have profile data
    622 	int profile_capacity_remaining = device->layout->rb_profile_end - device->layout->rb_profile_begin;
    623 
    624 	unsigned int dive_count = 0;
    625 	data->fp_dive_num = UNDEFINED;
    626 
    627 	// Start at end of log
    628 	if (data->dive_count < device->layout->rb_logbook_entry_count)
    629 		dive_count = data->dive_count;
    630 	else
    631 		dive_count = device->layout->rb_logbook_entry_count;
    632 
    633 	unsigned int sample_read_size = 0;
    634 	data->invalid_profile_dive_num = UNDEFINED;
    635 
    636 	// Remove the pre-dive events that occur after the last dive
    637 	unsigned int rb_head_ptr = 0;
    638 	if (device->layout->model == COCHRAN_MODEL_COMMANDER_TM)
    639 		// TM uses SRAM and does not need to erase pages
    640 		rb_head_ptr = base + array_uint16_be(data->config + device->layout->cf_last_log);
    641 	else if (device->layout->endian == ENDIAN_WORD_BE)
    642 		rb_head_ptr = base + (array_uint32_word_be(data->config + device->layout->cf_last_log) & 0xfffff000) + 0x2000;
    643 	else
    644 		rb_head_ptr = base + (array_uint32_le(data->config + device->layout->cf_last_log) & 0xfffff000) + 0x2000;
    645 
    646 	unsigned int head_dive = 0, tail_dive = 0;
    647 
    648 	if (data->dive_count <= device->layout->rb_logbook_entry_count) {
    649 		head_dive = data->dive_count;
    650 		tail_dive = 0;
    651 	} else {
    652 		// Log wrapped
    653 		tail_dive = data->dive_count % device->layout->rb_logbook_entry_count;
    654 		head_dive = tail_dive;
    655 	}
    656 
    657 	unsigned int last_profile_idx = (device->layout->rb_logbook_entry_count + head_dive - 1) % device->layout->rb_logbook_entry_count;
    658 	unsigned int last_profile_end = 0;
    659 	if (device->layout->model == COCHRAN_MODEL_COMMANDER_TM)
    660 		// There is no end pointer in this model and no inter-dive
    661 		// events. We could use profile_begin from the next dive but
    662 		// since this is the last dive, we'll use rb_head_ptr
    663 		last_profile_end = rb_head_ptr;
    664 	else
    665 		last_profile_end = base + array_uint32_le(data->logbook + last_profile_idx * device->layout->rb_logbook_entry_size + device->layout->pt_profile_end);
    666 
    667 	unsigned int last_profile_pre = 0xFFFFFFFF;
    668 	if (device->layout->endian == ENDIAN_WORD_BE)
    669 		last_profile_pre = base + array_uint32_word_be(data->config + device->layout->cf_last_log);
    670 	else
    671 		last_profile_pre = base + array_uint32_le(data->config + device->layout->cf_last_log);
    672 
    673 	if (rb_head_ptr > last_profile_end)
    674 		profile_capacity_remaining -= rb_head_ptr - last_profile_end;
    675 
    676 	// Loop through dives to find FP, Accumulate profile data size,
    677 	// and find the last dive with invalid profile
    678 	for (unsigned int i = 0; i < dive_count; ++i) {
    679 		unsigned int idx = (device->layout->rb_logbook_entry_count + head_dive - (i + 1)) % device->layout->rb_logbook_entry_count;
    680 
    681 		unsigned char *log_entry = data->logbook + idx * device->layout->rb_logbook_entry_size;
    682 
    683 		// We're done if we find the fingerprint
    684 		if (!memcmp(device->fingerprint, log_entry + device->layout->pt_fingerprint, device->layout->fingerprint_size)) {
    685 			data->fp_dive_num = idx;
    686 			break;
    687 		}
    688 
    689 		unsigned int profile_pre = 0;
    690 		if (device->layout->model == COCHRAN_MODEL_COMMANDER_TM)
    691 			profile_pre = base + array_uint16_le(log_entry + device->layout->pt_profile_pre);
    692 		else
    693 			profile_pre = base + array_uint32_le(log_entry + device->layout->pt_profile_pre);
    694 
    695 		unsigned int sample_size = cochran_commander_profile_size(device, data, idx, profile_pre, last_profile_pre);
    696 		last_profile_pre = profile_pre;
    697 
    698 		// Determine if sample exists
    699 		if (profile_capacity_remaining > 0) {
    700 			// Subtract this dive's profile size including post-dive events
    701 			profile_capacity_remaining -= sample_size;
    702 			if (profile_capacity_remaining < 0) {
    703 				// Save the last dive that is missing profile data
    704 				data->invalid_profile_dive_num = idx;
    705 			}
    706 			// Accumulate read size for progress bar
    707 			sample_read_size += sample_size;
    708 		}
    709 	}
    710 
    711 	return sample_read_size;
    712 }
    713 
    714 
    715 dc_status_t
    716 cochran_commander_device_open (dc_device_t **out, dc_context_t *context, dc_iostream_t *iostream)
    717 {
    718 	dc_status_t status = DC_STATUS_SUCCESS;
    719 	cochran_commander_device_t *device = NULL;
    720 
    721 	if (out == NULL)
    722 		return DC_STATUS_INVALIDARGS;
    723 
    724 	// Allocate memory.
    725 	device = (cochran_commander_device_t *) dc_device_allocate (context, &cochran_commander_device_vtable);
    726 	if (device == NULL) {
    727 		ERROR (context, "Failed to allocate memory.");
    728 		return DC_STATUS_NOMEMORY;
    729 	}
    730 
    731 	// Set the default values.
    732 	device->iostream = iostream;
    733 	cochran_commander_device_set_fingerprint((dc_device_t *) device, NULL, 0);
    734 
    735 	status = cochran_commander_serial_setup(device);
    736 	if (status != DC_STATUS_SUCCESS) {
    737 		goto error_free;
    738 	}
    739 
    740 	// Read ID from the device
    741 	status = cochran_commander_read_id (device, device->id, sizeof(device->id));
    742 	if (status != DC_STATUS_SUCCESS) {
    743 		ERROR (context, "Device not responding.");
    744 		goto error_free;
    745 	}
    746 
    747 	unsigned int model = cochran_commander_get_model(device);
    748 	switch (model) {
    749 	case COCHRAN_MODEL_COMMANDER_TM:
    750 		device->layout = &cochran_cmdr_tm_device_layout;
    751 		break;
    752 	case COCHRAN_MODEL_COMMANDER_PRE21000:
    753 		device->layout = &cochran_cmdr_1_device_layout;
    754 		break;
    755 	case COCHRAN_MODEL_COMMANDER_AIR_NITROX:
    756 		device->layout = &cochran_cmdr_device_layout;
    757 		break;
    758 	case COCHRAN_MODEL_EMC_14:
    759 		device->layout = &cochran_emc14_device_layout;
    760 		break;
    761 	case COCHRAN_MODEL_EMC_16:
    762 		device->layout = &cochran_emc16_device_layout;
    763 		break;
    764 	case COCHRAN_MODEL_EMC_20:
    765 		device->layout = &cochran_emc20_device_layout;
    766 		break;
    767 	default:
    768 		ERROR (context, "Unknown model");
    769 		status = DC_STATUS_UNSUPPORTED;
    770 		goto error_free;
    771 	}
    772 
    773 	*out = (dc_device_t *) device;
    774 
    775 	return DC_STATUS_SUCCESS;
    776 
    777 error_free:
    778 	dc_device_deallocate ((dc_device_t *) device);
    779 	return status;
    780 }
    781 
    782 static dc_status_t
    783 cochran_commander_device_set_fingerprint (dc_device_t *abstract, const unsigned char data[], unsigned int size)
    784 {
    785 	cochran_commander_device_t *device = (cochran_commander_device_t *) abstract;
    786 
    787 	if (size && size != device->layout->fingerprint_size)
    788 		return DC_STATUS_INVALIDARGS;
    789 
    790 	if (size)
    791 		memcpy (device->fingerprint, data, device->layout->fingerprint_size);
    792 	else
    793 		memset (device->fingerprint, 0xFF, sizeof(device->fingerprint));
    794 
    795 	return DC_STATUS_SUCCESS;
    796 }
    797 
    798 
    799 static dc_status_t
    800 cochran_commander_device_read (dc_device_t *abstract, unsigned int address, unsigned char data[], unsigned int size)
    801 {
    802 	cochran_commander_device_t *device = (cochran_commander_device_t *) abstract;
    803 
    804 	return cochran_commander_read_retry(device, NULL, address, data, size);
    805 }
    806 
    807 
    808 static dc_status_t
    809 cochran_commander_device_dump (dc_device_t *abstract, dc_buffer_t *buffer)
    810 {
    811 	cochran_commander_device_t *device = (cochran_commander_device_t *) abstract;
    812 	dc_status_t rc = DC_STATUS_SUCCESS;
    813 	unsigned char config[1024];
    814 	unsigned int config_size = sizeof(config);
    815 	unsigned int size = device->layout->rb_profile_end - device->layout->rb_logbook_begin;
    816 
    817 	// Reserve space
    818 	if (!dc_buffer_resize(buffer, size)) {
    819 		ERROR(abstract->context, "Insufficient buffer space available.");
    820 		return DC_STATUS_NOMEMORY;
    821 	}
    822 
    823 	if (device->layout->model == COCHRAN_MODEL_COMMANDER_TM)
    824 		config_size = 512;
    825 
    826 	// Determine size for progress
    827 	dc_event_progress_t progress = EVENT_PROGRESS_INITIALIZER;
    828 	progress.maximum = config_size + size;
    829 	device_event_emit (abstract, DC_EVENT_PROGRESS, &progress);
    830 
    831 	// Emit ID block
    832 	dc_event_vendor_t vendor;
    833 	vendor.data = device->id;
    834 	vendor.size = sizeof (device->id);
    835 	device_event_emit (abstract, DC_EVENT_VENDOR, &vendor);
    836 
    837 	rc = cochran_commander_read_config (device, &progress, config, config_size);
    838 	if (rc != DC_STATUS_SUCCESS)
    839 		return rc;
    840 
    841 	// Read the sample data, logbook and sample data are contiguous
    842 	rc = cochran_commander_read_retry (device, &progress, device->layout->rb_logbook_begin, dc_buffer_get_data(buffer), size);
    843 	if (rc != DC_STATUS_SUCCESS) {
    844 		ERROR (abstract->context, "Failed to read the sample data.");
    845 		return rc;
    846 	}
    847 
    848 	return DC_STATUS_SUCCESS;
    849 }
    850 
    851 
    852 static dc_status_t
    853 cochran_commander_device_foreach (dc_device_t *abstract, dc_dive_callback_t callback, void *userdata)
    854 {
    855 	cochran_commander_device_t *device = (cochran_commander_device_t *) abstract;
    856 	const cochran_device_layout_t *layout = device->layout;
    857 	dc_status_t status = DC_STATUS_SUCCESS;
    858 	dc_rbstream_t *rbstream = NULL;
    859 
    860 	cochran_data_t data;
    861 	data.logbook = NULL;
    862 
    863 	// Calculate max data sizes
    864 	unsigned int max_config = sizeof(data.config);
    865 	unsigned int max_logbook = layout->rb_logbook_end - layout->rb_logbook_begin;
    866 	unsigned int max_sample = layout->rb_profile_end - layout->rb_profile_begin;
    867 	unsigned int base = device->layout->rb_logbook_begin;
    868 
    869 	if (device->layout->model == COCHRAN_MODEL_COMMANDER_TM)
    870 		max_config = 512;
    871 
    872 	// setup progress indication
    873 	dc_event_progress_t progress = EVENT_PROGRESS_INITIALIZER;
    874 	progress.maximum = max_config + max_logbook + max_sample;
    875 	device_event_emit (abstract, DC_EVENT_PROGRESS, &progress);
    876 
    877 	// Emit ID block
    878 	dc_event_vendor_t vendor;
    879 	vendor.data = device->id;
    880 	vendor.size = sizeof (device->id);
    881 	device_event_emit (abstract, DC_EVENT_VENDOR, &vendor);
    882 
    883 	// Read config
    884 	dc_status_t rc = DC_STATUS_SUCCESS;
    885 	rc = cochran_commander_read_config(device, &progress, data.config, max_config);
    886 	if (rc != DC_STATUS_SUCCESS)
    887 		return rc;
    888 
    889 	// Determine size of dive list to read.
    890 	if (layout->endian == ENDIAN_LE)
    891 		data.dive_count = array_uint16_le (data.config + layout->cf_dive_count);
    892 	else
    893 		data.dive_count = array_uint16_be (data.config + layout->cf_dive_count);
    894 
    895 	if (data.dive_count == 0) {
    896 		// No dives to read
    897 		WARNING(abstract->context, "This dive computer has no recorded dives.");
    898 		return DC_STATUS_SUCCESS;
    899 	}
    900 
    901 	if (data.dive_count > layout->rb_logbook_entry_count) {
    902 		data.logbook_size = layout->rb_logbook_entry_count * layout->rb_logbook_entry_size;
    903 	} else {
    904 		data.logbook_size = data.dive_count * layout->rb_logbook_entry_size;
    905 	}
    906 
    907 	// Update progress indicator with new maximum
    908 	progress.maximum -= max_logbook - data.logbook_size;
    909 	device_event_emit (abstract, DC_EVENT_PROGRESS, &progress);
    910 
    911 	// Allocate space for log book.
    912 	data.logbook = (unsigned char *) malloc(data.logbook_size);
    913 	if (data.logbook == NULL) {
    914 		ERROR (abstract->context, "Failed to allocate memory.");
    915 		return DC_STATUS_NOMEMORY;
    916 	}
    917 
    918 	// Request log book
    919 	rc = cochran_commander_read_retry(device, &progress, layout->rb_logbook_begin, data.logbook, data.logbook_size);
    920 	if (rc != DC_STATUS_SUCCESS) {
    921 		status = rc;
    922 		goto error;
    923 	}
    924 
    925 	// Locate fingerprint, recent dive with invalid profile and calc read size
    926 	unsigned int profile_read_size = cochran_commander_find_fingerprint(device, &data);
    927 
    928 	// Update progress indicator with new maximum
    929 	progress.maximum -= (max_sample - profile_read_size);
    930 	device_event_emit (abstract, DC_EVENT_PROGRESS, &progress);
    931 
    932 	// Emit a device info event.
    933 	dc_event_devinfo_t devinfo;
    934 	devinfo.model = layout->model;
    935 	devinfo.firmware = 0; // unknown
    936 	if (layout->endian == ENDIAN_WORD_BE)
    937 		devinfo.serial = array_uint32_word_be(data.config + layout->cf_serial_number);
    938 	else
    939 		devinfo.serial = array_uint32_le(data.config + layout->cf_serial_number);
    940 	device_event_emit (abstract, DC_EVENT_DEVINFO, &devinfo);
    941 
    942 	unsigned int head_dive = 0, tail_dive = 0, dive_count = 0;
    943 
    944 	if (data.dive_count <= layout->rb_logbook_entry_count) {
    945 		head_dive = data.dive_count;
    946 		tail_dive = 0;
    947 	} else {
    948 		// Log wrapped
    949 		tail_dive = data.dive_count % layout->rb_logbook_entry_count;
    950 		head_dive = tail_dive;
    951 	}
    952 
    953 	// Change tail to dive following the fingerprint dive.
    954 	if (data.fp_dive_num != UNDEFINED)
    955 		tail_dive = (data.fp_dive_num + 1) % layout->rb_logbook_entry_count;
    956 
    957 	// Number of dives to read
    958 	dive_count = (layout->rb_logbook_entry_count + head_dive - tail_dive) % layout->rb_logbook_entry_count;
    959 
    960 	unsigned int last_start_address = 0;
    961 	if (layout->endian == ENDIAN_WORD_BE)
    962 		last_start_address = base + array_uint32_word_be(data.config + layout->cf_last_log );
    963 	else
    964 		last_start_address = base + array_uint32_le(data.config + layout->cf_last_log );
    965 
    966 	// Create the ringbuffer stream.
    967 	status = dc_rbstream_new (&rbstream, abstract, 1, layout->rbstream_size, layout->rb_profile_begin, layout->rb_profile_end, last_start_address, DC_RBSTREAM_BACKWARD);
    968 	if (status != DC_STATUS_SUCCESS) {
    969 		ERROR (abstract->context, "Failed to create the ringbuffer stream.");
    970 		goto error;
    971 	}
    972 
    973 	int invalid_profile_flag = 0;
    974 
    975 	// Loop through each dive
    976 	for (unsigned int i = 0; i < dive_count; ++i) {
    977 		unsigned int idx = (layout->rb_logbook_entry_count + head_dive - (i + 1)) % layout->rb_logbook_entry_count;
    978 
    979 		unsigned char *log_entry = data.logbook + idx * layout->rb_logbook_entry_size;
    980 
    981 		unsigned int sample_start_address = 0;
    982 		unsigned int sample_end_address = 0;
    983 		if (layout->model == COCHRAN_MODEL_COMMANDER_TM) {
    984 			sample_start_address = base + array_uint16_le (log_entry + layout->pt_profile_begin);
    985 			sample_end_address = last_start_address;
    986 			// Commander TM has SRAM which seems to randomize when they lose power for too long
    987 			// Check for bad entries.
    988 			if (sample_start_address < layout->rb_profile_begin || sample_start_address > layout->rb_profile_end ||
    989 				sample_end_address < layout->rb_profile_begin || sample_end_address > layout->rb_profile_end ||
    990 				array_uint16_le(log_entry + layout->pt_dive_number) % layout->rb_logbook_entry_count != idx) {
    991 				ERROR(abstract->context, "Corrupt dive (%d).", idx);
    992 				continue;
    993 			}
    994 		} else {
    995 			sample_start_address = base + array_uint32_le (log_entry + layout->pt_profile_begin);
    996 			sample_end_address = base + array_uint32_le (log_entry + layout->pt_profile_end);
    997 		}
    998 
    999 		int sample_size = 0, pre_size = 0;
   1000 
   1001 		// Determine if profile exists
   1002 		if (idx == data.invalid_profile_dive_num)
   1003 			invalid_profile_flag = 1;
   1004 
   1005 		if (!invalid_profile_flag) {
   1006 			sample_size = cochran_commander_profile_size(device, &data, idx, sample_start_address, sample_end_address);
   1007 			pre_size = cochran_commander_profile_size(device, &data, idx, sample_end_address, last_start_address);
   1008 			last_start_address = sample_start_address;
   1009 		}
   1010 
   1011 		// Build dive blob
   1012 		unsigned int dive_size = layout->rb_logbook_entry_size + sample_size;
   1013 		unsigned char *dive = (unsigned char *) malloc(dive_size + pre_size);
   1014 		if (dive == NULL) {
   1015 			status = DC_STATUS_NOMEMORY;
   1016 			goto error;
   1017 		}
   1018 
   1019 		memcpy(dive, log_entry, layout->rb_logbook_entry_size); // log
   1020 
   1021 		// Read profile data
   1022 		if (sample_size) {
   1023 			rc = dc_rbstream_read(rbstream, &progress, dive + layout->rb_logbook_entry_size, sample_size + pre_size);
   1024 			if (rc != DC_STATUS_SUCCESS) {
   1025 				ERROR (abstract->context, "Failed to read the sample data.");
   1026 				status = rc;
   1027 				free(dive);
   1028 				goto error;
   1029 			}
   1030 		}
   1031 
   1032 		if (callback && !callback (dive, dive_size, dive + layout->pt_fingerprint, layout->fingerprint_size, userdata)) {
   1033 			free(dive);
   1034 			break;
   1035 		}
   1036 
   1037 		free(dive);
   1038 	}
   1039 
   1040 error:
   1041 	dc_rbstream_free(rbstream);
   1042 	free(data.logbook);
   1043 	return status;
   1044 }