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_parser.c (42923B)


      1 /*
      2  * libdivecomputer
      3  *
      4  * Copyright (C) 2010 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 <stdlib.h>
     23 #include <stdio.h>
     24 #include <string.h>
     25 #include <stdbool.h>
     26 #include <limits.h>
     27 
     28 #ifdef _MSC_VER
     29 #define snprintf _snprintf
     30 #endif
     31 
     32 #include "libdivecomputer/units.h"
     33 
     34 #include "hw_ostc.h"
     35 #include "hw_ostc3.h"
     36 #include "context-private.h"
     37 #include "parser-private.h"
     38 #include "array.h"
     39 
     40 #define ISINSTANCE(parser) dc_parser_isinstance((parser), &hw_ostc_parser_vtable)
     41 
     42 #define MAXCONFIG 7
     43 #define NGASMIXES 15
     44 #define OSTC4_CC_DILUENT_GAS_OFFSET 5
     45 
     46 #define UNDEFINED 0xFFFFFFFF
     47 
     48 #define HEADER  1
     49 #define PROFILE 2
     50 
     51 #define TEMPERATURE 0
     52 #define DECO        1
     53 #define GF          2
     54 #define PPO2        3
     55 #define DECOPLAN    4
     56 #define CNS         5
     57 #define TANK        6
     58 
     59 #define OSTC_ZHL16_OC    0
     60 #define OSTC_GAUGE       1
     61 #define OSTC_ZHL16_CC    2
     62 #define OSTC_APNEA       3
     63 #define OSTC_ZHL16_OC_GF 4
     64 #define OSTC_ZHL16_CC_GF 5
     65 #define OSTC_PSCR_GF     6
     66 
     67 #define FROG_ZHL16    0
     68 #define FROG_ZHL16_GF 1
     69 #define FROG_APNEA    2
     70 
     71 #define OSTC3_OC    0
     72 #define OSTC3_CC    1
     73 #define OSTC3_GAUGE 2
     74 #define OSTC3_APNEA 3
     75 #define OSTC3_PSCR  4
     76 
     77 #define OSTC3_ZHL16    0
     78 #define OSTC3_ZHL16_GF 1
     79 #define OSTC4_VPM      2
     80 
     81 #define OSTC4      0x43
     82 #define OSTC5      0x44
     83 
     84 #define OSTC3FW(major,minor) ( \
     85 		(((major) & 0xFF) << 8) | \
     86 		((minor) & 0xFF))
     87 
     88 #define OSTC4FW(major,minor,micro,beta) ( \
     89 		(((major) & 0x1F) << 11) | \
     90 		(((minor) & 0x1F) << 6) | \
     91 		(((micro) & 0x1F) << 1) | \
     92 		((beta) & 0x01))
     93 
     94 #define OSTC4_COMPASS_HEADING_CLEARED_FLAG 0x8000
     95 #define OSTC4_COMPASS_HEADING_SET_FLAG 0x4000
     96 
     97 #define OSTC4_SCRUBBER_STATE_ERROR_FLAG 0x4000
     98 #define OSTC4_SCRUBBER_STATE_WARNING_FLAG 0x2000
     99 
    100 #define OSTC4_SURFACE_GF_OFFSET 56
    101 
    102 typedef struct hw_ostc_sample_info_t {
    103 	unsigned int type;
    104 	unsigned int divisor;
    105 	unsigned int size;
    106 } hw_ostc_sample_info_t;
    107 
    108 typedef struct hw_ostc_layout_t {
    109 	unsigned int datetime;
    110 	unsigned int maxdepth;
    111 	unsigned int divetime;
    112 	unsigned int temperature;
    113 	unsigned int atmospheric;
    114 	unsigned int desat;
    115 	unsigned int firmware;
    116 	unsigned int battery;
    117 	unsigned int battery_percentage;
    118 	unsigned int salinity;
    119 	unsigned int avgdepth;
    120 	unsigned int duration;
    121 	unsigned int gf;
    122 	unsigned int decomodel;
    123 	unsigned int divemode;
    124 } hw_ostc_layout_t;
    125 
    126 typedef struct hw_ostc_gasmix_t {
    127 	unsigned int id;
    128 	unsigned int oxygen;
    129 	unsigned int helium;
    130 	unsigned int type;
    131 	unsigned int enabled;
    132 	unsigned int active;
    133 	unsigned int diluent;
    134 } hw_ostc_gasmix_t;
    135 
    136 typedef struct hw_ostc_parser_t {
    137 	dc_parser_t base;
    138 	unsigned int hwos;
    139 	unsigned int model;
    140 	unsigned int serial;
    141 	// Cached fields.
    142 	unsigned int cached;
    143 	unsigned int version;
    144 	unsigned int header;
    145 	const hw_ostc_layout_t *layout;
    146 	unsigned int ngasmixes;
    147 	unsigned int nfixed;
    148 	unsigned int ndisabled;
    149 	unsigned int initial;
    150 	unsigned int initial_setpoint;
    151 	unsigned int initial_cns;
    152 	hw_ostc_gasmix_t gasmix[NGASMIXES];
    153 	int first_scrubber_time_minutes;
    154 	int last_scrubber_time_minutes;
    155 	bool scrubber_error_reported;
    156 	bool scrubber_warning_reported;
    157 } hw_ostc_parser_t;
    158 
    159 static dc_status_t hw_ostc_parser_get_datetime (dc_parser_t *abstract, dc_datetime_t *datetime);
    160 static dc_status_t hw_ostc_parser_get_field (dc_parser_t *abstract, dc_field_type_t type, unsigned int flags, void *value);
    161 static dc_status_t hw_ostc_parser_samples_foreach (dc_parser_t *abstract, dc_sample_callback_t callback, void *userdata);
    162 
    163 static dc_status_t hw_ostc_parser_internal_foreach (hw_ostc_parser_t *parser, dc_sample_callback_t callback, void *userdata);
    164 
    165 static const dc_parser_vtable_t hw_ostc_parser_vtable = {
    166 	sizeof(hw_ostc_parser_t),
    167 	DC_FAMILY_HW_OSTC,
    168 	NULL, /* set_clock */
    169 	NULL, /* set_atmospheric */
    170 	NULL, /* set_density */
    171 	hw_ostc_parser_get_datetime, /* datetime */
    172 	hw_ostc_parser_get_field, /* fields */
    173 	hw_ostc_parser_samples_foreach, /* samples_foreach */
    174 	NULL /* destroy */
    175 };
    176 
    177 static const hw_ostc_layout_t hw_ostc_layout_ostc = {
    178 	3,  /* datetime */
    179 	8,  /* maxdepth */
    180 	10, /* divetime */
    181 	13, /* temperature */
    182 	15, /* atmospheric */
    183 	17, /* desat */
    184 	32, /* firmware */
    185 	34, /* battery volt after dive */
    186 	0,  /* battery percentage TBD */
    187 	43, /* salinity */
    188 	45, /* avgdepth */
    189 	47, /* duration */
    190 	49, /* gf */
    191 	UNDEFINED, /* decomodel */
    192 	51, /* divemode */
    193 };
    194 
    195 static const hw_ostc_layout_t hw_ostc_layout_frog = {
    196 	9,  /* datetime */
    197 	14, /* maxdepth */
    198 	16, /* divetime */
    199 	19, /* temperature */
    200 	21, /* atmospheric */
    201 	23, /* desat */
    202 	32, /* firmware */
    203 	34, /* battery volt after dive */
    204 	0,  /* battery percentage TBD */
    205 	43, /* salinity */
    206 	45, /* avgdepth */
    207 	47, /* duration */
    208 	49, /* gf */
    209 	UNDEFINED, /* decomodel */
    210 	51, /* divemode */
    211 };
    212 
    213 static const hw_ostc_layout_t hw_ostc_layout_ostc3 = {
    214 	12, /* datetime */
    215 	17, /* maxdepth */
    216 	19, /* divetime */
    217 	22, /* temperature */
    218 	24, /* atmospheric */
    219 	26, /* desat */
    220 	48, /* firmware */
    221 	50, /* battery volt after dive */
    222 	59, /* battery percentage */
    223 	70, /* salinity */
    224 	73, /* avgdepth */
    225 	75, /* duration */
    226 	77, /* gf */
    227 	79, /* decomodel */
    228 	82, /* divemode */
    229 };
    230 
    231 static unsigned int
    232 hw_ostc_find_gasmix_manual (hw_ostc_parser_t *parser, unsigned int o2, unsigned int he, unsigned int dil)
    233 {
    234 	unsigned int offset = parser->nfixed - parser->ndisabled;
    235 	unsigned int count = parser->ngasmixes;
    236 
    237 	unsigned int i = offset;
    238 	while (i < count) {
    239 		if (o2 == parser->gasmix[i].oxygen && he == parser->gasmix[i].helium && dil == parser->gasmix[i].diluent)
    240 			break;
    241 		i++;
    242 	}
    243 
    244 	return i;
    245 }
    246 
    247 static unsigned int
    248 hw_ostc_find_gasmix_fixed (hw_ostc_parser_t *parser, unsigned int id)
    249 {
    250 	unsigned int offset = 0;
    251 	unsigned int count = parser->nfixed - parser->ndisabled;
    252 
    253 	unsigned int i = offset;
    254 	while (i < count) {
    255 		if (id == parser->gasmix[i].id)
    256 			break;
    257 		i++;
    258 	}
    259 
    260 	return i;
    261 }
    262 
    263 static unsigned int
    264 hw_ostc_is_ccr (unsigned int divemode, unsigned int version)
    265 {
    266 	if (version == 0x21) {
    267 		return divemode == OSTC_ZHL16_CC || divemode == OSTC_ZHL16_CC_GF || divemode == OSTC_PSCR_GF;
    268 	} else if (version == 0x23 || version == 0x24) {
    269 		return divemode == OSTC3_CC || divemode == OSTC3_PSCR;
    270 	} else {
    271 		return 0;
    272 	}
    273 }
    274 
    275 static dc_status_t
    276 hw_ostc_parser_cache (hw_ostc_parser_t *parser)
    277 {
    278 	dc_parser_t *abstract = (dc_parser_t *) parser;
    279 	const unsigned char *data = abstract->data;
    280 	unsigned int size = abstract->size;
    281 
    282 	if (parser->cached) {
    283 		return DC_STATUS_SUCCESS;
    284 	}
    285 
    286 	if (size < 9) {
    287 		ERROR(abstract->context, "Header too small.");
    288 		return DC_STATUS_DATAFORMAT;
    289 	}
    290 
    291 	// Check the profile version
    292 	unsigned int version = data[parser->hwos ? 8 : 2];
    293 	const hw_ostc_layout_t *layout = NULL;
    294 	unsigned int header = 0;
    295 	switch (version) {
    296 	case 0x20:
    297 		layout = &hw_ostc_layout_ostc;
    298 		header = 47;
    299 		break;
    300 	case 0x21:
    301 		layout = &hw_ostc_layout_ostc;
    302 		header = 57;
    303 		break;
    304 	case 0x22:
    305 		layout = &hw_ostc_layout_frog;
    306 		header = 256;
    307 		break;
    308 	case 0x23:
    309 	case 0x24:
    310 		layout = &hw_ostc_layout_ostc3;
    311 		header = 256;
    312 		break;
    313 	default:
    314 		ERROR(abstract->context, "Unknown data format version.");
    315 		return DC_STATUS_DATAFORMAT;
    316 	}
    317 
    318 	if (size < header) {
    319 		ERROR(abstract->context, "Header too small.");
    320 		return DC_STATUS_DATAFORMAT;
    321 	}
    322 
    323 	// Get the dive mode.
    324 	unsigned int divemode = layout->divemode < header ?
    325 		data[layout->divemode] : UNDEFINED;
    326 
    327 	// Get the CCR mode.
    328 	unsigned int ccr = hw_ostc_is_ccr (divemode, version);
    329 
    330 	// Get all the gas mixes, the index of the inital mix,
    331 	// the initial setpoint (used in the fixed setpoint CCR mode),
    332 	// and the initial CNS from the header
    333 	unsigned int initial = UNDEFINED;
    334 	unsigned int initial_setpoint = UNDEFINED;
    335 	unsigned int initial_cns = UNDEFINED;
    336 	unsigned int ngasmixes = 0;
    337 	hw_ostc_gasmix_t gasmix[NGASMIXES] = {{0}};
    338 	if (version == 0x22) {
    339 		ngasmixes = 3;
    340 		if (data[31] != 0xFF) {
    341 			initial = data[31];
    342 		}
    343 		for (unsigned int i = 0; i < ngasmixes; ++i) {
    344 			gasmix[i].id = i + 1;
    345 			gasmix[i].oxygen = data[25 + 2 * i];
    346 			gasmix[i].helium = 0;
    347 			gasmix[i].type = 0;
    348 			gasmix[i].enabled = 1;
    349 			gasmix[i].active = 0;
    350 			gasmix[i].diluent = 0;
    351 		}
    352 	} else if (version == 0x23 || version == 0x24) {
    353 		ngasmixes = 5;
    354 		for (unsigned int i = 0; i < ngasmixes; ++i) {
    355 			gasmix[i].id = i + 1;
    356 			gasmix[i].oxygen = data[28 + 4 * i + 0];
    357 			gasmix[i].helium = data[28 + 4 * i + 1];
    358 			gasmix[i].type   = data[28 + 4 * i + 3];
    359 			gasmix[i].enabled = gasmix[i].type != 0;
    360 			gasmix[i].active = 0;
    361 			gasmix[i].diluent = ccr;
    362 			// Find the first gas marked as the initial gas.
    363 			if (initial == UNDEFINED && data[28 + 4 * i + 3] == 1) {
    364 				initial = i + 1; /* One based index! */
    365 			}
    366 		}
    367 		// The first fixed setpoint is the initial setpoint in CCR mode.
    368 		if (ccr) {
    369 			initial_setpoint = data[60];
    370 		}
    371 		// Initial CNS
    372 		initial_cns = array_uint16_le (data + 53);
    373 	} else {
    374 		ngasmixes = 5;
    375 		if (data[31] != 0xFF) {
    376 			initial = data[31];
    377 		}
    378 		for (unsigned int i = 0; i < ngasmixes; ++i) {
    379 			gasmix[i].id = i + 1;
    380 			gasmix[i].oxygen = data[19 + 2 * i + 0];
    381 			gasmix[i].helium = data[19 + 2 * i + 1];
    382 			gasmix[i].type = 0;
    383 			if (version == 0x21) {
    384 				gasmix[i].enabled = data[53] & (1 << i);
    385 			} else {
    386 				gasmix[i].enabled = 1;
    387 			}
    388 			gasmix[i].active = 0;
    389 			gasmix[i].diluent = ccr;
    390 		}
    391 	}
    392 	if (initial != UNDEFINED) {
    393 		if (initial < 1 || initial > ngasmixes) {
    394 			ERROR(abstract->context, "Invalid initial gas mix.");
    395 			return DC_STATUS_DATAFORMAT;
    396 		}
    397 	} else {
    398 		WARNING(abstract->context, "No initial gas mix available.");
    399 	}
    400 
    401 	// Cache the data for later use.
    402 	parser->version = version;
    403 	parser->header = header;
    404 	parser->layout = layout;
    405 	parser->ngasmixes = ngasmixes;
    406 	parser->nfixed = ngasmixes;
    407 	parser->ndisabled = 0;
    408 	parser->initial = initial;
    409 	parser->initial_setpoint = initial_setpoint;
    410 	parser->initial_cns = initial_cns;
    411 	for (unsigned int i = 0; i < ngasmixes; ++i) {
    412 		parser->gasmix[i] = gasmix[i];
    413 	}
    414 	parser->cached = HEADER;
    415 
    416 	return DC_STATUS_SUCCESS;
    417 }
    418 
    419 static dc_status_t
    420 hw_ostc_parser_create_internal (dc_parser_t **out, dc_context_t *context, const unsigned char data[], size_t size, unsigned int hwos, unsigned int model, unsigned int serial)
    421 {
    422 	hw_ostc_parser_t *parser = NULL;
    423 
    424 	if (out == NULL)
    425 		return DC_STATUS_INVALIDARGS;
    426 
    427 	// Allocate memory.
    428 	parser = (hw_ostc_parser_t *) dc_parser_allocate (context, &hw_ostc_parser_vtable, data, size);
    429 	if (parser == NULL) {
    430 		ERROR (context, "Failed to allocate memory.");
    431 		return DC_STATUS_NOMEMORY;
    432 	}
    433 
    434 	// Set the default values.
    435 	parser->hwos = hwos;
    436 	parser->model = model;
    437 	parser->cached = 0;
    438 	parser->version = 0;
    439 	parser->header = 0;
    440 	parser->layout = NULL;
    441 	parser->ngasmixes = 0;
    442 	parser->nfixed = 0;
    443 	parser->ndisabled = 0;
    444 	parser->initial = 0;
    445 	parser->initial_setpoint = 0;
    446 	parser->initial_cns = 0;
    447 	for (unsigned int i = 0; i < NGASMIXES; ++i) {
    448 		parser->gasmix[i].id = 0;
    449 		parser->gasmix[i].oxygen = 0;
    450 		parser->gasmix[i].helium = 0;
    451 		parser->gasmix[i].type = 0;
    452 		parser->gasmix[i].enabled = 0;
    453 		parser->gasmix[i].active = 0;
    454 		parser->gasmix[i].diluent = 0;
    455 	}
    456 	parser->first_scrubber_time_minutes = INT_MAX;
    457 	parser->last_scrubber_time_minutes = INT_MAX;
    458 	parser->scrubber_error_reported = false;
    459 	parser->scrubber_warning_reported = false;
    460 	parser->serial = serial;
    461 
    462 	*out = (dc_parser_t *) parser;
    463 
    464 	return DC_STATUS_SUCCESS;
    465 }
    466 
    467 
    468 dc_status_t
    469 hw_ostc_parser_create (dc_parser_t **out, dc_context_t *context, const unsigned char data[], size_t size, unsigned int serial)
    470 {
    471 	return hw_ostc_parser_create_internal (out, context, data, size, 0, 0, serial);
    472 }
    473 
    474 dc_status_t
    475 hw_ostc3_parser_create (dc_parser_t **out, dc_context_t *context, const unsigned char data[], size_t size, unsigned int model, unsigned int serial)
    476 {
    477 	return hw_ostc_parser_create_internal (out, context, data, size, 1, model, serial);
    478 }
    479 
    480 static dc_status_t
    481 hw_ostc_parser_get_datetime (dc_parser_t *abstract, dc_datetime_t *datetime)
    482 {
    483 	hw_ostc_parser_t *parser = (hw_ostc_parser_t *) abstract;
    484 	const unsigned char *data = abstract->data;
    485 
    486 	// Cache the header data.
    487 	dc_status_t rc = hw_ostc_parser_cache (parser);
    488 	if (rc != DC_STATUS_SUCCESS)
    489 		return rc;
    490 
    491 	unsigned int version = parser->version;
    492 	const hw_ostc_layout_t *layout = parser->layout;
    493 
    494 	unsigned int divetime = 0;
    495 	if (version > 0x20) {
    496 		// Use the dive time stored in the extended header, rounded down towards
    497 		// the nearest minute, to match the value displayed by the ostc.
    498 		divetime = (array_uint16_le (data + layout->duration) / 60) * 60;
    499 	} else {
    500 		// Use the normal dive time (excluding the shallow parts of the dive).
    501 		divetime = array_uint16_le (data + layout->divetime) * 60 + data[layout->divetime + 2];
    502 	}
    503 
    504 	const unsigned char *p = data + layout->datetime;
    505 
    506 	dc_datetime_t dt;
    507 	if (version == 0x23 || version == 0x24) {
    508 		dt.year   = p[0] + 2000;
    509 		dt.month  = p[1];
    510 		dt.day    = p[2];
    511 	} else {
    512 		dt.year   = p[2] + 2000;
    513 		dt.month  = p[0];
    514 		dt.day    = p[1];
    515 	}
    516 	dt.hour   = p[3];
    517 	dt.minute = p[4];
    518 	dt.second = 0;
    519 	dt.timezone = DC_TIMEZONE_NONE;
    520 
    521 	if (version == 0x24) {
    522 		if (datetime)
    523 			*datetime = dt;
    524 	} else {
    525 		dc_ticks_t ticks = dc_datetime_mktime (&dt);
    526 		if (ticks == (dc_ticks_t) -1)
    527 			return DC_STATUS_DATAFORMAT;
    528 
    529 		ticks -= divetime;
    530 
    531 		if (!dc_datetime_gmtime (datetime, ticks))
    532 			return DC_STATUS_DATAFORMAT;
    533 
    534 		datetime->timezone = DC_TIMEZONE_NONE;
    535 	}
    536 
    537 	return DC_STATUS_SUCCESS;
    538 }
    539 
    540 #define BUFLEN 64
    541 
    542 static dc_status_t
    543 hw_ostc_parser_get_field (dc_parser_t *abstract, dc_field_type_t type, unsigned int flags, void *value)
    544 {
    545 	hw_ostc_parser_t *parser = (hw_ostc_parser_t *) abstract;
    546 	const unsigned char *data = abstract->data;
    547 
    548 	// Cache the header data.
    549 	dc_status_t rc = hw_ostc_parser_cache (parser);
    550 	if (rc != DC_STATUS_SUCCESS)
    551 		return rc;
    552 
    553 	// Cache the profile data.
    554 	if (parser->cached < PROFILE) {
    555 		rc = hw_ostc_parser_internal_foreach (parser, NULL, NULL);
    556 		if (rc != DC_STATUS_SUCCESS)
    557 			return rc;
    558 	}
    559 
    560 	unsigned int version = parser->version;
    561 	const hw_ostc_layout_t *layout = parser->layout;
    562 
    563 	dc_gasmix_t *gasmix = (dc_gasmix_t *) value;
    564 	dc_salinity_t *water = (dc_salinity_t *) value;
    565 	dc_decomodel_t *decomodel = (dc_decomodel_t *) value;
    566 	dc_field_string_t *string = (dc_field_string_t *) value;
    567 
    568 	unsigned int salinity = data[layout->salinity];
    569 	if (version == 0x23 || version == 0x24)
    570 		salinity += 100;
    571 	char buf[BUFLEN];
    572 
    573 	if (value) {
    574 		switch (type) {
    575 		case DC_FIELD_DIVETIME:
    576 			*((unsigned int *) value) = array_uint16_le (data + layout->divetime) * 60 + data[layout->divetime + 2];
    577 			break;
    578 		case DC_FIELD_MAXDEPTH:
    579 			*((double *) value) = array_uint16_le (data + layout->maxdepth) / 100.0;
    580 			break;
    581 		case DC_FIELD_AVGDEPTH:
    582 			if (parser->version < 0x21)
    583 				return DC_STATUS_UNSUPPORTED;
    584 			*((double *) value) = array_uint16_le (data + layout->avgdepth) / 100.0;
    585 			break;
    586 		case DC_FIELD_TANK_COUNT:
    587 		case DC_FIELD_GASMIX_COUNT:
    588 			*((unsigned int *) value) = parser->ngasmixes;
    589 			break;
    590 		case DC_FIELD_GASMIX:
    591 			if (flags >= parser->ngasmixes) {
    592 				return DC_STATUS_UNSUPPORTED;
    593 			}
    594 
    595 			gasmix->usage = parser->gasmix[flags].diluent ?
    596 				DC_USAGE_DILUENT : DC_USAGE_OPEN_CIRCUIT;
    597 			gasmix->oxygen = parser->gasmix[flags].oxygen / 100.0;
    598 			gasmix->helium = parser->gasmix[flags].helium / 100.0;
    599 			gasmix->nitrogen = 1.0 - gasmix->oxygen - gasmix->helium;
    600 
    601 			break;
    602 		case DC_FIELD_TANK:
    603 			if (flags >= parser->ngasmixes || !parser->gasmix[flags].enabled) {
    604 				return DC_STATUS_UNSUPPORTED;
    605 			}
    606 
    607 			dc_tank_t *tank = (dc_tank_t *) value;
    608 
    609 			tank->volume = 0.0;
    610 			tank->gasmix = flags;
    611 			tank->workpressure = 0.0;
    612 			tank->type = DC_TANKINFO_METRIC;
    613 
    614 			break;
    615 		case DC_FIELD_SALINITY:
    616 			if (salinity < 100 || salinity > 104)
    617 				return DC_STATUS_UNSUPPORTED;
    618 
    619 			if (salinity == 100)
    620 				water->type = DC_WATER_FRESH;
    621 			else
    622 				water->type = DC_WATER_SALT;
    623 			water->density = salinity * 10.0;
    624 			break;
    625 		case DC_FIELD_ATMOSPHERIC:
    626 			*((double *) value) = array_uint16_le (data + layout->atmospheric) / 1000.0;
    627 			break;
    628 		case DC_FIELD_TEMPERATURE_MINIMUM:
    629 			*((double *) value) = (signed short) array_uint16_le (data + layout->temperature) / 10.0;
    630 			break;
    631 		case DC_FIELD_DIVEMODE:
    632 			if (version == 0x21) {
    633 				switch (data[layout->divemode]) {
    634 				case OSTC_APNEA:
    635 					*((dc_divemode_t *) value) = DC_DIVEMODE_FREEDIVE;
    636 					break;
    637 				case OSTC_GAUGE:
    638 					*((dc_divemode_t *) value) = DC_DIVEMODE_GAUGE;
    639 					break;
    640 				case OSTC_ZHL16_OC:
    641 				case OSTC_ZHL16_OC_GF:
    642 					*((dc_divemode_t *) value) = DC_DIVEMODE_OC;
    643 					break;
    644 				case OSTC_ZHL16_CC:
    645 				case OSTC_ZHL16_CC_GF:
    646 					*((dc_divemode_t *) value) = DC_DIVEMODE_CCR;
    647 					break;
    648 				case OSTC_PSCR_GF:
    649 					*((dc_divemode_t *) value) = DC_DIVEMODE_SCR;
    650 					break;
    651 				default:
    652 					return DC_STATUS_DATAFORMAT;
    653 				}
    654 			} else if (version == 0x22) {
    655 				switch (data[layout->divemode]) {
    656 				case FROG_ZHL16:
    657 				case FROG_ZHL16_GF:
    658 					*((dc_divemode_t *) value) = DC_DIVEMODE_OC;
    659 					break;
    660 				case FROG_APNEA:
    661 					*((dc_divemode_t *) value) = DC_DIVEMODE_FREEDIVE;
    662 					break;
    663 				default:
    664 					return DC_STATUS_DATAFORMAT;
    665 				}
    666 			} else if (version == 0x23 || version == 0x24) {
    667 				switch (data[layout->divemode]) {
    668 				case OSTC3_OC:
    669 					*((dc_divemode_t *) value) = DC_DIVEMODE_OC;
    670 					break;
    671 				case OSTC3_CC:
    672 					*((dc_divemode_t *) value) = DC_DIVEMODE_CCR;
    673 					break;
    674 				case OSTC3_GAUGE:
    675 					*((dc_divemode_t *) value) = DC_DIVEMODE_GAUGE;
    676 					break;
    677 				case OSTC3_APNEA:
    678 					*((dc_divemode_t *) value) = DC_DIVEMODE_FREEDIVE;
    679 					break;
    680 				case OSTC3_PSCR:
    681 					*((dc_divemode_t *) value) = DC_DIVEMODE_SCR;
    682 					break;
    683 				default:
    684 					return DC_STATUS_DATAFORMAT;
    685 				}
    686 			} else {
    687 				return DC_STATUS_UNSUPPORTED;
    688 			}
    689 			break;
    690 		case DC_FIELD_DECOMODEL:
    691 			if (version == 0x21) {
    692 				switch (data[layout->divemode]) {
    693 				case OSTC_APNEA:
    694 				case OSTC_GAUGE:
    695 					decomodel->type = DC_DECOMODEL_NONE;
    696 					break;
    697 				case OSTC_ZHL16_OC:
    698 				case OSTC_ZHL16_CC:
    699 					decomodel->type = DC_DECOMODEL_BUHLMANN;
    700 					decomodel->params.gf.low  = 100;
    701 					decomodel->params.gf.high = 100;
    702 					break;
    703 				case OSTC_ZHL16_OC_GF:
    704 				case OSTC_ZHL16_CC_GF:
    705 				case OSTC_PSCR_GF:
    706 					decomodel->type = DC_DECOMODEL_BUHLMANN;
    707 					decomodel->params.gf.low  = data[layout->gf + 0];
    708 					decomodel->params.gf.high = data[layout->gf + 1];
    709 					break;
    710 				default:
    711 					return DC_STATUS_DATAFORMAT;
    712 				}
    713 			} else if (version == 0x22) {
    714 				switch (data[layout->divemode]) {
    715 				case FROG_ZHL16:
    716 					decomodel->type = DC_DECOMODEL_BUHLMANN;
    717 					decomodel->params.gf.low  = 100;
    718 					decomodel->params.gf.high = 100;
    719 					break;
    720 				case FROG_ZHL16_GF:
    721 					decomodel->type = DC_DECOMODEL_BUHLMANN;
    722 					decomodel->params.gf.low  = data[layout->gf + 0];
    723 					decomodel->params.gf.high = data[layout->gf + 1];
    724 					break;
    725 				case FROG_APNEA:
    726 					decomodel->type = DC_DECOMODEL_NONE;
    727 					break;
    728 				default:
    729 					return DC_STATUS_DATAFORMAT;
    730 				}
    731 			} else if (version == 0x23 || version == 0x24) {
    732 				switch (data[layout->decomodel]) {
    733 				case OSTC3_ZHL16:
    734 					decomodel->type = DC_DECOMODEL_BUHLMANN;
    735 					decomodel->params.gf.low  = 100;
    736 					decomodel->params.gf.high = 100;
    737 					break;
    738 				case OSTC3_ZHL16_GF:
    739 					decomodel->type = DC_DECOMODEL_BUHLMANN;
    740 					decomodel->params.gf.low  = data[layout->gf + 0];
    741 					decomodel->params.gf.high = data[layout->gf + 1];
    742 					break;
    743 				case OSTC4_VPM:
    744 					decomodel->type = DC_DECOMODEL_VPM;
    745 					break;
    746 				default:
    747 					return DC_STATUS_DATAFORMAT;
    748 				}
    749 			} else {
    750 				return DC_STATUS_UNSUPPORTED;
    751 			}
    752 			decomodel->conservatism = 0;
    753 			break;
    754 		case DC_FIELD_STRING:
    755 			switch(flags) {
    756 			case 0: /* serial */
    757 				string->desc = STRING_KEY_SERIAL_NUMBER;
    758 				snprintf(buf, BUFLEN, "%u", parser->serial);
    759 				break;
    760 			case 1: /* battery */
    761 				string->desc = "Battery at end";
    762 				unsigned int percentage = (unsigned int) data[layout->battery_percentage];
    763 				if (percentage != 0xFF && (version == 0x23 || version == 0x24)) {
    764 					percentage = percentage>100? 100: percentage;
    765 					snprintf(buf, BUFLEN, "%.2fV, %u%% remaining",
    766 					         array_uint16_le (data + layout->battery) / 1000.0,
    767 					         percentage);
    768 				} else {
    769 					snprintf(buf, BUFLEN, "%.2fV", array_uint16_le (data + layout->battery) / 1000.0);
    770 				}
    771 				break;
    772 			case 2: /* desat */
    773 				string->desc = "Desat time";
    774 				snprintf(buf, BUFLEN, "%0u:%02u", array_uint16_le (data + layout->desat) / 60,
    775 						 array_uint16_le (data + layout->desat) % 60);
    776 				break;
    777 			case 3: /* firmware */
    778 				string->desc = STRING_KEY_FIRMWARE_VERSION;
    779 				/* OSTC4 stores firmware as XXXX XYYY YYZZ ZZZB, -> X.Y.Z beta? */
    780 				if (ISHWOS4(parser->model)) {
    781 					int firmwareOnDevice = array_uint16_le (data + layout->firmware);
    782 					unsigned char X = 0, Y = 0, Z = 0, beta = 0;
    783 					X = (firmwareOnDevice & 0xF800) >> 11;
    784 					Y = (firmwareOnDevice & 0x07C0) >> 6;
    785 					Z = (firmwareOnDevice & 0x003E) >> 1;
    786 					beta = firmwareOnDevice & 0x0001;
    787 
    788 					snprintf(buf, BUFLEN, "%u.%u.%u%s", X, Y, Z, beta? "beta": "");
    789 				} else {
    790 					snprintf(buf, BUFLEN, "%0u.%02u", data[layout->firmware], data[layout->firmware + 1]);
    791 				}
    792 				break;
    793 
    794 			case 4: /* Deco model */
    795 				string->desc = "Deco model";
    796 				if (((version == 0x23 || version == 0x24) && data[layout->decomodel] == OSTC3_ZHL16) ||
    797 						(version == 0x22 && data[layout->divemode] == FROG_ZHL16) ||
    798 						(version == 0x21 && (data[layout->divemode] == OSTC_ZHL16_OC || data[layout->divemode] == OSTC_ZHL16_CC)))
    799 					strncpy(buf, "ZH-L16", BUFLEN);
    800 				else if (((version == 0x23 || version == 0x24) && data[layout->decomodel] == OSTC3_ZHL16_GF) ||
    801 						(version == 0x22 && data[layout->divemode] == FROG_ZHL16_GF) ||
    802 						(version == 0x21 && (data[layout->divemode] == OSTC_ZHL16_OC_GF || data[layout->divemode] == OSTC_ZHL16_CC_GF)))
    803 					strncpy(buf, "ZH-L16-GF", BUFLEN);
    804 				else if (((version == 0x24) && data[layout->divemode] == OSTC4_VPM))
    805 					strncpy(buf, "VPM", BUFLEN);
    806 				else
    807 					return DC_STATUS_DATAFORMAT;
    808 				break;
    809 			case 5: /* Deco model info */
    810 				string->desc = "Deco model info";
    811 				if (((version == 0x23 || version == 0x24) && data[layout->decomodel] == OSTC3_ZHL16) ||
    812 						(version == 0x22 && data[layout->divemode] == FROG_ZHL16) ||
    813 						(version == 0x21 && (data[layout->divemode] == OSTC_ZHL16_OC || data[layout->divemode] == OSTC_ZHL16_CC)))
    814 					snprintf(buf, BUFLEN, "Saturation %u, Desaturation %u", data[layout->gf], data[layout->gf+1]);
    815 				else if (((version == 0x23 || version == 0x24) && data[layout->decomodel] == OSTC3_ZHL16_GF) ||
    816 						(version == 0x22 && data[layout->divemode] == FROG_ZHL16_GF) ||
    817 						(version == 0x21 && (data[layout->divemode] == OSTC_ZHL16_OC_GF || data[layout->divemode] == OSTC_ZHL16_CC_GF)))
    818 					snprintf(buf, BUFLEN, "GF %u/%u", data[layout->gf], data[layout->gf+1]);
    819 				else
    820 					return DC_STATUS_DATAFORMAT;
    821 				break;
    822 			case 6:
    823 				if (parser->first_scrubber_time_minutes == INT_MAX) {
    824 					return DC_STATUS_UNSUPPORTED;
    825 				}
    826 
    827 				string->desc = "Remaining scrubber time at start [minutes]";
    828 				snprintf(buf, BUFLEN, "%d", parser->first_scrubber_time_minutes);
    829 				break;
    830 			case 7:
    831 				if (parser->last_scrubber_time_minutes == INT_MAX) {
    832 					return DC_STATUS_UNSUPPORTED;
    833 				}
    834 
    835 				string->desc = "Remaining scrubber time at end [minutes]";
    836 				snprintf(buf, BUFLEN, "%d", parser->last_scrubber_time_minutes);
    837 				break;
    838 			case 8:
    839 				if (!ISHWOS4(parser->model)) {
    840 					return DC_STATUS_UNSUPPORTED;
    841 				}
    842 
    843 				int firmwareOnDevice = array_uint16_le (data + layout->firmware);
    844 				if  (firmwareOnDevice < OSTC4FW(1, 7, 5, 0) || firmwareOnDevice == OSTC4FW(1, 7, 5, 1)) {
    845 					return DC_STATUS_UNSUPPORTED;
    846 				}
    847 
    848 				string->desc = "Surface GF at end";
    849 				snprintf(buf, BUFLEN, "%d", data[OSTC4_SURFACE_GF_OFFSET]);
    850 
    851 				break;
    852 			default:
    853 				return DC_STATUS_UNSUPPORTED;
    854 			}
    855 			string->value = strdup(buf);
    856 			break;
    857 		default:
    858 			return DC_STATUS_UNSUPPORTED;
    859 		}
    860 	}
    861 
    862 	return DC_STATUS_SUCCESS;
    863 }
    864 
    865 static dc_status_t
    866 hw_ostc_parser_internal_foreach (hw_ostc_parser_t *parser, dc_sample_callback_t callback, void *userdata)
    867 {
    868 	dc_parser_t *abstract = (dc_parser_t *) parser;
    869 	const unsigned char *data = abstract->data;
    870 	unsigned int size = abstract->size;
    871 
    872 	unsigned int version = parser->version;
    873 	unsigned int header = parser->header;
    874 	const hw_ostc_layout_t *layout = parser->layout;
    875 
    876 	// Exit if no profile data available.
    877 	const unsigned char empty[] = {0x08, 0x00, 0x00, 0xFD, 0xFD};
    878 	if (size == header ||
    879 		(size == header + 2 && memcmp(data + header, empty + 3, 2) == 0) ||
    880 		(size == header + 5 && memcmp(data + header, empty, 5) == 0)) {
    881 		parser->cached = PROFILE;
    882 		return DC_STATUS_SUCCESS;
    883 	}
    884 
    885 	// Check the header length.
    886 	if (version == 0x23 || version == 0x24) {
    887 		if (size < header + 5) {
    888 			ERROR (abstract->context, "Buffer overflow detected!");
    889 			return DC_STATUS_DATAFORMAT;
    890 		}
    891 	}
    892 
    893 	// Get the sample rate.
    894 	unsigned int samplerate = 0;
    895 	if (version == 0x23 || version == 0x24)
    896 		samplerate = data[header + 3];
    897 	else
    898 		samplerate = data[36];
    899 
    900 	// Get the number of sample descriptors.
    901 	unsigned int nconfig = 0;
    902 	if (version == 0x23 || version == 0x24)
    903 		nconfig = data[header + 4];
    904 	else
    905 		nconfig = 6;
    906 	if (nconfig > MAXCONFIG) {
    907 		ERROR(abstract->context, "Too many sample descriptors.");
    908 		return DC_STATUS_DATAFORMAT;
    909 	}
    910 
    911 	// Check the header length.
    912 	if (version == 0x23 || version == 0x24) {
    913 		if (size < header + 5 + 3 * nconfig) {
    914 			ERROR (abstract->context, "Buffer overflow detected!");
    915 			return DC_STATUS_DATAFORMAT;
    916 		}
    917 	}
    918 
    919 	// Get the extended sample configuration.
    920 	hw_ostc_sample_info_t info[MAXCONFIG] = {{0}};
    921 	for (unsigned int i = 0; i < nconfig; ++i) {
    922 		if (version == 0x23 || version == 0x24) {
    923 			info[i].type    = data[header + 5 + 3 * i + 0];
    924 			info[i].size    = data[header + 5 + 3 * i + 1];
    925 			info[i].divisor = data[header + 5 + 3 * i + 2];
    926 		} else {
    927 			info[i].type    = i;
    928 			info[i].divisor = (data[37 + i] & 0x0F);
    929 			info[i].size    = (data[37 + i] & 0xF0) >> 4;
    930 		}
    931 
    932 		if (info[i].divisor) {
    933 			switch (info[i].type) {
    934 			case TEMPERATURE:
    935 			case DECO:
    936 			case TANK:
    937 				if (info[i].size != 2) {
    938 					ERROR(abstract->context, "Unexpected sample size.");
    939 					return DC_STATUS_DATAFORMAT;
    940 				}
    941 				break;
    942 			case PPO2:
    943 				if (info[i].size != 3 && info[i].size != 9) {
    944 					ERROR(abstract->context, "Unexpected sample size.");
    945 					return DC_STATUS_DATAFORMAT;
    946 				}
    947 				break;
    948 			case CNS:
    949 				if (info[i].size != 1 && info[i].size != 2) {
    950 					ERROR(abstract->context, "Unexpected sample size.");
    951 					return DC_STATUS_DATAFORMAT;
    952 				}
    953 				break;
    954 			default: // Not yet used.
    955 				break;
    956 			}
    957 		}
    958 	}
    959 
    960 	// Get the firmware version.
    961 	unsigned int firmware = 0;
    962 	if (ISHWOS4(parser->model)) {
    963 		firmware = array_uint16_le (data + layout->firmware);
    964 		DEBUG (abstract->context, "Device: firmware=%u (%u.%u.%u.%u)",
    965 			firmware,
    966 			(firmware >> 11) & 0x1F,
    967 			(firmware >>  6) & 0x1F,
    968 			(firmware >>  1) & 0x1F,
    969 			(firmware      ) & 0x01);
    970 	} else {
    971 		firmware = array_uint16_be (data + layout->firmware);
    972 		DEBUG (abstract->context, "Device: firmware=%u (%u.%u)",
    973 			firmware,
    974 			(firmware >>  8) & 0xFF,
    975 			(firmware      ) & 0xFF);
    976 	}
    977 
    978 	// Get the dive mode.
    979 	unsigned int divemode = layout->divemode < header ?
    980 		data[layout->divemode] : UNDEFINED;
    981 
    982 	// Get the CCR mode.
    983 	unsigned int ccr = hw_ostc_is_ccr (divemode, version);
    984 
    985 	unsigned int time = 0;
    986 	unsigned int nsamples = 0;
    987 	unsigned int tank = parser->initial != UNDEFINED ? parser->initial - 1 : 0;
    988 
    989 	unsigned int offset = header;
    990 	char buf[BUFLEN];
    991 	if (version == 0x23 || version == 0x24)
    992 		offset += 5 + 3 * nconfig;
    993 	while (offset + 3 <= size) {
    994 		dc_sample_value_t sample = {0};
    995 
    996 		nsamples++;
    997 
    998 		// Time (seconds).
    999 		time += samplerate;
   1000 		sample.time = time * 1000;
   1001 		if (callback) callback (DC_SAMPLE_TIME, &sample, userdata);
   1002 
   1003 		// Initial gas mix.
   1004 		if (time == samplerate && parser->initial != UNDEFINED) {
   1005 			unsigned int idx = hw_ostc_find_gasmix_fixed (parser, parser->initial);
   1006 			parser->gasmix[idx].active = 1;
   1007 			sample.gasmix = idx;
   1008 			if (callback) callback (DC_SAMPLE_GASMIX, &sample, userdata);
   1009 		}
   1010 
   1011 		// Initial setpoint (mbar).
   1012 		if (time == samplerate && parser->initial_setpoint != UNDEFINED) {
   1013 			sample.setpoint = parser->initial_setpoint / 100.0;
   1014 			if (callback) callback (DC_SAMPLE_SETPOINT, &sample, userdata);
   1015 		}
   1016 
   1017 		// Initial CNS (%).
   1018 		if (time == samplerate && parser->initial_cns != UNDEFINED) {
   1019 			sample.cns = parser->initial_cns / 100.0;
   1020 			if (callback) callback (DC_SAMPLE_CNS, &sample, userdata);
   1021 		}
   1022 
   1023 		// Depth (1/100 m).
   1024 		unsigned int depth = array_uint16_le (data + offset);
   1025 		sample.depth = depth / 100.0;
   1026 		if (callback) callback (DC_SAMPLE_DEPTH, &sample, userdata);
   1027 		offset += 2;
   1028 
   1029 		// Extended sample info.
   1030 		unsigned int length = data[offset] & 0x7F;
   1031 		offset += 1;
   1032 
   1033 		// Check for buffer overflows.
   1034 		if (offset + length > size) {
   1035 			ERROR (abstract->context, "Buffer overflow detected!");
   1036 			return DC_STATUS_DATAFORMAT;
   1037 		}
   1038 
   1039 		// Get the event byte(s).
   1040 		unsigned int nbits = 0;
   1041 		unsigned int events = 0;
   1042 		while (data[offset - 1] & 0x80) {
   1043 			if (nbits && version != 0x23 && version != 0x24)
   1044 				break;
   1045 			if (length < 1) {
   1046 				ERROR (abstract->context, "Buffer overflow detected!");
   1047 				return DC_STATUS_DATAFORMAT;
   1048 			}
   1049 			events |= data[offset] << nbits;
   1050 			nbits += 8;
   1051 			offset++;
   1052 			length--;
   1053 		}
   1054 
   1055 		// Alarms
   1056 		sample.event.type = 0;
   1057 		sample.event.time = 0;
   1058 		sample.event.flags = 0;
   1059 		sample.event.value = 0;
   1060 		switch (events & 0x0F) {
   1061 		case 0: // No Alarm
   1062 			break;
   1063 		case 1: // Slow
   1064 			sample.event.type = SAMPLE_EVENT_ASCENT;
   1065 			break;
   1066 		case 2: // Deco Stop missed
   1067 			sample.event.type = SAMPLE_EVENT_CEILING;
   1068 			break;
   1069 		case 3: // Deep Stop missed
   1070 			sample.event.type = SAMPLE_EVENT_CEILING;
   1071 			break;
   1072 		case 4: // ppO2 Low Warning
   1073 			sample.event.type = SAMPLE_EVENT_PO2;
   1074 			break;
   1075 		case 5: // ppO2 High Warning
   1076 			sample.event.type = SAMPLE_EVENT_PO2;
   1077 			break;
   1078 		case 6: // Manual Marker
   1079 			sample.event.type = SAMPLE_EVENT_BOOKMARK;
   1080 			break;
   1081 		case 7: // Low Battery
   1082 			break;
   1083 		}
   1084 		if (sample.event.type && callback)
   1085 			callback (DC_SAMPLE_EVENT, &sample, userdata);
   1086 
   1087 		// Manual Gas Set & Change
   1088 		if (events & 0x10) {
   1089 			if (length < 2) {
   1090 				ERROR (abstract->context, "Buffer overflow detected!");
   1091 				return DC_STATUS_DATAFORMAT;
   1092 			}
   1093 			unsigned int o2 = data[offset];
   1094 			unsigned int diluent;
   1095 			if (ISHWOS4(parser->model)) {
   1096 				// all manually added gas mixes on OSTC4 are OC gases
   1097 				diluent = 0;
   1098 			} else {
   1099 				diluent = ccr;
   1100 			}
   1101 			unsigned int he = data[offset + 1];
   1102 			unsigned int idx = hw_ostc_find_gasmix_manual (parser, o2, he, diluent);
   1103 			if (idx >= parser->ngasmixes) {
   1104 				if (idx >= NGASMIXES) {
   1105 					ERROR (abstract->context, "Maximum number of gas mixes reached.");
   1106 					return DC_STATUS_NOMEMORY;
   1107 				}
   1108 				parser->gasmix[idx].id = 0;
   1109 				parser->gasmix[idx].oxygen = o2;
   1110 				parser->gasmix[idx].helium = he;
   1111 				parser->gasmix[idx].type = 0;
   1112 				parser->gasmix[idx].enabled = 1;
   1113 				parser->gasmix[idx].active = 1;
   1114 				parser->gasmix[idx].diluent = diluent;
   1115 				parser->ngasmixes = idx + 1;
   1116 			}
   1117 
   1118 			sample.gasmix = idx;
   1119 			if (callback) callback (DC_SAMPLE_GASMIX, &sample, userdata);
   1120 
   1121 			offset += 2;
   1122 			length -= 2;
   1123 		}
   1124 
   1125 		// Gas Change
   1126 		if (events & 0x20) {
   1127 			if (length < 1) {
   1128 				ERROR (abstract->context, "Buffer overflow detected!");
   1129 				return DC_STATUS_DATAFORMAT;
   1130 			}
   1131 			unsigned int id = data[offset];
   1132 			if (id > parser->nfixed && id <= parser->nfixed + OSTC4_CC_DILUENT_GAS_OFFSET) {
   1133 				// OSTC4 reports gas changes to another diluent with an offset
   1134 				id -= OSTC4_CC_DILUENT_GAS_OFFSET;
   1135 			}
   1136 			if (id < 1 || id > parser->nfixed) {
   1137 				ERROR(abstract->context, "Invalid gas mix (%u).", id);
   1138 				return DC_STATUS_DATAFORMAT;
   1139 			}
   1140 			unsigned int idx = hw_ostc_find_gasmix_fixed (parser, id);
   1141 			parser->gasmix[idx].active = 1;
   1142 			sample.gasmix = idx;
   1143 			if (callback) callback (DC_SAMPLE_GASMIX, &sample, userdata);
   1144 			tank = id - 1;
   1145 
   1146 			offset++;
   1147 			length--;
   1148 		}
   1149 
   1150 		if (version == 0x23 || version == 0x24) {
   1151 			// SetPoint Change
   1152 			if (events & 0x40) {
   1153 				if (length < 1) {
   1154 					ERROR (abstract->context, "Buffer overflow detected!");
   1155 					return DC_STATUS_DATAFORMAT;
   1156 				}
   1157 				sample.setpoint = data[offset] / 100.0;
   1158 				if (callback) callback (DC_SAMPLE_SETPOINT, &sample, userdata);
   1159 				offset++;
   1160 				length--;
   1161 			}
   1162 
   1163 			// Bailout Event
   1164 			if (events & 0x0100) {
   1165 				if (length < 2) {
   1166 					ERROR (abstract->context, "Buffer overflow detected!");
   1167 					return DC_STATUS_DATAFORMAT;
   1168 				}
   1169 
   1170 				unsigned int o2 = data[offset];
   1171 				unsigned int he = data[offset + 1];
   1172 				unsigned int idx = hw_ostc_find_gasmix_manual (parser, o2, he, 0);
   1173 				if (idx >= parser->ngasmixes) {
   1174 					if (idx >= NGASMIXES) {
   1175 						ERROR (abstract->context, "Maximum number of gas mixes reached.");
   1176 						return DC_STATUS_NOMEMORY;
   1177 					}
   1178 					parser->gasmix[idx].id = 0;
   1179 					parser->gasmix[idx].oxygen = o2;
   1180 					parser->gasmix[idx].helium = he;
   1181 					parser->gasmix[idx].type = 0;
   1182 					parser->gasmix[idx].enabled = 1;
   1183 					parser->gasmix[idx].active = 1;
   1184 					parser->gasmix[idx].diluent = 0;
   1185 					parser->ngasmixes = idx + 1;
   1186 				}
   1187 
   1188 				sample.gasmix = idx;
   1189 				if (callback) callback (DC_SAMPLE_GASMIX, &sample, userdata);
   1190 
   1191 				offset += 2;
   1192 				length -= 2;
   1193 			}
   1194 
   1195 			// Compass heading update
   1196 			if (events & 0x0200) {
   1197 				if (length < 2) {
   1198 					ERROR (abstract->context, "Buffer underflow detected!");
   1199 					return DC_STATUS_DATAFORMAT;
   1200 				}
   1201 
   1202 				if (callback) {
   1203 					unsigned int value = array_uint16_le(data + offset);
   1204 					dc_sample_value_t sample = {
   1205 						.event.type = SAMPLE_EVENT_STRING,
   1206 						.event.flags = SAMPLE_FLAGS_SEVERITY_INFO,
   1207 					};
   1208 
   1209 					unsigned int heading = value & 0x1FF;
   1210 					if (value & OSTC4_COMPASS_HEADING_CLEARED_FLAG) {
   1211 						snprintf(buf, BUFLEN, "Cleared compass heading");
   1212 					} else {
   1213 						sample.event.value = heading;
   1214 
   1215 						if (value & OSTC4_COMPASS_HEADING_SET_FLAG) {
   1216 							sample.event.type = SAMPLE_EVENT_HEADING;
   1217 							snprintf(buf, BUFLEN, "Set compass heading [degrees]%s", sample.event.value ? "" : ": 0");
   1218 						} else {
   1219 							snprintf(buf, BUFLEN, "Logged compass heading [degrees]%s", sample.event.value ? "" : ": 0");
   1220 						}
   1221 
   1222 					}
   1223 
   1224 					sample.event.name = buf;
   1225 
   1226 					callback(DC_SAMPLE_EVENT, &sample, userdata);
   1227 				}
   1228 
   1229 				offset += 2;
   1230 				length -= 2;
   1231 			}
   1232 
   1233 			// GNSS position
   1234 			if (events & 0x0400) {
   1235 				if (length < 8) {
   1236 					ERROR (abstract->context, "Buffer overflow detected!");
   1237 					return DC_STATUS_DATAFORMAT;
   1238 				}
   1239 
   1240 				offset += 8;
   1241 				length -= 8;
   1242 			}
   1243 
   1244 			// Scrubber state update
   1245 			if (events & 0x0800) {
   1246 				if (length < 2) {
   1247 					ERROR (abstract->context, "Buffer underflow detected!");
   1248 					return DC_STATUS_DATAFORMAT;
   1249 				}
   1250 
   1251 				unsigned int scrubberState = array_uint16_le(data + offset);
   1252 				int scrubberTimeMinutes = scrubberState & 0x0FFF; // Extract the 12-bit value
   1253 				if (scrubberState & 0x0800) { // Check if the sign bit is set
   1254 					scrubberTimeMinutes -= 0x1000; // Perform sign extension
   1255 				}
   1256 				if (parser->first_scrubber_time_minutes == INT_MAX) {
   1257 					parser->first_scrubber_time_minutes = scrubberTimeMinutes;
   1258 				}
   1259 				parser->last_scrubber_time_minutes = scrubberTimeMinutes;
   1260 
   1261 				if (callback) {
   1262 					dc_sample_value_t sample = {
   1263 						.event.type = SAMPLE_EVENT_STRING,
   1264 						.event.flags = SAMPLE_FLAGS_SEVERITY_STATE,
   1265 						.event.value = scrubberTimeMinutes,
   1266 					};
   1267 
   1268 					if (scrubberState & OSTC4_SCRUBBER_STATE_ERROR_FLAG) {
   1269 						if (!parser->scrubber_error_reported) {
   1270 							sample.event.flags = SAMPLE_FLAGS_SEVERITY_ALARM;
   1271 							parser->scrubber_error_reported = true;
   1272 						}
   1273 						snprintf(buf, BUFLEN, "Scrubber exhausted, time remaining [minutes]%s", sample.event.value ? "" : ": 0");
   1274 					} else if (scrubberState & OSTC4_SCRUBBER_STATE_WARNING_FLAG) {
   1275 						if (!parser->scrubber_warning_reported) {
   1276 							sample.event.flags = SAMPLE_FLAGS_SEVERITY_WARN;
   1277 							parser->scrubber_warning_reported = true;
   1278 						}
   1279 						snprintf(buf, BUFLEN, "Scrubber warning, time remaining [minutes]%s", sample.event.value ? "" : ": 0");
   1280 					} else {
   1281 						snprintf(buf, BUFLEN, "Scrubber time remaining [minutes]%s", sample.event.value ? "" : ": 0");
   1282 					}
   1283 
   1284 					sample.event.name = buf;
   1285 
   1286 					callback(DC_SAMPLE_EVENT, &sample, userdata);
   1287 				}
   1288 
   1289 				offset += 2;
   1290 				length -= 2;
   1291 			}
   1292 
   1293 		}
   1294 
   1295 		// Extended sample info.
   1296 		for (unsigned int i = 0; i < nconfig; ++i) {
   1297 			if (info[i].divisor && (nsamples % info[i].divisor) == 0) {
   1298 				if (length < info[i].size) {
   1299 					// Due to a bug in the hwOS Tech firmware v3.03 to v3.08, and
   1300 					// the hwOS Sport firmware v10.57 to v10.63, the ppO2 divisor
   1301 					// is sometimes not correctly reset to zero when no ppO2
   1302 					// samples are being recorded.
   1303 					if (info[i].type == PPO2 && parser->hwos && !ISHWOS4(parser->model) &&
   1304 						((firmware >= OSTC3FW(3,3) && firmware <= OSTC3FW(3,8)) ||
   1305 						(firmware >= OSTC3FW(10,57) && firmware <= OSTC3FW(10,63)))) {
   1306 						WARNING (abstract->context, "Reset invalid ppO2 divisor to zero.");
   1307 						info[i].divisor = 0;
   1308 						continue;
   1309 					}
   1310 
   1311 					ERROR(abstract->context, "Buffer overflow detected!");
   1312 					return DC_STATUS_DATAFORMAT;
   1313 				}
   1314 
   1315 				unsigned int ppo2[3] = {0};
   1316 				unsigned int count = 0;
   1317 				unsigned int value = 0;
   1318 				switch (info[i].type) {
   1319 				case TEMPERATURE:
   1320 					value = array_uint16_le (data + offset);
   1321 					sample.temperature = value / 10.0;
   1322 					if (callback) callback (DC_SAMPLE_TEMPERATURE, &sample, userdata);
   1323 					break;
   1324 				case DECO:
   1325 					// Due to a firmware bug, the deco/ndl info is incorrect for
   1326 					// all OSTC4 dives with a firmware older than version 1.0.8.
   1327 					if (ISHWOS4(parser->model) && firmware < OSTC4FW(1,0,8,0))
   1328 						break;
   1329 					if (data[offset]) {
   1330 						sample.deco.type = DC_DECO_DECOSTOP;
   1331 						sample.deco.depth = data[offset];
   1332 					} else {
   1333 						sample.deco.type = DC_DECO_NDL;
   1334 						sample.deco.depth = 0.0;
   1335 					}
   1336 					sample.deco.time = data[offset + 1] * 60;
   1337 					sample.deco.tts = 0;
   1338 					if (callback) callback (DC_SAMPLE_DECO, &sample, userdata);
   1339 					break;
   1340 				case PPO2:
   1341 					for (unsigned int j = 0; j < 3; ++j) {
   1342 						if (info[i].size == 3) {
   1343 							ppo2[j] = data[offset + j];
   1344 						} else {
   1345 							ppo2[j] = data[offset + j * 3];
   1346 						}
   1347 						if (ppo2[j] != 0)
   1348 							count++;
   1349 					}
   1350 					if (count) {
   1351 						for (unsigned int j = 0; j < 3; ++j) {
   1352 							sample.ppo2.sensor = j;
   1353 							sample.ppo2.value = ppo2[j] / 100.0;
   1354 							if (callback) callback (DC_SAMPLE_PPO2, &sample, userdata);
   1355 						}
   1356 					}
   1357 					break;
   1358 				case CNS:
   1359 					if (info[i].size == 2)
   1360 						sample.cns = array_uint16_le (data + offset) / 100.0;
   1361 					else
   1362 						sample.cns = data[offset] / 100.0;
   1363 					if (callback) callback (DC_SAMPLE_CNS, &sample, userdata);
   1364 					break;
   1365 				case TANK:
   1366 					value = array_uint16_le (data + offset);
   1367 					if (value != 0) {
   1368 						sample.pressure.tank = tank;
   1369 						sample.pressure.value = value;
   1370 						// The hwOS Sport firmware used a resolution of
   1371 						// 0.1 bar between versions 10.40 and 10.50.
   1372 						if (parser->hwos && !ISHWOS4(parser->model) &&
   1373 							(firmware >= OSTC3FW(10,40) && firmware <= OSTC3FW(10,50))) {
   1374 							sample.pressure.value /= 10.0;
   1375 						}
   1376 						if (callback) callback (DC_SAMPLE_PRESSURE, &sample, userdata);
   1377 					}
   1378 					break;
   1379 				default: // Not yet used.
   1380 					break;
   1381 				}
   1382 
   1383 				offset += info[i].size;
   1384 				length -= info[i].size;
   1385 			}
   1386 		}
   1387 
   1388 		if (version != 0x23 && version != 0x24) {
   1389 			// SetPoint Change
   1390 			if (events & 0x40) {
   1391 				if (length < 1) {
   1392 					ERROR (abstract->context, "Buffer overflow detected!");
   1393 					return DC_STATUS_DATAFORMAT;
   1394 				}
   1395 				sample.setpoint = data[offset] / 100.0;
   1396 				if (callback) callback (DC_SAMPLE_SETPOINT, &sample, userdata);
   1397 				offset++;
   1398 				length--;
   1399 			}
   1400 
   1401 			// Bailout Event
   1402 			if (events & 0x80) {
   1403 				if (length < 2) {
   1404 					ERROR (abstract->context, "Buffer overflow detected!");
   1405 					return DC_STATUS_DATAFORMAT;
   1406 				}
   1407 
   1408 				unsigned int o2 = data[offset];
   1409 				unsigned int he = data[offset + 1];
   1410 				unsigned int idx = hw_ostc_find_gasmix_manual (parser, o2, he, 0);
   1411 				if (idx >= parser->ngasmixes) {
   1412 					if (idx >= NGASMIXES) {
   1413 						ERROR (abstract->context, "Maximum number of gas mixes reached.");
   1414 						return DC_STATUS_NOMEMORY;
   1415 					}
   1416 					parser->gasmix[idx].id = 0;
   1417 					parser->gasmix[idx].oxygen = o2;
   1418 					parser->gasmix[idx].helium = he;
   1419 					parser->gasmix[idx].type = 0;
   1420 					parser->gasmix[idx].enabled = 1;
   1421 					parser->gasmix[idx].active = 1;
   1422 					parser->gasmix[idx].diluent = 0;
   1423 					parser->ngasmixes = idx + 1;
   1424 				}
   1425 
   1426 				sample.gasmix = idx;
   1427 				if (callback) callback (DC_SAMPLE_GASMIX, &sample, userdata);
   1428 
   1429 				offset += 2;
   1430 				length -= 2;
   1431 			}
   1432 		}
   1433 
   1434 		// Skip remaining sample bytes (if any).
   1435 		if (length) {
   1436 			WARNING (abstract->context, "Remaining %u bytes skipped.", length);
   1437 		}
   1438 		offset += length;
   1439 	}
   1440 
   1441 	if (offset + 2 > size || data[offset] != 0xFD || data[offset + 1] != 0xFD) {
   1442 		ERROR (abstract->context, "Invalid end marker found!");
   1443 		return DC_STATUS_DATAFORMAT;
   1444 	}
   1445 
   1446 	// Remove the disabled gas mixes from the fixed gas mixes.
   1447 	unsigned int ndisabled = 0, nenabled = 0;
   1448 	unsigned int count = parser->nfixed - parser->ndisabled;
   1449 	for (unsigned int i = 0; i < count; ++i) {
   1450 		if (parser->gasmix[i].enabled || parser->gasmix[i].active) {
   1451 			// Move the fixed gas mix.
   1452 			parser->gasmix[nenabled] = parser->gasmix[i];
   1453 			nenabled++;
   1454 		} else {
   1455 			ndisabled++;
   1456 		}
   1457 	}
   1458 
   1459 	// Move all the manual gas mixes.
   1460 	memmove (parser->gasmix + nenabled, parser->gasmix + count,
   1461 		(parser->ngasmixes - count) * sizeof (hw_ostc_gasmix_t));
   1462 	memset (parser->gasmix + parser->ngasmixes - ndisabled, 0,
   1463 		ndisabled * sizeof (hw_ostc_gasmix_t));
   1464 
   1465 	// Adjust the counts.
   1466 	parser->ngasmixes -= ndisabled;
   1467 	parser->ndisabled += ndisabled;
   1468 
   1469 	parser->cached = PROFILE;
   1470 
   1471 	return DC_STATUS_SUCCESS;
   1472 }
   1473 
   1474 static dc_status_t
   1475 hw_ostc_parser_samples_foreach (dc_parser_t *abstract, dc_sample_callback_t callback, void *userdata)
   1476 {
   1477 	hw_ostc_parser_t *parser = (hw_ostc_parser_t *) abstract;
   1478 
   1479 	// Cache the header data.
   1480 	dc_status_t rc = hw_ostc_parser_cache (parser);
   1481 	if (rc != DC_STATUS_SUCCESS)
   1482 		return rc;
   1483 
   1484 	// Cache the profile data.
   1485 	if (parser->cached < PROFILE) {
   1486 		rc = hw_ostc_parser_internal_foreach (parser, NULL, NULL);
   1487 		if (rc != DC_STATUS_SUCCESS)
   1488 			return rc;
   1489 	}
   1490 
   1491 	return hw_ostc_parser_internal_foreach (parser, callback, userdata);
   1492 }