API Reference¶
This page documents the public API for Fit File Faker.
Main Application interface (app.py)¶
Main application module for Fit File Faker.
This module provides the command-line interface and core application logic for modifying FIT files and uploading them to Garmin Connect. It simulates a Garmin Edge 830 device (by default) to enable Training Effect calculations for activities from non-Garmin sources.
The module includes:
- CLI argument parsing and validation
- FIT file upload to Garmin Connect with OAuth authentication
- Batch processing of multiple FIT files
- Directory monitoring for automatic processing of new files
- Rich console output with colored logs
Typical usage:
$ fit-file-faker --config-menu # Initial setup
$ fit-file-faker activity.fit # Edit single file
$ fit-file-faker -u activity.fit # Edit and upload
$ fit-file-faker -ua # Upload all new files
$ fit-file-faker -m # Monitor directory
NewFileEventHandler ¶
Bases: PatternMatchingEventHandler
Event handler for monitoring directory changes and processing new FIT files.
Extends watchdog's PatternMatchingEventHandler to automatically process and upload new FIT files as they're created in the monitored directory. Also handles file modification events for MyWhoosh files that follow the pattern "MyNewActivity-*.fit", as MyWhoosh overwrites the same file on completion rather than creating a new file.
Includes a 5-second delay to ensure the file is fully written before processing.
Attributes:
| Name | Type | Description |
|---|---|---|
dryrun | If | |
profile | The profile to use for uploading files. |
Examples:
>>> # Typically used via monitor() function, but can be instantiated directly:
>>> from watchdog.observers.polling import PollingObserver as Observer
>>> handler = NewFileEventHandler(profile=profile, dryrun=False)
>>> observer = Observer()
>>> observer.schedule(handler, "/path/to/fitfiles", recursive=True)
>>> observer.start()
Initialize the file event handler.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
profile | Profile | The profile to use for uploading files. | required |
dryrun | bool | If | False |
Source code in fit_file_faker/app.py
on_created ¶
Handle file creation events.
Called by watchdog when a new .fit file is created in the monitored directory. Waits 5 seconds to ensure the file is fully written, then processes all new files in the directory via upload_all().
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
event | FileCreatedEvent | The file system event containing the path to the new file. | required |
Note
The 5-second delay is necessary because TrainingPeaks Virtual may still be writing to the file when the creation event fires. Without this delay, the file might be incomplete or corrupt.
Source code in fit_file_faker/app.py
on_modified ¶
Handle file modification events.
Called by watchdog when a .fit file is modified in the monitored directory. This is specifically useful for MyWhoosh files that follow the pattern "MyNewActivity-*.fit", as MyWhoosh overwrites the same file on completion rather than creating a new file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
event | FileModifiedEvent | The file system event containing the path to the modified file. | required |
Note
Waits 5 seconds to ensure the file is fully written, similar to the creation event handler. This handles the case where MyWhoosh overwrites existing files. Only processes the specific modified file rather than all files in the directory.
Source code in fit_file_faker/app.py
get_garth_dir ¶
Get profile-specific garth directory for credential isolation.
Each profile gets its own garth directory to prevent credential conflicts when managing multiple Garmin accounts. The profile name is sanitized to ensure filesystem compatibility.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
profile_name | str | The name of the profile. | required |
Returns:
| Type | Description |
|---|---|
Path | Path to the profile-specific garth directory. |
Examples:
>>> get_garth_dir("tpv")
PosixPath('/Users/josh/Library/Caches/FitFileFaker/.garth_tpv')
>>>
>>> get_garth_dir("work-account")
PosixPath('/Users/josh/Library/Caches/FitFileFaker/.garth_work-account')
Note
The directory is automatically created if it doesn't exist. Profile names with special characters are sanitized (replaced with '_').
Source code in fit_file_faker/app.py
monitor ¶
Monitor a directory for new FIT files and automatically process them.
Uses watchdog's PollingObserver to watch for new .fit files in the specified directory. When a new file is detected, waits 5 seconds to ensure it's fully written, then processes and uploads it via upload_all().
The monitor runs until interrupted by Ctrl-C (KeyboardInterrupt).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
watch_dir | Path | Path to the directory to monitor. | required |
profile | Profile | The profile to use for authentication and upload. | required |
dryrun | bool | If | False |
Examples:
>>> from pathlib import Path
>>>
>>> # Monitor a directory
>>> monitor(Path("/home/user/TPVirtual/abc123/FITFiles"), profile=my_profile)
Monitoring directory: "/home/user/TPVirtual/abc123/FITFiles"
# Press Ctrl-C to stop
Note
Uses PollingObserver for cross-platform compatibility. This may be less efficient than platform-specific observers but works consistently across macOS, Windows, and Linux.
Source code in fit_file_faker/app.py
run ¶
Main entry point for the fit-file-faker command-line application.
Parses command-line arguments, validates configuration, and executes the appropriate operation (edit, upload, batch upload, or monitor). This function is registered as the console script entry point in pyproject.toml.
Command-line options:
--profile: Specify which profile to use
--list-profiles: List all available profiles
--config-menu: Launch the interactive profile management menu
--show-dirs: Show directories used for configuration and cache
-u, --upload: Upload file after editing
-ua, --upload-all: Batch upload all new files
-p, --preinitialize: Mark all existing files as already uploaded
-m, --monitor: Monitor directory for new files
-d, --dryrun: Perform dry run (no file writes or uploads)
-v, --verbose: Enable verbose debug logging
Raises:
| Type | Description |
|---|---|
SystemExit | If configuration is invalid, required arguments are missing, or conflicting arguments are provided. |
Examples:
# run() is called automatically when running the installed command:
$ fit-file-faker --config-menu
$ fit-file-faker --show-dirs
$ fit-file-faker -u activity.fit
$ fit-file-faker -ua
$ fit-file-faker -m
Note
Requires Python 3.12 or higher. Exits with error if Python version requirement is not met.
Source code in fit_file_faker/app.py
537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 | |
select_profile ¶
Select a profile to use for the current operation.
Uses the following priority: 1. If profile_name is provided, use that profile (error if not found) 2. Use the default profile if one is set 3. If only one profile exists, use it 4. If multiple profiles exist, prompt the user to select one 5. If no profiles exist, raise an error
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
profile_name | Optional[str] | Optional name of the profile to use. If not provided, uses the default profile or prompts the user. | None |
Returns:
| Type | Description |
|---|---|
Profile | The selected Profile object. |
Raises:
| Type | Description |
|---|---|
ValueError | If the specified profile is not found or no profiles are configured. |
Examples:
>>> # Use a specific profile
>>> profile = select_profile("tpv")
>>>
>>> # Use default profile (or prompt if no default)
>>> profile = select_profile()
Source code in fit_file_faker/app.py
upload ¶
Upload a FIT file to Garmin Connect.
Authenticates to Garmin Connect using credentials from the specified profile, then uploads the specified FIT file. Credentials are cached in a profile-specific cache directory for future use.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fn | Path | Path to the (modified) FIT file to upload. | required |
profile | Profile | The profile to use for authentication and upload. | required |
original_path | Optional[Path] | Optional path to the original file for logging purposes. Defaults to | None |
dryrun | bool | If | False |
Raises:
| Type | Description |
|---|---|
GarthHTTPError | If upload fails with an HTTP error. 409 (conflict/duplicate) errors are caught and logged as warnings, but other HTTP errors are re-raised. |
Examples:
>>> from pathlib import Path
>>> # Upload a modified file
>>> upload(Path("activity_modified.fit"), profile=my_profile)
>>>
>>> # Dry run (authenticate but don't upload)
>>> upload(Path("activity_modified.fit"), profile=my_profile, dryrun=True)
Note
Garmin Connect credentials are read from the profile. Credentials are cached in profile-specific directories like ~/.cache/FitFileFaker/.garth_
Source code in fit_file_faker/app.py
247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 | |
upload_all ¶
Batch process and upload all new FIT files in a directory.
Scans the directory for FIT files that haven't been processed yet, edits them to appear as Garmin Edge 830 files, and uploads them to Garmin Connect. Maintains a .uploaded_files.json file to track which files have been processed.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dir | Path | Path to the directory containing FIT files to process. | required |
profile | Profile | The profile to use for authentication and upload. | required |
preinitialize | bool | If | False |
dryrun | bool | If | False |
Note
Files ending in "_modified.fit" are automatically excluded to avoid re-processing previously modified files. Temporary files are used for uploads and are automatically deleted afterwards.
Examples:
>>> from pathlib import Path
>>>
>>> # Process and upload all new files
>>> upload_all(Path("/home/user/TPVirtual/abc123/FITFiles"), profile=my_profile)
>>>
>>> # Initialize tracking without processing
>>> upload_all(Path("/path/to/fitfiles"), profile=my_profile, preinitialize=True)
>>>
>>> # Dry run (no uploads or tracking updates)
>>> upload_all(Path("/path/to/fitfiles"), profile=my_profile, dryrun=True)
Source code in fit_file_faker/app.py
334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 | |
FIT Editor (fit_editor.py)¶
FitEditor ¶
Handles FIT file editing and manipulation.
This class provides methods to read, modify, and save FIT files from various cycling platforms (TrainingPeaks Virtual, Zwift, COROS, etc.), converting them to appear as if they came from a Garmin Edge 830 device (or a custom device if configured via profile).
The editor modifies only device metadata (manufacturer, product IDs) while preserving all activity data including records, laps, and sessions. This enables Garmin Connect's Training Effect calculations for activities from non-Garmin sources.
Examples:
>>> from fit_file_faker.fit_editor import fit_editor
>>> from pathlib import Path
>>>
>>> # Edit a single file
>>> output = fit_editor.edit_fit(Path("activity.fit"))
>>>
>>> # Dry run mode (no file written)
>>> output = fit_editor.edit_fit(Path("activity.fit"), dryrun=True)
>>>
>>> # Custom output location
>>> output = fit_editor.edit_fit(
... Path("activity.fit"),
... output=Path("modified_activity.fit")
... )
Initialize the FIT editor.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
profile | Optional Profile object for device simulation settings. If None, defaults to Garmin Edge 830. | None |
Applies a logging filter to suppress verbose fit_tool warnings.
Source code in fit_file_faker/fit_editor.py
edit_fit ¶
edit_fit(
fit_input: Path | FitFile,
output: Optional[Path] = None,
dryrun: bool = False,
) -> Path | None
Edit a FIT file to appear as if it came from a Garmin Edge 830.
This is the primary method for converting FIT files from virtual cycling platforms to Garmin-compatible format. It modifies device metadata (manufacturer and product IDs) while preserving all activity data.
The method performs the following transformations:
- Strips unknown field definitions to prevent corruption
- Rewrites
FileIdMessagewith Garmin Edge 830 metadata - Adds a
FileCreatorMessagewith Edge 830 software/hardware versions - Modifies
DeviceInfoMessagerecords to match Edge 830 - Reorders
Activitymessages to end of file (COROS compatibility)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fit_input | Path | FitFile | Either a | required |
output | Optional[Path] | Optional output path. Defaults to {original}_modified.fit when | None |
dryrun | bool | If | False |
Returns:
| Type | Description |
|---|---|
Path | None | Path to the output file if successful, or |
Path | None | failed (e.g., invalid FIT file). |
Raises:
| Type | Description |
|---|---|
None | Errors are logged but not raised. Returns |
Examples:
>>> from pathlib import Path
>>> from fit_file_faker.fit_editor import fit_editor
>>>
>>> # Basic usage
>>> output = fit_editor.edit_fit(Path("activity.fit"))
>>> print(f"Modified file: {output}")
>>>
>>> # Custom output path
>>> output = fit_editor.edit_fit(
... Path("activity.fit"),
... output=Path("custom_output.fit")
... )
>>>
>>> # Dry run (no file written)
>>> output = fit_editor.edit_fit(Path("activity.fit"), dryrun=True)
Note
Only modifies device metadata. All activity data (records, laps, sessions, heart rate, power, etc.) is preserved exactly as-is.
Source code in fit_file_faker/fit_editor.py
360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 | |
rewrite_file_id_message ¶
rewrite_file_id_message(
m: FileIdMessage, message_num: int
) -> tuple[DefinitionMessage, FileIdMessage]
Rewrite FileIdMessage to appear as if from Garmin Edge 830.
Creates a new FileIdMessage with Garmin Edge 830 manufacturer and product IDs while preserving the original timestamp, type, and serial number. This is the primary transformation that enables Garmin Connect to recognize and process the activity.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
m | FileIdMessage | The original FileIdMessage to rewrite. | required |
message_num | int | The record number for logging purposes. | required |
Returns:
| Type | Description |
|---|---|
tuple[DefinitionMessage, FileIdMessage] | A tuple containing:
|
Note
The product_name field is intentionally not copied as Garmin devices typically don't set this field. Only files from supported manufacturers (DEVELOPMENT, ZWIFT, WAHOO_FITNESS, PEAKSWARE, HAMMERHEAD, COROS, MYWHOOSH) are modified; others are returned unchanged.
Source code in fit_file_faker/fit_editor.py
get_date_from_fit ¶
Extract the creation date from a FIT file.
Reads the FIT file and extracts the timestamp from the FileIdMessage, which indicates when the activity was recorded.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fit_path | Path |
| required |
Returns:
| Type | Description |
|---|---|
Optional[datetime] | The activity creation datetime, or |
Optional[datetime] | a valid timestamp was found. |
Note
The timestamp in FIT files is stored in milliseconds since the FIT epoch, which is converted to a standard Python datetime object.
Source code in fit_file_faker/fit_editor.py
strip_unknown_fields ¶
Force regeneration of definition messages for messages with unknown fields.
This fixes a bug where fit_tool skips unknown fields (like Zwift's field 193) during reading but keeps them in the definition, causing a mismatch when writing. Without this fix, the file would be corrupted when written back out.
The method sets definition_message to None for affected messages, forcing FitFileBuilder to regenerate clean definitions based only on fields that actually exist in the message.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fit_file | FitFile | The parsed FIT file to process. Messages are modified in place. | required |
Note
This is called automatically by edit_fit() before processing any FIT file. It's essential for handling files from platforms like Zwift that use custom/unknown field IDs.
Source code in fit_file_faker/fit_editor.py
_should_modify_manufacturer ¶
Check if manufacturer should be modified to Garmin.
Determines whether a FIT file's manufacturer should be changed to Garmin based on whether it's from a supported virtual cycling platform.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
manufacturer | int | None | The manufacturer code from the FIT file, or | required |
Returns:
| Type | Description |
|---|---|
bool | True if the manufacturer is from a supported platform and should |
bool | be modified, False otherwise. |
Note
Supported manufacturers include: DEVELOPMENT (TrainingPeaks Virtual), ZWIFT, WAHOO_FITNESS, PEAKSWARE, HAMMERHEAD, COROS, and MYWHOOSH (331).
Source code in fit_file_faker/fit_editor.py
_should_modify_device_info ¶
Check if device info should be modified to Garmin Edge 830.
Similar to _should_modify_manufacturer but also includes blank/unknown manufacturers (code 0) for DeviceInfoMessage records.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
manufacturer | int | None | The manufacturer code from the | required |
Returns:
| Type | Description |
|---|---|
bool | True if the device info should be modified to Garmin Edge 830, |
bool | False otherwise. |
Note
This includes all manufacturers from _should_modify_manufacturer() plus manufacturer code 0 (blank/unknown).
Source code in fit_file_faker/fit_editor.py
Configuration (config.py)¶
Configuration management for Fit File Faker.
This module handles all configuration file operations including creation, validation, loading, and saving. Configuration is stored in a platform-specific user configuration directory using platformdirs.
The configuration includes Garmin Connect credentials and the path to the directory containing FIT files to process. Depending on the trainer app selected in the profile, the FIT files directory is auto-detected (but can be overridden).
Typical usage example:
AppType ¶
Bases: Enum
Supported trainer/cycling applications.
Each app type has associated directory detection logic and display names. Used to identify the source application for FIT files and enable platform-specific auto-detection.
Attributes:
| Name | Type | Description |
|---|---|---|
TP_VIRTUAL | TrainingPeaks Virtual (formerly indieVelo) | |
ZWIFT | Zwift virtual cycling platform | |
MYWHOOSH | MyWhoosh virtual cycling platform | |
CUSTOM | Custom/manual path specification |
Config dataclass ¶
Multi-profile configuration container for Fit File Faker.
Stores multiple profile configurations, each with independent Garmin credentials and FIT files directory. Supports backward compatibility with single-profile configs via automatic migration.
Attributes:
| Name | Type | Description |
|---|---|---|
profiles | list[Profile] | List of Profile objects, each representing a complete configuration for a trainer app and Garmin account. |
default_profile | str | None | Name of the default profile to use when no profile is explicitly specified. If None, the first profile is used. |
Examples:
>>> from pathlib import Path
>>> config = Config(
... profiles=[
... Profile(
... name="tpv",
... app_type=AppType.TP_VIRTUAL,
... garmin_username="user@example.com",
... garmin_password="secret",
... fitfiles_path=Path("/home/user/TPVirtual/abc123/FITFiles")
... )
... ],
... default_profile="tpv"
... )
>>> profile = config.get_profile("tpv")
>>> default = config.get_default_profile()
__post_init__ ¶
Convert dict profiles to Profile objects after initialization.
Handles deserialization from JSON where profiles may be dictionaries instead of Profile objects.
Source code in fit_file_faker/config.py
get_default_profile ¶
Get the default profile or first profile if no default set.
Returns:
| Type | Description |
|---|---|
Profile | None | The default Profile object, or the first profile if no default |
Profile | None | is set, or None if no profiles exist. |
Examples:
>>> config = Config(profiles=[...], default_profile="tpv")
>>> profile = config.get_default_profile()
Source code in fit_file_faker/config.py
get_profile ¶
Get profile by name.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name | str | The name of the profile to retrieve. | required |
Returns:
| Type | Description |
|---|---|
Profile | None | Profile object if found, None otherwise. |
Examples:
Source code in fit_file_faker/config.py
ConfigManager ¶
Manages configuration file operations and validation.
Handles loading, saving, and validating configuration stored in a platform-specific user configuration directory. Provides interactive configuration building for missing or invalid values.
The configuration file is stored as .config.json in the user's config directory (location varies by platform).
Attributes:
| Name | Type | Description |
|---|---|---|
config_file | Path to the JSON configuration file. | |
config_keys | List of required configuration keys. | |
config | Current Config object loaded from file. |
Examples:
>>> from fit_file_faker.config import config_manager
>>>
>>> # Check if config is valid
>>> if not config_manager.is_valid():
... print(f"Config file: {config_manager.get_config_file_path()}")
... config_manager.build_config_file()
>>>
>>> # Access config values
>>> username = config_manager.config.garmin_username
Initialize the configuration manager.
Creates the config file if it doesn't exist and loads existing configuration or creates a new empty Config object.
Source code in fit_file_faker/config.py
_load_config ¶
Load configuration from file or create new Config if file doesn't exist.
Automatically migrates legacy single-profile configs (v1.2.4 and earlier) to multi-profile format. The migration is transparent and preserves all existing settings in a "default" profile. Migrated configs are automatically saved back to disk in the new format.
Returns:
| Type | Description |
|---|---|
Config | Loaded Config object if file exists and contains valid JSON, |
Config | otherwise a new empty Config object with no profiles. |
Note
Creates an empty config file if one doesn't exist.
Source code in fit_file_faker/config.py
build_config_file ¶
build_config_file(
overwrite_existing_vals: bool = False,
rewrite_config: bool = True,
excluded_keys: list[str] | None = None,
) -> None
Interactively build configuration file.
Prompts the user for missing or invalid configuration values using questionary for an interactive CLI experience. Passwords are masked during input, and the FIT files path is auto-detected for TrainingPeaks Virtual users when possible.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
overwrite_existing_vals | bool | If | False |
rewrite_config | bool | If | True |
excluded_keys | list[str] | None | Optional list of keys to skip during interactive building. Useful for partial configuration. | None |
Raises:
| Type | Description |
|---|---|
SystemExit | If user presses Ctrl-C to cancel configuration. |
Examples:
>>> # Interactive setup for missing values only
>>> config_manager.build_config_file()
>>>
>>> # Rebuild entire configuration
>>> config_manager.build_config_file(overwrite_existing_vals=True)
>>>
>>> # Update only credentials (skip fitfiles_path)
>>> config_manager.build_config_file(
... excluded_keys=["fitfiles_path"]
... )
Note
Passwords are masked in both user input and log output for security. The final configuration is logged with passwords hidden.
Source code in fit_file_faker/config.py
1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 | |
get_config_file_path ¶
Get the path to the configuration file.
Returns:
| Type | Description |
|---|---|
Path | Path to the .config.json file in the platform-specific user |
Path | configuration directory. |
Examples:
>>> path = config_manager.get_config_file_path()
>>> print(f"Config file: {path}")
Config file: /home/user/.config/FitFileFaker/.config.json
Source code in fit_file_faker/config.py
is_valid ¶
Check if configuration is valid (all required keys have values).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
excluded_keys | list[str] | None | Optional list of keys to exclude from validation. Useful when certain config values aren't needed for specific operations (e.g., fitfiles_path when path is provided via CLI). | None |
Returns:
| Type | Description |
|---|---|
bool | True if all required (non-excluded) keys have non-None values, |
bool | False otherwise. Logs missing keys as errors. |
Examples:
>>> # Check all keys
>>> if not config_manager.is_valid():
... print("Configuration incomplete")
>>>
>>> # Exclude fitfiles_path from validation
>>> if not config_manager.is_valid(excluded_keys=["fitfiles_path"]):
... print("Missing Garmin credentials")
Source code in fit_file_faker/config.py
save_config ¶
Save current configuration to file.
Serializes the current Config object to JSON and writes it to the config file with 2-space indentation. Path objects are automatically converted to strings via PathEncoder.
Source code in fit_file_faker/config.py
GarminDeviceInfo dataclass ¶
GarminDeviceInfo(
name: str,
product_id: int,
category: str,
year_released: int,
is_common: bool,
description: str,
software_version: int | None = None,
software_date: str | None = None,
)
Metadata for a Garmin device (supplemental to fit_tool's enum).
Provides enhanced device information for modern Garmin devices not fully represented in fit_tool's GarminProduct enum, or to add curation metadata for devices that already exist.
Attributes:
| Name | Type | Description |
|---|---|---|
name | str | Human-readable device name (e.g., "Edge 1050") |
product_id | int | FIT file product ID (integer) |
category | str | Device category ("bike_computer", "multisport_watch", "trainer") |
year_released | int | Release year for sorting (integer) |
is_common | bool | Show in first-level menu (boolean) |
description | str | Brief description for UI display |
software_version | int | None | Latest stable firmware version in FIT format (int, e.g., 2922 = v29.22) |
software_date | str | None | Latest firmware release date (YYYY-MM-DD format) |
PathEncoder ¶
Bases: JSONEncoder
JSON encoder that handles pathlib.Path and Enum objects.
Extends json.JSONEncoder to automatically convert Path and Enum objects to strings when serializing configuration to JSON format.
Examples:
>>> import json
>>> from pathlib import Path
>>> data = {"path": Path("/home/user"), "type": AppType.ZWIFT}
>>> json.dumps(data, cls=PathEncoder)
'{"path": "/home/user", "type": "zwift"}'
Profile dataclass ¶
Profile(
name: str,
app_type: AppType,
garmin_username: str,
garmin_password: str,
fitfiles_path: Path,
manufacturer: int | None = None,
device: int | None = None,
serial_number: int | None = None,
software_version: int | None = None,
)
Single profile configuration.
Represents a complete configuration profile with app type, credentials, and FIT files directory. Each profile is independent with isolated Garmin Connect credentials.
Attributes:
| Name | Type | Description |
|---|---|---|
name | str | Unique profile identifier (used for display and garth dir naming) |
app_type | AppType | Type of trainer app (for auto-detection and validation) |
garmin_username | str | Garmin Connect account email address |
garmin_password | str | Garmin Connect account password |
fitfiles_path | Path | Path to directory containing FIT files to process |
manufacturer | int | None | Manufacturer ID to use for device simulation (defaults to Garmin) |
device | int | None | Device/product ID to use for device simulation (defaults to Edge 830) |
serial_number | int | None | Device serial number (should be the device's Unit ID; auto-generated if not specified) |
software_version | int | None | Firmware version in FIT format (e.g., 2922 = v29.22). If None, no FileCreatorMessage will be added to FIT files. |
Examples:
>>> from pathlib import Path
>>> profile = Profile(
... name="zwift",
... app_type=AppType.ZWIFT,
... garmin_username="user@example.com",
... garmin_password="secret",
... fitfiles_path=Path("/Users/user/Documents/Zwift/Activities")
... )
__post_init__ ¶
Convert string types to proper objects after initialization.
Handles deserialization from JSON where app_type may be a string and fitfiles_path may be a string path. Also sets default values for manufacturer and device if not specified.
Source code in fit_file_faker/config.py
get_device_name ¶
Get human-readable device name.
Returns:
| Type | Description |
|---|---|
str | Device name if found in GarminProduct enum or supplemental registry, |
str | otherwise "UNKNOWN (id)". |
Examples:
>>> profile.get_device_name()
'EDGE_830'
>>> # For supplemental device
>>> profile.device = 4440
>>> profile.get_device_name()
'Edge 1050'
Source code in fit_file_faker/config.py
get_manufacturer_name ¶
Get human-readable manufacturer name.
Returns:
| Type | Description |
|---|---|
str | Manufacturer name if found in enum, otherwise "UNKNOWN (id)". |
Examples:
Source code in fit_file_faker/config.py
validate_serial_number ¶
Validate that serial_number is valid for FIT spec (uint32z).
Returns:
| Type | Description |
|---|---|
bool | True if serial_number is valid (1,000,000,000 to 4,294,967,295), False otherwise. |
Examples:
Source code in fit_file_faker/config.py
ProfileManager ¶
Manages profile CRUD operations and TUI interactions.
Provides methods for creating, reading, updating, and deleting profiles, as well as interactive TUI wizards for profile management.
Attributes:
| Name | Type | Description |
|---|---|---|
config_manager | Reference to the global ConfigManager instance. |
Initialize ProfileManager with config manager reference.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config_manager | ConfigManager | The ConfigManager instance to use for persistence. | required |
Source code in fit_file_faker/config.py
create_profile ¶
create_profile(
name: str,
app_type: AppType,
garmin_username: str,
garmin_password: str,
fitfiles_path: Path,
manufacturer: int | None = None,
device: int | None = None,
serial_number: int | None = None,
software_version: int | None = None,
) -> Profile
Create a new profile and add it to config.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name | str | Unique profile name. | required |
app_type | AppType | Type of trainer application. | required |
garmin_username | str | Garmin Connect email. | required |
garmin_password | str | Garmin Connect password. | required |
fitfiles_path | Path | Path to FIT files directory. | required |
manufacturer | int | None | Manufacturer ID for device simulation (defaults to Garmin). | None |
device | int | None | Device/product ID for device simulation (defaults to Edge 830). | None |
serial_number | int | None | Device serial number (defaults to auto-generated 10-digit number). | None |
software_version | int | None | Firmware version in FIT format (e.g., 2922 = v29.22). If None, no FileCreatorMessage will be added to FIT files. | None |
Returns:
| Type | Description |
|---|---|
Profile | The newly created Profile object. |
Raises:
| Type | Description |
|---|---|
ValueError | If profile name already exists. |
Examples:
>>> manager = ProfileManager(config_manager)
>>> profile = manager.create_profile(
... "zwift",
... AppType.ZWIFT,
... "user@example.com",
... "secret",
... Path("/path/to/fitfiles")
... )
Source code in fit_file_faker/config.py
1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 | |
create_profile_wizard ¶
Interactive wizard for creating a new profile.
Follows app-first flow: 1. Select app type 2. Auto-detect directory (with confirm/override) 3. Enter Garmin credentials 4. Enter profile name
Returns:
| Type | Description |
|---|---|
Profile | None | The newly created Profile, or None if cancelled. |
Source code in fit_file_faker/config.py
1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 | |
delete_profile ¶
Delete a profile.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name | str | Name of profile to delete. | required |
Raises:
| Type | Description |
|---|---|
ValueError | If profile not found or trying to delete the only profile. |
Source code in fit_file_faker/config.py
delete_profile_wizard ¶
Interactive wizard for deleting a profile with confirmation.
Source code in fit_file_faker/config.py
display_profiles_table ¶
Display all profiles in a Rich table.
Shows profile name, app type, device, Garmin username, and FIT files path in a formatted table. Marks the default profile with ⭐.
Source code in fit_file_faker/config.py
edit_profile_wizard ¶
Interactive wizard for editing an existing profile.
Source code in fit_file_faker/config.py
2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 | |
get_profile ¶
Get profile by name.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name | str | The profile name to retrieve. | required |
Returns:
| Type | Description |
|---|---|
Profile | None | Profile object if found, None otherwise. |
Source code in fit_file_faker/config.py
interactive_menu ¶
Display interactive profile management menu.
Shows profile table and presents menu options for creating, editing, deleting profiles, and setting default.
Source code in fit_file_faker/config.py
list_profiles ¶
set_default_profile ¶
Set a profile as the default.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name | str | Name of profile to set as default. | required |
Raises:
| Type | Description |
|---|---|
ValueError | If profile not found. |
Source code in fit_file_faker/config.py
set_default_wizard ¶
Interactive wizard for setting the default profile.
Source code in fit_file_faker/config.py
update_profile ¶
update_profile(
name: str,
app_type: AppType | None = None,
garmin_username: str | None = None,
garmin_password: str | None = None,
fitfiles_path: Path | None = None,
new_name: str | None = None,
manufacturer: int | None = None,
device: int | None = None,
serial_number: int | None = None,
software_version: int | None = None,
) -> Profile
Update an existing profile.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name | str | Name of profile to update. | required |
app_type | AppType | None | New app type (optional). | None |
garmin_username | str | None | New Garmin username (optional). | None |
garmin_password | str | None | New Garmin password (optional). | None |
fitfiles_path | Path | None | New FIT files path (optional). | None |
new_name | str | None | New profile name (optional). | None |
manufacturer | int | None | New manufacturer ID (optional). | None |
device | int | None | New device ID (optional). | None |
serial_number | int | None | New serial number (optional). | None |
software_version | int | None | New firmware version in FIT format (optional). | None |
Returns:
| Type | Description |
|---|---|
Profile | The updated Profile object. |
Raises:
| Type | Description |
|---|---|
ValueError | If profile not found or new name already exists. |
Source code in fit_file_faker/config.py
1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 | |
get_fitfiles_path ¶
Auto-find the FITFiles folder inside a TrainingPeaks Virtual directory.
Attempts to automatically locate the user's TrainingPeaks Virtual FITFiles directory. On macOS/Windows, the TPVirtual data directory is auto-detected. On Linux, the user is prompted to provide the path.
If multiple user directories exist, the user is prompted to select one.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
existing_path | Path | None | Optional path to use as default. If provided, this path's | required |
Returns:
| Type | Description |
|---|---|
Path | Path to the FITFiles directory (e.g., |
Raises:
| Type | Description |
|---|---|
SystemExit | If no TP Virtual user folder is found, the user rejects the auto-detected folder, or the user cancels the selection. |
Note
The TPVirtual folder location can be overridden using the TPV_DATA_PATH environment variable. User directories are identified by 16-character hexadecimal folder names.
Examples:
>>> # Auto-detect FITFiles path
>>> path = get_fitfiles_path(None)
>>> print(path)
/Users/me/TPVirtual/a1b2c3d4e5f6g7h8/FITFiles
Source code in fit_file_faker/config.py
1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 | |
get_supported_garmin_devices ¶
Get list of Garmin devices for picker UI.
Combines devices from fit_tool's GarminProduct enum (filtered to cycling/training devices with "EDGE", "TACX", or "TRAINING" in their names) with the supplemental device registry containing modern devices with metadata.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
show_all | bool | If False, return only common devices (is_common=True). If True, return all devices. Defaults to False. | False |
Returns:
| Type | Description |
|---|---|
list[tuple[str, int, str]] | List of tuples containing (display_name, product_id, description). |
list[tuple[str, int, str]] | Sorted by: is_common (desc), year_released (desc), name (asc). |
Examples:
>>> # Get common devices only
>>> devices = get_supported_garmin_devices(show_all=False)
>>> print(devices[0])
('Edge 1050', 4440, 'Latest flagship bike computer - 2024')
>>>
>>> # Get all devices
>>> all_devices = get_supported_garmin_devices(show_all=True)
>>> len(all_devices) > len(devices)
True
Source code in fit_file_faker/config.py
get_tpv_folder ¶
Get the TrainingPeaks Virtual base folder path.
Auto-detects the TPVirtual directory based on platform, or prompts the user to provide it if auto-detection is not available.
Platform-specific default locations:
- macOS:
~/TPVirtual - Windows:
~/Documents/TPVirtual - Linux: User is prompted (no auto-detection)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
default_path | Path | None | Optional default path to show in the prompt for Linux users. | required |
Returns:
| Type | Description |
|---|---|
Path | Path to the |
Note
The auto-detected path can be overridden by setting the TPV_DATA_PATH environment variable.
Examples:
>>> # macOS
>>> path = get_tpv_folder(None)
>>> print(path)
/Users/me/TPVirtual
>>>
>>> # Linux (prompts user)
>>> path = get_tpv_folder(Path("/home/me/custom/path"))
Please enter your TrainingPeaks Virtual data folder: /home/me/TPVirtual
Source code in fit_file_faker/config.py
migrate_legacy_config ¶
Migrate single-profile config to multi-profile format.
Detects legacy config structure (v1.2.4 and earlier) and converts to multi-profile format. Creates a "default" profile with existing values and sets it as the default profile.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
old_config | dict | Dictionary containing either legacy single-profile config (keys: garmin_username, garmin_password, fitfiles_path) or new multi-profile config (keys: profiles, default_profile). | required |
Returns:
| Type | Description |
|---|---|
Config | Config object in multi-profile format. If already migrated, returns |
Config | as-is. Otherwise, creates new Config with "default" profile. |
Examples:
>>> legacy = {
... "garmin_username": "user@example.com",
... "garmin_password": "secret",
... "fitfiles_path": "/path/to/fitfiles"
... }
>>> config = migrate_legacy_config(legacy)
>>> config.profiles[0].name
'default'
>>> config.default_profile
'default'
Source code in fit_file_faker/config.py
Utilities (utils.py)¶
utils ¶
Utility functions for Fit File Faker.
This module provides utility functions including a monkey patch for fit_tool to handle malformed FIT files from certain manufacturers (e.g., COROS) and a CRC-16 checksum calculation function.
The fit_tool patch is automatically applied when the fit_editor module is imported, making it transparent to users of the library.
_lenient_get_length_from_size ¶
Lenient field length calculator that truncates instead of raising exceptions.
This is a replacement for fit_tool's Field.get_length_from_size that handles malformed FIT files more gracefully. Some manufacturers (e.g., COROS) create FIT files where field sizes are not exact multiples of their base type size. Instead of failing with an exception, this function truncates to the nearest valid length.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
base_type | BaseType | The | required |
size | int | The declared size of the field in bytes. | required |
Returns:
| Name | Type | Description |
|---|---|---|
length | int | The field length (number of values, not bytes). For |
Note
When truncation occurs (size not a multiple of base_type.size), a debug message is logged. This typically indicates a malformed FIT file but allows processing to continue.
Examples:
>>> # Normal case: 8 bytes for UINT32 (4 bytes each) = length 2
>>> _lenient_get_length_from_size(BaseType.UINT32, 8)
2
>>> # Malformed case: 7 bytes for UINT32 = length 1 (truncated)
>>> _lenient_get_length_from_size(BaseType.UINT32, 7)
1
Source code in fit_file_faker/utils.py
_lenient_read_strings_from_bytes ¶
Lenient string decoder that handles non-UTF-8 encoded strings.
This is a replacement for fit_tool's Field.read_strings_from_bytes that handles FIT files with non-UTF-8 encoded strings more gracefully. Some devices use Windows-1252, Latin-1, or other encodings instead of UTF-8.
The function tries multiple decoding strategies: 1. UTF-8 (standard) 2. Latin-1 / ISO-8859-1 (fallback) 3. Replace invalid bytes with � (last resort)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
bytes_buffer | bytes | Raw bytes containing null-terminated strings. | required |
Note
When non-UTF-8 encoding is detected, a debug message is logged. This allows processing to continue even with malformed string data.
Source code in fit_file_faker/utils.py
apply_fit_tool_patch ¶
Apply monkey patch to fit_tool to handle malformed FIT files.
Replaces fit_tool's Field.get_length_from_size method with a more lenient version that truncates field lengths instead of raising exceptions when field sizes aren't exact multiples of their base type size.
Also replaces Field.read_strings_from_bytes to handle non-UTF-8 encoded strings gracefully by falling back to Latin-1 or replacement characters.
This patch is essential for processing FIT files from manufacturers like COROS that don't strictly follow the FIT specification. Without it, fit_tool would raise exceptions and refuse to process these files.
The patch is automatically applied when the fit_editor module is imported, so users don't need to call this function manually.
Note
This is a global monkey patch that affects all subsequent fit_tool operations in the same Python process. It's applied once at module import time.
Examples:
>>> # Typically called automatically, but can be invoked manually:
>>> from fit_file_faker.utils import apply_fit_tool_patch
>>> apply_fit_tool_patch()
>>> # Now fit_tool can handle COROS files without errors
Source code in fit_file_faker/utils.py
fit_crc_get16 ¶
Calculate FIT file CRC-16 checksum for a single byte.
Implements the CRC-16 algorithm used by FIT files. This function processes one byte at a time and should be called repeatedly for each byte in the data to calculate a complete checksum.
The algorithm uses a lookup table and processes the byte in two 4-bit nibbles (lower 4 bits first, then upper 4 bits) to compute the CRC.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
crc | int | Current CRC value (16-bit unsigned integer). Use 0 for the first byte in the sequence. | required |
byte | int | Byte value to add to the checksum (8-bit unsigned integer, 0-255). | required |
Returns:
| Type | Description |
|---|---|
int | Updated CRC value (16-bit unsigned integer) after processing this byte. |
Examples:
>>> # Calculate CRC for a single byte
>>> crc = fit_crc_get16(0, 0x42)
>>> print(f"CRC: {crc:#06x}")
CRC: 0x...
>>>
>>> # Calculate CRC for a byte array
>>> def calculate_fit_crc(data: bytes) -> int:
... '''Calculate CRC-16 for FIT file data.'''
... crc = 0
... for byte in data:
... crc = fit_crc_get16(crc, byte)
... return crc
>>>
>>> data = b"\x0e\x10\x43\x08\x28\x06\x00\x00"
>>> checksum = calculate_fit_crc(data)
Note
This is the standard CRC-16 algorithm used in FIT file headers and data records. It's primarily used for validation but is not currently required by fit_file_faker since fit_tool handles CRC calculation automatically.