diff --git a/fit_tool/components.py b/fit_tool/components.py index 1b90196..08c6588 100644 --- a/fit_tool/components.py +++ b/fit_tool/components.py @@ -2,8 +2,9 @@ Decode-time expansion uses the generated Profile main-field registry (:mod:`fit_tool.profile.component_registry`) plus any -:class:`~fit_tool.field_component.FieldComponent` entries already attached to a -:class:`~fit_tool.field.Field` (for tests and future codegen). +:class:`~fit_tool.field_component.FieldComponent` entries attached to the packing +:class:`~fit_tool.field.Field` or its active subfield (generated subfields such as +``event.data`` gear-change / radar-threat sets, and synthetic test fields). Active-subfield components are selected via ``components_for_field`` when sibling fields are provided. Nested components (a destination that is itself a @@ -63,7 +64,7 @@ def registry_coverage() -> dict[str, object]: 'profile_main_field_sources': 37, 'registry_entries': 37, 'coverage_ratio': 1.0, - 'subfield_components': 'via active subfield when sibling_fields given', + 'subfield_components': 'generated Profile subfields + synthetic test subfields', } """ registry_entries = len(PROFILE_COMPONENTS) @@ -75,7 +76,7 @@ def registry_coverage() -> dict[str, object]: 'profile_main_field_sources': profile_sources, 'registry_entries': registry_entries, 'coverage_ratio': ratio, - 'subfield_components': 'via active subfield when sibling_fields given', + 'subfield_components': 'generated Profile subfields + synthetic test subfields', } diff --git a/fit_tool/gen/component_registry.py b/fit_tool/gen/component_registry.py index 59a05f1..ad3e065 100644 --- a/fit_tool/gen/component_registry.py +++ b/fit_tool/gen/component_registry.py @@ -1,7 +1,8 @@ """Extract main-field component definitions from Profile.xlsx for code generation. -Subfield-gated components (empty Field Def # with Ref Field Name) are intentionally -omitted — those ship with subfield resolution (Multica D / Stage 2). +Subfield-gated components (empty Field Def # with Ref Field Name) do not belong in +this registry, whose key is the packing field: they are attached to the generated +``SubField`` objects by :mod:`fit_tool.gen.profile` instead. """ from __future__ import annotations @@ -133,7 +134,8 @@ def load_main_field_components(xlsx_path: str | Path) -> list[SourceFieldCompone components_cell = row[5].value if _is_blank(components_cell): continue - # Subfield rows have no Field Def # — deferred to subfield resolution (D). + # Subfield rows have no Field Def # — their components are emitted on the + # generated SubField objects instead. if _is_blank(field_id) or _is_blank(field_name): continue @@ -196,7 +198,7 @@ def render_component_registry( '# Autogenerated. Do not modify.', '#', f'# Profile: {sdk_version}', - '# Main-field components only (subfield-gated components omitted — see Stage 2 D).', + '# Main-field components; subfield-gated sets live on generated SubField objects.', '"""Profile component registry for decode-time expansion.', '', 'Generated from the bundled Garmin Profile spreadsheet by ``gen-profile``.', diff --git a/fit_tool/gen/gen_profile.py b/fit_tool/gen/gen_profile.py index a2c3ca2..33024eb 100755 --- a/fit_tool/gen/gen_profile.py +++ b/fit_tool/gen/gen_profile.py @@ -241,6 +241,12 @@ def main(): for field in message.fields_by_name.values(): field.is_common_field = is_common_field(field) + message.has_subfield_components = any( + sub_field.components + for field in message.fields_by_name.values() + for sub_field in field.sub_fields + ) + message.field_class_name_by_name = {k: field_name_to_class_name(message, message.fields_by_name[k], k) for k in message.fields_by_name.keys()} message.field_property_name_by_name = {k: field_name_to_property_name(message, k) for k in diff --git a/fit_tool/gen/profile.py b/fit_tool/gen/profile.py index f8f19a3..5c7e21d 100755 --- a/fit_tool/gen/profile.py +++ b/fit_tool/gen/profile.py @@ -4,6 +4,7 @@ from fit_tool import SDK_VERSION from fit_tool.base_type import BaseType, FieldType from fit_tool.field import ArrayType, Field +from fit_tool.field_component import FieldComponent from fit_tool.utils.logging import logger @@ -60,6 +61,54 @@ def parse_array_field(value): raise ValueError(f'Invalid array field value: {value!r}') +def split_profile_list(value) -> list[str]: + """Split a comma-separated Profile cell into stripped non-empty entries.""" + if value is None: + return [] + if isinstance(value, (int, float)): + return [str(value)] + return [part.strip() for part in str(value).split(',') if part.strip() != ''] + + +def parse_subfield_components(message_name: str, subfield_name: str, row, + field_ids_by_name: dict[tuple[str, str], int]) -> list[FieldComponent]: + """Build packed-component specs for a subfield row's ``Components`` cell. + + Subfield rows declare components by destination field name, with per-component + scale, offset, bit width and accumulate flag in the same row. Destination ids + come from ``field_ids_by_name`` because a destination field can be declared + after the subfield row that packs it (``event.data`` → ``front_gear``). + """ + component_names = split_profile_list(row[5].value) + if not component_names: + return [] + + scales = split_profile_list(row[6].value) + offsets = split_profile_list(row[7].value) + bits_list = split_profile_list(row[9].value) + accumulate_list = split_profile_list(row[10].value) + + def cell_value(values: list[str], index: int): + return values[index] if index < len(values) else None + + components = [] + for index, dest_name in enumerate(component_names): + dest_id = field_ids_by_name.get((message_name, dest_name)) + if dest_id is None: + raise ValueError( + f'Component destination {dest_name!r} not found on message ' + f'{message_name!r} (subfield {subfield_name!r})' + ) + components.append(FieldComponent( + field_id=dest_id, + accumulate=bool(parse_profile_number(cell_value(accumulate_list, index), 0)), + bits=int(parse_profile_number(cell_value(bits_list, index), 0)), + scale=parse_profile_number(cell_value(scales, index), 1), + offset=parse_profile_number(cell_value(offsets, index), 0), + )) + return components + + def parse_profile_number(value, default): """Parse numeric cells stored as either spreadsheet numbers or strings.""" if value is None or (isinstance(value, str) and value.strip() == ''): @@ -199,6 +248,25 @@ def normalize_blank(value): # Parse the Messages worksheet # ws = wb['Messages'] + + # Field names → ids per message. Subfield component destinations are + # listed by name, and a destination can appear after its packing row, so + # resolve ids up front instead of relying on parse order. + field_ids_by_name: dict[tuple[str, str], int] = {} + field_message_name = None + for index, row in enumerate(ws.rows): + if index == 0: + continue + message_name = row[0].value + if message_name: + field_message_name = str(message_name) + continue + field_id = normalize_blank(row[1].value) + field_name = normalize_blank(row[2].value) + if field_id is None or field_name is None: + continue + field_ids_by_name[(field_message_name, str(field_name))] = int(field_id) + current_message = None for index, row in enumerate(ws.rows): if index == 0: @@ -327,6 +395,12 @@ def normalize_blank(value): current_message.add_field(field) else: subfield = field_or_subfield + subfield.components = parse_subfield_components( + current_message.name, + subfield.name, + row, + field_ids_by_name, + ) field.sub_fields.append(subfield) cls._resolve_subfield_references(profile) diff --git a/fit_tool/gen/templates/template_message.jinja b/fit_tool/gen/templates/template_message.jinja index bfb5326..c2b076a 100644 --- a/fit_tool/gen/templates/template_message.jinja +++ b/fit_tool/gen/templates/template_message.jinja @@ -9,7 +9,8 @@ from fit_tool.definition_message import DefinitionMessage from fit_tool.developer_field import DeveloperField from fit_tool.endian import Endian from fit_tool.field import Field -from fit_tool.sub_field import SubField +{% if message.has_subfield_components %}from fit_tool.field_component import FieldComponent +{% endif %}from fit_tool.sub_field import SubField from fit_tool.profile.messages.common_fields import MessageIndexField, TimestampField from fit_tool.profile.profile_type import * from typing import List as list @@ -232,7 +233,18 @@ class {{message.field_class_name_by_name[field_name]}}(Field): {{message.field_class_name_by_name[reference_name]}}.ID: {{sub_field.ref_field_map[reference_name]}} {%- if not loop.last %}, {% endif %} {%- endfor %} - }){%- if not loop.last %}, {% endif %} + }{%- if sub_field.components %}, + components = [ + {%- for component in sub_field.components %} + FieldComponent( + field_id={{ component.field_id }}, + accumulate={{ component.accumulate }}, + bits={{ component.bits }}, + scale={{ component.scale }}, + offset={{ component.offset }}) + {%- if not loop.last %}, {% endif %} + {%- endfor %} + ]{%- endif %}){%- if not loop.last %}, {% endif %} {%- endfor %} ] ) diff --git a/fit_tool/profile/component_registry.py b/fit_tool/profile/component_registry.py index 8589f00..50342a7 100644 --- a/fit_tool/profile/component_registry.py +++ b/fit_tool/profile/component_registry.py @@ -1,7 +1,7 @@ # Autogenerated. Do not modify. # # Profile: 21.222.0 -# Main-field components only (subfield-gated components omitted — see Stage 2 D). +# Main-field components; subfield-gated sets live on generated SubField objects. """Profile component registry for decode-time expansion. Generated from the bundled Garmin Profile spreadsheet by ``gen-profile``. diff --git a/fit_tool/profile/messages/event_message.py b/fit_tool/profile/messages/event_message.py index d3ba181..cf1a55a 100644 --- a/fit_tool/profile/messages/event_message.py +++ b/fit_tool/profile/messages/event_message.py @@ -9,6 +9,7 @@ from fit_tool.developer_field import DeveloperField from fit_tool.endian import Endian from fit_tool.field import Field +from fit_tool.field_component import FieldComponent from fit_tool.sub_field import SubField from fit_tool.profile.messages.common_fields import MessageIndexField, TimestampField from fit_tool.profile.profile_type import * @@ -1447,7 +1448,21 @@ def __init__(self, size: int = 0, growable: bool = True): offset = 0, reference_map = { EventEventField.ID: [33] - }), + }, + components = [ + FieldComponent( + field_id=7, + accumulate=False, + bits=16, + scale=1, + offset=0), + FieldComponent( + field_id=8, + accumulate=False, + bits=16, + scale=1, + offset=0) + ]), SubField( name='gear_change_data', base_type=BaseType.UINT32, @@ -1455,7 +1470,33 @@ def __init__(self, size: int = 0, growable: bool = True): offset = 0, reference_map = { EventEventField.ID: [42, 43] - }), + }, + components = [ + FieldComponent( + field_id=11, + accumulate=False, + bits=8, + scale=1, + offset=0), + FieldComponent( + field_id=12, + accumulate=False, + bits=8, + scale=1, + offset=0), + FieldComponent( + field_id=9, + accumulate=False, + bits=8, + scale=1, + offset=0), + FieldComponent( + field_id=10, + accumulate=False, + bits=8, + scale=1, + offset=0) + ]), SubField( name='rider_position', base_type=BaseType.ENUM, @@ -1496,7 +1537,33 @@ def __init__(self, size: int = 0, growable: bool = True): offset = 0, reference_map = { EventEventField.ID: [75] - }) + }, + components = [ + FieldComponent( + field_id=21, + accumulate=False, + bits=8, + scale=1, + offset=0), + FieldComponent( + field_id=22, + accumulate=False, + bits=8, + scale=1, + offset=0), + FieldComponent( + field_id=23, + accumulate=False, + bits=8, + scale=10, + offset=0), + FieldComponent( + field_id=24, + accumulate=False, + bits=8, + scale=10, + offset=0) + ]) ] ) diff --git a/fit_tool/tests/data/README.md b/fit_tool/tests/data/README.md index bc7c4c3..a2be68c 100644 --- a/fit_tool/tests/data/README.md +++ b/fit_tool/tests/data/README.md @@ -71,7 +71,7 @@ capability matrix; residual §11 blockers are in | Component: 16-bit / 8-bit / 12-bit accumulator **rollover** | Supported | Constructive expansion helper | `test_components.py`, `test_protocol_gap_fixtures` | C done | | Nested components (e.g. speed → enhanced_speed) | Supported | Constructive | `test_components.py` | C done | | Full Profile **main-field** component set | Supported (37/37 sources, generated registry) | `fit_tool/profile/component_registry.py` | `test_components.TestRegistryCoverage` | C done | -| Subfield-gated components (event sport_point, etc.) | **Supported** (active subfield via D) | Constructive / unit | `test_components`, `test_subfields` | D done | +| Subfield-gated components (`event.data` gear change / radar threat / sport point) | **Supported** (3/3 Profile sets generated onto `SubField`) | Generated from Profile subfield rows; constructed wire bytes (no device fixture) | `test_components.TestProfileSubfieldGatedComponents`, `test_subfields` | D done | | Unknown **global** messages | Partial (`GenericMessage`) | Device/SDK files with odd IDs; wire decode | `test_wire.py`, SDK smokes | E | | Unknown **field ids** on known messages | **Supported** (`UnknownField` + `raw_bytes`; unedited + post-edit preserve when not mutated) | Constructive definition + data | `test_protocol_gap_fixtures`, `test_post_edit_preservation` | E/F done | | Subfields (e.g. `workout_step.duration_value`) | **Supported** (ref match + scale/units; multi-ref AND; PROFILE ERROR on ambiguity) | Constructive workout step | `test_subfields`, `test_protocol_gap_fixtures` | D done | diff --git a/fit_tool/tests/test_components.py b/fit_tool/tests/test_components.py index f045a92..3dbbc52 100644 --- a/fit_tool/tests/test_components.py +++ b/fit_tool/tests/test_components.py @@ -15,7 +15,9 @@ from fit_tool.field_component import FieldComponent from fit_tool.field_definition import FieldDefinition from fit_tool.fit_file import FitFile +from fit_tool.profile.messages.event_message import EventMessage from fit_tool.profile.messages.record_message import RecordMessage +from fit_tool.profile.profile_type import Event from fit_tool.tests.protocol_fixture_helpers import ( build_record_with_compressed_speed_distance, definition_and_data, @@ -264,3 +266,93 @@ def test_variable_length_stops_at_payload_bits(self): expand_message_components(msg) values = [v for v in dest.encoded_values if v is not None] self.assertEqual(len(values), 2) + + +class TestProfileSubfieldGatedComponents(unittest.TestCase): + """Profile subfield-gated components on ``event.data``. + + Profile 21.222.0 packs gear-change, Varia radar-threat and sport-point data into + ``event.data`` under a gated subfield. No committed fixture carries those event + types, so these cases use constructed messages and constructed wire bytes. + """ + + @staticmethod + def _expand(event, packed_data): + message = EventMessage() + message.event = event + data = message.get_field(3) + assert data is not None + data.size = 4 + data.encoded_values = [packed_data] + expand_message_components(message) + return message + + def test_front_gear_change_expands_all_four_gear_fields(self): + # LSB first: rear_gear_num, rear_gear, front_gear_num, front_gear. + packed = 2 | (11 << 8) | (1 << 16) | (52 << 24) + message = self._expand(Event.FRONT_GEAR_CHANGE, packed) + self.assertEqual(1, message.front_gear_num) + self.assertEqual(52, message.front_gear) + self.assertEqual(2, message.rear_gear_num) + self.assertEqual(11, message.rear_gear) + + def test_rear_gear_change_uses_the_same_layout(self): + packed = 3 | (28 << 8) | (2 << 16) | (36 << 24) + message = self._expand(Event.REAR_GEAR_CHANGE, packed) + self.assertEqual(2, message.front_gear_num) + self.assertEqual(36, message.front_gear) + self.assertEqual(3, message.rear_gear_num) + self.assertEqual(28, message.rear_gear) + + def test_radar_threat_alert_scales_approach_speeds_per_component(self): + # level 3, count 2, average 100/10 = 10.0 m/s, maximum 250/10 = 25.0 m/s. + packed = 3 | (2 << 8) | (100 << 16) | (250 << 24) + message = self._expand(Event.RADAR_THREAT_ALERT, packed) + self.assertEqual(3, message.radar_threat_level_max) + self.assertEqual(2, message.radar_threat_count) + self.assertAlmostEqual(10.0, message.radar_threat_avg_approach_speed) + self.assertAlmostEqual(25.0, message.radar_threat_max_approach_speed) + + def test_sport_point_splits_two_16_bit_scores(self): + packed = 21 | (17 << 16) + message = self._expand(Event.SPORT_POINT, packed) + self.assertEqual(21, message.score) + self.assertEqual(17, message.opponent_score) + + def test_other_event_types_do_not_expand_packed_data(self): + packed = 2 | (11 << 8) | (1 << 16) | (52 << 24) + message = self._expand(Event.TIMER, packed) + self.assertIsNone(message.front_gear_num) + self.assertIsNone(message.front_gear) + self.assertIsNone(message.rear_gear_num) + self.assertIsNone(message.rear_gear) + + def test_wire_decode_expands_gear_change_and_keeps_bytes(self): + packed = 2 | (11 << 8) | (1 << 16) | (52 << 24) + payload = ( + struct.pack('