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_ostc3.c (56550B)


      1 /*
      2  * libdivecomputer
      3  *
      4  * Copyright (C) 2013 Jef Driesen
      5  * Copyright (C) 2014 Anton Lundin
      6  *
      7  * This library is free software; you can redistribute it and/or
      8  * modify it under the terms of the GNU Lesser General Public
      9  * License as published by the Free Software Foundation; either
     10  * version 2.1 of the License, or (at your option) any later version.
     11  *
     12  * This library is distributed in the hope that it will be useful,
     13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
     14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
     15  * Lesser General Public License for more details.
     16  *
     17  * You should have received a copy of the GNU Lesser General Public
     18  * License along with this library; if not, write to the Free Software
     19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
     20  * MA 02110-1301 USA
     21  */
     22 
     23 #include <string.h> // memcmp, memcpy
     24 #include <stdlib.h> // malloc, free
     25 #include <stdio.h>  // FILE, fopen
     26 
     27 #include "hw_ostc3.h"
     28 #include "context-private.h"
     29 #include "device-private.h"
     30 #include "array.h"
     31 #include "aes.h"
     32 #include "platform.h"
     33 #include "packet.h"
     34 #include "ringbuffer.h"
     35 
     36 #define ISINSTANCE(device) dc_device_isinstance((device), &hw_ostc3_device_vtable)
     37 
     38 #define OSTC3FW(major,minor) ( \
     39 		(((major) & 0xFF) << 8) | \
     40 		((minor) & 0xFF))
     41 
     42 #define SZ_DISPLAY_FROG     15
     43 #define SZ_DISPLAY_OSTC3    16
     44 #define SZ_DISPLAY_MAX      SZ_DISPLAY_OSTC3
     45 #define SZ_CUSTOMTEXT_FROG  13
     46 #define SZ_CUSTOMTEXT_OSTC3 60
     47 #define SZ_CUSTOMTEXT_MAX   SZ_CUSTOMTEXT_OSTC3
     48 #define SZ_VERSION_FROG     (SZ_CUSTOMTEXT_FROG + 4)
     49 #define SZ_VERSION_OSTC3    (SZ_CUSTOMTEXT_OSTC3 + 4)
     50 #define SZ_VERSION_MAX      SZ_VERSION_OSTC3
     51 
     52 #define SZ_HARDWARE   1
     53 #define SZ_HARDWARE2  5
     54 #define SZ_MEMORY     0x400000
     55 #define SZ_CONFIG     4
     56 #define SZ_FWINFO     4
     57 #define SZ_FIRMWARE_OSTC3   0x01E000        // 120KB
     58 #define SZ_FIRMWARE_FROG    0x01D000        // 116KB
     59 #define SZ_FIRMWARE_BLOCK    0x1000   //   4KB
     60 #define SZ_FIRMWARE_BLOCK2   0x0100   //  256B
     61 #define FIRMWARE_AREA      0x3E0000
     62 
     63 #define RB_LOGBOOK_SIZE_COMPACT  16
     64 #define RB_LOGBOOK_SIZE_FULL     256
     65 #define RB_LOGBOOK_COUNT 256
     66 
     67 #define RB_PROFILE_BEGIN 0x000000
     68 #define RB_PROFILE_END   0x200000
     69 #define RB_PROFILE_DISTANCE(a,b) ringbuffer_distance (a, b, DC_RINGBUFFER_EMPTY, RB_PROFILE_BEGIN, RB_PROFILE_END)
     70 
     71 #define S_BLOCK_READ 0x20
     72 #define S_BLOCK_WRITE 0x30
     73 #define S_BLOCK_WRITE2 0x31
     74 #define S_ERASE    0x42
     75 #define S_KEY      0x4B
     76 #define S_READY    0x4C
     77 #define READY      0x4D
     78 #define S_UPGRADE  0x50
     79 #define HARDWARE2  0x60
     80 #define HEADER     0x61
     81 #define CLOCK      0x62
     82 #define CUSTOMTEXT 0x63
     83 #define DIVE       0x66
     84 #define IDENTITY   0x69
     85 #define HARDWARE   0x6A
     86 #define S_FWINFO   0x6B
     87 #define DISPLAY    0x6E
     88 #define COMPACT    0x6D
     89 #define READ       0x72
     90 #define S_UPLOAD   0x73
     91 #define WRITE      0x77
     92 #define RESET      0x78
     93 #define S_INIT     0xAA
     94 #define INIT       0xBB
     95 #define EXIT       0xFF
     96 
     97 #define INVALID    0xFFFFFFFF
     98 #define UNKNOWN    0x00
     99 #define OSTC3      0x0A
    100 #define SPORT      0x12
    101 #define CR         0x05
    102 #define MODEL_OSTC4 0x43
    103 #define MODEL_OSTC5 0x44
    104 
    105 #define UNDEFINED  0xFFFFFFFF
    106 
    107 #define NODELAY 0
    108 #define TIMEOUT 400
    109 
    110 #define HDR_COMPACT_LENGTH   0 // 3 bytes
    111 #define HDR_COMPACT_SUMMARY  3 // 10 bytes
    112 #define HDR_COMPACT_NUMBER  13 // 2 bytes
    113 #define HDR_COMPACT_VERSION 15 // 1 byte
    114 
    115 #define HDR_FULL_LENGTH      9 // 3 bytes
    116 #define HDR_FULL_SUMMARY    12 // 10 bytes
    117 #define HDR_FULL_NUMBER     80 // 2 bytes
    118 #define HDR_FULL_VERSION     8 // 1 byte
    119 
    120 #define HDR_FULL_POINTERS    2 // 6 bytes
    121 #define HDR_FULL_FIRMWARE   48 // 2 bytes
    122 
    123 typedef enum hw_ostc3_state_t {
    124 	OPEN,
    125 	DOWNLOAD,
    126 	SERVICE,
    127 	REBOOTING,
    128 } hw_ostc3_state_t;
    129 
    130 typedef struct hw_ostc3_device_t {
    131 	dc_device_t base;
    132 	dc_iostream_t *iostream;
    133 	unsigned int frog;
    134 	unsigned int hardware;
    135 	unsigned int feature;
    136 	unsigned int model;
    137 	unsigned int serial;
    138 	unsigned int firmware;
    139 	unsigned char fingerprint[5];
    140 	hw_ostc3_state_t state;
    141 } hw_ostc3_device_t;
    142 
    143 typedef struct hw_ostc3_logbook_t {
    144 	unsigned int size;
    145 	unsigned int profile;
    146 	unsigned int fingerprint;
    147 	unsigned int number;
    148 	unsigned int version;
    149 	unsigned int pointers;
    150 	unsigned int firmware;
    151 } hw_ostc3_logbook_t;
    152 
    153 typedef struct hw_ostc3_firmware_t {
    154 	unsigned int size;
    155 	unsigned int checksum;
    156 	unsigned char data[];
    157 } hw_ostc3_firmware_t;
    158 
    159 static dc_status_t hw_ostc3_device_set_fingerprint (dc_device_t *abstract, const unsigned char data[], unsigned int size);
    160 static dc_status_t hw_ostc3_device_read (dc_device_t *abstract, unsigned int address, unsigned char data[], unsigned int size);
    161 static dc_status_t hw_ostc3_device_write (dc_device_t *abstract, unsigned int address, const unsigned char data[], unsigned int size);
    162 static dc_status_t hw_ostc3_device_dump (dc_device_t *abstract, dc_buffer_t *buffer);
    163 static dc_status_t hw_ostc3_device_foreach (dc_device_t *abstract, dc_dive_callback_t callback, void *userdata);
    164 static dc_status_t hw_ostc3_device_timesync (dc_device_t *abstract, const dc_datetime_t *datetime);
    165 static dc_status_t hw_ostc3_device_close (dc_device_t *abstract);
    166 
    167 static const dc_device_vtable_t hw_ostc3_device_vtable = {
    168 	sizeof(hw_ostc3_device_t),
    169 	DC_FAMILY_HW_OSTC3,
    170 	hw_ostc3_device_set_fingerprint, /* set_fingerprint */
    171 	hw_ostc3_device_read, /* read */
    172 	hw_ostc3_device_write, /* write */
    173 	hw_ostc3_device_dump, /* dump */
    174 	hw_ostc3_device_foreach, /* foreach */
    175 	hw_ostc3_device_timesync, /* timesync */
    176 	hw_ostc3_device_close /* close */
    177 };
    178 
    179 static const hw_ostc3_logbook_t hw_ostc3_logbook_compact = {
    180 	RB_LOGBOOK_SIZE_COMPACT, /* size */
    181 	0,                       /* profile */
    182 	3,                       /* fingerprint */
    183 	13,                      /* number */
    184 	15,                      /* version */
    185 	UNDEFINED,               /* pointers */
    186 	UNDEFINED,               /* firmware */
    187 };
    188 
    189 static const hw_ostc3_logbook_t hw_ostc3_logbook_full[2] = {
    190 	/* OSTC3 */
    191 	{
    192 		RB_LOGBOOK_SIZE_FULL, /* size */
    193 		9,                    /* profile */
    194 		12,                   /* fingerprint */
    195 		80,                   /* number */
    196 		8,                    /* version */
    197 		2,                    /* pointers */
    198 		48,                   /* firmware */
    199 	},
    200 	/* Frog */
    201 	{
    202 		RB_LOGBOOK_SIZE_FULL, /* size */
    203 		UNDEFINED,            /* profile */
    204 		9,                    /* fingerprint */
    205 		52,                   /* number */
    206 		8,                    /* version */
    207 		2,                    /* pointers */
    208 		32,                   /* firmware */
    209 	}
    210 };
    211 
    212 static const unsigned char hw_ostc3_key[2][16] = {
    213 	/* OSTC3 */
    214 	{
    215 		0xF1, 0xE9, 0xB0, 0x30,
    216 		0x45, 0x6F, 0xBE, 0x55,
    217 		0xFF, 0xE7, 0xF8, 0x31,
    218 		0x13, 0x6C, 0xF2, 0xFE
    219 	},
    220 	/* Frog */
    221 	{
    222 		0x6F, 0x55, 0xBE, 0x45,
    223 		0x6C, 0xFE, 0xF2, 0x13,
    224 		0xE7, 0x31, 0xF8, 0xFF,
    225 		0xE9, 0x30, 0xB0, 0xF1
    226 	}
    227 };
    228 
    229 static int
    230 hw_ostc3_strncpy (unsigned char *data, unsigned int size, const char *text)
    231 {
    232 	// Check the maximum length.
    233 	size_t length = (text ? strlen (text) : 0);
    234 	if (length > size) {
    235 		return -1;
    236 	}
    237 
    238 	// Copy the text.
    239 	if (length)
    240 		memcpy (data, text, length);
    241 
    242 	// Pad with spaces.
    243 	memset (data + length, 0x20, size - length);
    244 
    245 	return 0;
    246 }
    247 
    248 static dc_status_t
    249 hw_ostc3_read (hw_ostc3_device_t *device, dc_event_progress_t *progress, unsigned char data[], size_t size)
    250 {
    251 	dc_status_t rc = DC_STATUS_SUCCESS;
    252 
    253 	size_t nbytes = 0;
    254 	while (nbytes < size) {
    255 		// Set the minimum packet size.
    256 		size_t length = 1024;
    257 
    258 		// Limit the packet size to the total size.
    259 		if (nbytes + length > size)
    260 			length = size - nbytes;
    261 
    262 		// Read the packet.
    263 		rc = dc_iostream_read (device->iostream, data + nbytes, length, NULL);
    264 		if (rc != DC_STATUS_SUCCESS)
    265 			return rc;
    266 
    267 		// Update and emit a progress event.
    268 		if (progress) {
    269 			progress->current += length;
    270 			device_event_emit ((dc_device_t *) device, DC_EVENT_PROGRESS, progress);
    271 		}
    272 
    273 		nbytes += length;
    274 	}
    275 
    276 	return rc;
    277 }
    278 
    279 static dc_status_t
    280 hw_ostc3_write (hw_ostc3_device_t *device, dc_event_progress_t *progress, const unsigned char data[], size_t size)
    281 {
    282 	dc_status_t rc = DC_STATUS_SUCCESS;
    283 
    284 	size_t nbytes = 0;
    285 	while (nbytes < size) {
    286 		// Set the maximum packet size.
    287 		size_t length = ISHWOS4(device->hardware) ? 64 : 1024;
    288 
    289 		// Limit the packet size to the total size.
    290 		if (nbytes + length > size)
    291 			length = size - nbytes;
    292 
    293 		// Write the packet.
    294 		rc = dc_iostream_write (device->iostream, data + nbytes, length, NULL);
    295 		if (rc != DC_STATUS_SUCCESS)
    296 			return rc;
    297 
    298 		// Update and emit a progress event.
    299 		if (progress) {
    300 			progress->current += length;
    301 			device_event_emit ((dc_device_t *) device, DC_EVENT_PROGRESS, progress);
    302 		}
    303 
    304 		nbytes += length;
    305 	}
    306 
    307 	return rc;
    308 }
    309 
    310 static dc_status_t
    311 hw_ostc3_transfer (hw_ostc3_device_t *device,
    312                   dc_event_progress_t *progress,
    313                   unsigned char cmd,
    314                   const unsigned char input[],
    315                   unsigned int isize,
    316                   unsigned char output[],
    317                   unsigned int osize,
    318                   unsigned int *actual,
    319                   unsigned int delay)
    320 {
    321 	dc_device_t *abstract = (dc_device_t *) device;
    322 	dc_status_t status = DC_STATUS_SUCCESS;
    323 	const hw_ostc3_logbook_t *layout = &hw_ostc3_logbook_full[device->frog];
    324 	unsigned int length = osize;
    325 
    326 	if (cmd == DIVE && length < RB_LOGBOOK_SIZE_FULL)
    327 		return DC_STATUS_INVALIDARGS;
    328 
    329 	if (device_is_cancelled (abstract))
    330 		return DC_STATUS_CANCELLED;
    331 
    332 	// Get the correct ready byte for the current state.
    333 	const unsigned char ready = (device->state == SERVICE ? S_READY : READY);
    334 
    335 	// Send the command.
    336 	unsigned char command[1] = {cmd};
    337 	status = dc_iostream_write (device->iostream, command, sizeof (command), NULL);
    338 	if (status != DC_STATUS_SUCCESS) {
    339 		ERROR (abstract->context, "Failed to send the command.");
    340 		return status;
    341 	}
    342 
    343 	if (!device->frog || (cmd != INIT && cmd != HEADER)) {
    344 		// Read the echo.
    345 		unsigned char echo[1] = {0};
    346 		status = dc_iostream_read (device->iostream, echo, sizeof (echo), NULL);
    347 		if (status != DC_STATUS_SUCCESS) {
    348 			ERROR (abstract->context, "Failed to receive the echo.");
    349 			return status;
    350 		}
    351 
    352 		// Verify the echo.
    353 		if (memcmp (echo, command, sizeof (command)) != 0) {
    354 			if (echo[0] == ready) {
    355 				ERROR (abstract->context, "Unsupported command.");
    356 				return DC_STATUS_UNSUPPORTED;
    357 			} else {
    358 				ERROR (abstract->context, "Unexpected echo.");
    359 				return DC_STATUS_PROTOCOL;
    360 			}
    361 		}
    362 	}
    363 
    364 	if (input) {
    365 		if (cmd == WRITE) {
    366 			// Send the first byte of the input data packet.
    367 			status = hw_ostc3_write (device, progress, input, 1);
    368 			if (status != DC_STATUS_SUCCESS) {
    369 				ERROR (abstract->context, "Failed to send the data packet.");
    370 				return status;
    371 			}
    372 
    373 			dc_iostream_sleep (device->iostream, 10);
    374 
    375 			// Send the remainder of the input data packet.
    376 			status = hw_ostc3_write (device, progress, input + 1, isize - 1);
    377 			if (status != DC_STATUS_SUCCESS) {
    378 				ERROR (abstract->context, "Failed to send the data packet.");
    379 				return status;
    380 			}
    381 		} else {
    382 			// Send the input data packet.
    383 			status = hw_ostc3_write (device, progress, input, isize);
    384 			if (status != DC_STATUS_SUCCESS) {
    385 				ERROR (abstract->context, "Failed to send the data packet.");
    386 				return status;
    387 			}
    388 		}
    389 	}
    390 
    391 	if (output) {
    392 		if (cmd == DIVE) {
    393 			// Read the dive header.
    394 			status = hw_ostc3_read (device, progress, output, RB_LOGBOOK_SIZE_FULL);
    395 			if (status != DC_STATUS_SUCCESS) {
    396 				ERROR (abstract->context, "Failed to receive the dive header.");
    397 				return status;
    398 			}
    399 
    400 			// When the hwOS firmware detects the dive profile is no longer
    401 			// valid, it sends a modified dive header (with the begin/end
    402 			// pointer fields reset to zero, and the length field reduced to 8
    403 			// bytes), along with an empty dive profile. Detect this condition
    404 			// and adjust the expected length.
    405 			if (!device->frog &&
    406 				array_isequal (output + layout->pointers, 6, 0x00) &&
    407 				array_uint24_le (output + layout->profile) == 8 &&
    408 				length > RB_LOGBOOK_SIZE_FULL + 5) {
    409 				length = RB_LOGBOOK_SIZE_FULL + 5;
    410 			}
    411 
    412 			// Read the dive profile.
    413 			status = hw_ostc3_read (device, progress, output + RB_LOGBOOK_SIZE_FULL, length - RB_LOGBOOK_SIZE_FULL);
    414 			if (status != DC_STATUS_SUCCESS) {
    415 				ERROR (abstract->context, "Failed to receive the dive profile.");
    416 				return status;
    417 			}
    418 
    419 			// Update and emit a progress event.
    420 			if (progress && osize > length) {
    421 				progress->current += osize - length;
    422 				device_event_emit ((dc_device_t *) device, DC_EVENT_PROGRESS, progress);
    423 			}
    424 		} else {
    425 			// Read the output data packet.
    426 			status = hw_ostc3_read (device, progress, output, length);
    427 			if (status != DC_STATUS_SUCCESS) {
    428 				ERROR (abstract->context, "Failed to receive the answer.");
    429 				return status;
    430 			}
    431 		}
    432 	}
    433 
    434 	if (delay) {
    435 		dc_iostream_poll (device->iostream, delay);
    436 	}
    437 
    438 	if (cmd != EXIT) {
    439 		// Read the ready byte.
    440 		unsigned char answer[1] = {0};
    441 		status = dc_iostream_read (device->iostream, answer, sizeof (answer), NULL);
    442 		if (status != DC_STATUS_SUCCESS) {
    443 			ERROR (abstract->context, "Failed to receive the ready byte.");
    444 			return status;
    445 		}
    446 
    447 		// Verify the ready byte.
    448 		if (answer[0] != ready) {
    449 			ERROR (abstract->context, "Unexpected ready byte.");
    450 			return DC_STATUS_PROTOCOL;
    451 		}
    452 	}
    453 
    454 	if (actual)
    455 		*actual = length;
    456 
    457 	return DC_STATUS_SUCCESS;
    458 }
    459 
    460 
    461 dc_status_t
    462 hw_ostc3_device_open (dc_device_t **out, dc_context_t *context, dc_iostream_t *iostream, unsigned int frog)
    463 {
    464 	dc_status_t status = DC_STATUS_SUCCESS;
    465 	hw_ostc3_device_t *device = NULL;
    466 	dc_transport_t transport = dc_iostream_get_transport (iostream);
    467 
    468 	if (out == NULL)
    469 		return DC_STATUS_INVALIDARGS;
    470 
    471 	// Allocate memory.
    472 	device = (hw_ostc3_device_t *) dc_device_allocate (context, &hw_ostc3_device_vtable);
    473 	if (device == NULL) {
    474 		ERROR (context, "Failed to allocate memory.");
    475 		return DC_STATUS_NOMEMORY;
    476 	}
    477 
    478 	// Set the default values.
    479 	device->frog = frog;
    480 	device->hardware = INVALID;
    481 	device->feature = 0;
    482 	device->model = 0;
    483 	device->serial = 0;
    484 	device->firmware = 0;
    485 	memset (device->fingerprint, 0, sizeof (device->fingerprint));
    486 
    487 	// Create the packet stream.
    488 	if (transport == DC_TRANSPORT_BLE) {
    489 		status = dc_packet_open (&device->iostream, context, iostream, 244, 20);
    490 		if (status != DC_STATUS_SUCCESS) {
    491 			ERROR (context, "Failed to create the packet stream.");
    492 			goto error_free;
    493 		}
    494 	} else {
    495 		device->iostream = iostream;
    496 	}
    497 
    498 	// Set the serial communication protocol (115200 8N1).
    499 	status = dc_iostream_configure (device->iostream, 115200, 8, DC_PARITY_NONE, DC_STOPBITS_ONE, DC_FLOWCONTROL_NONE);
    500 	if (status != DC_STATUS_SUCCESS) {
    501 		ERROR (context, "Failed to set the terminal attributes.");
    502 		goto error_free_iostream;
    503 	}
    504 
    505 	// Set the timeout for receiving data (3000ms).
    506 	status = dc_iostream_set_timeout (device->iostream, 3000);
    507 	if (status != DC_STATUS_SUCCESS) {
    508 		ERROR (context, "Failed to set the timeout.");
    509 		goto error_free_iostream;
    510 	}
    511 
    512 	// Make sure everything is in a sane state.
    513 	dc_iostream_sleep (device->iostream, 300);
    514 	dc_iostream_purge (device->iostream, DC_DIRECTION_ALL);
    515 
    516 	device->state = OPEN;
    517 
    518 	*out = (dc_device_t *) device;
    519 
    520 	return DC_STATUS_SUCCESS;
    521 
    522 error_free_iostream:
    523 	if (transport == DC_TRANSPORT_BLE) {
    524 		dc_iostream_close (device->iostream);
    525 	}
    526 error_free:
    527 	dc_device_deallocate ((dc_device_t *) device);
    528 	return status;
    529 }
    530 
    531 
    532 static dc_status_t
    533 hw_ostc3_device_id (hw_ostc3_device_t *device, unsigned char data[], unsigned int size)
    534 {
    535 	dc_status_t status = DC_STATUS_SUCCESS;
    536 
    537 	if (size != SZ_HARDWARE && size != SZ_HARDWARE2)
    538 		return DC_STATUS_INVALIDARGS;
    539 
    540 	unsigned char hardware[SZ_HARDWARE2] = {0};
    541 	if (size == SZ_HARDWARE2) {
    542 		status = hw_ostc3_transfer(device, NULL, HARDWARE2, NULL, 0, hardware, SZ_HARDWARE2, NULL, NODELAY);
    543 	}
    544 
    545 	if (size == SZ_HARDWARE || status == DC_STATUS_UNSUPPORTED) {
    546 		status = hw_ostc3_transfer(device, NULL, HARDWARE, NULL, 0, hardware + 1, SZ_HARDWARE, NULL, NODELAY);
    547 	}
    548 
    549 	if (status != DC_STATUS_SUCCESS)
    550 		return status;
    551 
    552 	if (size == SZ_HARDWARE2) {
    553 		memcpy (data, hardware, SZ_HARDWARE2);
    554 	} else {
    555 		memcpy (data, hardware + 1, SZ_HARDWARE);
    556 	}
    557 
    558 	return DC_STATUS_SUCCESS;
    559 }
    560 
    561 
    562 static dc_status_t
    563 hw_ostc3_device_init_download (hw_ostc3_device_t *device)
    564 {
    565 	dc_device_t *abstract = (dc_device_t *) device;
    566 	dc_context_t *context = (abstract ? abstract->context : NULL);
    567 
    568 	// Send the init command.
    569 	dc_status_t status = hw_ostc3_transfer (device, NULL, INIT, NULL, 0, NULL, 0, NULL, NODELAY);
    570 	if (status != DC_STATUS_SUCCESS) {
    571 		ERROR (context, "Failed to send the command.");
    572 		return status;
    573 	}
    574 
    575 	device->state = DOWNLOAD;
    576 
    577 	return DC_STATUS_SUCCESS;
    578 }
    579 
    580 
    581 static dc_status_t
    582 hw_ostc3_device_init_service (hw_ostc3_device_t *device)
    583 {
    584 	dc_status_t status = DC_STATUS_SUCCESS;
    585 	dc_device_t *abstract = (dc_device_t *) device;
    586 
    587 	const unsigned char command[2][4] = {
    588 		{S_INIT, 0xAB, 0xCD, 0xEF}, // OSTC3
    589 		{S_INIT, 0xAA, 0xAB, 0xAC}, // Frog
    590 	};
    591 	const unsigned int echolen = device->frog ? 0 : sizeof(command[device->frog]) - 1;
    592 	unsigned char answer[5] = {0};
    593 
    594 	// Send the command and service key.
    595 	status = dc_iostream_write (device->iostream, command[device->frog], sizeof (command[device->frog]), NULL);
    596 	if (status != DC_STATUS_SUCCESS) {
    597 		ERROR (abstract->context, "Failed to send the command.");
    598 		return status;
    599 	}
    600 
    601 	// Read the response.
    602 	status = dc_iostream_read (device->iostream, answer, 1 + echolen + 1, NULL);
    603 	if (status != DC_STATUS_SUCCESS) {
    604 		ERROR (abstract->context, "Failed to receive the answer.");
    605 		return status;
    606 	}
    607 
    608 	// Verify the response to service mode.
    609 	if (answer[0] != S_KEY ||
    610 		memcmp (answer + 1, command[device->frog] + 1, echolen) != 0 ||
    611 		answer[1 + echolen] != S_READY) {
    612 		ERROR (abstract->context, "Failed to verify the answer.");
    613 		return DC_STATUS_PROTOCOL;
    614 	}
    615 
    616 	device->state = SERVICE;
    617 
    618 	return DC_STATUS_SUCCESS;
    619 }
    620 
    621 
    622 static dc_status_t
    623 hw_ostc3_device_init (hw_ostc3_device_t *device, hw_ostc3_state_t state)
    624 {
    625 	dc_status_t rc = DC_STATUS_SUCCESS;
    626 	dc_device_t *abstract = (dc_device_t *) device;
    627 
    628 	if (device->state == state) {
    629 		// No change.
    630 		rc = DC_STATUS_SUCCESS;
    631 	} else if (device->state == OPEN) {
    632 		// Change to download or service mode.
    633 		if (state == DOWNLOAD) {
    634 			rc = hw_ostc3_device_init_download(device);
    635 		} else if (state == SERVICE) {
    636 			rc = hw_ostc3_device_init_service(device);
    637 		} else {
    638 			rc = DC_STATUS_INVALIDARGS;
    639 		}
    640 	} else if (device->state == SERVICE && state == DOWNLOAD) {
    641 		// Switching between service and download mode is not possible.
    642 		// But in service mode, all download commands are supported too,
    643 		// so there is no need to change the state.
    644 		rc = DC_STATUS_SUCCESS;
    645 	} else {
    646 		// Not supported.
    647 		rc = DC_STATUS_INVALIDARGS;
    648 	}
    649 
    650 	if (rc != DC_STATUS_SUCCESS)
    651 		return rc;
    652 
    653 	if (device->hardware != INVALID)
    654 		return DC_STATUS_SUCCESS;
    655 
    656 	// Read the hardware descriptor.
    657 	unsigned int hardware_prefix;
    658 	if (device->state == SERVICE) {
    659 		// We need to try the HARDWARE command first, as HARDWARE2 results
    660 		// in a bluetooth disconnect when the OSTC 4/5 is in bootloader mode.
    661 		unsigned char hardware[SZ_HARDWARE] = {UNKNOWN};
    662 		rc = hw_ostc3_device_id (device, hardware, sizeof(hardware));
    663 		if (rc != DC_STATUS_SUCCESS && rc != DC_STATUS_UNSUPPORTED) {
    664 			ERROR (abstract->context, "Failed to read the hardware descriptor.");
    665 			return rc;
    666 		}
    667 
    668 		HEXDUMP (abstract->context, DC_LOGLEVEL_DEBUG, "Hardware", hardware, sizeof(hardware));
    669 
    670 		hardware_prefix = hardware[0];
    671 	}
    672 
    673 	unsigned char hardware2[SZ_HARDWARE2] = {0, UNKNOWN, 0, 0, MODEL_OSTC4};
    674 	if (device->state != SERVICE || hardware_prefix != OSTC4_5_PREFIX) {
    675 		rc = hw_ostc3_device_id (device, hardware2, sizeof(hardware2));
    676 		if (rc != DC_STATUS_SUCCESS && rc != DC_STATUS_UNSUPPORTED) {
    677 			ERROR (abstract->context, "Failed to read the hardware2 descriptor.");
    678 			return rc;
    679 		}
    680 
    681 		HEXDUMP (abstract->context, DC_LOGLEVEL_DEBUG, "Hardware2", hardware2, sizeof(hardware2));
    682 
    683 		hardware_prefix = array_uint16_be(hardware2 + 0);
    684 	}
    685 
    686 	// Read the version information.
    687 	unsigned char version[SZ_VERSION_MAX] = {0};
    688 	const unsigned int versionsize = device->frog ?
    689 		SZ_VERSION_FROG : SZ_VERSION_OSTC3;
    690 	rc = hw_ostc3_transfer (device, NULL, IDENTITY, NULL, 0, version, versionsize, NULL, NODELAY);
    691 	if (rc != DC_STATUS_SUCCESS) {
    692 		ERROR (abstract->context, "Failed to read the version information.");
    693 		return rc;
    694 	}
    695 
    696 	HEXDUMP (abstract->context, DC_LOGLEVEL_DEBUG, "Version", version, versionsize);
    697 
    698 	// Cache the descriptor.
    699 	if (hardware_prefix != OSTC4_5_PREFIX) {
    700 		device->hardware = hardware_prefix;
    701 		device->feature = array_uint16_be(hardware2 + 2);
    702 		device->firmware = array_uint16_be (version + 2);
    703 		device->model = 0;
    704 	} else {
    705 		device->hardware = (hardware_prefix << 8) | hardware2[4];
    706 		device->firmware = array_uint16_le (version + 2);
    707 		device->model = hardware2[4];
    708 	}
    709 	device->serial = array_uint16_le (version + 0);
    710 
    711 	DEBUG (abstract->context, "Device: hardware=%04x, feature=%04x, model=%02x",
    712 		device->hardware, device->feature, device->model);
    713 
    714 	if (ISHWOS4(device->hardware)) {
    715 		DEBUG (abstract->context, "Device: serial=%u, firmware=%u (%u.%u.%u.%u)",
    716 			device->serial,
    717 			device->firmware,
    718 			(device->firmware >> 11) & 0x1F,
    719 			(device->firmware >>  6) & 0x1F,
    720 			(device->firmware >>  1) & 0x1F,
    721 			(device->firmware      ) & 0x01);
    722 	} else {
    723 		DEBUG (abstract->context, "Device: serial=%u, firmware=%u (%u.%u)",
    724 			device->serial,
    725 			device->firmware,
    726 			(device->firmware >>  8) & 0xFF,
    727 			(device->firmware      ) & 0xFF);
    728 	}
    729 
    730 	return DC_STATUS_SUCCESS;
    731 }
    732 
    733 
    734 static dc_status_t
    735 hw_ostc3_device_close (dc_device_t *abstract)
    736 {
    737 	dc_status_t status = DC_STATUS_SUCCESS;
    738 	hw_ostc3_device_t *device = (hw_ostc3_device_t*) abstract;
    739 	dc_status_t rc = DC_STATUS_SUCCESS;
    740 
    741 	// Send the exit command
    742 	if (device->state == DOWNLOAD || device->state == SERVICE) {
    743 		rc = hw_ostc3_transfer (device, NULL, EXIT, NULL, 0, NULL, 0, NULL, NODELAY);
    744 		if (rc != DC_STATUS_SUCCESS) {
    745 			ERROR (abstract->context, "Failed to send the command.");
    746 			dc_status_set_error(&status, rc);
    747 		}
    748 	}
    749 
    750 	// Close the packet stream.
    751 	if (dc_iostream_get_transport (device->iostream) == DC_TRANSPORT_BLE) {
    752 		rc = dc_iostream_close (device->iostream);
    753 		if (rc != DC_STATUS_SUCCESS) {
    754 			ERROR (abstract->context, "Failed to close the packet stream.");
    755 			dc_status_set_error(&status, rc);
    756 		}
    757 	}
    758 
    759 	return status;
    760 }
    761 
    762 
    763 static dc_status_t
    764 hw_ostc3_device_set_fingerprint (dc_device_t *abstract, const unsigned char data[], unsigned int size)
    765 {
    766 	hw_ostc3_device_t *device = (hw_ostc3_device_t *) abstract;
    767 
    768 	if (size && size != sizeof (device->fingerprint))
    769 		return DC_STATUS_INVALIDARGS;
    770 
    771 	if (size)
    772 		memcpy (device->fingerprint, data, sizeof (device->fingerprint));
    773 	else
    774 		memset (device->fingerprint, 0, sizeof (device->fingerprint));
    775 
    776 	return DC_STATUS_SUCCESS;
    777 }
    778 
    779 
    780 dc_status_t
    781 hw_ostc3_device_version (dc_device_t *abstract, unsigned char data[], unsigned int size)
    782 {
    783 	hw_ostc3_device_t *device = (hw_ostc3_device_t *) abstract;
    784 
    785 	if (!ISINSTANCE (abstract))
    786 		return DC_STATUS_INVALIDARGS;
    787 
    788 	const unsigned int versionsize = device->frog ?
    789 		SZ_VERSION_FROG : SZ_VERSION_OSTC3;
    790 
    791 	if (size != versionsize)
    792 		return DC_STATUS_INVALIDARGS;
    793 
    794 	dc_status_t rc = hw_ostc3_device_init (device, DOWNLOAD);
    795 	if (rc != DC_STATUS_SUCCESS)
    796 		return rc;
    797 
    798 	// Send the command.
    799 	rc = hw_ostc3_transfer (device, NULL, IDENTITY, NULL, 0, data, size, NULL, NODELAY);
    800 	if (rc != DC_STATUS_SUCCESS)
    801 		return rc;
    802 
    803 	return DC_STATUS_SUCCESS;
    804 }
    805 
    806 
    807 dc_status_t
    808 hw_ostc3_device_hardware (dc_device_t *abstract, unsigned char data[], unsigned int size)
    809 {
    810 	hw_ostc3_device_t *device = (hw_ostc3_device_t *) abstract;
    811 
    812 	if (!ISINSTANCE (abstract))
    813 		return DC_STATUS_INVALIDARGS;
    814 
    815 	if (size != SZ_HARDWARE && size != SZ_HARDWARE2)
    816 		return DC_STATUS_INVALIDARGS;
    817 
    818 	dc_status_t rc = hw_ostc3_device_init (device, DOWNLOAD);
    819 	if (rc != DC_STATUS_SUCCESS)
    820 		return rc;
    821 
    822 	// Send the requested command without synthesising a HARDWARE2 reply.
    823 	const unsigned char cmd = size == SZ_HARDWARE2 ? HARDWARE2 : HARDWARE;
    824 	rc = hw_ostc3_transfer (device, NULL, cmd, NULL, 0, data, size, NULL, NODELAY);
    825 	if (rc != DC_STATUS_SUCCESS)
    826 		return rc;
    827 
    828 	return DC_STATUS_SUCCESS;
    829 }
    830 
    831 
    832 static dc_status_t
    833 hw_ostc3_device_foreach (dc_device_t *abstract, dc_dive_callback_t callback, void *userdata)
    834 {
    835 	hw_ostc3_device_t *device = (hw_ostc3_device_t *) abstract;
    836 
    837 	// Enable progress notifications.
    838 	dc_event_progress_t progress = EVENT_PROGRESS_INITIALIZER;
    839 	progress.maximum = SZ_MEMORY;
    840 	device_event_emit (abstract, DC_EVENT_PROGRESS, &progress);
    841 
    842 	dc_status_t rc = hw_ostc3_device_init (device, DOWNLOAD);
    843 	if (rc != DC_STATUS_SUCCESS)
    844 		return rc;
    845 
    846 	// Emit a device info event.
    847 	dc_event_devinfo_t devinfo;
    848 	device_set_hw_id (abstract, device->hardware);
    849 	devinfo.firmware = device->firmware;
    850 	devinfo.serial = device->serial;
    851 	devinfo.model = device->model;
    852 	device_event_emit (abstract, DC_EVENT_DEVINFO, &devinfo);
    853 
    854 	// Allocate memory.
    855 	unsigned char *header = (unsigned char *) malloc (RB_LOGBOOK_SIZE_FULL * RB_LOGBOOK_COUNT);
    856 	if (header == NULL) {
    857 		ERROR (abstract->context, "Failed to allocate memory.");
    858 		return DC_STATUS_NOMEMORY;
    859 	}
    860 
    861 	// Download the compact logbook headers. If the firmware doesn't support
    862 	// compact headers yet, fallback to downloading the full logbook headers.
    863 	// This is slower, but also works for older firmware versions.
    864 	// The Frog always uses the full header format.
    865 	unsigned int compact = !device->frog;
    866 	if (compact) {
    867 		rc = hw_ostc3_transfer (device, &progress, COMPACT,
    868 		              NULL, 0, header, RB_LOGBOOK_SIZE_COMPACT * RB_LOGBOOK_COUNT, NULL, NODELAY);
    869 		if (rc == DC_STATUS_UNSUPPORTED) {
    870 			compact = 0;
    871 		} else if (rc != DC_STATUS_SUCCESS) {
    872 			ERROR (abstract->context, "Failed to read the header.");
    873 			free (header);
    874 			return rc;
    875 		}
    876 	}
    877 	if (!compact) {
    878 		rc = hw_ostc3_transfer (device, &progress, HEADER,
    879 		          NULL, 0, header, RB_LOGBOOK_SIZE_FULL * RB_LOGBOOK_COUNT, NULL, NODELAY);
    880 		if (rc != DC_STATUS_SUCCESS) {
    881 			ERROR (abstract->context, "Failed to read the header.");
    882 			free (header);
    883 			return rc;
    884 		}
    885 	}
    886 
    887 	// Get the correct header layout.
    888 	const hw_ostc3_logbook_t *layout = &hw_ostc3_logbook_full[device->frog];
    889 
    890 	// Get the correct logbook layout.
    891 	const hw_ostc3_logbook_t *logbook = NULL;
    892 	if (compact) {
    893 		logbook = &hw_ostc3_logbook_compact;
    894 	} else {
    895 		logbook = layout;
    896 	}
    897 
    898 	// Locate the most recent dive.
    899 	// The device maintains an internal counter which is incremented for every
    900 	// dive, and the current value at the time of the dive is stored in the
    901 	// dive header. Thus the most recent dive will have the highest value.
    902 	unsigned int latest = 0;
    903 	unsigned int maximum = 0;
    904 	for (unsigned int i = 0; i < RB_LOGBOOK_COUNT; ++i) {
    905 		unsigned int offset = i * logbook->size;
    906 
    907 		// Ignore uninitialized header entries.
    908 		if (array_isequal (header + offset, logbook->size, 0xFF))
    909 			continue;
    910 
    911 		// Get the internal dive number.
    912 		unsigned int current = array_uint16_le (header + offset + logbook->number);
    913 		if (current > maximum || ISHWOS4(device->hardware)) {
    914 			maximum = current;
    915 			latest = i;
    916 		}
    917 	}
    918 
    919 	// Calculate the total and maximum size.
    920 	unsigned int ndives = 0;
    921 	unsigned int size = 0;
    922 	unsigned int maxsize = 0;
    923 	unsigned char dive[RB_LOGBOOK_COUNT] = {0};
    924 	for (unsigned int i = 0; i < RB_LOGBOOK_COUNT; ++i) {
    925 		unsigned int idx = (latest + RB_LOGBOOK_COUNT - i) % RB_LOGBOOK_COUNT;
    926 		unsigned int offset = idx * logbook->size;
    927 
    928 		// Ignore uninitialized header entries.
    929 		if (array_isequal (header + offset, logbook->size, 0xFF)) {
    930 			WARNING (abstract->context, "Unexpected empty header found.");
    931 			continue;
    932 		}
    933 
    934 
    935 		// Calculate the profile length.
    936 		unsigned int length = 0;
    937 		if (device->frog) {
    938 			// Get the ringbuffer pointers.
    939 			unsigned int begin = array_uint24_le (header + offset + logbook->pointers);
    940 			unsigned int end   = array_uint24_le (header + offset + logbook->pointers + 3);
    941 			if (begin < RB_PROFILE_BEGIN ||
    942 				begin >= RB_PROFILE_END ||
    943 				end < RB_PROFILE_BEGIN ||
    944 				end >= RB_PROFILE_END)
    945 			{
    946 				ERROR (abstract->context, "Invalid ringbuffer pointer detected (0x%06x 0x%06x).", begin, end);
    947 				free (header);
    948 				return DC_STATUS_DATAFORMAT;
    949 			}
    950 
    951 			length = RB_LOGBOOK_SIZE_FULL + RB_PROFILE_DISTANCE (begin, end) - 6;
    952 		} else {
    953 			length = RB_LOGBOOK_SIZE_FULL + array_uint24_le (header + offset + logbook->profile) - 3;
    954 			if (!compact) {
    955 				// Workaround for a bug in older firmware versions.
    956 				unsigned int firmware = array_uint16_be (header + offset + logbook->firmware);
    957 				if (firmware < OSTC3FW(0,93))
    958 					length -= 3;
    959 			}
    960 		}
    961 		if (length < RB_LOGBOOK_SIZE_FULL) {
    962 			ERROR (abstract->context, "Invalid profile length (%u bytes).", length);
    963 			free (header);
    964 			return DC_STATUS_DATAFORMAT;
    965 		}
    966 
    967 		// Check the fingerprint data.
    968 		if (memcmp (header + offset + logbook->fingerprint, device->fingerprint, sizeof (device->fingerprint)) == 0)
    969 			break;
    970 
    971 		if (length > maxsize)
    972 			maxsize = length;
    973 		size += length;
    974 		dive[ndives] = idx;
    975 		ndives++;
    976 	}
    977 
    978 	// Update and emit a progress event.
    979 	progress.maximum = (logbook->size * RB_LOGBOOK_COUNT) + size + ndives;
    980 	device_event_emit (abstract, DC_EVENT_PROGRESS, &progress);
    981 
    982 	// Finish immediately if there are no dives available.
    983 	if (ndives == 0) {
    984 		free (header);
    985 		return DC_STATUS_SUCCESS;
    986 	}
    987 
    988 	// Allocate enough memory for the largest dive.
    989 	unsigned char *profile = (unsigned char *) malloc (maxsize);
    990 	if (profile == NULL) {
    991 		ERROR (abstract->context, "Failed to allocate memory.");
    992 		free (header);
    993 		return DC_STATUS_NOMEMORY;
    994 	}
    995 
    996 	// Download the dives.
    997 	for (unsigned int i = 0; i < ndives; ++i) {
    998 		unsigned int idx = dive[i];
    999 		unsigned int offset = idx * logbook->size;
   1000 
   1001 		// Calculate the profile length.
   1002 		unsigned int length = 0;
   1003 		if (device->frog) {
   1004 			// Get the ringbuffer pointers.
   1005 			unsigned int begin = array_uint24_le (header + offset + logbook->pointers);
   1006 			unsigned int end   = array_uint24_le (header + offset + logbook->pointers + 3);
   1007 
   1008 			length = RB_LOGBOOK_SIZE_FULL + RB_PROFILE_DISTANCE (begin, end) - 6;
   1009 		} else {
   1010 			length = RB_LOGBOOK_SIZE_FULL + array_uint24_le (header + offset + logbook->profile) - 3;
   1011 			if (!compact) {
   1012 				// Workaround for a bug in older firmware versions.
   1013 				unsigned int firmware = array_uint16_be (header + offset + logbook->firmware);
   1014 				if (firmware < OSTC3FW(0,93))
   1015 					length -= 3;
   1016 			}
   1017 		}
   1018 
   1019 		// Download the dive.
   1020 		unsigned char number[1] = {idx};
   1021 		rc = hw_ostc3_transfer (device, &progress, DIVE,
   1022 			number, sizeof (number), profile, length, &length, NODELAY);
   1023 		if (rc != DC_STATUS_SUCCESS) {
   1024 			ERROR (abstract->context, "Failed to read the dive.");
   1025 			free (profile);
   1026 			free (header);
   1027 			return rc;
   1028 		}
   1029 
   1030 		// Verify the header in the logbook and profile are identical.
   1031 		if (memcmp (profile + layout->version, header + offset + logbook->version, 1) != 0 ||
   1032 			(compact ?
   1033 			 (memcmp (profile + layout->fingerprint, header + offset + logbook->fingerprint, 10) != 0 ||
   1034 			  memcmp (profile + layout->number, header + offset + logbook->number, 2) != 0) :
   1035 			  memcmp (profile + layout->fingerprint, header + offset + layout->fingerprint, RB_LOGBOOK_SIZE_FULL - layout->fingerprint) != 0)) {
   1036 			ERROR (abstract->context, "Unexpected profile header.");
   1037 			free (profile);
   1038 			free (header);
   1039 			return DC_STATUS_DATAFORMAT;
   1040 		}
   1041 
   1042 		// Detect invalid profile data.
   1043 		unsigned int delta = ISHWOS4(device->hardware) ? 3 : 0;
   1044 		if (length < RB_LOGBOOK_SIZE_FULL + 2 ||
   1045 			profile[length - 2] != 0xFD || profile[length - 1] != 0xFD) {
   1046 			// A valid profile should have at least a correct 2 byte
   1047 			// end-of-profile marker.
   1048 			WARNING (abstract->context, "Invalid profile end marker detected!");
   1049 			length = RB_LOGBOOK_SIZE_FULL;
   1050 		} else if (length == RB_LOGBOOK_SIZE_FULL + 2) {
   1051 			// A profile containing only the 2 byte end-of-profile
   1052 			// marker is considered a valid empty profile.
   1053 		} else if (!device->frog && (length < RB_LOGBOOK_SIZE_FULL + 5 ||
   1054 			array_uint24_le (profile + RB_LOGBOOK_SIZE_FULL) + delta != array_uint24_le (profile + layout->profile))) {
   1055 			// If there is more data available, then there should be a
   1056 			// valid profile header containing a length matching the
   1057 			// length in the dive header.
   1058 			WARNING (abstract->context, "Invalid profile header detected.");
   1059 			length = RB_LOGBOOK_SIZE_FULL;
   1060 		}
   1061 
   1062 		if (callback && !callback (profile, length, profile + layout->fingerprint, sizeof (device->fingerprint), userdata))
   1063 			break;
   1064 	}
   1065 
   1066 	free (profile);
   1067 	free (header);
   1068 
   1069 	return DC_STATUS_SUCCESS;
   1070 }
   1071 
   1072 
   1073 static dc_status_t
   1074 hw_ostc3_device_timesync (dc_device_t *abstract, const dc_datetime_t *datetime)
   1075 {
   1076 	hw_ostc3_device_t *device = (hw_ostc3_device_t *) abstract;
   1077 
   1078 	dc_status_t rc = hw_ostc3_device_init (device, DOWNLOAD);
   1079 	if (rc != DC_STATUS_SUCCESS)
   1080 		return rc;
   1081 
   1082 	// Send the command.
   1083 	unsigned char packet[6] = {
   1084 		datetime->hour, datetime->minute, datetime->second,
   1085 		datetime->month, datetime->day, datetime->year - 2000};
   1086 	rc = hw_ostc3_transfer (device, NULL, CLOCK, packet, sizeof (packet), NULL, 0, NULL, NODELAY);
   1087 	if (rc != DC_STATUS_SUCCESS)
   1088 		return rc;
   1089 
   1090 	return DC_STATUS_SUCCESS;
   1091 }
   1092 
   1093 
   1094 dc_status_t
   1095 hw_ostc3_device_display (dc_device_t *abstract, const char *text)
   1096 {
   1097 	hw_ostc3_device_t *device = (hw_ostc3_device_t *) abstract;
   1098 
   1099 	if (!ISINSTANCE (abstract))
   1100 		return DC_STATUS_INVALIDARGS;
   1101 
   1102 	const unsigned int packetsize = device->frog ?
   1103 		SZ_DISPLAY_FROG : SZ_DISPLAY_OSTC3;
   1104 
   1105 	// Pad the data packet with spaces.
   1106 	unsigned char packet[SZ_DISPLAY_MAX] = {0};
   1107 	if (hw_ostc3_strncpy (packet, packetsize, text) != 0) {
   1108 		ERROR (abstract->context, "Invalid parameter specified.");
   1109 		return DC_STATUS_INVALIDARGS;
   1110 	}
   1111 
   1112 	dc_status_t rc = hw_ostc3_device_init (device, DOWNLOAD);
   1113 	if (rc != DC_STATUS_SUCCESS)
   1114 		return rc;
   1115 
   1116 	// Send the command.
   1117 	rc = hw_ostc3_transfer (device, NULL, DISPLAY, packet, packetsize, NULL, 0, NULL, NODELAY);
   1118 	if (rc != DC_STATUS_SUCCESS)
   1119 		return rc;
   1120 
   1121 	return DC_STATUS_SUCCESS;
   1122 }
   1123 
   1124 
   1125 dc_status_t
   1126 hw_ostc3_device_customtext (dc_device_t *abstract, const char *text)
   1127 {
   1128 	hw_ostc3_device_t *device = (hw_ostc3_device_t *) abstract;
   1129 
   1130 	if (!ISINSTANCE (abstract))
   1131 		return DC_STATUS_INVALIDARGS;
   1132 
   1133 	const unsigned int packetsize = device->frog ?
   1134 		SZ_CUSTOMTEXT_FROG : SZ_CUSTOMTEXT_OSTC3;
   1135 
   1136 	// Pad the data packet with spaces.
   1137 	unsigned char packet[SZ_CUSTOMTEXT_MAX] = {0};
   1138 	if (hw_ostc3_strncpy (packet, packetsize, text) != 0) {
   1139 		ERROR (abstract->context, "Invalid parameter specified.");
   1140 		return DC_STATUS_INVALIDARGS;
   1141 	}
   1142 
   1143 	dc_status_t rc = hw_ostc3_device_init (device, DOWNLOAD);
   1144 	if (rc != DC_STATUS_SUCCESS)
   1145 		return rc;
   1146 
   1147 	// Send the command.
   1148 	rc = hw_ostc3_transfer (device, NULL, CUSTOMTEXT, packet, packetsize, NULL, 0, NULL, NODELAY);
   1149 	if (rc != DC_STATUS_SUCCESS)
   1150 		return rc;
   1151 
   1152 	return DC_STATUS_SUCCESS;
   1153 }
   1154 
   1155 dc_status_t
   1156 hw_ostc3_device_config_read (dc_device_t *abstract, unsigned int config, unsigned char data[], unsigned int size)
   1157 {
   1158 	hw_ostc3_device_t *device = (hw_ostc3_device_t *) abstract;
   1159 
   1160 	if (!ISINSTANCE (abstract))
   1161 		return DC_STATUS_INVALIDARGS;
   1162 
   1163 	dc_status_t rc = hw_ostc3_device_init (device, DOWNLOAD);
   1164 	if (rc != DC_STATUS_SUCCESS)
   1165 		return rc;
   1166 
   1167 	if (ISHWOS4(device->hardware) ? size != SZ_CONFIG : size > SZ_CONFIG) {
   1168 		ERROR (abstract->context, "Invalid parameter specified.");
   1169 		return DC_STATUS_INVALIDARGS;
   1170 	}
   1171 
   1172 	// Send the command.
   1173 	unsigned char command[1] = {config};
   1174 	rc = hw_ostc3_transfer (device, NULL, READ, command, sizeof (command), data, size, NULL, NODELAY);
   1175 	if (rc != DC_STATUS_SUCCESS)
   1176 		return rc;
   1177 
   1178 	return DC_STATUS_SUCCESS;
   1179 }
   1180 
   1181 dc_status_t
   1182 hw_ostc3_device_config_write (dc_device_t *abstract, unsigned int config, const unsigned char data[], unsigned int size)
   1183 {
   1184 	hw_ostc3_device_t *device = (hw_ostc3_device_t *) abstract;
   1185 
   1186 	if (!ISINSTANCE (abstract))
   1187 		return DC_STATUS_INVALIDARGS;
   1188 
   1189 	dc_status_t rc = hw_ostc3_device_init (device, DOWNLOAD);
   1190 	if (rc != DC_STATUS_SUCCESS)
   1191 		return rc;
   1192 
   1193 	if (ISHWOS4(device->hardware) ? size != SZ_CONFIG : size > SZ_CONFIG) {
   1194 		ERROR (abstract->context, "Invalid parameter specified.");
   1195 		return DC_STATUS_INVALIDARGS;
   1196 	}
   1197 
   1198 	// Send the command.
   1199 	unsigned char command[SZ_CONFIG + 1] = {config};
   1200 	memcpy(command + 1, data, size);
   1201 	rc = hw_ostc3_transfer (device, NULL, WRITE, command, size + 1, NULL, 0, NULL, NODELAY);
   1202 	if (rc != DC_STATUS_SUCCESS)
   1203 		return rc;
   1204 
   1205 	return DC_STATUS_SUCCESS;
   1206 }
   1207 
   1208 dc_status_t
   1209 hw_ostc3_device_config_reset (dc_device_t *abstract)
   1210 {
   1211 	hw_ostc3_device_t *device = (hw_ostc3_device_t *) abstract;
   1212 
   1213 	if (!ISINSTANCE (abstract))
   1214 		return DC_STATUS_INVALIDARGS;
   1215 
   1216 	dc_status_t rc = hw_ostc3_device_init (device, DOWNLOAD);
   1217 	if (rc != DC_STATUS_SUCCESS)
   1218 		return rc;
   1219 
   1220 	// Send the command.
   1221 	rc = hw_ostc3_transfer (device, NULL, RESET, NULL, 0, NULL, 0, NULL, NODELAY);
   1222 	if (rc != DC_STATUS_SUCCESS)
   1223 		return rc;
   1224 
   1225 	return DC_STATUS_SUCCESS;
   1226 }
   1227 
   1228 // This is a variant of fletcher16 with a 16 bit sum instead of an 8 bit sum,
   1229 // and modulo 2^16 instead of 2^16-1
   1230 static unsigned int
   1231 hw_ostc3_firmware_checksum (const unsigned char data[], unsigned int size)
   1232 {
   1233 	unsigned short low = 0;
   1234 	unsigned short high = 0;
   1235 	for (unsigned int i = 0; i < size; i++) {
   1236 		low  += data[i];
   1237 		high += low;
   1238 	}
   1239 	return (((unsigned int)high) << 16) + low;
   1240 }
   1241 
   1242 static dc_status_t
   1243 hw_ostc3_firmware_readline (FILE *fp, dc_context_t *context, unsigned int addr, unsigned char data[], unsigned int size)
   1244 {
   1245 	unsigned char ascii[39];
   1246 	unsigned char faddr_byte[3];
   1247 	unsigned int faddr = 0;
   1248 	size_t n = 0;
   1249 
   1250 	if (size > 16) {
   1251 		ERROR (context, "Invalid arguments.");
   1252 		return DC_STATUS_INVALIDARGS;
   1253 	}
   1254 
   1255 	// Read the start code.
   1256 	while (1) {
   1257 		n = fread (ascii, 1, 1, fp);
   1258 		if (n != 1) {
   1259 			ERROR (context, "Failed to read the start code.");
   1260 			return DC_STATUS_IO;
   1261 		}
   1262 
   1263 		if (ascii[0] == ':')
   1264 			break;
   1265 
   1266 		// Ignore CR and LF characters.
   1267 		if (ascii[0] != '\n' && ascii[0] != '\r') {
   1268 			ERROR (context, "Unexpected character (0x%02x).", ascii[0]);
   1269 			return DC_STATUS_DATAFORMAT;
   1270 		}
   1271 	}
   1272 
   1273 	// Read the payload.
   1274 	n = fread (ascii + 1, 1, 6 + size * 2, fp);
   1275 	if (n != 6 + size * 2) {
   1276 		ERROR (context, "Failed to read the data.");
   1277 		return DC_STATUS_IO;
   1278 	}
   1279 
   1280 	// Convert the address to binary representation.
   1281 	if (array_convert_hex2bin(ascii + 1, 6, faddr_byte, sizeof(faddr_byte)) != 0) {
   1282 		ERROR (context, "Invalid hexadecimal character.");
   1283 		return DC_STATUS_DATAFORMAT;
   1284 	}
   1285 
   1286 	// Get the address.
   1287 	faddr = array_uint24_be (faddr_byte);
   1288 	if (faddr != addr) {
   1289 		ERROR (context, "Unexpected address (0x%06x, 0x%06x).", faddr, addr);
   1290 		return DC_STATUS_DATAFORMAT;
   1291 	}
   1292 
   1293 	// Convert the payload to binary representation.
   1294 	if (array_convert_hex2bin (ascii + 1 + 6, size * 2, data, size) != 0) {
   1295 		ERROR (context, "Invalid hexadecimal character.");
   1296 		return DC_STATUS_DATAFORMAT;
   1297 	}
   1298 
   1299 	return DC_STATUS_SUCCESS;
   1300 }
   1301 
   1302 
   1303 static dc_status_t
   1304 hw_ostc3_firmware_readfile3 (hw_ostc3_firmware_t *firmware, dc_context_t *context, const char *filename, const unsigned char key[])
   1305 {
   1306 	dc_status_t rc = DC_STATUS_SUCCESS;
   1307 	FILE *fp = NULL;
   1308 	unsigned char iv[16] = {0};
   1309 	unsigned char tmpbuf[16] = {0};
   1310 	unsigned char encrypted[16] = {0};
   1311 	unsigned int bytes = 0, addr = 0;
   1312 	unsigned char checksum[4];
   1313 
   1314 	if (firmware == NULL) {
   1315 		ERROR (context, "Invalid arguments.");
   1316 		return DC_STATUS_INVALIDARGS;
   1317 	}
   1318 
   1319 	// Initialize the buffers.
   1320 	memset (firmware->data, 0xFF, firmware->size);
   1321 	firmware->checksum = 0;
   1322 
   1323 	fp = fopen (filename, "rb");
   1324 	if (fp == NULL) {
   1325 		ERROR (context, "Failed to open the file.");
   1326 		return DC_STATUS_IO;
   1327 	}
   1328 
   1329 	rc = hw_ostc3_firmware_readline (fp, context, 0, iv, sizeof(iv));
   1330 	if (rc != DC_STATUS_SUCCESS) {
   1331 		ERROR (context, "Failed to parse header.");
   1332 		fclose (fp);
   1333 		return rc;
   1334 	}
   1335 	bytes += 16;
   1336 
   1337 	// Load the iv for AES-FCB-mode
   1338 	AES128_ECB_encrypt (iv, key, tmpbuf);
   1339 
   1340 	for (addr = 0; addr < firmware->size; addr += 16, bytes += 16) {
   1341 		rc = hw_ostc3_firmware_readline (fp, context, bytes, encrypted, sizeof(encrypted));
   1342 		if (rc != DC_STATUS_SUCCESS) {
   1343 			ERROR (context, "Failed to parse file data.");
   1344 			fclose (fp);
   1345 			return rc;
   1346 		}
   1347 
   1348 		// Decrypt AES-FCB data
   1349 		for (unsigned int i = 0; i < 16; i++)
   1350 			firmware->data[addr + i] = encrypted[i] ^ tmpbuf[i];
   1351 
   1352 		// Run the next round of encryption
   1353 		AES128_ECB_encrypt (encrypted, key, tmpbuf);
   1354 	}
   1355 
   1356 	// This file format contains a tail with the checksum in
   1357 	rc = hw_ostc3_firmware_readline (fp, context, bytes, checksum, sizeof(checksum));
   1358 	if (rc != DC_STATUS_SUCCESS) {
   1359 		ERROR (context, "Failed to parse file tail.");
   1360 		fclose (fp);
   1361 		return rc;
   1362 	}
   1363 
   1364 	fclose (fp);
   1365 
   1366 	unsigned int csum1 = array_uint32_le (checksum);
   1367 	unsigned int csum2 = hw_ostc3_firmware_checksum (firmware->data, firmware->size);
   1368 	if (csum1 != csum2) {
   1369 		ERROR (context, "Failed to verify file checksum.");
   1370 		return DC_STATUS_DATAFORMAT;
   1371 	}
   1372 
   1373 	firmware->checksum = csum1;
   1374 
   1375 	return DC_STATUS_SUCCESS;
   1376 }
   1377 
   1378 static dc_status_t
   1379 hw_ostc3_firmware_readfile4 (dc_buffer_t *buffer, dc_context_t *context, const char *filename)
   1380 {
   1381 	FILE *fp = NULL;
   1382 
   1383 	if (buffer == NULL) {
   1384 		ERROR (context, "Invalid arguments.");
   1385 		return DC_STATUS_INVALIDARGS;
   1386 	}
   1387 
   1388 	// Open the file.
   1389 	fp = fopen (filename, "rb");
   1390 	if (fp == NULL) {
   1391 		ERROR (context, "Failed to open the file.");
   1392 		return DC_STATUS_IO;
   1393 	}
   1394 
   1395 	// Read the entire file into the buffer.
   1396 	size_t n = 0;
   1397 	unsigned char block[1024] = {0};
   1398 	while ((n = fread (block, 1, sizeof (block), fp)) > 0) {
   1399 		if (!dc_buffer_append (buffer, block, n)) {
   1400 			ERROR (context, "Insufficient buffer space available.");
   1401 			fclose (fp);
   1402 			return DC_STATUS_NOMEMORY;
   1403 		}
   1404 	}
   1405 
   1406 	// Close the file.
   1407 	fclose (fp);
   1408 
   1409 	// Verify the minimum size.
   1410 	size_t size = dc_buffer_get_size (buffer);
   1411 	if (size < 4) {
   1412 		ERROR (context, "Invalid file size.");
   1413 		return DC_STATUS_DATAFORMAT;
   1414 
   1415 	}
   1416 
   1417 	// Verify the checksum.
   1418 	const unsigned char *data = dc_buffer_get_data (buffer);
   1419 	unsigned int csum1 = array_uint32_le (data + size - 4);
   1420 	unsigned int csum2 = hw_ostc3_firmware_checksum (data, size - 4);
   1421 	if (csum1 != csum2) {
   1422 		ERROR (context, "Failed to verify file checksum.");
   1423 		return DC_STATUS_DATAFORMAT;
   1424 	}
   1425 
   1426 	// Remove the checksum.
   1427 	dc_buffer_slice (buffer, 0, size - 4);
   1428 
   1429 	return DC_STATUS_SUCCESS;
   1430 }
   1431 
   1432 static dc_status_t
   1433 hw_ostc3_firmware_erase (hw_ostc3_device_t *device, unsigned int addr, unsigned int size)
   1434 {
   1435 	// Convert size to number of pages, rounded up.
   1436 	unsigned char blocks = ((size + SZ_FIRMWARE_BLOCK - 1) / SZ_FIRMWARE_BLOCK);
   1437 
   1438 	// Estimate the required delay. Erasing a 4K flash memory page
   1439 	// takes around 25 milliseconds.
   1440 	unsigned int delay = blocks * 25;
   1441 
   1442 	// Erase just the needed pages.
   1443 	unsigned char buffer[4];
   1444 	array_uint24_be_set (buffer, addr);
   1445 	buffer[3] = blocks;
   1446 
   1447 	return hw_ostc3_transfer (device, NULL, S_ERASE, buffer, sizeof (buffer), NULL, 0, NULL, delay);
   1448 }
   1449 
   1450 static dc_status_t
   1451 hw_ostc3_firmware_block_read (hw_ostc3_device_t *device, unsigned int addr, unsigned char block[], unsigned int block_size)
   1452 {
   1453 	unsigned char buffer[6];
   1454 	array_uint24_be_set (buffer, addr);
   1455 	array_uint24_be_set (buffer + 3, block_size);
   1456 
   1457 	return hw_ostc3_transfer (device, NULL, S_BLOCK_READ, buffer, sizeof (buffer), block, block_size, NULL, NODELAY);
   1458 }
   1459 
   1460 static dc_status_t
   1461 hw_ostc3_firmware_block_write1 (hw_ostc3_device_t *device, unsigned int addr, const unsigned char block[], unsigned int block_size)
   1462 {
   1463 	unsigned char buffer[3 + SZ_FIRMWARE_BLOCK];
   1464 
   1465 	// We currently only support writing max SZ_FIRMWARE_BLOCK sized blocks.
   1466 	if (block_size > SZ_FIRMWARE_BLOCK)
   1467 		return DC_STATUS_INVALIDARGS;
   1468 
   1469 	array_uint24_be_set (buffer, addr);
   1470 	memcpy (buffer + 3, block, block_size);
   1471 
   1472 	return hw_ostc3_transfer (device, NULL, S_BLOCK_WRITE, buffer, 3 + block_size, NULL, 0, NULL, TIMEOUT);
   1473 }
   1474 
   1475 static dc_status_t
   1476 hw_ostc3_firmware_block_write2 (hw_ostc3_device_t *device, unsigned int address, const unsigned char data[], unsigned int size)
   1477 {
   1478 	dc_status_t status = DC_STATUS_SUCCESS;
   1479 
   1480 	if ((address % SZ_FIRMWARE_BLOCK2 != 0) ||
   1481 		(size % SZ_FIRMWARE_BLOCK2 != 0)) {
   1482 		return DC_STATUS_INVALIDARGS;
   1483 	}
   1484 
   1485 	unsigned int nbytes = 0;
   1486 	while (nbytes < size) {
   1487 		unsigned char buffer[3 + SZ_FIRMWARE_BLOCK2];
   1488 		array_uint24_be_set (buffer, address);
   1489 		memcpy (buffer + 3, data + nbytes, SZ_FIRMWARE_BLOCK2);
   1490 
   1491 		status = hw_ostc3_transfer (device, NULL, S_BLOCK_WRITE2, buffer, sizeof(buffer), NULL, 0, NULL, NODELAY);
   1492 		if (status != DC_STATUS_SUCCESS) {
   1493 			return status;
   1494 		}
   1495 
   1496 		address += SZ_FIRMWARE_BLOCK2;
   1497 		nbytes += SZ_FIRMWARE_BLOCK2;
   1498 	}
   1499 
   1500 	return DC_STATUS_SUCCESS;
   1501 }
   1502 
   1503 static dc_status_t
   1504 hw_ostc3_firmware_block_write (hw_ostc3_device_t *device, unsigned int address, const unsigned char data[], unsigned int size)
   1505 {
   1506 	// Support for the S_BLOCK_WRITE2 command is only available since the
   1507 	// hwOS Tech firmware v3.09 and the hwOS Sport firmware v10.64.
   1508 	if ((device->firmware < OSTC3FW(3,9)) ||
   1509 		(device->firmware >= OSTC3FW(10,0) && device->firmware < OSTC3FW(10,64))) {
   1510 		return hw_ostc3_firmware_block_write1 (device, address, data, size);
   1511 	} else {
   1512 		return hw_ostc3_firmware_block_write2 (device, address, data, size);
   1513 	}
   1514 }
   1515 
   1516 static dc_status_t
   1517 hw_ostc3_firmware_upgrade (dc_device_t *abstract, unsigned int checksum)
   1518 {
   1519 	dc_status_t rc = DC_STATUS_SUCCESS;
   1520 	hw_ostc3_device_t *device = (hw_ostc3_device_t *) abstract;
   1521 	dc_context_t *context = (abstract ? abstract->context : NULL);
   1522 	unsigned char buffer[5];
   1523 	array_uint32_le_set (buffer, checksum);
   1524 
   1525 	// Compute a one byte checksum, so the device can validate the firmware image.
   1526 	buffer[4] = 0x55;
   1527 	for (unsigned int i = 0; i < 4; i++) {
   1528 		buffer[4] ^= buffer[i];
   1529 		buffer[4]  = (buffer[4]<<1 | buffer[4]>>7);
   1530 	}
   1531 
   1532 	rc = hw_ostc3_transfer (device, NULL, S_UPGRADE, buffer, sizeof (buffer), NULL, 0, NULL, NODELAY);
   1533 	if (rc != DC_STATUS_SUCCESS) {
   1534 		ERROR (context, "Failed to send flash firmware command");
   1535 		return rc;
   1536 	}
   1537 
   1538 	// Now the device resets, and if everything is well, it reprograms.
   1539 	device->state = REBOOTING;
   1540 
   1541 	return DC_STATUS_SUCCESS;
   1542 }
   1543 
   1544 
   1545 static dc_status_t
   1546 hw_ostc3_device_fwupdate3 (dc_device_t *abstract, const char *filename)
   1547 {
   1548 	dc_status_t rc = DC_STATUS_SUCCESS;
   1549 	hw_ostc3_device_t *device = (hw_ostc3_device_t *) abstract;
   1550 	dc_context_t *context = (abstract ? abstract->context : NULL);
   1551 
   1552 	// Firmware size.
   1553 	const unsigned int firmwaresize = device->frog ?
   1554 		SZ_FIRMWARE_FROG : SZ_FIRMWARE_OSTC3;
   1555 
   1556 	// Enable progress notifications.
   1557 	// load, erase, upload FZ, verify FZ, reprogram
   1558 	dc_event_progress_t progress = EVENT_PROGRESS_INITIALIZER;
   1559 	progress.maximum = 3 + firmwaresize * 2 / SZ_FIRMWARE_BLOCK;
   1560 	device_event_emit (abstract, DC_EVENT_PROGRESS, &progress);
   1561 
   1562 	// Allocate memory for the firmware data.
   1563 	hw_ostc3_firmware_t *firmware = (hw_ostc3_firmware_t *) malloc (sizeof (hw_ostc3_firmware_t) + firmwaresize);
   1564 	if (firmware == NULL) {
   1565 		ERROR (context, "Failed to allocate memory.");
   1566 		return DC_STATUS_NOMEMORY;
   1567 	}
   1568 
   1569 	// Initialize the size.
   1570 	firmware->size = firmwaresize;
   1571 
   1572 	// Read the hex file.
   1573 	rc = hw_ostc3_firmware_readfile3 (firmware, context, filename, hw_ostc3_key[device->frog]);
   1574 	if (rc != DC_STATUS_SUCCESS) {
   1575 		free (firmware);
   1576 		return rc;
   1577 	}
   1578 
   1579 	// Device open and firmware loaded
   1580 	progress.current++;
   1581 	device_event_emit (abstract, DC_EVENT_PROGRESS, &progress);
   1582 
   1583 	hw_ostc3_device_display (abstract, " Erasing FW...");
   1584 
   1585 	rc = hw_ostc3_firmware_erase (device, FIRMWARE_AREA, firmware->size);
   1586 	if (rc != DC_STATUS_SUCCESS) {
   1587 		ERROR (context, "Failed to erase old firmware");
   1588 		free (firmware);
   1589 		return rc;
   1590 	}
   1591 
   1592 	// Memory erased
   1593 	progress.current++;
   1594 	device_event_emit (abstract, DC_EVENT_PROGRESS, &progress);
   1595 
   1596 	hw_ostc3_device_display (abstract, " Uploading...");
   1597 
   1598 	for (unsigned int len = 0; len < firmware->size; len += SZ_FIRMWARE_BLOCK) {
   1599 		char msg[SZ_DISPLAY_MAX + 1]; // Status message on the display
   1600 		dc_platform_snprintf (msg, sizeof(msg), " Uploading %2d%%", (100 * len) / firmware->size);
   1601 		hw_ostc3_device_display (abstract, msg);
   1602 
   1603 		rc = hw_ostc3_firmware_block_write (device, FIRMWARE_AREA + len, firmware->data + len, SZ_FIRMWARE_BLOCK);
   1604 		if (rc != DC_STATUS_SUCCESS) {
   1605 			ERROR (context, "Failed to write block to device");
   1606 			free(firmware);
   1607 			return rc;
   1608 		}
   1609 		// One block uploaded
   1610 		progress.current++;
   1611 		device_event_emit (abstract, DC_EVENT_PROGRESS, &progress);
   1612 	}
   1613 
   1614 	hw_ostc3_device_display (abstract, " Verifying...");
   1615 
   1616 	for (unsigned int len = 0; len < firmware->size; len += SZ_FIRMWARE_BLOCK) {
   1617 		unsigned char block[SZ_FIRMWARE_BLOCK];
   1618 		char msg[SZ_DISPLAY_MAX + 1]; // Status message on the display
   1619 		dc_platform_snprintf (msg, sizeof(msg), " Verifying %2d%%", (100 * len) / firmware->size);
   1620 		hw_ostc3_device_display (abstract, msg);
   1621 
   1622 		rc = hw_ostc3_firmware_block_read (device, FIRMWARE_AREA + len, block, sizeof (block));
   1623 		if (rc != DC_STATUS_SUCCESS) {
   1624 			ERROR (context, "Failed to read block.");
   1625 			free (firmware);
   1626 			return rc;
   1627 		}
   1628 		if (memcmp (firmware->data + len, block, sizeof (block)) != 0) {
   1629 			ERROR (context, "Failed verify.");
   1630 			hw_ostc3_device_display (abstract, " Verify FAILED");
   1631 			free (firmware);
   1632 			return DC_STATUS_PROTOCOL;
   1633 		}
   1634 		// One block verified
   1635 		progress.current++;
   1636 		device_event_emit (abstract, DC_EVENT_PROGRESS, &progress);
   1637 	}
   1638 
   1639 	hw_ostc3_device_display (abstract, " Programming...");
   1640 
   1641 	rc = hw_ostc3_firmware_upgrade (abstract, firmware->checksum);
   1642 	if (rc != DC_STATUS_SUCCESS) {
   1643 		ERROR (context, "Failed to start programming");
   1644 		free (firmware);
   1645 		return rc;
   1646 	}
   1647 
   1648 	// Programing done!
   1649 	progress.current++;
   1650 	device_event_emit (abstract, DC_EVENT_PROGRESS, &progress);
   1651 
   1652 	free (firmware);
   1653 
   1654 	// Finished!
   1655 	return DC_STATUS_SUCCESS;
   1656 }
   1657 
   1658 static dc_status_t
   1659 hw_ostc3_device_fwupdate4 (dc_device_t *abstract, const char *filename, bool forceUpdate)
   1660 {
   1661 	dc_status_t status = DC_STATUS_SUCCESS;
   1662 	hw_ostc3_device_t *device = (hw_ostc3_device_t *) abstract;
   1663 	dc_context_t *context = (abstract ? abstract->context : NULL);
   1664 
   1665 	// Allocate memory for the firmware data.
   1666 	dc_buffer_t *buffer = dc_buffer_new (0);
   1667 	if (buffer == NULL) {
   1668 		ERROR (context, "Failed to allocate memory.");
   1669 		status = DC_STATUS_NOMEMORY;
   1670 		goto error;
   1671 	}
   1672 
   1673 	// Read the firmware file.
   1674 	status = hw_ostc3_firmware_readfile4 (buffer, context, filename);
   1675 	if (status != DC_STATUS_SUCCESS) {
   1676 		goto error;
   1677 	}
   1678 
   1679 	// Enable progress notifications.
   1680 	dc_event_progress_t progress = EVENT_PROGRESS_INITIALIZER;
   1681 	progress.maximum = dc_buffer_get_size (buffer);
   1682 	device_event_emit (abstract, DC_EVENT_PROGRESS, &progress);
   1683 
   1684 	// Cache the pointer and size.
   1685 	const unsigned char *data = dc_buffer_get_data (buffer);
   1686 	unsigned int size = dc_buffer_get_size (buffer);
   1687 
   1688 	unsigned int offset = 0;
   1689 	while (offset + 4 <= size) {
   1690 		// Get the length of the firmware blob.
   1691 		unsigned int length = array_uint32_be(data + offset) + 20;
   1692 		if (offset + length > size) {
   1693 			status = DC_STATUS_DATAFORMAT;
   1694 			goto error;
   1695 		}
   1696 
   1697 		// Get the blob type.
   1698 		unsigned char type = data[offset + 4];
   1699 
   1700 		// Estimate the required delay.
   1701 		// After uploading the firmware blob, the device writes the data
   1702 		// to flash memory. Since this takes a significant amount of
   1703 		// time, the ready byte is delayed. Therefore, the standard
   1704 		// timeout is no longer sufficient. The delays are estimated
   1705 		// based on actual measurements of the delay per byte.
   1706 		unsigned int usecs = length;
   1707 		if (type == 0xFF) {
   1708 			// Firmware
   1709 			usecs *= 50;
   1710 		} else if (type == 0xFE) {
   1711 			// RTE
   1712 			usecs *= 500;
   1713 		} else {
   1714 			// Fonts
   1715 			usecs *= 25;
   1716 		}
   1717 
   1718 		// Read the firmware version info.
   1719 		unsigned char fwinfo[SZ_FWINFO] = {0};
   1720 		status = hw_ostc3_transfer (device, NULL, S_FWINFO,
   1721 			data + offset + 4, 1, fwinfo, sizeof(fwinfo), NULL, NODELAY);
   1722 		if (status != DC_STATUS_SUCCESS) {
   1723 			ERROR (abstract->context, "Failed to read the firmware info.");
   1724 			goto error;
   1725 		}
   1726 
   1727 		// Upload the firmware blob.
   1728 		// The update is skipped if the two versions are already
   1729 		// identical, or if the blob is not present on the device.
   1730 		if ((memcmp(data + offset + 12, fwinfo, sizeof(fwinfo)) != 0 || forceUpdate) &&
   1731 			!array_isequal(fwinfo, sizeof(fwinfo), 0xFF))
   1732 		{
   1733 			status = hw_ostc3_transfer (device, &progress, S_UPLOAD,
   1734 				data + offset, length, NULL, 0, NULL, usecs / 1000);
   1735 			if (status != DC_STATUS_SUCCESS) {
   1736 				goto error;
   1737 			}
   1738 		} else {
   1739 			// Update and emit a progress event.
   1740 			progress.current += length;
   1741 			device_event_emit (abstract, DC_EVENT_PROGRESS, &progress);
   1742 		}
   1743 
   1744 		offset += length;
   1745 	}
   1746 
   1747 error:
   1748 	dc_buffer_free (buffer);
   1749 	return status;
   1750 }
   1751 
   1752 dc_status_t
   1753 hw_ostc3_device_fwupdate (dc_device_t *abstract, const char *filename, bool forceUpdate)
   1754 {
   1755 	dc_status_t status = DC_STATUS_SUCCESS;
   1756 	hw_ostc3_device_t *device = (hw_ostc3_device_t *) abstract;
   1757 
   1758 	if (!ISINSTANCE (abstract))
   1759 		return DC_STATUS_INVALIDARGS;
   1760 
   1761 	// Make sure the device is in service mode.
   1762 	status = hw_ostc3_device_init (device, SERVICE);
   1763 	if (status != DC_STATUS_SUCCESS) {
   1764 		return status;
   1765 	}
   1766 
   1767 	if (ISHWOS4(device->hardware)) {
   1768 		return hw_ostc3_device_fwupdate4 (abstract, filename, forceUpdate);
   1769 	} else {
   1770 		if (forceUpdate) {
   1771 			return DC_STATUS_INVALIDARGS;
   1772 		}
   1773 
   1774 		return hw_ostc3_device_fwupdate3 (abstract, filename);
   1775 	}
   1776 }
   1777 
   1778 static dc_status_t
   1779 hw_ostc3_device_read (dc_device_t *abstract, unsigned int address, unsigned char data[], unsigned int size)
   1780 {
   1781 	dc_status_t status = DC_STATUS_SUCCESS;
   1782 	hw_ostc3_device_t *device = (hw_ostc3_device_t *) abstract;
   1783 
   1784 	if ((address % SZ_FIRMWARE_BLOCK != 0) ||
   1785 		(size % SZ_FIRMWARE_BLOCK != 0)) {
   1786 		ERROR (abstract->context, "Address or size not aligned to the page size!");
   1787 		return DC_STATUS_INVALIDARGS;
   1788 	}
   1789 
   1790 	// Make sure the device is in service mode.
   1791 	status = hw_ostc3_device_init (device, SERVICE);
   1792 	if (status != DC_STATUS_SUCCESS) {
   1793 		return status;
   1794 	}
   1795 
   1796 	if (ISHWOS4(device->hardware)) {
   1797 		return DC_STATUS_UNSUPPORTED;
   1798 	}
   1799 
   1800 	unsigned int nbytes = 0;
   1801 	while (nbytes < size) {
   1802 		// Read a memory page.
   1803 		status = hw_ostc3_firmware_block_read (device, address + nbytes, data + nbytes, SZ_FIRMWARE_BLOCK);
   1804 		if (status != DC_STATUS_SUCCESS) {
   1805 			ERROR (abstract->context, "Failed to read block.");
   1806 			return status;
   1807 		}
   1808 
   1809 		nbytes += SZ_FIRMWARE_BLOCK;
   1810 	}
   1811 
   1812 	return DC_STATUS_SUCCESS;
   1813 }
   1814 
   1815 static dc_status_t
   1816 hw_ostc3_device_write (dc_device_t *abstract, unsigned int address, const unsigned char data[], unsigned int size)
   1817 {
   1818 	dc_status_t status = DC_STATUS_SUCCESS;
   1819 	hw_ostc3_device_t *device = (hw_ostc3_device_t *) abstract;
   1820 
   1821 	if ((address % SZ_FIRMWARE_BLOCK != 0) ||
   1822 		(size % SZ_FIRMWARE_BLOCK != 0)) {
   1823 		ERROR (abstract->context, "Address or size not aligned to the page size!");
   1824 		return DC_STATUS_INVALIDARGS;
   1825 	}
   1826 
   1827 	// Make sure the device is in service mode.
   1828 	status = hw_ostc3_device_init (device, SERVICE);
   1829 	if (status != DC_STATUS_SUCCESS) {
   1830 		return status;
   1831 	}
   1832 
   1833 	if (ISHWOS4(device->hardware)) {
   1834 		return DC_STATUS_UNSUPPORTED;
   1835 	}
   1836 
   1837 	// Erase the memory pages.
   1838 	status = hw_ostc3_firmware_erase (device, address, size);
   1839 	if (status != DC_STATUS_SUCCESS) {
   1840 		ERROR (abstract->context, "Failed to erase blocks.");
   1841 		return status;
   1842 	}
   1843 
   1844 	unsigned int nbytes = 0;
   1845 	while (nbytes < size) {
   1846 		// Write a memory page.
   1847 		status = hw_ostc3_firmware_block_write (device, address + nbytes, data + nbytes, SZ_FIRMWARE_BLOCK);
   1848 		if (status != DC_STATUS_SUCCESS) {
   1849 			ERROR (abstract->context, "Failed to write block.");
   1850 			return status;
   1851 		}
   1852 
   1853 		nbytes += SZ_FIRMWARE_BLOCK;
   1854 	}
   1855 
   1856 	return DC_STATUS_SUCCESS;
   1857 }
   1858 
   1859 static dc_status_t
   1860 hw_ostc3_device_dump (dc_device_t *abstract, dc_buffer_t *buffer)
   1861 {
   1862 	hw_ostc3_device_t *device = (hw_ostc3_device_t *) abstract;
   1863 
   1864 	// Enable progress notifications.
   1865 	dc_event_progress_t progress = EVENT_PROGRESS_INITIALIZER;
   1866 	progress.maximum = SZ_MEMORY;
   1867 	device_event_emit (abstract, DC_EVENT_PROGRESS, &progress);
   1868 
   1869 	// Make sure the device is in service mode
   1870 	dc_status_t rc = hw_ostc3_device_init (device, SERVICE);
   1871 	if (rc != DC_STATUS_SUCCESS) {
   1872 		return rc;
   1873 	}
   1874 
   1875 	if (ISHWOS4(device->hardware)) {
   1876 		return DC_STATUS_UNSUPPORTED;
   1877 	}
   1878 
   1879 	// Emit a device info event.
   1880 	dc_event_devinfo_t devinfo;
   1881 	device_set_hw_id (abstract, device->hardware);
   1882 	devinfo.firmware = device->firmware;
   1883 	devinfo.serial = device->serial;
   1884 	devinfo.model = device->model;
   1885 	device_event_emit (abstract, DC_EVENT_DEVINFO, &devinfo);
   1886 
   1887 	// Allocate the required amount of memory.
   1888 	if (!dc_buffer_resize (buffer, SZ_MEMORY)) {
   1889 		ERROR (abstract->context, "Insufficient buffer space available.");
   1890 		return DC_STATUS_NOMEMORY;
   1891 	}
   1892 
   1893 	unsigned char *data = dc_buffer_get_data (buffer);
   1894 
   1895 	unsigned int nbytes = 0;
   1896 	while (nbytes < SZ_MEMORY) {
   1897 		// packet size. Can be almost arbitrary size.
   1898 		unsigned int len = SZ_FIRMWARE_BLOCK;
   1899 
   1900 		// Read a block
   1901 		rc = hw_ostc3_firmware_block_read (device, nbytes, data + nbytes, len);
   1902 		if (rc != DC_STATUS_SUCCESS) {
   1903 			ERROR (abstract->context, "Failed to read block.");
   1904 			return rc;
   1905 		}
   1906 
   1907 		// Update and emit a progress event.
   1908 		progress.current += len;
   1909 		device_event_emit (abstract, DC_EVENT_PROGRESS, &progress);
   1910 
   1911 		nbytes += len;
   1912 	}
   1913 
   1914 	return DC_STATUS_SUCCESS;
   1915 }