### Install python-fitparse from GitHub Source: https://github.com/dtcooper/python-fitparse/blob/master/docs/index.md This sequence of commands clones the python-fitparse repository from GitHub and installs it locally. This method is useful for developers who want to work with the latest code or contribute to the project. It requires Git to be installed. ```bash git clone git@github.com:dtcooper/python-fitparse.git cd python-fitparse python setup.py install ``` -------------------------------- ### Install Test Dependencies with Pip Source: https://github.com/dtcooper/python-fitparse/blob/master/CONTRIBUTING.md Installs all necessary dependencies for testing the python-fitparse project from a requirements file. Ensure pip is installed and accessible in your environment. ```bash pip install -r requirements-test.txt ``` -------------------------------- ### Install python-fitparse using pip Source: https://github.com/dtcooper/python-fitparse/blob/master/docs/index.md This command installs the python-fitparse library using the pip package manager. It ensures you have the latest version available through PyPI. This is the recommended method for most users. ```bash pip install fitparse ``` -------------------------------- ### Generate Test Requirements with Pip-Compile Source: https://github.com/dtcooper/python-fitparse/blob/master/CONTRIBUTING.md Generates the `requirements-test.txt` file using `pip-compile`. This process requires `pip-tools` to be installed first. The input file `etc/requirements-test.in` specifies the top-level dependencies. ```bash pip install pip-tools ``` ```bash pip-compile --output-file requirements-test.txt etc/requirements-test.in ``` -------------------------------- ### Parse FIT file records and data using Python Source: https://github.com/dtcooper/python-fitparse/blob/master/README.md Demonstrates how to load a FIT file, iterate through its 'record' messages, and extract individual data fields along with their values and units. This code snippet requires the 'fitparse' library to be installed. ```python import fitparse # Load the FIT file fitfile = fitparse.FitFile("my_activity.fit") # Iterate over all messages of type "record" # (other types include "device_info", "file_creator", "event", etc) for record in fitfile.get_messages("record"): # Records can contain multiple pieces of data (ex: timestamp, latitude, longitude, etc) for data in record: # Print the name and value of the data (and the units if it has any) if data.units: print(" * {}: {} ({})".format(data.name, data.value, data.units)) else: print(" * {}: {}".format(data.name, data.value)) print("---") ``` -------------------------------- ### Memory-Efficient FIT File Processing with UncachedFitFile in Python Source: https://context7.com/dtcooper/python-fitparse/llms.txt This example utilizes `UncachedFitFile` for memory-efficient processing of large FIT files by avoiding caching. It demonstrates streaming through 'record' messages to calculate total distance and maximum heart rate. ```python from fitparse import UncachedFitFile, StandardUnitsDataProcessor # Process large file without caching all messages in memory fitfile = UncachedFitFile( "large_activity.fit", data_processor=StandardUnitsDataProcessor(), check_crc=True ) # Stream through records - each message is only held in memory during iteration total_distance = 0 max_heart_rate = 0 for record in fitfile.get_messages("record"): distance = record.get_value("distance") hr = record.get_value("heart_rate") if distance: total_distance = distance # distance is cumulative if hr and hr > max_heart_rate: max_heart_rate = hr print(f"Total distance: {total_distance / 1000:.2f} km") print(f"Max heart rate: {max_heart_rate} bpm") ``` -------------------------------- ### fitdump Command Line Tool Usage Source: https://context7.com/dtcooper/python-fitparse/llms.txt This section provides examples of using the `fitdump` command-line tool to convert FIT files into various formats such as human-readable text, JSON, and GPX. It covers basic usage, filtering by message type, handling invalid CRC files, reading from stdin, and verbose output. ```bash # Basic usage - output readable format to stdout fitdump my_activity.fit # Output: # 1. file_id # * type: activity # * manufacturer: garmin # * product: 3570 # * serial_number: 3987654321 # * time_created: 2023-06-15 14:30:00 # # 2. record # * timestamp: 2023-06-15 14:30:45 # * position_lat: 47.123456 [deg] # * position_long: -122.654321 [deg] # * heart_rate: 147 [bpm] # ... # Export to JSON fitdump -t json my_activity.fit -o activity.json # Export to GPX for mapping applications fitdump -t gpx my_activity.fit -o activity.gpx # Filter specific message types fitdump -n record my_activity.fit fitdump -n session -n lap my_activity.fit # Handle files with invalid CRC fitdump --ignore-crc corrupted_file.fit # Read from stdin cat my_activity.fit | fitdump - # Verbose output with definition messages fitdump -v my_activity.fit ``` -------------------------------- ### Parse FIT file and print record data in Python Source: https://github.com/dtcooper/python-fitparse/blob/master/docs/index.md This Python script demonstrates how to use the fitparse library to open a .FIT file, iterate through its 'record' messages, and print the name, value, and units of each data field. It requires the fitparse library to be installed. ```python from fitparse import FitFile fitfile = FitFile('/home/dave/garmin-activities/2012-12-19-16-14-54.fit') # Get all data messages that are of type record for record in fitfile.get_messages('record'): # Go through all the data entries in this record for record_data in record: # Print the records name and value (and units if it has any) if record_data.units: print(" * %s: %s %s" % ( record_data.name, record_data.value, record_data.units, )) else: print(" * %s: %s" % (record_data.name, record_data.value)) print() ``` -------------------------------- ### Accessing DataMessage Fields and Values (Python) Source: https://context7.com/dtcooper/python-fitparse/llms.txt Details how to work with DataMessage objects, which represent individual FIT records. Shows how to access message metadata, retrieve specific fields by name, get field values, and convert the entire message to a dictionary. ```python from fitparse import FitFile fitfile = FitFile("my_activity.fit") # Get a specific record records = list(fitfile.get_messages("record")) record = records[100] # Access message metadata print(f"Message name: {record.name}") print(f"Message number: {record.mesg_num}") # Get specific field by name heart_rate = record.get("heart_rate") if heart_rate: print(f"Heart rate: {heart_rate.value} {heart_rate.units}") # Get just the value speed = record.get_value("speed") print(f"Speed: {speed}") # Get all values as a dictionary values = record.get_values() print(values) ``` -------------------------------- ### Processing FIT File Records with Standard Units Source: https://context7.com/dtcooper/python-fitparse/llms.txt This snippet demonstrates how to use the StandardUnitsDataProcessor to get human-readable values for distance, speed, and position from a FIT file. It iterates through 'record' messages and prints processed data, converting units like meters to kilometers and degrees. ```python from fitparse import FitFile, StandardUnitsDataProcessor fitfile = FitFile( "my_activity.fit", data_processor=StandardUnitsDataProcessor() ) for record in fitfile.get_messages("record"): # Distance is now in km instead of m distance = record.get("distance") if distance: print(f"Distance: {distance.value:.2f} {distance.units}") # Speed is now in km/h instead of m/s speed = record.get("speed") if speed: print(f"Speed: {speed.value:.1f} {speed.units}") # Position is now in degrees instead of semicircles lat = record.get("position_lat") lon = record.get("position_long") if lat and lon: print(f"Position: {lat.value:.6f}{lat.units}, {lon.value:.6f}{lon.units}") break ``` -------------------------------- ### Initialize and Parse a FIT File Source: https://github.com/dtcooper/python-fitparse/blob/master/tests/api_examples.txt Demonstrates how to import the necessary modules, initialize a FitFile object with a file path, and execute the parse method to prepare the data for extraction. ```python import os from fitparse import FitFile fitfile_path = os.path.join('files', 'garmin-edge-500-activitiy.fit') fitfile = FitFile(fitfile_path) fitfile.parse() ``` -------------------------------- ### Instantiating FitFile with Different File Inputs (Python) Source: https://github.com/dtcooper/python-fitparse/blob/master/docs/api.md Demonstrates how to create a FitFile object using various input types: a file path, a file-like object, or a raw string of bytes. This highlights the flexibility of the fileish parameter. ```python from fitparse import FitFile # Specifying a file path fitfile_path = FitFile('/path.to/fitfile.fit') # Providing a file-like object with open('/path.to/fitfile.fit', 'rb') as file_obj: fitfile_obj = FitFile(file_obj) # Providing a raw string of bytes with open('/path.to/fitfile.fit', 'rb') as file_obj: raw_fit_data = file_obj.read() fitfile_bytes = FitFile(raw_fit_data) ``` -------------------------------- ### Loading FIT Files with FitFile Class (Python) Source: https://context7.com/dtcooper/python-fitparse/llms.txt Demonstrates how to load .FIT files using the FitFile class from a file path, file object, or raw bytes. Includes error handling for parsing and accessing protocol/profile versions. ```python import fitparse from fitparse import FitFile, FitParseError # Load FIT file from path fitfile = FitFile("my_activity.fit") # Or from file object with open("my_activity.fit", "rb") as f: fitfile = FitFile(f) # Or from raw bytes with open("my_activity.fit", "rb") as f: raw_data = f.read() fitfile = FitFile(raw_data) # Parse the entire file upfront to catch errors early try: fitfile.parse() except FitParseError as e: print(f"Error parsing FIT file: {e}") exit(1) # Access protocol and profile versions print(f"Protocol version: {fitfile.protocol_version}") print(f"Profile version: {fitfile.profile_version}") ``` -------------------------------- ### Reading and Parsing a .FIT File Source: https://github.com/dtcooper/python-fitparse/blob/master/tests/api_examples.txt Demonstrates how to initialize a FitFile object with a file path and parse its contents. ```APIDOC ## Reading and Parsing a .FIT File ### Description This section shows the basic steps to read a .FIT file using the `FitFile` class and parse its data. ### Method Instantiate `FitFile` and call the `parse()` method. ### Endpoint N/A (Local file operation) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python import os from fitparse import FitFile fitfile_path = os.path.join('files', 'garmin-edge-500-activitiy.fit') fitfile = FitFile(fitfile_path) fitfile.parse() ``` ### Response #### Success Response (200) Upon successful parsing, the `fitfile` object will contain the parsed data. #### Response Example N/A (Object state change) ``` -------------------------------- ### Using FitFile as a Context Manager Source: https://context7.com/dtcooper/python-fitparse/llms.txt This Python snippet illustrates the use of the `FitFile` class as a context manager. This ensures that the FIT file is automatically closed after processing, preventing resource leaks. It shows how to extract session data like total distance, elapsed time, and average heart rate. ```python from fitparse import FitFile # Use as context manager for automatic cleanup with FitFile("my_activity.fit") as fitfile: for record in fitfile.get_messages("session"): total_distance = record.get_value("total_distance") total_time = record.get_value("total_elapsed_time") avg_hr = record.get_value("avg_heart_rate") print(f"Distance: {total_distance/1000:.2f} km") print(f"Duration: {total_time/60:.1f} minutes") print(f"Avg HR: {avg_hr} bpm") # File is automatically closed after the with block ``` -------------------------------- ### Run Unit Tests with Code Coverage Source: https://github.com/dtcooper/python-fitparse/blob/master/CONTRIBUTING.md Executes unit tests for the python-fitparse project and measures code coverage. This command uses the `coverage` tool to run the tests and generate a report. ```bash coverage run run_tests.py ``` ```bash coverage report ``` -------------------------------- ### Handling FitParseError during File Parsing (Python) Source: https://github.com/dtcooper/python-fitparse/blob/master/docs/api.md Shows how to gracefully handle potential FitParseError exceptions that may occur when parsing a .FIT file. It includes a try-except block to catch errors and print informative messages. ```python import sys from fitparse import FitFile, FitParseError try: fitfile = FitFile('/path.to/fitfile.fit') fitfile.parse() except FitParseError as e: print(f"Error while parsing .FIT file: {e}") sys.exit(1) ``` -------------------------------- ### FitFile - Main Interface for Parsing FIT Files Source: https://context7.com/dtcooper/python-fitparse/llms.txt The FitFile class is the primary interface for reading .FIT files. It accepts file paths, file-like objects, or raw bytes and provides methods for accessing parsed messages. The class caches parsed messages for repeated access and applies data processing to convert raw values to meaningful data types. ```APIDOC ## FitFile - Main Interface for Parsing FIT Files ### Description The `FitFile` class is the primary interface for reading `.FIT` files. It accepts file paths, file-like objects, or raw bytes and provides methods for accessing parsed messages. The class caches parsed messages for repeated access and applies data processing to convert raw values to meaningful data types. ### Method Instantiate the `FitFile` class. ### Endpoint N/A (Class instantiation) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python import fitparse from fitparse import FitFile, FitParseError # Load FIT file from path fitfile = FitFile("my_activity.fit") # Or from file object with open("my_activity.fit", "rb") as f: fitfile = FitFile(f) # Or from raw bytes with open("my_activity.fit", "rb") as f: raw_data = f.read() fitfile = FitFile(raw_data) # Parse the entire file upfront to catch errors early try: fitfile.parse() except FitParseError as e: print(f"Error parsing FIT file: {e}") exit(1) # Access protocol and profile versions print(f"Protocol version: {fitfile.protocol_version}") print(f"Profile version: {fitfile.profile_version}") ``` ### Response #### Success Response (200) - **protocol_version** (str) - The protocol version of the FIT file. - **profile_version** (str) - The profile version of the FIT file. #### Response Example ```json { "protocol_version": "2.0", "profile_version": "21.60" } ``` ``` -------------------------------- ### Fitdump command-line tool usage Source: https://github.com/dtcooper/python-fitparse/blob/master/README.md Provides the help message for the `fitdump` command-line script, which is part of the python-fitparse library. This tool can dump .FIT files to various formats like readable text or JSON, with options for output file, filtering by message name, and ignoring CRC errors. ```bash usage: fitdump [-h] [-v] [-o OUTPUT] [-t {readable,json}] [-n NAME] [--ignore-crc] FITFILE Dump .FIT files to various formats positional arguments: FITFILE Input .FIT file (Use - for stdin) optional arguments: -h, --help show this help message and exit -v, --verbose -o OUTPUT, --output OUTPUT File to output data into (defaults to stdout) -t {readable,json}, --type {readable,json} File type to output. (DEFAULT: readable) -n NAME, --name NAME Message name (or number) to filter --ignore-crc Some devices can write invalid crc's, ignore these. ``` -------------------------------- ### Iterate and Print Record Fields in Python Source: https://context7.com/dtcooper/python-fitparse/llms.txt This snippet demonstrates how to iterate over messages of type 'record' in a FIT file and print the name, value, and units of each field within a record. It shows basic field access and iteration. ```python from fitparse import FitFile fitfile = FitFile("my_activity.fit") for record in fitfile.get_messages("record"): for field in record: print(f"{field.name}: {field.value} {field.units or ''}") ``` -------------------------------- ### Iterating and Filtering FIT Messages with get_messages() (Python) Source: https://context7.com/dtcooper/python-fitparse/llms.txt Shows how to use the get_messages() method to iterate over DataMessage objects in a FIT file. Supports filtering by message name, including definition messages, and returning messages as dictionaries. ```python from fitparse import FitFile fitfile = FitFile("my_activity.fit") # Get all messages for message in fitfile.get_messages(): print(f"Message: {message.name}") # Filter by message type - get only GPS/sensor records for record in fitfile.get_messages("record"): for field in record: if field.units: print(f" {field.name}: {field.value} ({field.units})") else: print(f" {field.name}: {field.value}") print("---") # Filter multiple message types for msg in fitfile.get_messages(["session", "lap"]): print(f"{msg.name}: {msg.get_values()}") # Get messages as dictionaries for record in fitfile.get_messages("record", as_dict=True): print(record) ``` -------------------------------- ### Update FIT profile using Python script Source: https://github.com/dtcooper/python-fitparse/blob/master/README.md Command to update the FIT profile definitions for the python-fitparse library by running a Python script with the path to the downloaded ANT FIT SDK zip file. This process generates the necessary profile Python file. ```bash python3 scripts/generate_profile.py /path/to/fit_sdk.zip fitparse/profile.py ``` -------------------------------- ### Standard Unit Conversions for FIT Files in Python Source: https://context7.com/dtcooper/python-fitparse/llms.txt This snippet shows the usage of `StandardUnitsDataProcessor` from the fitparse library. This processor automatically converts common FIT data units to more human-readable formats, such as semicircles to degrees and meters per second to kilometers per hour. ```python from fitparse import FitFile, StandardUnitsDataProcessor ``` -------------------------------- ### Accessing DataMessage Values (Python) Source: https://github.com/dtcooper/python-fitparse/blob/master/docs/api.md Illustrates how to retrieve all field values from a DataMessage object as a dictionary. This is useful for quickly inspecting the data contained within a message. ```python import datetime # Assuming 'data_message' is an instance of fitparse.DataMessage # Example structure of data_message.get_values() { 'altitude': 24.6, 'cadence': 97, 'distance': 81.97, 'grade': None, 'heart_rate': 153, 'position_lat': None, 'position_long': None, 'power': None, 'resistance': None, 'speed': 7.792, 'temperature': 20, 'time_from_course': None, 'timestamp': datetime.datetime(2011, 11, 6, 13, 41, 50) } ``` -------------------------------- ### FIT File Parsing with CRC Validation and Error Handling Source: https://context7.com/dtcooper/python-fitparse/llms.txt This Python code shows how to parse FIT files using the fitparse library, including robust error handling for various parsing issues like header errors, CRC failures, and unexpected end-of-file conditions. It also demonstrates how to disable CRC validation for corrupted files. ```python from fitparse import FitFile, FitParseError, FitCRCError, FitHeaderError, FitEOFError # Normal usage with CRC validation (default) try: fitfile = FitFile("my_activity.fit") fitfile.parse() except FitHeaderError as e: print(f"Invalid FIT file header: {e}") except FitCRCError as e: print(f"CRC validation failed: {e}") except FitEOFError as e: print(f"Unexpected end of file: {e}") except FitParseError as e: print(f"General parsing error: {e}") # Disable CRC validation for corrupted files fitfile = FitFile("corrupted_activity.fit", check_crc=False) for record in fitfile.get_messages("record"): # Process records even if CRC is invalid print(record.get_values()) ``` -------------------------------- ### Accessing All FIT Messages with messages Property (Python) Source: https://context7.com/dtcooper/python-fitparse/llms.txt Explains how to use the `messages` property to retrieve a list of all parsed DataMessage objects from a FIT file. This property caches results for efficient repeated access and can be used for counting message types. ```python from fitparse import FitFile from collections import Counter fitfile = FitFile("my_activity.fit") # Get all messages as a list all_messages = fitfile.messages # Count message types message_types = Counter(msg.name for msg in all_messages) print(f"Total messages: {len(all_messages)}") print(f"Message types: {dict(message_types)}") ``` -------------------------------- ### get_messages() - Iterate Over FIT Messages Source: https://context7.com/dtcooper/python-fitparse/llms.txt The `get_messages()` method returns an iterator over `DataMessage` objects contained in the FIT file. You can filter by message name (e.g., "record", "session", "lap", "device_info") and optionally include definition messages or return messages as dictionaries. ```APIDOC ## get_messages() - Iterate Over FIT Messages ### Description The `get_messages()` method returns an iterator over `DataMessage` objects contained in the FIT file. You can filter by message name (e.g., "record", "session", "lap", "device_info") and optionally include definition messages or return messages as dictionaries. ### Method `get_messages(name=None, definition_messages=False, as_dict=False)` ### Endpoint N/A (Method of `FitFile` object) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python from fitparse import FitFile fitfile = FitFile("my_activity.fit") # Get all messages for message in fitfile.get_messages(): print(f"Message: {message.name}") # Filter by message type - get only GPS/sensor records for record in fitfile.get_messages("record"): for field in record: if field.units: print(f" {field.name}: {field.value} ({field.units})") else: print(f" {field.name}: {field.value}") print("---") # Filter multiple message types for msg in fitfile.get_messages(["session", "lap"]): print(f"{msg.name}: {msg.get_values()}") # Get messages as dictionaries for record in fitfile.get_messages("record", as_dict=True): print(record) ``` ### Response #### Success Response (200) - **Iterator of DataMessage objects** (or dictionaries if `as_dict=True`) - Contains the messages from the FIT file, optionally filtered by name. #### Response Example ```json { "name": "record", "fields": [ {"name": "timestamp", "value": "2023-06-15 14:30:45", "units": "s"}, {"name": "position_lat", "value": 522265991, "units": "semicircles"}, {"name": "position_long", "value": -947288309, "units": "semicircles"}, {"name": "heart_rate", "value": 147, "units": "bpm"}, {"name": "cadence", "value": 85, "units": "rpm"}, {"name": "speed", "value": 8.431, "units": "m/s"}, {"name": "distance", "value": 9027.49, "units": "m"} ] } ``` ``` -------------------------------- ### Extract and Iterate FIT Data Messages Source: https://github.com/dtcooper/python-fitparse/blob/master/tests/api_examples.txt Shows how to retrieve specific message types, such as 'record', from the parsed FIT file and iterate through the fields of an individual message to access values and units. ```python records = list(fitfile.get_messages(name='record')) print(len(records)) record = records[1234] for field in record: print(field.name, field.value, field.units) ``` -------------------------------- ### Custom Data Processing for FIT Files in Python Source: https://context7.com/dtcooper/python-fitparse/llms.txt This snippet defines a `CustomDataProcessor` class that extends `FitFileDataProcessor` to implement custom transformations for specific fields like latitude, longitude, and speed. It demonstrates converting semicircles to degrees and m/s to km/h. ```python from fitparse import FitFile, FitFileDataProcessor import datetime class CustomDataProcessor(FitFileDataProcessor): """Custom processor that adds additional field transformations.""" def process_field_position_lat(self, field_data): """Convert semicircles to decimal degrees.""" if field_data.value is not None: field_data.value = field_data.value * (180.0 / 2**31) field_data.units = "degrees" def process_field_position_long(self, field_data): """Convert semicircles to decimal degrees.""" if field_data.value is not None: field_data.value = field_data.value * (180.0 / 2**31) field_data.units = "degrees" def process_field_speed(self, field_data): """Convert m/s to km/h.""" if field_data.value is not None: field_data.value = field_data.value * 3.6 field_data.units = "km/h" # Use custom processor fitfile = FitFile("my_activity.fit", data_processor=CustomDataProcessor()) for record in fitfile.get_messages("record"): lat = record.get_value("position_lat") lon = record.get_value("position_long") speed = record.get_value("speed") if lat and lon: print(f"Position: {lat:.6f}, {lon:.6f} - Speed: {speed:.1f} km/h") ``` -------------------------------- ### Extracting Specific Message Types Source: https://github.com/dtcooper/python-fitparse/blob/master/tests/api_examples.txt Shows how to retrieve all messages of a specific type, such as 'record' messages, from a parsed .FIT file. ```APIDOC ## Extracting Specific Message Types ### Description This section demonstrates how to use the `get_messages()` method to filter and retrieve messages of a particular name (e.g., 'record') from a parsed `FitFile` object. ### Method Call the `get_messages(name='message_type')` method on a `FitFile` object. ### Endpoint N/A (Local file operation) ### Parameters #### Path Parameters None #### Query Parameters - **name** (string) - Required - The name of the message type to retrieve (e.g., 'record', 'session', 'activity'). #### Request Body None ### Request Example ```python records = list(fitfile.get_messages(name='record')) print len(records) ``` ### Response #### Success Response (200) A list of message objects matching the specified name. #### Response Example ``` 10686 ``` ``` -------------------------------- ### Accessing Data Fields within a Message Source: https://github.com/dtcooper/python-fitparse/blob/master/tests/api_examples.txt Illustrates how to iterate through the fields of a specific data message and access their name, value, and units. ```APIDOC ## Accessing Data Fields within a Message ### Description This section explains how to iterate over the fields of an individual data message (e.g., a 'record' message) and access the `name`, `value`, and `units` of each field. ### Method Iterate through the message object directly, which yields field objects. ### Endpoint N/A (Local file operation) ### Parameters None ### Request Example ```python record = records[1234] # Assuming 'records' is a list of record messages for field in record: print (field.name, field.value, field.units) ``` ### Response #### Success Response (200) Prints the name, value, and units for each field in the message. #### Response Example ``` ('altitude', 128.0, 'm') ('cadence', 0, 'rpm') ('distance', 9027.49, 'm') ('grade', None, '%') ('heart_rate', 147, 'bpm') ('position_lat', 522265991, 'semicircles') ('position_long', -947288309, 'semicircles') ('power', None, 'watts') ('resistance', None, None) ('speed', 8.431, 'm/s') ('temperature', 19, 'C') ('time_from_course', None, 's') ('timestamp', datetime.datetime(2011, 9, 25, 13, 21, 29), None) ``` ``` -------------------------------- ### Access Individual Field Properties in Python Source: https://context7.com/dtcooper/python-fitparse/llms.txt This code snippet shows how to access detailed properties of each field within a FIT record, including its name, value, raw value, units, type, and definition number. It iterates through 'record' messages and prints these properties for each field. ```python from fitparse import FitFile fitfile = FitFile("my_activity.fit") for record in fitfile.get_messages("record"): for field in record: # Field properties print(f"Name: {field.name}") print(f"Value: {field.value}") print(f"Raw value: {field.raw_value}") print(f"Units: {field.units}") print(f"Type: {field.type.name}") print(f"Definition number: {field.def_num}") print("---") break ``` -------------------------------- ### DataMessage - Access Individual Message Fields Source: https://context7.com/dtcooper/python-fitparse/llms.txt `DataMessage` objects represent parsed FIT data records. They provide methods to access field data by name, iterate over fields, and convert to dictionary format. Each message has a name, message number, and collection of `FieldData` objects. ```APIDOC ## DataMessage - Access Individual Message Fields ### Description `DataMessage` objects represent parsed FIT data records. They provide methods to access field data by name, iterate over fields, and convert to dictionary format. Each message has a name, message number, and collection of `FieldData` objects. ### Method Obtain `DataMessage` objects by iterating through `FitFile.get_messages()` or accessing `FitFile.messages`. ### Endpoint N/A (Represents a parsed data record) ### Parameters None (Accessed via methods/properties of the `DataMessage` object) ### Request Example ```python from fitparse import FitFile fitfile = FitFile("my_activity.fit") # Get a specific record records = list(fitfile.get_messages("record")) record = records[100] # Access message metadata print(f"Message name: {record.name}") print(f"Message number: {record.mesg_num}") # Get specific field by name heart_rate = record.get("heart_rate") if heart_rate: print(f"Heart rate: {heart_rate.value} {heart_rate.units}") # Get just the value speed = record.get_value("speed") print(f"Speed: {speed}") # Get all values as a dictionary values = record.get_values() print(values) ``` ### Response #### Success Response (200) - **name** (str) - The name of the message type (e.g., "record", "session"). - **mesg_num** (int) - The FIT message number. - **fields** (list of FieldData objects) - A list of fields within the message. - **FieldData.name** (str) - The name of the field. - **FieldData.value** - The value of the field. - **FieldData.units** (str, optional) - The units of the field. #### Response Example ```json { "name": "record", "mesg_num": 10, "fields": [ {"name": "altitude", "value": 128.0, "units": "m"}, {"name": "cadence", "value": 85, "units": "rpm"}, {"name": "distance", "value": 9027.49, "units": "m"}, {"name": "heart_rate", "value": 147, "units": "bpm"} ] } ``` ``` -------------------------------- ### messages Property - Access All Parsed Messages Source: https://context7.com/dtcooper/python-fitparse/llms.txt The `messages` property returns a list of all `DataMessage` objects in the FIT file. This is a convenience wrapper around `get_messages()` that caches results for efficient repeated access. ```APIDOC ## messages Property - Access All Parsed Messages ### Description The `messages` property returns a list of all `DataMessage` objects in the FIT file. This is a convenience wrapper around `get_messages()` that caches results for efficient repeated access. ### Method Access the `.messages` property of a `FitFile` object. ### Endpoint N/A (Property of `FitFile` object) ### Parameters None ### Request Example ```python from fitparse import FitFile from collections import Counter fitfile = FitFile("my_activity.fit") # Get all messages as a list all_messages = fitfile.messages # Count message types message_types = Counter(msg.name for msg in all_messages) print(f"Total messages: {len(all_messages)}") print(f"Message types: {dict(message_types)}") ``` ### Response #### Success Response (200) - **messages** (list) - A list containing all `DataMessage` objects parsed from the FIT file. #### Response Example ```json { "total_messages": 5432, "message_types": { "file_id": 1, "device_info": 3, "record": 5200, "event": 12, "lap": 5, "session": 1, "activity": 1 } } ``` ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.