From 556d27f1d74255e3a4fa889f1e6161c42c36065a Mon Sep 17 00:00:00 2001 From: friendsa <16186646+shaonianche@users.noreply.github.com> Date: Fri, 20 Nov 2026 04:05:44 +0000 Subject: [PATCH] fix: decode FIT invalid sentinels as None Map each base type's invalid value to None on read, for scalars and array elements, instead of returning the sentinel as a measurement (255 bpm, 65.535 m/s, 4294967.295 s, ...). Raw encoded values stay on the field so PRESERVE and CANONICAL re-encoding remain byte-identical. - BaseType.is_invalid_value() defines the per-type sentinel; byte fields stay opaque except when every byte is invalid (FIT protocol Table 7). - Field.has_value() distinguishes "on the wire" from "has a value"; is_valid() stays size-based so definitions and encode are unchanged. - FILE_TYPE required-field checks use has_value(), so a required field written as its sentinel is reported missing. - Component expansion skips all-invalid packed sources and may fill a present-but-invalid destination, matching Garmin's SDKs. - All-invalid numeric arrays stay lists of None so positions survive. Behaviour change: callers doing arithmetic or comparisons on decoded values must check for None first (or use Field.has_value()). Amp-Thread-ID: https://ampcode.com/threads/T-01a1f68a-2665-7000-a200-a75073933440 --- docs/CAPABILITY_BOUNDARY.md | 11 ++ fit_tool/base_type.py | 13 +++ fit_tool/components.py | 7 +- fit_tool/examples/modify_activity_example.py | 2 +- fit_tool/field.py | 55 +++++++--- fit_tool/tests/test_base_type.py | 33 ++++++ fit_tool/tests/test_components.py | 19 +++- fit_tool/tests/test_field.py | 103 +++++++++++++++++++ fit_tool/tests/test_protocol_gap_fixtures.py | 6 +- fit_tool/tests/test_sdk_files.py | 102 ++++++++++++++++++ fit_tool/tests/test_validation_file_types.py | 40 +++++++ fit_tool/validation/file_types/common.py | 16 ++- news/+invalid-values.break | 8 ++ 13 files changed, 393 insertions(+), 22 deletions(-) create mode 100644 news/+invalid-values.break diff --git a/docs/CAPABILITY_BOUNDARY.md b/docs/CAPABILITY_BOUNDARY.md index 6d388ef..474295e 100644 --- a/docs/CAPABILITY_BOUNDARY.md +++ b/docs/CAPABILITY_BOUNDARY.md @@ -80,6 +80,17 @@ validate_fit_file(fit_file, levels={ConformanceLevel.PRESERVATION}) with `raise_on_error=True`. Prefer `validate_fit_file` for reports and level selection on the read path. +## Invalid values + +FIT invalid sentinels decode as `None` (no value), both for scalars and for +array elements: `record.cadence` written as `0xFF` reads as `None`, and an +unset `time_in_*_zone` array contains `None` entries. The raw encoded value +stays on the field, so PRESERVE and CANONICAL re-encoding reproduce the same +bytes. `byte` payloads stay opaque (`0xFF` inside a developer +`application_id` is data), except that a wholly invalid byte field reads as +`None`. FILE_TYPE required-field checks treat an invalid required field as +missing. + --- ## Encode policies diff --git a/fit_tool/base_type.py b/fit_tool/base_type.py index d01fcf0..18cc22e 100644 --- a/fit_tool/base_type.py +++ b/fit_tool/base_type.py @@ -58,6 +58,19 @@ def is_valid(self, value) -> bool: def invalid_raw_value(self) -> int: return _BASE_TYPE_INFO[self][2] + def is_invalid_value(self, value) -> bool: + """Return True when *value* is the FIT invalid sentinel for this type. + + ``byte`` is opaque: the Profile uses it for packed bit fields and + developer application ids where ``0xFF`` is legal payload. Field-level + code decides when an entire byte field is unset. + """ + if value is None: + return True + if self.is_string() or self is BaseType.BYTE: + return False + return value == self.invalid_raw_value() + @property def max(self) -> int | None: return _BASE_TYPE_INFO[self][4] diff --git a/fit_tool/components.py b/fit_tool/components.py index b28f370..1b90196 100644 --- a/fit_tool/components.py +++ b/fit_tool/components.py @@ -81,7 +81,7 @@ def registry_coverage() -> dict[str, object]: def _field_raw_as_int(field: Field) -> int | None: """Combine numeric encoded values into a little-endian bit bucket.""" - if not field.is_valid() or not field.encoded_values: + if not field.has_value() or not field.encoded_values: return None if field.base_type.is_string() or field.base_type.is_float(): return None @@ -103,7 +103,10 @@ def _destination_has_wire_value(field: Field) -> bool: return False if not field.encoded_values: return False - return any(value is not None for value in field.encoded_values) + return any( + value is not None and not field.base_type.is_invalid_value(value) + for value in field.encoded_values + ) def _ensure_destination_slot(destination: Field, index: int) -> None: diff --git a/fit_tool/examples/modify_activity_example.py b/fit_tool/examples/modify_activity_example.py index a0a9e9b..0465a8a 100644 --- a/fit_tool/examples/modify_activity_example.py +++ b/fit_tool/examples/modify_activity_example.py @@ -28,7 +28,7 @@ def main(): if isinstance(message, RecordMessage): # remove records where the power is too high power_field = message.get_field(RecordPowerField.ID) - if power_field and power_field.is_valid(): + if power_field and power_field.has_value(): power = power_field.get_value() if power > 800: include_record = False diff --git a/fit_tool/field.py b/fit_tool/field.py index 2b65dd3..52686db 100644 --- a/fit_tool/field.py +++ b/fit_tool/field.py @@ -139,15 +139,41 @@ def is_valid(self) -> bool: def is_not_valid(self) -> bool: return not self.is_valid() + def has_value(self) -> bool: + """True when the field is on the wire and carries a real value. + + ``is_valid()`` stays size-based so encode and definition handling are + unchanged; a field whose payload is entirely the FIT invalid sentinel + is present on the wire but has no value. + """ + return self.is_valid() and not self._has_no_value() + + def _has_no_value(self) -> bool: + if not self.encoded_values: + return True + if self.base_type.is_string(): + return False + if self.base_type is BaseType.BYTE: + invalid = self.base_type.invalid_raw_value() + return all(value is None or value == invalid for value in self.encoded_values) + return all(self.base_type.is_invalid_value(value) for value in self.encoded_values) + def get_value(self, index: int = 0, sub_field: SubField = None): if index < 0 or index >= len(self.encoded_values): return None + # Byte fields are opaque, so only a wholly invalid payload means "no + # value"; other base types are handled per element in decode_value. + if self.base_type is BaseType.BYTE and self._has_no_value(): + return None encoded_value = self.encoded_values[index] return self.decode_value(encoded_value, sub_field) - # Return values as a list + # Return values as a list. Invalid array elements decode to None; a byte + # field whose payload is entirely the invalid sentinel has no value at all. def get_values(self): + if self.base_type is BaseType.BYTE and self._has_no_value(): + return None return [self.decode_value(encoded_value) for encoded_value in self.encoded_values] def set_values(self, values): @@ -158,6 +184,11 @@ def decode_value(self, encoded_value, sub_field: SubField = None): if encoded_value is None or isinstance(encoded_value, str): return encoded_value + # FIT sentinels mean "no value", not a real reading. Raw encoded values + # stay in ``encoded_values`` so re-encoding reproduces the same bytes. + if self.base_type.is_invalid_value(encoded_value): + return None + scale = self.get_scale(sub_field=sub_field) offset = self.get_offset(sub_field=sub_field) @@ -431,23 +462,23 @@ def get_valid_sub_field(self, fields: list) -> SubField | None: return self.resolve_sub_field(fields).selected def to_row(self, sub_field: SubField = None) -> list: - row = [] - values = [] + name = sub_field.name if sub_field else self.name + units = sub_field.units if sub_field else self.units - for i in range(len(self.encoded_values)): - values.append(self.get_value(index=i, sub_field=sub_field)) + if not self.has_value(): + return [name, None, units] - row.append(sub_field.name if sub_field else self.name) + values = [ + self.decode_value(value, sub_field) + for value in self.encoded_values + ] if len(values) == 1: - row.append(values[0]) + value = values[0] else: - values_str = '[' + ','.join([str(v) for v in values]) + ']' - row.append(values_str) - - row.append(sub_field.units if sub_field else self.units) + value = '[' + ','.join('' if item is None else str(item) for item in values) + ']' - return row + return [name, value, units] class UnknownField(Field): diff --git a/fit_tool/tests/test_base_type.py b/fit_tool/tests/test_base_type.py index cefc9d1..e0f2e81 100644 --- a/fit_tool/tests/test_base_type.py +++ b/fit_tool/tests/test_base_type.py @@ -267,3 +267,36 @@ def test_get_name_by_value(self): assert ft.get_name_by_value(0) == 'running' assert ft.get_name_by_value(1) == 'cycling' assert ft.get_name_by_value(99) is None + + +class TestBaseTypeIsInvalidValue: + @pytest.mark.parametrize("base_type, sentinel", [ + (BaseType.ENUM, 0xff), + (BaseType.SINT8, 0x7f), + (BaseType.UINT8, 0xff), + (BaseType.SINT16, 0x7fff), + (BaseType.UINT16, 0xffff), + (BaseType.SINT32, 0x7fffffff), + (BaseType.UINT32, 0xffffffff), + (BaseType.UINT8Z, 0), + (BaseType.UINT16Z, 0), + (BaseType.UINT32Z, 0), + (BaseType.SINT64, 0x7fffffffffffffff), + (BaseType.UINT64, 0xffffffffffffffff), + (BaseType.UINT64Z, 0), + ]) + def test_sentinel_is_invalid(self, base_type, sentinel): + assert base_type.is_invalid_value(sentinel) is True + neighbour = sentinel - 1 if sentinel else 1 + assert base_type.is_invalid_value(neighbour) is False + + def test_none_is_invalid(self): + assert BaseType.UINT8.is_invalid_value(None) is True + + def test_byte_is_opaque(self): + assert BaseType.BYTE.is_invalid_value(0xff) is False + assert BaseType.BYTE.is_invalid_value(0) is False + + def test_string_has_no_integer_sentinel(self): + assert BaseType.STRING.is_invalid_value('') is False + assert BaseType.STRING.is_invalid_value(0) is False diff --git a/fit_tool/tests/test_components.py b/fit_tool/tests/test_components.py index 93c2198..f045a92 100644 --- a/fit_tool/tests/test_components.py +++ b/fit_tool/tests/test_components.py @@ -147,9 +147,9 @@ def test_16bit_power_rollover(self): source.size = 2 acc: dict[tuple[int, int], int] = {} - source.encoded_values = [65535] + source.encoded_values = [65534] expand_message_components(message, acc) - self.assertEqual(acc[(20, 29)], 65535) + self.assertEqual(acc[(20, 29)], 65534) source.encoded_values = [1] expand_message_components(message, acc) @@ -158,6 +158,21 @@ def test_16bit_power_rollover(self): self.assertEqual(acc[(20, 29)], 65537) self.assertEqual(power.get_value(), 65537) + def test_all_invalid_source_does_not_expand(self): + """0xFFFF is the uint16 sentinel, so a packed field with no value expands nothing.""" + message = RecordMessage() + source = message.get_field(28) + assert source is not None + source.size = 2 + acc: dict[tuple[int, int], int] = {} + + source.encoded_values = [65535] + expand_message_components(message, acc) + self.assertNotIn((20, 29), acc) + power = message.get_field(29) + assert power is not None + self.assertEqual(power.size, 0) + def test_8bit_cycles_accumulate_to_total_cycles(self): message = RecordMessage() source = message.get_field(18) # cycles diff --git a/fit_tool/tests/test_field.py b/fit_tool/tests/test_field.py index 36f3798..f43512c 100755 --- a/fit_tool/tests/test_field.py +++ b/fit_tool/tests/test_field.py @@ -1,5 +1,6 @@ # nosetests --nocapture tests/test_field.py +import struct import unittest from fit_tool.base_type import BaseType @@ -357,3 +358,105 @@ def test_to_row_multi_value(self): self.assertEqual(row[0], 'hrv') self.assertIn('10', str(row[1])) self.assertIn('20', str(row[1])) + + +class TestInvalidValues(unittest.TestCase): + SENTINELS = ( + (BaseType.ENUM, 0xff), + (BaseType.SINT8, 0x7f), + (BaseType.UINT8, 0xff), + (BaseType.SINT16, 0x7fff), + (BaseType.UINT16, 0xffff), + (BaseType.SINT32, 0x7fffffff), + (BaseType.UINT32, 0xffffffff), + (BaseType.UINT8Z, 0), + (BaseType.UINT16Z, 0), + (BaseType.UINT32Z, 0), + (BaseType.SINT64, 0x7fffffffffffffff), + (BaseType.UINT64, 0xffffffffffffffff), + (BaseType.UINT64Z, 0), + ) + + def test_scalar_sentinel_decodes_as_none_and_round_trips(self): + for base_type, sentinel in self.SENTINELS: + with self.subTest(base_type=base_type): + field = Field(name='x', base_type=base_type, size=base_type.size) + wire = field.encoded_value_to_bytes(sentinel) + field.read_all_from_bytes(wire) + + self.assertIsNone(field.get_value()) + self.assertFalse(field.has_value()) + self.assertTrue(field.is_valid()) + self.assertEqual(field.encoded_values, [sentinel]) + self.assertEqual(field.to_bytes(), wire) + + def test_scaled_sentinel_is_none_not_a_measurement(self): + field = Field(name='speed', base_type=BaseType.UINT16, size=2, scale=1000.0) + field.read_all_from_bytes(b'\xff\xff') + + self.assertIsNone(field.get_value()) + self.assertNotEqual(field.get_value(), 65.535) + self.assertEqual(field.to_bytes(), b'\xff\xff') + + def test_invalid_array_elements_decode_as_none(self): + field = Field(name='time_in_power_zone', base_type=BaseType.UINT32, size=12, scale=1000.0) + wire = struct.pack(' None: - """Report one finding listing every required field the message left unset.""" - missing = [name for name in field_names if getattr(message, name, None) is None] + """Report one finding listing every required field the message left unset. + + A field present on the wire but carrying only FIT invalid sentinels counts + as unset (:meth:`~fit_tool.field.Field.has_value`), so a required field + written as the protocol sentinel is reported instead of accepted. + """ + missing = [] + for name in field_names: + field = message.get_field_by_name(name) + if field is not None and not field.has_value(): + missing.append(name) + elif getattr(message, name, None) is None: + missing.append(name) + if missing: add_error( findings, diff --git a/news/+invalid-values.break b/news/+invalid-values.break new file mode 100644 index 0000000..3ac6280 --- /dev/null +++ b/news/+invalid-values.break @@ -0,0 +1,8 @@ +**Behaviour change:** FIT invalid sentinel values now decode as `None` instead +of numbers — scalars such as `record.cadence` (0xFF) and `record.speed` +(0xFFFF), and invalid elements inside arrays such as unset `time_in_*_zone` +values. Callers must check for `None` before arithmetic or comparisons; an +all-invalid numeric array is returned as a list of `None` so positions survive. +Raw wire values are retained, so re-encoding is byte-identical, and FILE_TYPE +required-field checks now report a required field written as its sentinel as +missing.