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

hw_ostc.c (27441B)


      1 /*
      2  * libdivecomputer
      3  *
      4  * Copyright (C) 2009 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 "hw_ostc.h"
     26 #include "context-private.h"
     27 #include "device-private.h"
     28 #include "checksum.h"
     29 #include "array.h"
     30 #include "ihex.h"
     31 
     32 #define ISINSTANCE(device) dc_device_isinstance((device), &hw_ostc_device_vtable)
     33 
     34 #define MAXRETRIES 9
     35 
     36 #define FW_190 0x015A
     37 
     38 #define SZ_MD2HASH 18
     39 #define SZ_EEPROM 256
     40 #define SZ_HEADER 266
     41 #define SZ_FW_190 0x8000
     42 #define SZ_FW_NEW 0x10000
     43 
     44 #define SZ_FIRMWARE 0x17F40
     45 #define SZ_BLOCK    0x40
     46 
     47 #define ACK     0x4B /* "K" for ok */
     48 #define NAK     0x4E /* "N" for not ok */
     49 #define PICTYPE 0x57 /* PIC type (18F4685) */
     50 
     51 #define WIDTH  320
     52 #define HEIGHT 240
     53 #define BLACK  0x00
     54 #define WHITE  0xFF
     55 
     56 typedef struct hw_ostc_device_t {
     57 	dc_device_t base;
     58 	dc_iostream_t *iostream;
     59 	unsigned char fingerprint[5];
     60 } hw_ostc_device_t;
     61 
     62 typedef struct hw_ostc_firmware_t {
     63 	unsigned char data[SZ_FIRMWARE];
     64 	unsigned char bitmap[SZ_FIRMWARE / SZ_BLOCK];
     65 } hw_ostc_firmware_t;
     66 
     67 static dc_status_t hw_ostc_device_set_fingerprint (dc_device_t *abstract, const unsigned char data[], unsigned int size);
     68 static dc_status_t hw_ostc_device_dump (dc_device_t *abstract, dc_buffer_t *buffer);
     69 static dc_status_t hw_ostc_device_foreach (dc_device_t *abstract, dc_dive_callback_t callback, void *userdata);
     70 static dc_status_t hw_ostc_device_timesync (dc_device_t *abstract, const dc_datetime_t *datetime);
     71 
     72 static const dc_device_vtable_t hw_ostc_device_vtable = {
     73 	sizeof(hw_ostc_device_t),
     74 	DC_FAMILY_HW_OSTC,
     75 	hw_ostc_device_set_fingerprint, /* set_fingerprint */
     76 	NULL, /* read */
     77 	NULL, /* write */
     78 	hw_ostc_device_dump, /* dump */
     79 	hw_ostc_device_foreach, /* foreach */
     80 	hw_ostc_device_timesync, /* timesync */
     81 	NULL /* close */
     82 };
     83 
     84 static dc_status_t
     85 hw_ostc_extract_dives (dc_device_t *device, const unsigned char data[], unsigned int size, dc_dive_callback_t callback, void *userdata);
     86 
     87 static dc_status_t
     88 hw_ostc_send (hw_ostc_device_t *device, unsigned char cmd, unsigned int echo)
     89 {
     90 	dc_status_t status = DC_STATUS_SUCCESS;
     91 	dc_device_t *abstract = (dc_device_t *) device;
     92 
     93 	// Send the command.
     94 	unsigned char command[1] = {cmd};
     95 	status = dc_iostream_write (device->iostream, command, sizeof (command), NULL);
     96 	if (status != DC_STATUS_SUCCESS) {
     97 		ERROR (abstract->context, "Failed to send the command.");
     98 		return status;
     99 	}
    100 
    101 	if (echo) {
    102 		// Read the echo.
    103 		unsigned char answer[1] = {0};
    104 		status = dc_iostream_read (device->iostream, answer, sizeof (answer), NULL);
    105 		if (status != DC_STATUS_SUCCESS) {
    106 			ERROR (abstract->context, "Failed to receive the echo.");
    107 			return status;
    108 		}
    109 
    110 		// Verify the echo.
    111 		if (memcmp (answer, command, sizeof (command)) != 0) {
    112 			ERROR (abstract->context, "Unexpected echo.");
    113 			return DC_STATUS_PROTOCOL;
    114 		}
    115 	}
    116 
    117 	return DC_STATUS_SUCCESS;
    118 }
    119 
    120 
    121 dc_status_t
    122 hw_ostc_device_open (dc_device_t **out, dc_context_t *context, dc_iostream_t *iostream)
    123 {
    124 	dc_status_t status = DC_STATUS_SUCCESS;
    125 	hw_ostc_device_t *device = NULL;
    126 
    127 	if (out == NULL)
    128 		return DC_STATUS_INVALIDARGS;
    129 
    130 	// Allocate memory.
    131 	device = (hw_ostc_device_t *) dc_device_allocate (context, &hw_ostc_device_vtable);
    132 	if (device == NULL) {
    133 		ERROR (context, "Failed to allocate memory.");
    134 		return DC_STATUS_NOMEMORY;
    135 	}
    136 
    137 	// Set the default values.
    138 	device->iostream = iostream;
    139 	memset (device->fingerprint, 0, sizeof (device->fingerprint));
    140 
    141 	// Set the serial communication protocol (115200 8N1).
    142 	status = dc_iostream_configure (device->iostream, 115200, 8, DC_PARITY_NONE, DC_STOPBITS_ONE, DC_FLOWCONTROL_NONE);
    143 	if (status != DC_STATUS_SUCCESS) {
    144 		ERROR (context, "Failed to set the terminal attributes.");
    145 		goto error_free;
    146 	}
    147 
    148 	// Set the timeout for receiving data.
    149 	status = dc_iostream_set_timeout (device->iostream, 4000);
    150 	if (status != DC_STATUS_SUCCESS) {
    151 		ERROR (context, "Failed to set the timeout.");
    152 		goto error_free;
    153 	}
    154 
    155 	// Make sure everything is in a sane state.
    156 	dc_iostream_sleep (device->iostream, 100);
    157 	dc_iostream_purge (device->iostream, DC_DIRECTION_ALL);
    158 
    159 	*out = (dc_device_t*) device;
    160 
    161 	return DC_STATUS_SUCCESS;
    162 
    163 error_free:
    164 	dc_device_deallocate ((dc_device_t *) device);
    165 	return status;
    166 }
    167 
    168 
    169 static dc_status_t
    170 hw_ostc_device_set_fingerprint (dc_device_t *abstract, const unsigned char data[], unsigned int size)
    171 {
    172 	hw_ostc_device_t *device = (hw_ostc_device_t *) abstract;
    173 
    174 	if (size && size != sizeof (device->fingerprint))
    175 		return DC_STATUS_INVALIDARGS;
    176 
    177 	if (size)
    178 		memcpy (device->fingerprint, data, sizeof (device->fingerprint));
    179 	else
    180 		memset (device->fingerprint, 0, sizeof (device->fingerprint));
    181 
    182 	return DC_STATUS_SUCCESS;
    183 }
    184 
    185 
    186 static dc_status_t
    187 hw_ostc_device_dump (dc_device_t *abstract, dc_buffer_t *buffer)
    188 {
    189 	dc_status_t status = DC_STATUS_SUCCESS;
    190 	hw_ostc_device_t *device = (hw_ostc_device_t*) abstract;
    191 
    192 	// Enable progress notifications.
    193 	dc_event_progress_t progress = EVENT_PROGRESS_INITIALIZER;
    194 	progress.maximum = SZ_HEADER + SZ_FW_NEW;
    195 	device_event_emit (abstract, DC_EVENT_PROGRESS, &progress);
    196 
    197 	// Send the command.
    198 	unsigned char command[1] = {'a'};
    199 	status = dc_iostream_write (device->iostream, command, sizeof (command), NULL);
    200 	if (status != DC_STATUS_SUCCESS) {
    201 		ERROR (abstract->context, "Failed to send the command.");
    202 		return status;
    203 	}
    204 
    205 	// Read the header.
    206 	unsigned char header[SZ_HEADER] = {0};
    207 	status = dc_iostream_read (device->iostream, header, sizeof (header), NULL);
    208 	if (status != DC_STATUS_SUCCESS) {
    209 		ERROR (abstract->context, "Failed to receive the header.");
    210 		return status;
    211 	}
    212 
    213 	// Verify the header.
    214 	unsigned char preamble[] = {0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0x55};
    215 	if (memcmp (header, preamble, sizeof (preamble)) != 0) {
    216 		ERROR (abstract->context, "Unexpected answer header.");
    217 		return DC_STATUS_DATAFORMAT;
    218 	}
    219 
    220 	// Get the firmware version.
    221 	unsigned int firmware = array_uint16_be (header + 264);
    222 
    223 	// Get the amount of profile data.
    224 	unsigned int size = sizeof (header);
    225 	if (firmware > FW_190)
    226 		size += SZ_FW_NEW;
    227 	else
    228 		size += SZ_FW_190;
    229 
    230 	// Update and emit a progress event.
    231 	progress.current = sizeof (header);
    232 	progress.maximum = size;
    233 	device_event_emit (abstract, DC_EVENT_PROGRESS, &progress);
    234 
    235 	// Allocate the required amount of memory.
    236 	if (!dc_buffer_resize (buffer, size)) {
    237 		ERROR (abstract->context, "Insufficient buffer space available.");
    238 		return DC_STATUS_NOMEMORY;
    239 	}
    240 
    241 	unsigned char *data = dc_buffer_get_data (buffer);
    242 
    243 	// Copy the header to the output buffer.
    244 	memcpy (data, header, sizeof (header));
    245 
    246 	unsigned int nbytes = sizeof (header);
    247 	while (nbytes < size) {
    248 		// Set the minimum packet size.
    249 		unsigned int len = 1024;
    250 
    251 		// Increase the packet size if more data is immediately available.
    252 		size_t available = 0;
    253 		status = dc_iostream_get_available (device->iostream, &available);
    254 		if (status == DC_STATUS_SUCCESS && available > len)
    255 			len = available;
    256 
    257 		// Limit the packet size to the total size.
    258 		if (nbytes + len > size)
    259 			len = size - nbytes;
    260 
    261 		// Read the packet.
    262 		status = dc_iostream_read (device->iostream, data + nbytes, len, NULL);
    263 		if (status != DC_STATUS_SUCCESS) {
    264 			ERROR (abstract->context, "Failed to receive the answer.");
    265 			return status;
    266 		}
    267 
    268 		// Update and emit a progress event.
    269 		progress.current += len;
    270 		device_event_emit (abstract, DC_EVENT_PROGRESS, &progress);
    271 
    272 		nbytes += len;
    273 	}
    274 
    275 	// Emit a device info event.
    276 	dc_event_devinfo_t devinfo;
    277 	devinfo.firmware = array_uint16_be (data + 264);
    278 	devinfo.serial = array_uint16_le (data + 6);
    279 	if (devinfo.serial > 7000)
    280 		devinfo.model = 3; // OSTC 2C
    281 	else if (devinfo.serial > 2048)
    282 		devinfo.model = 2; // OSTC 2N
    283 	else if (devinfo.serial > 300)
    284 		devinfo.model = 1; // OSTC Mk2
    285 	else
    286 		devinfo.model = 0; // OSTC
    287 	device_event_emit (abstract, DC_EVENT_DEVINFO, &devinfo);
    288 
    289 	return DC_STATUS_SUCCESS;
    290 }
    291 
    292 
    293 static dc_status_t
    294 hw_ostc_device_foreach (dc_device_t *abstract, dc_dive_callback_t callback, void *userdata)
    295 {
    296 	dc_buffer_t *buffer = dc_buffer_new (0);
    297 	if (buffer == NULL)
    298 		return DC_STATUS_NOMEMORY;
    299 
    300 	dc_status_t rc = hw_ostc_device_dump (abstract, buffer);
    301 	if (rc != DC_STATUS_SUCCESS) {
    302 		dc_buffer_free (buffer);
    303 		return rc;
    304 	}
    305 
    306 	rc = hw_ostc_extract_dives (abstract, dc_buffer_get_data (buffer),
    307 		dc_buffer_get_size (buffer), callback, userdata);
    308 
    309 	dc_buffer_free (buffer);
    310 
    311 	return rc;
    312 }
    313 
    314 
    315 dc_status_t
    316 hw_ostc_device_md2hash (dc_device_t *abstract, unsigned char data[], unsigned int size)
    317 {
    318 	dc_status_t status = DC_STATUS_SUCCESS;
    319 	hw_ostc_device_t *device = (hw_ostc_device_t *) abstract;
    320 
    321 	if (!ISINSTANCE (abstract))
    322 		return DC_STATUS_INVALIDARGS;
    323 
    324 	if (size < SZ_MD2HASH) {
    325 		ERROR (abstract->context, "Insufficient buffer space available.");
    326 		return DC_STATUS_INVALIDARGS;
    327 	}
    328 
    329 	// Send the command.
    330 	dc_status_t rc = hw_ostc_send (device, 'e', 0);
    331 	if (rc != DC_STATUS_SUCCESS)
    332 		return rc;
    333 
    334 	// Read the answer.
    335 	status = dc_iostream_read (device->iostream, data, SZ_MD2HASH, NULL);
    336 	if (status != DC_STATUS_SUCCESS) {
    337 		ERROR (abstract->context, "Failed to receive the answer.");
    338 		return status;
    339 	}
    340 
    341 	return DC_STATUS_SUCCESS;
    342 }
    343 
    344 
    345 static dc_status_t
    346 hw_ostc_device_timesync (dc_device_t *abstract, const dc_datetime_t *datetime)
    347 {
    348 	dc_status_t status = DC_STATUS_SUCCESS;
    349 	hw_ostc_device_t *device = (hw_ostc_device_t *) abstract;
    350 
    351 	// Send the command.
    352 	dc_status_t rc = hw_ostc_send (device, 'b', 1);
    353 	if (rc != DC_STATUS_SUCCESS)
    354 		return rc;
    355 
    356 	// Send the data packet.
    357 	unsigned char packet[6] = {
    358 		datetime->hour, datetime->minute, datetime->second,
    359 		datetime->month, datetime->day, datetime->year - 2000};
    360 	status = dc_iostream_write (device->iostream, packet, sizeof (packet), NULL);
    361 	if (status != DC_STATUS_SUCCESS) {
    362 		ERROR (abstract->context, "Failed to send the data packet.");
    363 		return status;
    364 	}
    365 
    366 	return DC_STATUS_SUCCESS;
    367 }
    368 
    369 
    370 dc_status_t
    371 hw_ostc_device_eeprom_read (dc_device_t *abstract, unsigned int bank, unsigned char data[], unsigned int size)
    372 {
    373 	dc_status_t status = DC_STATUS_SUCCESS;
    374 	hw_ostc_device_t *device = (hw_ostc_device_t *) abstract;
    375 
    376 	if (!ISINSTANCE (abstract))
    377 		return DC_STATUS_INVALIDARGS;
    378 
    379 	if (bank > 2) {
    380 		ERROR (abstract->context, "Invalid eeprom bank specified.");
    381 		return DC_STATUS_INVALIDARGS;
    382 	}
    383 
    384 	if (size < SZ_EEPROM) {
    385 		ERROR (abstract->context, "Insufficient buffer space available.");
    386 		return DC_STATUS_INVALIDARGS;
    387 	}
    388 
    389 	// Send the command.
    390 	const unsigned char command[] = {'g', 'j', 'm'};
    391 	dc_status_t rc = hw_ostc_send (device, command[bank], 0);
    392 	if (rc != DC_STATUS_SUCCESS)
    393 		return rc;
    394 
    395 	// Read the answer.
    396 	status = dc_iostream_read (device->iostream, data, SZ_EEPROM, NULL);
    397 	if (status != DC_STATUS_SUCCESS) {
    398 		ERROR (abstract->context, "Failed to receive the answer.");
    399 		return status;
    400 	}
    401 
    402 	return DC_STATUS_SUCCESS;
    403 }
    404 
    405 
    406 dc_status_t
    407 hw_ostc_device_eeprom_write (dc_device_t *abstract, unsigned int bank, const unsigned char data[], unsigned int size)
    408 {
    409 	hw_ostc_device_t *device = (hw_ostc_device_t *) abstract;
    410 
    411 	if (!ISINSTANCE (abstract))
    412 		return DC_STATUS_INVALIDARGS;
    413 
    414 	if (bank > 2) {
    415 		ERROR (abstract->context, "Invalid eeprom bank specified.");
    416 		return DC_STATUS_INVALIDARGS;
    417 	}
    418 
    419 	if (size != SZ_EEPROM) {
    420 		ERROR (abstract->context, "Insufficient buffer space available.");
    421 		return DC_STATUS_INVALIDARGS;
    422 	}
    423 
    424 	// Send the command.
    425 	const unsigned char command[] = {'d', 'i', 'n'};
    426 	dc_status_t rc = hw_ostc_send (device, command[bank], 1);
    427 	if (rc != DC_STATUS_SUCCESS)
    428 		return rc;
    429 
    430 	for (unsigned int i = 4; i < SZ_EEPROM; ++i) {
    431 		// Send the data byte.
    432 		rc = hw_ostc_send (device, data[i], 1);
    433 		if (rc != DC_STATUS_SUCCESS)
    434 			return rc;
    435 	}
    436 
    437 	return DC_STATUS_SUCCESS;
    438 }
    439 
    440 
    441 dc_status_t
    442 hw_ostc_device_reset (dc_device_t *abstract)
    443 {
    444 	hw_ostc_device_t *device = (hw_ostc_device_t *) abstract;
    445 
    446 	if (!ISINSTANCE (abstract))
    447 		return DC_STATUS_INVALIDARGS;
    448 
    449 	// Send the command.
    450 	dc_status_t rc = hw_ostc_send (device, 'h', 1);
    451 	if (rc != DC_STATUS_SUCCESS)
    452 		return rc;
    453 
    454 	return DC_STATUS_SUCCESS;
    455 }
    456 
    457 
    458 dc_status_t
    459 hw_ostc_device_screenshot (dc_device_t *abstract, dc_buffer_t *buffer, hw_ostc_format_t format)
    460 {
    461 	dc_status_t status = DC_STATUS_SUCCESS;
    462 	hw_ostc_device_t *device = (hw_ostc_device_t *) abstract;
    463 
    464 	if (!ISINSTANCE (abstract))
    465 		return DC_STATUS_INVALIDARGS;
    466 
    467 	// Erase the current contents of the buffer.
    468 	if (!dc_buffer_clear (buffer)) {
    469 		ERROR (abstract->context, "Insufficient buffer space available.");
    470 		return DC_STATUS_NOMEMORY;
    471 	}
    472 
    473 	// Bytes per pixel (RGB formats only).
    474 	unsigned int bpp = 0;
    475 
    476 	if (format == HW_OSTC_FORMAT_RAW) {
    477 		// The RAW format has a variable size, depending on the actual image
    478 		// content. Usually the total size is around 4K, which is used as an
    479 		// initial guess and expanded when necessary.
    480 		if (!dc_buffer_reserve (buffer, 4096)) {
    481 			ERROR (abstract->context, "Insufficient buffer space available.");
    482 			return DC_STATUS_NOMEMORY;
    483 		}
    484 	} else {
    485 		// The RGB formats have a fixed size, depending only on the dimensions
    486 		// and the number of bytes per pixel. The required amount of memory is
    487 		// allocated immediately.
    488 		bpp = (format == HW_OSTC_FORMAT_RGB16) ? 2 : 3;
    489 		if (!dc_buffer_resize (buffer, WIDTH * HEIGHT * bpp)) {
    490 			ERROR (abstract->context, "Insufficient buffer space available.");
    491 			return DC_STATUS_NOMEMORY;
    492 		}
    493 	}
    494 
    495 	// Enable progress notifications.
    496 	dc_event_progress_t progress = EVENT_PROGRESS_INITIALIZER;
    497 	progress.maximum = WIDTH * HEIGHT;
    498 	device_event_emit (abstract, DC_EVENT_PROGRESS, &progress);
    499 
    500 	// Send the command.
    501 	dc_status_t rc = hw_ostc_send (device, 'l', 1);
    502 	if (rc != DC_STATUS_SUCCESS)
    503 		return rc;
    504 
    505 	// Cache the pointer to the image data (RGB formats only).
    506 	unsigned char *image = dc_buffer_get_data (buffer);
    507 
    508 	// The OSTC sends the image data in a column by column layout, which is
    509 	// converted on the fly to a more convenient row by row layout as used
    510 	// in the majority of image formats. This conversions requires knowledge
    511 	// of the pixel coordinates.
    512 	unsigned int x = 0, y = 0;
    513 
    514 	unsigned int npixels = 0;
    515 	while (npixels < WIDTH * HEIGHT) {
    516 		unsigned char raw[3] = {0};
    517 		status = dc_iostream_read (device->iostream, raw, 1, NULL);
    518 		if (status != DC_STATUS_SUCCESS) {
    519 			ERROR (abstract->context, "Failed to receive the packet.");
    520 			return status;
    521 		}
    522 
    523 		unsigned int nbytes = 1;
    524 		unsigned int count = raw[0];
    525 		if ((count & 0x80) == 0x00) {
    526 			// Black pixel.
    527 			raw[1] = raw[2] = BLACK;
    528 			count &= 0x7F;
    529 		} else if ((count & 0xC0) == 0xC0) {
    530 			// White pixel.
    531 			raw[1] = raw[2] = WHITE;
    532 			count &= 0x3F;
    533 		} else {
    534 			// Color pixel.
    535 			status = dc_iostream_read (device->iostream, raw + 1, 2, NULL);
    536 			if (status != DC_STATUS_SUCCESS) {
    537 				ERROR (abstract->context, "Failed to receive the packet.");
    538 				return status;
    539 			}
    540 
    541 			nbytes += 2;
    542 			count &= 0x3F;
    543 		}
    544 		count++;
    545 
    546 		// Check for buffer overflows.
    547 		if (npixels + count > WIDTH * HEIGHT) {
    548 			ERROR (abstract->context, "Unexpected number of pixels received.");
    549 			return DC_STATUS_DATAFORMAT;
    550 		}
    551 
    552 		if (format == HW_OSTC_FORMAT_RAW) {
    553 			// Append the raw data to the output buffer.
    554 			if (!dc_buffer_append (buffer, raw, nbytes)) {
    555 				ERROR (abstract->context, "Insufficient buffer space available.");
    556 				return DC_STATUS_NOMEMORY;
    557 			}
    558 		} else {
    559 			// Store the decompressed data in the output buffer.
    560 			for (unsigned int i = 0; i < count; ++i) {
    561 				// Calculate the offset to the current pixel (row layout)
    562 				unsigned int offset = (y * WIDTH + x) * bpp;
    563 
    564 				if (format == HW_OSTC_FORMAT_RGB16) {
    565 					image[offset + 0] = raw[1];
    566 					image[offset + 1] = raw[2];
    567 				} else {
    568 					unsigned int value = (raw[1] << 8) + raw[2];
    569 					unsigned char r = (value & 0xF800) >> 11;
    570 					unsigned char g = (value & 0x07E0) >> 5;
    571 					unsigned char b = (value & 0x001F);
    572 					image[offset + 0] = 255 * r / 31;
    573 					image[offset + 1] = 255 * g / 63;
    574 					image[offset + 2] = 255 * b / 31;
    575 				}
    576 
    577 				// Move to the next pixel coordinate (column layout).
    578 				y++;
    579 				if (y == HEIGHT) {
    580 					y = 0;
    581 					x++;
    582 				}
    583 			}
    584 		}
    585 
    586 		// Update and emit a progress event.
    587 		progress.current += count;
    588 		device_event_emit (abstract, DC_EVENT_PROGRESS, &progress);
    589 
    590 		npixels += count;
    591 	}
    592 
    593 	return DC_STATUS_SUCCESS;
    594 }
    595 
    596 
    597 static dc_status_t
    598 hw_ostc_extract_dives (dc_device_t *abstract, const unsigned char data[], unsigned int size, dc_dive_callback_t callback, void *userdata)
    599 {
    600 	hw_ostc_device_t *device = (hw_ostc_device_t *) abstract;
    601 
    602 	if (abstract && !ISINSTANCE (abstract))
    603 		return DC_STATUS_INVALIDARGS;
    604 
    605 	const unsigned char header[2] = {0xFA, 0xFA};
    606 	const unsigned char footer[2] = {0xFD, 0xFD};
    607 
    608 	// Initialize the data stream pointers.
    609 	const unsigned char *current  = data + size;
    610 	const unsigned char *previous = data + size;
    611 
    612 	// Search the data stream for header markers.
    613 	while ((current = array_search_backward (data + 266, current - data - 266, header, sizeof (header))) != NULL) {
    614 		// Move the pointer to the begin of the header.
    615 		current -= sizeof (header);
    616 
    617 		// Once a header marker is found, start searching
    618 		// for the corresponding footer marker. The search is
    619 		// now limited to the start of the previous dive.
    620 		previous = array_search_forward (current, previous - current, footer, sizeof (footer));
    621 
    622 		if (previous) {
    623 			// Move the pointer to the end of the footer.
    624 			previous += sizeof (footer);
    625 
    626 			if (device && memcmp (current + 3, device->fingerprint, sizeof (device->fingerprint)) == 0)
    627 				return DC_STATUS_SUCCESS;
    628 
    629 			if (callback && !callback (current, previous - current, current + 3, 5, userdata))
    630 				return DC_STATUS_SUCCESS;
    631 		}
    632 
    633 		// Prepare for the next iteration.
    634 		previous = current;
    635 	}
    636 
    637 	return DC_STATUS_SUCCESS;
    638 }
    639 
    640 
    641 static dc_status_t
    642 hw_ostc_firmware_readfile (hw_ostc_firmware_t *firmware, dc_context_t *context, const char *filename)
    643 {
    644 	dc_status_t rc = DC_STATUS_SUCCESS;
    645 
    646 	if (firmware == NULL) {
    647 		ERROR (context, "Invalid arguments.");
    648 		return DC_STATUS_INVALIDARGS;
    649 	}
    650 
    651 	// Initialize the buffers.
    652 	memset (firmware->data, 0xFF, sizeof (firmware->data));
    653 	memset (firmware->bitmap, 0x00, sizeof (firmware->bitmap));
    654 
    655 	// Open the hex file.
    656 	dc_ihex_file_t *file = NULL;
    657 	rc = dc_ihex_file_open (&file, context, filename);
    658 	if (rc != DC_STATUS_SUCCESS) {
    659 		ERROR (context, "Failed to open the hex file.");
    660 		return rc;
    661 	}
    662 
    663 	// Read the hex file.
    664 	unsigned int lba = 0;
    665 	dc_ihex_entry_t entry;
    666 	while ((rc = dc_ihex_file_read (file, &entry)) == DC_STATUS_SUCCESS) {
    667 		if (entry.type == 0) {
    668 			// Data record.
    669 			unsigned int address = (lba << 16) + entry.address;
    670 			if (address + entry.length > SZ_FIRMWARE) {
    671 				WARNING (context, "Ignoring out of range record (0x%08x,%u).", address, entry.length);
    672 				continue;
    673 			}
    674 
    675 			// Copy the record to the buffer.
    676 			memcpy (firmware->data + address, entry.data, entry.length);
    677 
    678 			// Mark the corresponding blocks in the bitmap.
    679 			unsigned int begin = address / SZ_BLOCK;
    680 			unsigned int end = (address + entry.length + SZ_BLOCK - 1) / SZ_BLOCK;
    681 			for (unsigned int i = begin; i < end; ++i) {
    682 				firmware->bitmap[i] = 1;
    683 			}
    684 		} else if (entry.type == 1) {
    685 			// End of file record.
    686 			break;
    687 		} else if (entry.type == 4) {
    688 			// Extended linear address record.
    689 			lba = array_uint16_be (entry.data);
    690 		} else {
    691 			ERROR (context, "Unexpected record type.");
    692 			dc_ihex_file_close (file);
    693 			return DC_STATUS_DATAFORMAT;
    694 		}
    695 	}
    696 	if (rc != DC_STATUS_SUCCESS && rc != DC_STATUS_DONE) {
    697 		ERROR (context, "Failed to read the record.");
    698 		dc_ihex_file_close (file);
    699 		return rc;
    700 	}
    701 
    702 	// Close the file.
    703 	dc_ihex_file_close (file);
    704 
    705 	// Verify the presence of the first block.
    706 	if (firmware->bitmap[0] == 0) {
    707 		ERROR (context, "No first data block.");
    708 		return DC_STATUS_DATAFORMAT;
    709 	}
    710 
    711 	// Setup the last block.
    712 	// Copy the "goto main" instruction, stored in the first 8 bytes of the hex
    713 	// file, to the end of the last block at address 0x17F38. This last block
    714 	// needs to be present, regardless of whether it's included in the hex file
    715 	// or not!
    716 	memset (firmware->data + SZ_FIRMWARE - SZ_BLOCK, 0xFF, SZ_BLOCK - 8);
    717 	memcpy (firmware->data + SZ_FIRMWARE - 8, firmware->data, 8);
    718 	firmware->bitmap[C_ARRAY_SIZE(firmware->bitmap) - 1] = 1;
    719 
    720 	// Setup the first block.
    721 	// Copy the hardcoded "goto 0x17F40" instruction to the start of the first
    722 	// block at address 0x00000.
    723 	const unsigned char header[] = {0xA0, 0xEF, 0xBF, 0xF0};
    724 	memcpy (firmware->data, header, sizeof (header));
    725 
    726 	return rc;
    727 }
    728 
    729 
    730 static dc_status_t
    731 hw_ostc_firmware_setup_internal (hw_ostc_device_t *device)
    732 {
    733 	dc_status_t status = DC_STATUS_SUCCESS;
    734 	dc_device_t *abstract = (dc_device_t *) device;
    735 
    736 	// Send the command.
    737 	unsigned char command[1] = {0xC1};
    738 	status = dc_iostream_write (device->iostream, command, sizeof (command), NULL);
    739 	if (status != DC_STATUS_SUCCESS) {
    740 		ERROR (abstract->context, "Failed to send the command.");
    741 		return status;
    742 	}
    743 
    744 	// Read the response.
    745 	unsigned char answer[2] = {0};
    746 	status = dc_iostream_read (device->iostream, answer, sizeof (answer), NULL);
    747 	if (status != DC_STATUS_SUCCESS) {
    748 		ERROR (abstract->context, "Failed to receive the response.");
    749 		return status;
    750 	}
    751 
    752 	// Verify the response.
    753 	const unsigned char expected[2] = {PICTYPE, ACK};
    754 	if (memcmp (answer, expected, sizeof (expected)) != 0) {
    755 		ERROR (abstract->context, "Unexpected response.");
    756 		return DC_STATUS_PROTOCOL;
    757 	}
    758 
    759 	return DC_STATUS_SUCCESS;
    760 }
    761 
    762 
    763 static dc_status_t
    764 hw_ostc_firmware_setup (hw_ostc_device_t *device, unsigned int maxretries)
    765 {
    766 	dc_status_t rc = DC_STATUS_SUCCESS;
    767 
    768 	unsigned int nretries = 0;
    769 	while ((rc = hw_ostc_firmware_setup_internal (device)) != DC_STATUS_SUCCESS) {
    770 		if (rc != DC_STATUS_TIMEOUT && rc != DC_STATUS_PROTOCOL)
    771 			break;
    772 
    773 		// Abort if the maximum number of retries is reached.
    774 		if (nretries++ >= maxretries)
    775 			break;
    776 	}
    777 
    778 	return rc;
    779 }
    780 
    781 
    782 static dc_status_t
    783 hw_ostc_firmware_write_internal (hw_ostc_device_t *device, unsigned char *data, unsigned int size)
    784 {
    785 	dc_status_t status = DC_STATUS_SUCCESS;
    786 	dc_device_t *abstract = (dc_device_t *) device;
    787 
    788 	// Send the packet.
    789 	status = dc_iostream_write (device->iostream, data, size, NULL);
    790 	if (status != DC_STATUS_SUCCESS) {
    791 		ERROR (abstract->context, "Failed to send the packet.");
    792 		return status;
    793 	}
    794 
    795 	// Read the response.
    796 	unsigned char answer[1] = {0};
    797 	status = dc_iostream_read (device->iostream, answer, sizeof (answer), NULL);
    798 	if (status != DC_STATUS_SUCCESS) {
    799 		ERROR (abstract->context, "Failed to receive the response.");
    800 		return status;
    801 	}
    802 
    803 	// Verify the response.
    804 	const unsigned char expected[] = {ACK};
    805 	if (memcmp (answer, expected, sizeof (expected)) != 0) {
    806 		ERROR (abstract->context, "Unexpected response.");
    807 		return DC_STATUS_PROTOCOL;
    808 	}
    809 
    810 	return DC_STATUS_SUCCESS;
    811 }
    812 
    813 
    814 static dc_status_t
    815 hw_ostc_firmware_write (hw_ostc_device_t *device, unsigned char *data, unsigned int size)
    816 {
    817 	dc_status_t rc = DC_STATUS_SUCCESS;
    818 
    819 	unsigned int nretries = 0;
    820 	while ((rc = hw_ostc_firmware_write_internal (device, data, size)) != DC_STATUS_SUCCESS) {
    821 		if (rc != DC_STATUS_TIMEOUT && rc != DC_STATUS_PROTOCOL)
    822 			break;
    823 
    824 		// Abort if the maximum number of retries is reached.
    825 		if (nretries++ >= MAXRETRIES)
    826 			break;
    827 	}
    828 
    829 	return rc;
    830 }
    831 
    832 /*
    833  * Think twice before modifying the code for updating the ostc firmware!
    834  * It has been carefully developed and tested with assistance from
    835  * Heinrichs-Weikamp, using a special development unit. If you start
    836  * experimenting with a normal unit and accidentally screw up, you might
    837  * brick the device permanently and turn it into an expensive
    838  * paperweight. You have been warned!
    839  */
    840 dc_status_t
    841 hw_ostc_device_fwupdate (dc_device_t *abstract, const char *filename)
    842 {
    843 	dc_status_t rc = DC_STATUS_SUCCESS;
    844 	hw_ostc_device_t *device = (hw_ostc_device_t *) abstract;
    845 	dc_context_t *context = (abstract ? abstract->context : NULL);
    846 
    847 	if (!ISINSTANCE (abstract))
    848 		return DC_STATUS_INVALIDARGS;
    849 
    850 	// Allocate memory for the firmware data.
    851 	hw_ostc_firmware_t *firmware = (hw_ostc_firmware_t *) malloc (sizeof (hw_ostc_firmware_t));
    852 	if (firmware == NULL) {
    853 		ERROR (context, "Failed to allocate memory.");
    854 		return DC_STATUS_NOMEMORY;
    855 	}
    856 
    857 	// Read the hex file.
    858 	rc = hw_ostc_firmware_readfile (firmware, context, filename);
    859 	if (rc != DC_STATUS_SUCCESS) {
    860 		ERROR (context, "Failed to read the firmware file.");
    861 		free (firmware);
    862 		return rc;
    863 	}
    864 
    865 	// Temporary set a relative short timeout. The command to setup the
    866 	// bootloader needs to be send repeatedly, until the response packet is
    867 	// received. Thus the time between each two attempts is directly controlled
    868 	// by the timeout value.
    869 	rc = dc_iostream_set_timeout (device->iostream, 300);
    870 	if (rc != DC_STATUS_SUCCESS) {
    871 		ERROR (context, "Failed to set the timeout.");
    872 		free (firmware);
    873 		return rc;
    874 	}
    875 
    876 	// Setup the bootloader.
    877 	const unsigned int baudrates[] = {19200, 115200};
    878 	for (unsigned int i = 0; i < C_ARRAY_SIZE(baudrates); ++i) {
    879 		// Adjust the baudrate.
    880 		rc = dc_iostream_configure (device->iostream, baudrates[i], 8, DC_PARITY_NONE, DC_STOPBITS_ONE, DC_FLOWCONTROL_NONE);
    881 		if (rc != DC_STATUS_SUCCESS) {
    882 			ERROR (abstract->context, "Failed to set the terminal attributes.");
    883 			free (firmware);
    884 			return rc;
    885 		}
    886 
    887 		// Try to setup the bootloader.
    888 		unsigned int maxretries = (i == 0 ? 1 : MAXRETRIES);
    889 		rc = hw_ostc_firmware_setup (device, maxretries);
    890 		if (rc == DC_STATUS_SUCCESS)
    891 			break;
    892 	}
    893 	if (rc != DC_STATUS_SUCCESS) {
    894 		ERROR (abstract->context, "Failed to setup the bootloader.");
    895 		free (firmware);
    896 		return rc;
    897 	}
    898 
    899 	// Increase the timeout again.
    900 	rc = dc_iostream_set_timeout (device->iostream, 1000);
    901 	if (rc != DC_STATUS_SUCCESS) {
    902 		ERROR (context, "Failed to set the timeout.");
    903 		free (firmware);
    904 		return rc;
    905 	}
    906 
    907 	// Enable progress notifications.
    908 	dc_event_progress_t progress = EVENT_PROGRESS_INITIALIZER;
    909 	progress.maximum = C_ARRAY_SIZE(firmware->bitmap);
    910 	device_event_emit (abstract, DC_EVENT_PROGRESS, &progress);
    911 
    912 	for (unsigned int i = 0; i < C_ARRAY_SIZE(firmware->bitmap); ++i) {
    913 		// Skip empty blocks.
    914 		if (firmware->bitmap[i] == 0)
    915 			continue;
    916 
    917 		// Create the packet.
    918 		unsigned int address = i * SZ_BLOCK;
    919 		unsigned char packet[4 + SZ_BLOCK + 1] = {
    920 			(address >> 16) & 0xFF,
    921 			(address >>  8) & 0xFF,
    922 			(address      ) & 0xFF,
    923 			SZ_BLOCK
    924 		};
    925 		memcpy (packet + 4, firmware->data + address, SZ_BLOCK);
    926 		packet[sizeof (packet) - 1] = ~checksum_add_uint8 (packet, 4 + SZ_BLOCK, 0x00) + 1;
    927 
    928 		// Send the packet.
    929 		rc = hw_ostc_firmware_write (device, packet, sizeof (packet));
    930 		if (rc != DC_STATUS_SUCCESS) {
    931 			ERROR (abstract->context, "Failed to send the packet.");
    932 			free (firmware);
    933 			return rc;
    934 		}
    935 
    936 		// Update and emit a progress event.
    937 		progress.current = i + 1;
    938 		device_event_emit (abstract, DC_EVENT_PROGRESS, &progress);
    939 	}
    940 
    941 	free (firmware);
    942 
    943 	return DC_STATUS_SUCCESS;
    944 }